code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
import xml.etree.ElementTree as ET from collections import OrderedDict as ODict import logging, sys import numpy as np import math import kgprim.core as primitives import kgprim.motions as motions from kgprim.motions import MotionSequence from kgprim.motions import PoseSpec from kgprim.motions import MotionPath import robmodel.connectivity import robmodel.ordering import robmodel.frames import robmodel.geometry from robmodel.connectivity import JointKind logger = logging.getLogger(__name__) ''' Simply reads the XML file and stores the links/joints data, no conversions ''' class URDFWrapper : class Link: def __init__(self, name): self.name = name self.inertia = None self.parent = None self.supportingJoint = None class Joint: def __init__(self, name): self.name = name self.type = None self.frame = None self.parent= None self.child = None #self.predec_H_joint = np.identity(4) iMomentsLabels = ['ixx', 'iyy', 'izz', 'ixy', 'ixz', 'iyz'] def __init__(self, urdfInFile): root = ET.parse(urdfInFile) self.robotName = root.getroot().get('name') linkNodes = root.findall("link") jointNodes = root.findall("joint") self.links = ODict() self.joints = ODict() self.frames = ODict() for nodelink in linkNodes: name = nodelink.get('name') link = URDFWrapper.Link( name ) link.inertia = self.readInertialData(nodelink) self.links[name] = link for nodejoint in jointNodes: name = nodejoint.get('name') joint = URDFWrapper.Joint( name ) joint.type = nodejoint.get('type') joint.frame = self.readJointFrameData( nodejoint ) #joint.predec_H_joint[:3,:3] = getR_extrinsicXYZ( * joint.frame['rpy'] ) #joint.predec_H_joint[:3,3] = np.array( joint.frame['xyz'] ) joint.parent= nodejoint.find('parent').get('link') joint.child = nodejoint.find('child').get('link') # Note I keep URDF nomenclature ("parent" and "child") just to # stress the bond with the source URDF XML file. I will later use # the more appropriate terms (e.g. "predecessor") self.joints[name] = joint predecessor = self.links[ joint.parent ] successor = self.links[ joint.child ] successor.parent = predecessor # a Link instance, not a name successor.supportingJoint = joint def readInertialData(self, linkNode): params = dict() paramsNode = linkNode.find('inertial') # Default inertia parameters if the URDF does not have the data if paramsNode == None : params['mass'] = 0.0 params['xyz'] = (0.0, 0.0, 0.0) for m in URDFWrapper.iMomentsLabels : params[m] = 0.0 return params mass = float(paramsNode.find('mass').get('value')) xyz = (0.0, 0.0, 0.0) originNode = paramsNode.find('origin') if originNode != None : comstr = originNode.get('xyz') if(comstr != None) : xyz = tuple([float(x) for x in comstr.split()]) # We cannot deal with non-zero values for the 'rpy' attribute rpystr = originNode.get('rpy') if(rpystr != None) : tmp = [float(x) for x in rpystr.split()] if(sum(tmp) != 0) : logger.warning('The rpy attribute in the inertial section is not yet supported (link ' + linkNode.get('name') + '). Ignoring it.') moments = paramsNode.find('inertia') for m in URDFWrapper.iMomentsLabels : params[m] = float(moments.get(m)) params['mass'] = mass params['xyz'] = xyz return params def readJointFrameData(self, jointNode): params = dict() # URDF defaults: params['xyz'] = (0.,0.,0.) params['rpy'] = (0.,0.,0.) frameNode = jointNode.find('origin') if frameNode != None : xyz_node = frameNode.get('xyz') if xyz_node != None : params['xyz'] = tuple([float(x) for x in xyz_node.split()]) rpy_node = frameNode.get('rpy') if rpy_node != None : params['rpy'] = tuple([float(x) for x in rpy_node.split()]) axis_node = jointNode.find('axis') if axis_node != None : params['axis'] = tuple([float(x) for x in axis_node.get('xyz').split()]) else : params['axis'] = (1.,0.,0.) # URDF default return params def toValidID( name ) : return name.replace('-', '__') def linkFrameToJointFrameInURDF(urdfjoint): ''' Return the data about the location of the joint frame relative to the predecessor link frame. This function returns three values: - the `xyz` attribute as found in the source URDF - the `rpy` attribute as found in the source URDF - the rigid motion model representing the relative pose (this is the motion that the link frame should undergo to coincide with the joint frame) ''' xyz = urdfjoint.frame['xyz'] rpy = urdfjoint.frame['rpy'] tr = [motions.translation(a, xyz[a.value]) for a in motions.Axis if round(xyz[a.value],5) != 0.0] rt = [motions.rotation (a, rpy[a.value]) for a in motions.Axis if round(rpy[a.value],5) != 0.0] motion__linkToJoint = MotionSequence(tr+rt, MotionSequence.Mode.fixedFrame) return xyz, rpy, motion__linkToJoint def convert( urdf ) : ''' Reads the model from a URDFWrapper instance, and construct the corresponding models in our format. ''' robotName = urdf.robotName links = ODict() joints = ODict() pairs = [] children = {} orphans = [] for urdfname in urdf.links.keys() : name = toValidID( urdfname ) link = robmodel.connectivity.Link(name) links[name] = link children[name] = [] if urdf.links[urdfname].parent == None : orphans.append(link) if len(orphans)==0 : logger.fatal("Could not find any root link (i.e. a link without parent).") logger.fatal("Check for kinematic loops.") print("Error, no root link found. Aborting", file=sys.stderr) sys.exit(-1) if len(orphans) > 1 : logger.warning("Found {0} links without parent, only one expected".format(len(orphans))) logger.warning("Any robot model must have exactly one root element.") logger.warning("This might lead to unexpected results.") robotBase = orphans[0] for jname in urdf.joints.keys() : urdfjoint = urdf.joints[jname] name = toValidID( jname ) jkind = urdfjoint.type if jkind in JointKind.__members__.keys() : jkind = JointKind[jkind] # otherwise, it stays a string (like 'fixed') joint = robmodel.connectivity.Joint(name, jkind) parent = links[ toValidID(urdfjoint.parent) ] child = links[ toValidID(urdfjoint.child) ] children[parent.name].append( child ) joints[name] = joint pairs.append( robmodel.connectivity.KPair(joint, parent, child) ) # CONNECTIVITY MODEL connectivityModel = robmodel.connectivity.Robot( urdf.robotName, links, joints, pairs) # REGULAR NUMBERING # There is no numbering scheme in the URDF format, so we arbitrarily # associate code to each link via a Depth-First-Traversal code = 0 numbering = {} def setCode(currentLink): nonlocal code, numbering if currentLink == None : return numbering[currentLink.name] = code for child in children[currentLink.name] : code = code + 1 setCode( child ) setCode( robotBase ) ordering = { 'robot': robotName, 'nums' : numbering } orderedModel = robmodel.ordering.Robot(connectivityModel, ordering) # FRAMES # The URDF does not have explicit frames, so there are no more frames than # joints and links; thus the second argument is always the empty list framesModel = robmodel.frames.RobotDefaultFrames(orderedModel, []) # GEOMETRY MEASUREMENTS poses = [] axes = {} for joint in urdf.joints.values() : # Get the current joint and link (predecessor) myjoint = joints[ toValidID( joint.name ) ] mylink = orderedModel.predecessor(myjoint) logger.debug("Processing joint * {0} * and predecessor link * {1} *".format(myjoint.name, mylink.name) ) # The relative pose of the URDF joint frame relative to the URDF link frame xyz, rpy, motion_link_to_joint = linkFrameToJointFrameInURDF(joint) jaxis = np.round( np.array(joint.frame['axis']), 5) logger.debug("Joint axis in URDF coordinates : {0}".format(jaxis) ) logger.debug("URDF joint xyz and rpy attributes : {0} {1}".format(xyz, rpy) ) frame_joint = framesModel.framesByName[ myjoint.name ] frame_link = framesModel.framesByName[ mylink.name ] pose = primitives.Pose(target=frame_joint, reference=frame_link) poses.append( PoseSpec(pose, motion_link_to_joint) ) axes[myjoint.name] = joint.frame['axis'] posesModel = motions.PosesSpec(robotName, poses) geometryModel = robmodel.geometry.Geometry(orderedModel, framesModel, posesModel, axes) return connectivityModel, orderedModel, framesModel, geometryModel
/robot-model-tools-0.1.0.tar.gz/robot-model-tools-0.1.0/src/robmodel/convert/urdf/imp.py
0.53437
0.240741
imp.py
pypi
import logging from mako.template import Template import robmodel.convert.utils as utils import kgprim.ct as ct import kgprim.ct.repr.mxrepr as mxrepr from robmodel.connectivity import JointKind from robmodel.treeutils import TreeUtils import robmodel.frames logger = logging.getLogger(__name__) tpl = Template(''' Robot ${robot.name} { % for link in robot.links.values(): % if link == robot.base : RobotBase ${link.name} { % else : link ${link.name} { id = ${robot.linkNum(link)} % endif children { % for child in tree.children(link): ${child.name} via ${robot.linkPairToJoint(link, child).name} % endfor } <% userFrames = linkUserFrames(link) %> % if len(userFrames) > 0 : frames { % for f in userFrames : <% x,y,z,rx,ry,rz = frameParams(f) %> ${f.name} { translation = (${tostr(x)}, ${tostr(y)}, ${tostr(z)}) rotation = (${tostr(rx, True)}, ${tostr(ry, True)}, ${tostr(rz, True)}) } % endfor } % endif } % endfor % for joint in robot.joints.values() : <% x,y,z,rx,ry,rz = jointFrameParams(joint) %> ${jSection(joint)} ${joint.name} { ref_frame { translation = (${tostr(x)}, ${tostr(y)}, ${tostr(z)}) rotation = (${tostr(rx, True)}, ${tostr(ry, True)}, ${tostr(rz, True)}) } } % endfor } ''' ) __joint_section = { JointKind.prismatic : "p_joint", JointKind.revolute : "r_joint" } def jointSectionName(joint): return __joint_section[ joint.kind ] def jointFrameParams(geometryModel, joint): poseSpec = geometryModel.byJoint[ joint ] return poseParams(poseSpec) def userFrameParams(geometryModel, framesModel, frame): pose = framesModel.poseRelativeToSupportingLinkFrame(frame) if pose is not None : if pose in geometryModel.byPose : poseSpec = geometryModel.byPose[ pose ] return poseParams(poseSpec) logger.warning("Could not find pose information for frame '{f}'".format(f=frame.name)) return 0,0,0,0,0,0 def poseParams( poseSpec ): xt = ct.frommotions.toCoordinateTransform( poseSpec ) H = mxrepr.hCoordinatesNumeric(xt) irx,iry,irz = utils.getIntrinsicXYZFromR( H ) return H[0,3], H[1,3], H[2,3], irx,iry,irz def linkUserFrames(framesModel, link): ret = [] lf = framesModel.linkFrames[link] for uf in framesModel.graph[lf] : kind = framesModel.kind(lf, uf) if kind == robmodel.frames.FrameRelationKind.generic : ret.append(uf) return ret def geometry(geometryModel): connect= geometryModel.connectivityModel frames = geometryModel.framesModel formatter = utils.FloatsFormatter(pi_string="PI") tree = TreeUtils(connect) return tpl.render( robot=connect, tree=tree, jSection=jointSectionName, jointFrameParams=lambda j : jointFrameParams(geometryModel, j), linkUserFrames=lambda l : linkUserFrames(frames, l), frameParams= lambda f : userFrameParams(geometryModel, frames, f), tostr=lambda num, isAngle=False: formatter.float2str(num, isAngle) )
/robot-model-tools-0.1.0.tar.gz/robot-model-tools-0.1.0/src/robmodel/convert/kindsl/exp.py
0.464416
0.271559
exp.py
pypi
import logging import numpy import kgprim.motions as motions import kgprim.ct.frommotions as frommotions import kgprim.ct.repr.mxrepr as mxrepr import motiondsl.motiondsl as motdsl logger = logging.getLogger(__name__) class RobotKinematics: '''The composition of the constant poses and the joint poses of a robot. This class is a simple aggregation of the geometry model and the joint-poses model. By merging the two, this class have access to the full robot kinematics. Thanks to `kgprim.motions.ConnectedFramesInspector`, an arbitrary relative pose between two frames on the robot can be obtained. ''' def __init__(self, geometry, jointPoses): self.robotGeometry = geometry self.jointPoses = jointPoses self.baseFrame = geometry.framesModel.linkFrames[ geometry.connectivityModel.base ] allPoses = geometry.posesModel.mergeModel( jointPoses.jointPosesModel ) self.framesConnectivity = motions.ConnectedFramesInspector(allPoses) def base_H_ee(kinematics, framename): if framename not in kinematics.robotGeometry.framesModel.framesByName: logger.error("Could not find frame '{0}' in model '{1}'".format(framename, kinematics.robotGeometry.robotName)) return None ee = kinematics.robotGeometry.framesModel.framesByName[ framename ] if not kinematics.framesConnectivity.hasRelativePose(ee, kinematics.baseFrame): logger.error("Frame '{0}' and the base frame do not seem to be connected".format(framename)) return None poseSpec = kinematics.framesConnectivity.getPoseSpec(ee, kinematics.baseFrame) cotr = frommotions.toCoordinateTransform(poseSpec) H = mxrepr.hCoordinatesSymbolic(cotr) q = numpy.zeros( len(H.variables) ) H = H.setVariablesValue( valueslist=q ) return H def serializeToMotionDSLModel(robotKinematics, ostream): header =''' Model {modelname} Convention = currentFrame '''.format(modelname=robotKinematics.robotGeometry.robotName) ostream.write(header) for jp in robotKinematics.jointPoses.poseSpecByJoint.values(): text = motdsl.poseSpecToMotionDSLSnippet( jp ) ostream.write(text) ostream.write('\n') for cp in robotKinematics.robotGeometry.byPose.values() : text = motdsl.poseSpecToMotionDSLSnippet( cp ) ostream.write(text) ostream.write('\n')
/robot-model-tools-0.1.0.tar.gz/robot-model-tools-0.1.0/src/rmt/kinematics.py
0.668772
0.476823
kinematics.py
pypi
from contextlib import suppress import numpy as np from general_robotics_toolbox import * from pandas import read_csv import sys from .robots_def import * from .error_check import * from .toolbox_circular_fit import * from .lambda_calc import * from .dual_arm import * import RobotRaconteur as RR from RobotRaconteurCompanion.Util.GeometryUtil import GeometryUtil class MotionSendRobotRaconteurMP(object): def __init__(self, robot_mp=None, node=None): self._robot_mp = robot_mp if robot_mp is not None and node is None: self._node = robot_mp.RRGetNode() else: self._node = node self._robot_const = self._node.GetConstants("com.robotraconteur.robotics.robot", self._robot_mp) self._abb_robot_const = self._node.GetConstants("experimental.abb_robot", self._robot_mp) self._abb_robot_mp_const = self._node.GetConstants("experimental.abb_robot.motion_program", self._robot_mp) self._halt_mode = self._robot_const["RobotCommandMode"]["halt"] self._motion_program_mode = self._abb_robot_const["ABBRobotCommandMode"]["motion_program"] self._cir_path_mode_switch = self._abb_robot_mp_const["CirPathModeSwitch"] self._robot_pose_type = self._node.GetStructureType("experimental.robotics.motion_program.RobotPose",self._robot_mp) self._moveabsj_type = self._node.GetStructureType("experimental.robotics.motion_program.MoveAbsJCommand",self._robot_mp) self._movej_type = self._node.GetStructureType("experimental.robotics.motion_program.MoveJCommand",self._robot_mp) self._movel_type = self._node.GetStructureType("experimental.robotics.motion_program.MoveLCommand",self._robot_mp) self._movec_type = self._node.GetStructureType("experimental.robotics.motion_program.MoveCCommand",self._robot_mp) self._settool_type = self._node.GetStructureType("experimental.robotics.motion_program.SetToolCommand",self._robot_mp) self._setpayload_type = self._node.GetStructureType("experimental.robotics.motion_program.SetPayloadCommand",self._robot_mp) self._waittime_type = self._node.GetStructureType("experimental.robotics.motion_program.WaitTimeCommand",self._robot_mp) self._cirpathmode_type = self._node.GetStructureType("experimental.abb_robot.motion_program.CirPathModeCommand",self._robot_mp) self._motionprogram_type = self._node.GetStructureType("experimental.robotics.motion_program.MotionProgram",self._robot_mp) self._toolinfo_type = self._node.GetStructureType("com.robotraconteur.robotics.tool.ToolInfo",self._robot_mp) self._payloadinfo_type = self._node.GetStructureType("com.robotraconteur.robotics.payload.PayloadInfo",self._robot_mp) self._transform_dt = self._node.GetNamedArrayDType("com.robotraconteur.geometry.Transform",self._robot_mp) self._spatialinertia_dt = self._node.GetNamedArrayDType("com.robotraconteur.geometry.SpatialInertia",self._robot_mp) self._geom_util = GeometryUtil(self._node, self._robot_mp) def robot_pose(self,p,q,joint_seed): ret = self._robot_pose_type() ret.tcp_pose[0]["orientation"]["w"] = q[0] ret.tcp_pose[0]["orientation"]["x"] = q[1] ret.tcp_pose[0]["orientation"]["y"] = q[2] ret.tcp_pose[0]["orientation"]["z"] = q[3] ret.tcp_pose[0]["position"]["x"] = p[0]*1e-3 ret.tcp_pose[0]["position"]["y"] = p[1]*1e-3 ret.tcp_pose[0]["position"]["z"] = p[2]*1e-3 ret.joint_position_seed=joint_seed return ret def moveabsj(self,j,velocity,blend_radius,fine_point=False): cmd = self._moveabsj_type() cmd.joint_position = j cmd.tcp_velocity = velocity cmd.blend_radius = blend_radius cmd.fine_point = fine_point return RR.VarValue(cmd,"experimental.robotics.motion_program.MoveAbsJCommand") def movel(self,robot_pose,velocity,blend_radius,fine_point=False): cmd = self._movel_type() cmd.tcp_pose = robot_pose cmd.tcp_velocity = velocity*1e-3 cmd.blend_radius = blend_radius*1e-1 cmd.fine_point = fine_point return RR.VarValue(cmd,"experimental.robotics.motion_program.MoveLCommand") def movej(self,robot_pose,velocity,blend_radius,fine_point=False): cmd = self._movej_type() cmd.tcp_pose = robot_pose cmd.tcp_velocity = velocity*1e-3 cmd.blend_radius = blend_radius*1e-3 cmd.fine_point = fine_point return RR.VarValue(cmd,"experimental.robotics.motion_program.MoveJCommand") def movec(self,robot_via_pose,robot_pose,velocity,blend_radius,fine_point=False): cmd = self._movec_type() cmd.tcp_pose = robot_pose cmd.tcp_via_pose = robot_via_pose cmd.tcp_velocity = velocity*1e-3 cmd.blend_radius = blend_radius*1e-3 cmd.fine_point = fine_point return RR.VarValue(cmd,"experimental.robotics.motion_program.MoveCCommand") def moveL_target(self,robot,q,point): quat=R2q(robot.fwd(q).R) robt = self.robot_pose([point[0], point[1], point[2]], [ quat[0], quat[1], quat[2], quat[3]], q) return robt def moveC_target(self,robot,q1,q2,point1,point2): quat1=R2q(robot.fwd(q1).R) cf1=quadrant(q1,robot) quat2=R2q(robot.fwd(q2).R) cf2=quadrant(q2,robot) robt1 = self.robot_pose([point1[0], point1[1], point1[2]], [ quat1[0], quat1[1], quat1[2], quat1[3]], q1) robt2 = self.robot_pose([point2[0], point2[1], point2[2]], [ quat2[0], quat2[1], quat2[2], quat2[3]], q2) return robt1, robt2 def moveJ_target(self,q): return q def waittime(self, t): wt = self._waittime_type() wt.time = t return (RR.VarValue(wt,"experimental.robotics.motion_program.WaitTimeCommand")) def settool(self, robot): toolinfo = self._toolinfo_type() toolinfo.tcp = self._geom_util.rox_transform_to_transform(rox.Transform(robot.R_tool, np.multiply(robot.p_tool,1e-3))) ii = np.zeros((1,),dtype=self._spatialinertia_dt) ii[0]["m"] = 1e-3 ii[0]["com"] = (0,0,1e-3) ii[0]["ixx"] = 1e-3 ii[0]["ixy"] = 0 ii[0]["ixz"] = 0 ii[0]["iyy"] = 1e-3 ii[0]["iyz"] = 0 ii[0]["izz"] = 1e-3 toolinfo.inertia = ii #toolinfo.inertia = RRN.ArrayToNamedArray([0.1,0,0,0.01,.001,0,0,.001,0,.001],) settool = self._settool_type() settool.tool_info = toolinfo return RR.VarValue(settool,"experimental.robotics.motion_program.SetToolCommand") def convert_motion_program(self,robot,primitives,breakpoints,p_bp,q_bp,speed,zone): #mp = MotionProgram(tool=tooldata(True,pose(robot.p_tool,R2q(robot.R_tool)),loaddata(1,[0,0,0.001],[1,0,0,0],0,0,0))) setup_cmds=[self.settool(robot)] ###change cirpath mode mp_cmds = [] cirpath = self._cirpathmode_type() cirpath.switch = self._cir_path_mode_switch["ObjectFrame"] mp_cmds.append(RR.VarValue(cirpath,"experimental.abb_robot.motion_program.CirPathModeCommand")) for i in range(len(primitives)): if 'movel' in primitives[i]: robt = self.moveL_target(robot,q_bp[i][0],p_bp[i][0]) if type(speed) is list: if type(zone) is list: mp_cmds.append(self.movel(robt,speed[i],zone[i])) else: mp_cmds.append(self.movel(robt,speed[i],zone)) else: if type(zone) is list: mp_cmds.append(self.movel(robt,speed,zone[i])) else: mp_cmds.append(self.movel(robt,speed,zone)) elif 'movec' in primitives[i]: robt1, robt2 = self.moveC_target(robot,q_bp[i][0],q_bp[i][1],p_bp[i][0],p_bp[i][1]) if type(speed) is list: if type(zone) is list: mp_cmds.append(self.movec(robt1,robt2,speed[i],zone[i])) else: mp_cmds.append(self.movec(robt1,robt2,speed[i],zone)) else: if type(zone) is list: mp_cmds.append(self.movec(robt1,robt2,speed,zone[i])) else: mp_cmds.append(self.movec(robt1,robt2,speed,zone)) elif 'movej' in primitives[i]: robt = self.moveL_target(robot,q_bp[i][0],p_bp[i][0]) if type(speed) is list: if type(zone) is list: mp_cmds.append(self.movej(robt,speed[i],zone[i])) else: mp_cmds.append(self.movej(robt,speed[i],zone)) else: if type(zone) is list: mp_cmds.append(self.movej(robt,speed,zone[i])) else: mp_cmds.append(self.movej(robt,speed,zone)) else: # moveabsj jointt = self.moveJ_target(q_bp[i][0]) if i==0: mp_cmds.append(self.moveabsj(jointt,0.5,0.1,True)) mp_cmds.append(self.waittime(1)) mp_cmds.append(self.moveabsj(jointt,0.5,0.1,True)) mp_cmds.append(self.waittime(0.1)) else: if type(speed) is list: if type(zone) is list: mp_cmds.append(self.moveabsj(jointt,speed[i],zone[i])) else: mp_cmds.append(self.moveabsj(jointt,speed[i],zone)) else: if type(zone) is list: mp_cmds.append(self.moveabsj(jointt,speed,zone[i])) else: mp_cmds.append(self.moveabsj(jointt,speed,zone)) ###add sleep at the end to wait for train_data transmission mp_cmds.append(self.waittime(0.1)) mp = self._motionprogram_type() mp.motion_setup_commands = setup_cmds mp.motion_program_commands = mp_cmds return mp def exec_motions(self,robot,primitives,breakpoints,p_bp,q_bp,speed,zone): self._robot_mp.disable_motion_program_mode() self._robot_mp.enable_motion_program_mode() mp=self.convert_motion_program(robot,primitives,breakpoints,p_bp,q_bp,speed,zone) mp_gen = self._robot_mp.execute_motion_program_record(mp, False) res = None with suppress(RR.StopIterationException): while True: res = mp_gen.Next() recording_gen = self._robot_mp.read_recording(res.recording_handle) recording = recording_gen.NextAll()[0] self._robot_mp.clear_recordings() return recording def extend(self,robot,q_bp,primitives,breakpoints,p_bp,extension_start=100,extension_end=100): p_bp_extended=copy.deepcopy(p_bp) q_bp_extended=copy.deepcopy(q_bp) ###initial point extension pose_start=robot.fwd(q_bp[0][0]) p_start=pose_start.p R_start=pose_start.R pose_end=robot.fwd(q_bp[1][-1]) p_end=pose_end.p R_end=pose_end.R if 'movel' in primitives[1]: #find new start point slope_p=p_end-p_start slope_p=slope_p/np.linalg.norm(slope_p) p_start_new=p_start-extension_start*slope_p ###extend 5cm backward #find new start orientation k,theta=R2rot(R_end@R_start.T) theta_new=-extension_start*theta/np.linalg.norm(p_end-p_start) R_start_new=rot(k,theta_new)@R_start #solve invkin for initial point p_bp_extended[0][0]=p_start_new q_bp_extended[0][0]=car2js(robot,q_bp[0][0],p_start_new,R_start_new)[0] elif 'movec' in primitives[1]: #define circle first pose_mid=robot.fwd(q_bp[1][0]) p_mid=pose_mid.p R_mid=pose_mid.R center, radius=circle_from_3point(p_start,p_end,p_mid) #find desired rotation angle angle=extension_start/radius #find new start point plane_N=np.cross(p_end-center,p_start-center) plane_N=plane_N/np.linalg.norm(plane_N) R_temp=rot(plane_N,angle) p_start_new=center+R_temp@(p_start-center) #modify mid point to be in the middle of new start and old end (to avoid RS circle uncertain error) modified_bp=arc_from_3point(p_start_new,p_end,p_mid,N=3) p_bp_extended[1][0]=modified_bp[1] #find new start orientation k,theta=R2rot(R_end@R_start.T) theta_new=-extension_start*theta/np.linalg.norm(p_end-p_start) R_start_new=rot(k,theta_new)@R_start #solve invkin for initial point p_bp_extended[0][0]=p_start_new q_bp_extended[0][0]=car2js(robot,q_bp[0][0],p_start_new,R_start_new)[0] else: #find new start point J_start=robot.jacobian(q_bp[0][0]) qdot=q_bp[0][0]-q_bp[1][0] v=np.linalg.norm(J_start[3:,:]@qdot) t=extension_start/v q_bp_extended[0][0]=q_bp[0][0]+qdot*t p_bp_extended[0][0]=robot.fwd(q_bp_extended[0][0]).p ###end point extension pose_start=robot.fwd(q_bp[-2][-1]) p_start=pose_start.p R_start=pose_start.R pose_end=robot.fwd(q_bp[-1][-1]) p_end=pose_end.p R_end=pose_end.R if 'movel' in primitives[-1]: #find new end point slope_p=(p_end-p_start)/np.linalg.norm(p_end-p_start) p_end_new=p_end+extension_end*slope_p ###extend 5cm backward #find new end orientation k,theta=R2rot(R_end@R_start.T) slope_theta=theta/np.linalg.norm(p_end-p_start) R_end_new=rot(k,extension_end*slope_theta)@R_end #solve invkin for end point q_bp_extended[-1][0]=car2js(robot,q_bp[-1][0],p_end_new,R_end_new)[0] p_bp_extended[-1][0]=p_end_new elif 'movec' in primitives[-1]: #define circle first pose_mid=robot.fwd(q_bp[-1][0]) p_mid=pose_mid.p R_mid=pose_mid.R center, radius=circle_from_3point(p_start,p_end,p_mid) #find desired rotation angle angle=extension_end/radius #find new end point plane_N=np.cross(p_start-center,p_end-center) plane_N=plane_N/np.linalg.norm(plane_N) R_temp=rot(plane_N,angle) p_end_new=center+R_temp@(p_end-center) #modify mid point to be in the middle of new end and old start (to avoid RS circle uncertain error) modified_bp=arc_from_3point(p_start,p_end_new,p_mid,N=3) p_bp_extended[-1][0]=modified_bp[1] #find new end orientation k,theta=R2rot(R_end@R_start.T) theta_new=extension_end*theta/np.linalg.norm(p_end-p_start) R_end_new=rot(k,theta_new)@R_end #solve invkin for end point q_bp_extended[-1][-1]=car2js(robot,q_bp[-1][-1],p_end_new,R_end_new)[0] p_bp_extended[-1][-1]=p_end_new #midpoint not changed else: #find new end point J_end=robot.jacobian(q_bp[-1][0]) qdot=q_bp[-1][0]-q_bp[-2][0] v=np.linalg.norm(J_end[3:,:]@qdot) t=extension_end/v q_bp_extended[-1][0]=q_bp[-1][-1]+qdot*t p_bp_extended[-1][0]=robot.fwd(q_bp_extended[-1][-1]).p return p_bp_extended,q_bp_extended def logged_data_analysis(self,robot,log_results,realrobot=True): cmd_num=log_results.command_number #find closest to 5 cmd_num idx = np.absolute(cmd_num-5).argmin() start_idx=np.where(cmd_num==cmd_num[idx])[0][0] curve_exe_js=log_results.joints[start_idx:] timestamp=log_results.time[start_idx:] ###filter noise timestamp, curve_exe_js=lfilter(timestamp, curve_exe_js) speed=[0] lam=[0] curve_exe=[] curve_exe_R=[] for i in range(len(curve_exe_js)): robot_pose=robot.fwd(curve_exe_js[i],qlim_override=True) curve_exe.append(robot_pose.p) curve_exe_R.append(robot_pose.R) if i>0: lam.append(lam[-1]+np.linalg.norm(curve_exe[i]-curve_exe[i-1])) try: if timestamp[i-1]!=timestamp[i] and np.linalg.norm(curve_exe_js[i-1]-curve_exe_js[i])!=0: speed.append(np.linalg.norm(curve_exe[-1]-curve_exe[-2])/(timestamp[i]-timestamp[i-1])) else: speed.append(speed[-1]) except IndexError: pass speed=moving_average(speed,padding=True) return np.array(lam), np.array(curve_exe), np.array(curve_exe_R),np.array(curve_exe_js), np.array(speed), timestamp-timestamp[0] def chop_extension(self,curve_exe, curve_exe_R,curve_exe_js, speed, timestamp,p_start,p_end): start_idx=np.argmin(np.linalg.norm(p_start-curve_exe,axis=1)) end_idx=np.argmin(np.linalg.norm(p_end-curve_exe,axis=1)) #make sure extension doesn't introduce error if np.linalg.norm(curve_exe[start_idx]-p_start)>0.5: start_idx+=1 if np.linalg.norm(curve_exe[end_idx]-p_end)>0.5: end_idx-=1 curve_exe=curve_exe[start_idx:end_idx+1] curve_exe_js=curve_exe_js[start_idx:end_idx+1] curve_exe_R=curve_exe_R[start_idx:end_idx+1] speed=speed[start_idx:end_idx+1] lam=calc_lam_cs(curve_exe) return lam, curve_exe, curve_exe_R,curve_exe_js, speed, timestamp[start_idx:end_idx+1]-timestamp[start_idx]
/robot_motion_program_opt-0.0.1-py3-none-any.whl/robot_motion_program_opt/toolbox/robotraconteur_mp_utils.py
0.487795
0.193604
robotraconteur_mp_utils.py
pypi
import RPi.GPIO as gpio from robot_core.executor.executor import Executor class Motor2wdExecutor(Executor): gpio.setwarnings(False) gpio.setmode(gpio.BCM) def execute(self, **kwargs): if kwargs["command"] == "start_forward": return self.start_forward() elif kwargs["command"] == "stop_forward": return self.stop() elif kwargs["command"] == "start_backward": return self.start_backward() elif kwargs["command"] == "start_left": return self.start_left() elif kwargs["command"] == "start_right": return self.start_right() def start_forward(self): # roda esquerda frente gpio.setup(2, gpio.OUT) gpio.output(2, True) gpio.setup(3, gpio.OUT) gpio.output(3, False) # roda direta pra frente gpio.setup(18, gpio.OUT) gpio.output(18, True) gpio.setup(24, gpio.OUT) gpio.output(24, False) def stop(self): gpio.output(2, False) gpio.output(3, False) gpio.output(18, False) gpio.output(24, False) def start_backward(self): # roda esquerda tras gpio.setup(2, gpio.OUT) gpio.output(2, False) gpio.setup(3, gpio.OUT) gpio.output(3, True) # roda direita pra tras gpio.setup(18, gpio.OUT) gpio.output(18, False) gpio.setup(24, gpio.OUT) gpio.output(24, True) def start_left(self): # roda direta pra frente gpio.setup(18, gpio.OUT) gpio.output(18, True) gpio.setup(24, gpio.OUT) gpio.output(24, False) # roda esquerda tras gpio.setup(2, gpio.OUT) gpio.output(2, False) gpio.setup(3, gpio.OUT) gpio.output(3, True) def start_right(self): # roda esquerda frente gpio.setup(2, gpio.OUT) gpio.output(2, True) gpio.setup(3, gpio.OUT) gpio.output(3, False) # roda direita pra tras gpio.setup(18, gpio.OUT) gpio.output(18, False) gpio.setup(24, gpio.OUT) gpio.output(24, True)
/robot_motor_2wd-0.0.1.tar.gz/robot_motor_2wd-0.0.1/robot_motor_2wd/executor.py
0.505127
0.313577
executor.py
pypi
import cv2 from robot_core.executor.executor import Executor class FakeMotorExecutor(Executor): # Start Capture cap = cv2.VideoCapture(1) # Get frame dimensions frame_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) frame_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) def execute(self, **kwargs): if kwargs["command"] == "forward": return self.forward() elif kwargs["command"] == "backward": return self.backward() elif kwargs["command"] == "right": return self.right() elif kwargs["command"] == "left": return self.left() def forward(self): img = cv2.imread('forward.png') img_height, img_width, _ = img.shape ret, frame = self.cap.read() frame_height, frame_width, _ = frame.shape x = (frame_width / 2) - (img_width / 2) y = 50 frame[y:y + img_height, x:x + img_width] = img return frame def backward(self): img = cv2.imread('backward.png') img_height, img_width, _ = img.shape ret, frame = self.cap.read() frame_height, frame_width, _ = frame.shape x = (frame_width / 2) - (img_width / 2) y = frame_height - img_height - 10 frame[y:y + img_height, x:x + img_width] = img return frame def right(self): img = cv2.imread('right.png') img_height, img_width, _ = img.shape ret, frame = self.cap.read() frame_height, frame_width, _ = frame.shape x = frame_width - img_width - 10 y = (frame_height / 2) - (img_height /2 ) frame[y:y + img_height, x:x + img_width] = img return frame def left(self): img = cv2.imread('left.png') img_height, img_width, _ = img.shape ret, frame = self.cap.read() frame_height, frame_width, _ = frame.shape x = 10 y = (frame_height / 2) - (img_height / 2) frame[y:y + img_height, x:x + img_width] = img return frame
/robot_motor_fake-0.0.3.tar.gz/robot_motor_fake-0.0.3/robot_motor_fake/executor.py
0.656988
0.32122
executor.py
pypi
import numpy as np from robot_mouse_track.utils import num_runs from robot_mouse_track.mouse_track import MouseTrack class VerticalHorizontalLinearMotion: """ 横/竖直线运动(人手可能会画出横/竖直线,但是很难画出非常长的横/竖直线) :var int default=10 least_point: 这条线上至少有多少个点 :var int default=500 th_length_x: 横向直线运动长度超过多少,认为是风险,单位px :var int default=500 th_length_y: 纵向直线运动长度超过多少,认为是风险,单位px """ def __init__(self): self.least_point = 10 self.th_length_x = 500 self.th_length_y = 500 def judge_risk(self, mouse_track: MouseTrack): """ 风险判定 :param MouseTrack mouse_track: 鼠标轨迹对象 :return: (have_risk, x_risk_level, y_risk_level) :rtype: bool, (float, float) """ arr_trace_x = mouse_track.arr_trace[:, 0] arr_trace_y = mouse_track.arr_trace[:, 1] arr_diff = mouse_track.arr_trace[1:, :-1] - mouse_track.arr_trace[:-1, :-1] arr_diff_x = arr_diff[:, 0] arr_diff_y = arr_diff[:, 1] lst_x_is_0 = num_runs(arr_diff_x) lst_y_is_0 = num_runs(arr_diff_y) lst_x_is_0 = [i for i in lst_x_is_0 if i[-1] - i[0] >= self.least_point] lst_y_is_0 = [i for i in lst_y_is_0 if i[-1] - i[0] >= self.least_point] max_length_y = 0 for y_start, y_end in lst_x_is_0: arr = arr_trace_y[y_start:y_end + 1] length = np.max(arr) - np.min(arr) if length > max_length_y: max_length_y = length max_length_x = 0 for x_start, x_end in lst_y_is_0: arr = arr_trace_x[x_start:x_end + 1] length = np.max(arr) - np.min(arr) if length > max_length_x: max_length_x = length exceed_times_x = max_length_x / self.th_length_x exceed_times_y = max_length_y / self.th_length_y if exceed_times_x > 1.0 or exceed_times_y > 1.0: return True, (exceed_times_x, exceed_times_y) return False, (exceed_times_x, exceed_times_y)
/robot_mouse_track-0.0.6.tar.gz/robot_mouse_track-0.0.6/robot_mouse_track/risk_motion/motion_vertical_horizontal_linear.py
0.52074
0.403038
motion_vertical_horizontal_linear.py
pypi
from robot_mouse_track.mouse_track import MouseTrack import numpy as np from robot_mouse_track.utils import small_runs from robot_mouse_track import contants class ConstantVelocityMotion: """ 分速度的匀速运动 分速度的匀变速运动 分速度的匀变加速运动 合速度的匀速运动 合速度的匀变速运动 合速度的匀变加速运动 :var str default="combine" direction: 求导方向。 "x":对 ``x`` 分量求导;"y":对 ``y`` 分量求导;"combine":对合速度 ``combine`` 求导 :var int default=2 n_order_dev: 距离对时间的几阶导数 1阶是速度 2阶是加速度 3阶是加速度的变化速率 :var int default=5 least_point: 最少要包含的点的个数 :var int default=100 least_length: 最少移动的距离 :var float default=0.01 th_span: 两点之间的最大变化幅度,低于这个值,则认为是风险 """ def __init__(self): self.direction = contants.COMBINE self.n_order_dev = 2 self.least_point = 5 self.least_length = 100 self.th_span = 0.01 def judge_risk(self, mouse_track: MouseTrack): """ 风险判定 :param MouseTrack mouse_track: 鼠标轨迹对象 :return: (have_risk, risk_level) :rtype: (bool, float) """ arr_dev = "" if self.direction in [contants.X, contants.Y]: feature_dev = mouse_track.get_feature_dev(order=self.n_order_dev, mode=contants.DECOMPOSITION) if self.direction == contants.X: arr_dev = feature_dev[self.n_order_dev - 1][:, 0] elif self.direction == contants.Y: arr_dev = feature_dev[self.n_order_dev - 1][:, 1] elif self.direction == contants.COMBINE: feature_dev = mouse_track.get_feature_dev(order=self.n_order_dev, mode=contants.COMBINE) arr_dev = feature_dev[self.n_order_dev - 1] else: raise Exception("请输入正确的类型") lst_small = small_runs(arr_dev.reshape(-1), span=self.th_span) min_span = 1000000 for left, right in lst_small: if right - left + 1 < self.least_point: # 如果该直线上的点的个数少,则不考虑 continue point1 = mouse_track.arr_trace[left, :-1] point2 = mouse_track.arr_trace[right, :-1] length = np.sum((point2 - point1) ** 2) ** 0.5 if length < self.least_length: # 如果该直线的长度小,则不考虑 continue if right - left + 1 >= self.least_point + 4: arr_part = arr_dev[left + 2:right - 2 + 1] elif right - left + 1 >= self.least_point + 2: arr_part = arr_dev[left + 1:right - 1 + 1] else: arr_part = arr_dev[left:right + 1] # 如果长度较大,则切头去尾(头尾可能有异常变化点),再算span span = arr_part.max() - arr_part.min() if span < min_span: min_span = span if min_span == 0: min_span = 0.0000001 exceed_times = self.th_span / min_span if exceed_times > 1.0: return True, exceed_times return False, exceed_times
/robot_mouse_track-0.0.6.tar.gz/robot_mouse_track-0.0.6/robot_mouse_track/risk_motion/motion_constant_velocity.py
0.562657
0.50592
motion_constant_velocity.py
pypi
import os import sys from contextlib import contextmanager from tinydb import TinyDB, table from tinydb.operations import decrement, increment __all__ = ["Robot"] ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) DB_PATH = os.path.join(ROOT_DIR, "db.json") @contextmanager def robot_db(db_path): db = TinyDB(db_path) yield db db.close() def validate_coordinate(coord): """Check the coordinates input by the user are integers between 0 and 4.""" try: coord = int(coord) if coord >= 0 and coord <= 4: return coord except: print("Position must be between 0 and 4.") sys.exit(1) def validate_facing(facing): """Check the direction the user turned the robot to face is valid.""" if (facing := facing.upper()) in ("NORTH", "SOUTH", "EAST", "WEST"): return facing else: print("The robot can only face NORTH, SOUTH, EAST, or WEST.") sys.exit(1) class Robot: @staticmethod def place(placement, db_path=DB_PATH): """Place the robot on the board.""" try: x, y, facing = placement.split(",") except: print("Error: invalid placement. Try 'robot --help' for help.") sys.exit(1) x = validate_coordinate(x) y = validate_coordinate(y) facing = validate_facing(facing) with robot_db(db_path) as db: db.upsert(table.Document({"x": x, "y": y, "facing": facing}, doc_id=1)) @staticmethod def report(db_path=DB_PATH): """Report the robot's position on the board.""" with robot_db(db_path) as db: robot = db.all()[0] x, y, facing = robot["x"], robot["y"], robot["facing"] print(f"{x},{y},{facing}") @staticmethod def move(db_path=DB_PATH): """Move the robot one square in the direction it's facing, if possible.""" with robot_db(db_path) as db: robot = db.all()[0] if robot["facing"] == "NORTH" and robot["y"] < 4: db.update(increment("y")) elif robot["facing"] == "SOUTH" and robot["y"] > 0: db.update(decrement("y")) elif robot["facing"] == "EAST" and robot["x"] < 4: db.update(increment("x")) elif robot["facing"] == "WEST" and robot["x"] > 0: db.update(decrement("x")) else: print("I'm sorry Dave, I'm afraid I can't do that.") @staticmethod def rotate(direction, db_path=DB_PATH): """Rotate the robot 90 degrees [anti]clockwise.""" if direction not in ("LEFT", "RIGHT"): print("The robot can only rotate LEFT OR RIGHT.") sys.exit(1) with robot_db(db_path) as db: robot = db.all()[0] if robot["facing"] == "NORTH": facing = "EAST" if direction == "RIGHT" else "WEST" elif robot["facing"] == "SOUTH": facing = "WEST" if direction == "RIGHT" else "EAST" elif robot["facing"] == "EAST": facing = "SOUTH" if direction == "RIGHT" else "NORTH" elif robot["facing"] == "WEST": facing = "NORTH" if direction == "RIGHT" else "SOUTH" db.update({"facing": facing}) def __repr__(self): return f"{self.x},{self.y},{self.facing}"
/robot-rock-0.2.3.tar.gz/robot-rock-0.2.3/robot_rock/api.py
0.52756
0.251356
api.py
pypi
from importlib.resources import files import arcade import math import robot_rumble.constants as constants import random class projectile(arcade.Sprite): def __init__(self, timeToExist, radius, x, y, destx=0, desty=0, init_angle=0): # Set up parent class super().__init__() self.time_before_death = timeToExist self.timer = 0 self.radius = radius self.angle = math.radians(init_angle) self.omega = constants.BULLET_SPEED # angular velocity self.center_x = x + radius * math.cos(math.radians(init_angle)) self.center_y = y + radius * math.cos(math.radians(init_angle)) self.diff_x = destx - self.center_x self.diff_y = desty - self.center_y self.texture = arcade.load_texture(files("robot_rumble.assets.boss_assets").joinpath("projectile.png"), x=0, y=0, width=32, height=32) self.scale = constants.BULLET_SIZE def pathing(self, offset_x, offset_y, delta_time): self.angle = self.angle + math.radians(self.omega / 5) self.timer = self.timer + delta_time self.center_x = offset_x + self.radius * math.sin(self.angle) # New x self.center_y = offset_y + self.radius * math.cos(self.angle) # New y # self.center_x = constants.SCREEN_WIDTH // 2 # self.center_y = constants.SCREEN_HEIGHT // 2 if self.timer >= self.time_before_death: super().kill() def homing(self, delta_time): self.timer = self.timer + delta_time # print("diff x and y:") # print(self.diff_x) # print(self.diff_y) # print(math.degrees(math.atan2(self.diff_y,self.diff_x))) angle = math.atan2(self.diff_y, self.diff_x) # print("angle:", angle) # self.angle = math.degrees(angle) self.center_x = self.center_x + math.cos(angle) * constants.BULLET_SPEED self.center_y = self.center_y + math.sin(angle) * constants.BULLET_SPEED # self.center_x = constants.SCREEN_WIDTH // 2 # self.center_y = constants.SCREEN_HEIGHT // 2 # print("x", self.center_x) # print("y", self.center_y) if self.timer >= self.time_before_death: super().kill()
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/projectile.py
0.401336
0.316739
projectile.py
pypi
import arcade import robot_rumble.Util.constants as constants from robot_rumble.Characters.Player.playerFighter import PlayerFighter from robot_rumble.Characters.Player.playerSwordster import PlayerSwordster from robot_rumble.Characters.death import Explosion class CollisionHandle: def __init__(self,player): self.player = player self.invuln_frames_timer = 0 self.explosion_list = [] def setup(self): pass def update_collision(self, delta_time, enemy_bullets, list_of_enemy_lists=[[]]): for explosion in self.explosion_list: if explosion.explode(delta_time): explosion.remove_from_sprite_lists() # collision with bullet types bullet_collision = arcade.check_for_collision_with_list(self.player, enemy_bullets) for bullet in bullet_collision: bullet.remove_from_sprite_lists() self.player.hit() # collision w enemies for enemy_list in list_of_enemy_lists: enemy_collision = arcade.check_for_collision_with_list(self.player, enemy_list) for enemy in enemy_collision: self.player.hit() def update_player_collision_with_enemy(self, enemy_list, delta_time): enemy_collision = arcade.check_for_collision_with_list(self.player, enemy_list) self.invuln_frames_timer += delta_time if self.invuln_frames_timer > 1: for self_hit in enemy_collision: self.player.hit() self.invuln_frames_timer = 0 enemy_collision.clear() def update_player_collision_with_bullet(self, bullet_list, delta_time): enemy_collision = arcade.check_for_collision_with_list(self.player, bullet_list) self.invuln_frames_timer += delta_time if self.invuln_frames_timer > 1: for bullet in enemy_collision: self.player.hit() bullet.remove_from_sprite_lists() self.invuln_frames_timer = 0 enemy_collision.clear() def update_enemy_collision(self, player_bullet_list, enemy_list, enemy_type): if enemy_type == constants.ENEMY_DRONE: for bullet in player_bullet_list: drone_collisions_with_player_bullet = arcade.check_for_collision_with_list(bullet, enemy_list) for collision in drone_collisions_with_player_bullet: collision.kill_all() collision.explosion = Explosion(collision.center_x,collision.center_y,collision.character_face_direction) collision.remove_from_sprite_lists() self.explosion_list.append(collision.explosion) return collision.explosion if type(self.player) == PlayerSwordster or type(self.player) == PlayerFighter: if self.player.is_alive and self.player.is_attacking: drone_collisions = arcade.check_for_collision_with_list(self.player, enemy_list) for collision in drone_collisions: if (self.player.character_face_direction == constants.RIGHT_FACING and collision.center_x > self.player.center_x) \ or (self.player.character_face_direction == constants.LEFT_FACING and collision.center_x < self.player.center_x): collision.kill_all() collision.explosion = Explosion(collision.center_x, collision.center_y, collision.character_face_direction) collision.remove_from_sprite_lists() self.explosion_list.append(collision.explosion) return collision.explosion elif enemy_type == constants.HEART: heart_collision = arcade.check_for_collision_with_list(self.player, enemy_list) for collision in heart_collision: self.player.heal() collision.kill() collision.remove_from_sprite_lists() else: return None def update_player_boss(self, player, boss): if arcade.check_for_collision(boss, player) and not boss.is_damaged and not player.is_attacking and not player.is_blocking: player.hit() if not boss.boss_first_form and boss.damaged == -1: boss.damaged = 0 def update_boss_collision(self, player_bullet_list, boss): boss_collisions_with_player_bullet = arcade.check_for_collision_with_list(boss, player_bullet_list) for collision in boss_collisions_with_player_bullet: boss.hit() collision.kill() def update_boss_collision_melee(self, boss_list, boss): if type(self.player) == PlayerSwordster or type(self.player) == PlayerFighter: if self.player.is_alive and self.player.is_attacking: if (self.player.character_face_direction == constants.RIGHT_FACING and boss.center_x > self.player.center_x) \ or (self.player.character_face_direction == constants.LEFT_FACING and boss.center_x < self.player.center_x): self.player_hit_boss = arcade.check_for_collision_with_list(self.player, boss_list) if len(self.player_hit_boss) > 0: if (self.player.attack[0] < self.player.slashes[0]) and self.player.slash_can_hit[0]: boss.hit() self.player.slash_can_hit[0] = False elif ((self.player.attack[0] >= self.player.slashes[0] and self.player.attack[0] < self.player.slashes[1])) and self.player.slash_can_hit[1]: boss.hit() self.player.slash_can_hit[1] = False elif (self.player.attack[0] >= self.player.slashes[1]) and self.player.slash_can_hit[2]: if type(self.player) == PlayerSwordster or self.player.attack[0] < self.player.slashes[2]: self.player.slash_can_hit[2] = False boss.hit() elif type(self.player) == PlayerFighter and self.player.slash_can_hit[3]: self.player.slash_can_hit[3] = False boss.hit() elif self.player.is_jumping and self.player.jump_can_hit: boss.hit() self.player.jump_can_hit = False else: return None def enemy_bullet_collision_walls(self, enemy_bullet_list, wall_list): for bullet in enemy_bullet_list: enemy_bullet_collisions_with_walls = arcade.check_for_collision_with_list(bullet, wall_list) if len(enemy_bullet_collisions_with_walls) > 0: bullet.kill()
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Util/collisionHandler.py
0.49292
0.24621
collisionHandler.py
pypi
from importlib.resources import files import arcade from robot_rumble.Characters.entities import Entity from robot_rumble.Util import constants from robot_rumble.Util.spriteload import load_spritesheet_pair class Explosion(Entity): def __init__(self, x, y, direction): # Setup parent class super().__init__() self.scale = constants.ENEMY_SCALING self.character_face_direction = direction self.center_x = x self.center_y = y # Used for flipping between image sequences self.cur_texture = 0 # Explosion sound self.explosion_sound = \ arcade.load_sound(files("robot_rumble.assets.sounds.effects").joinpath("enemy_explosion.wav")) self.explosion_sound_played = False self.explode_time = 0 self.bomb_r, self.bomb_l = load_spritesheet_pair("robot_rumble.assets.enemies", "explode.png", 7, 64, 64) self.scale = constants.ENEMY_SCALING if self.character_face_direction == constants.RIGHT_FACING: self.bomb = self.bomb_r else: self.bomb = self.bomb_l self.texture = self.bomb[1] def face_direction(self, direction): self.character_face_direction = direction if self.character_face_direction == constants.RIGHT_FACING: self.bomb = self.bomb_r else: self.bomb = self.bomb_l self.texture = self.bomb[1] def explode(self, delta_time): self.explode_time += delta_time if self.bomb[0] + 1 >= len(self.bomb): self.bomb[0] = 1 return True elif self.explode_time > constants.DRONE_TIMER / 2: if self.explosion_sound_played is False: self.explosion_sound_played = True arcade.play_sound(self.explosion_sound) self.texture = self.bomb[self.bomb[0]] self.bomb[0] += 1 self.explode_time = 0 return False class Player_Death(Entity): def __init__(self): # Setup parent class super().__init__() # Used for flipping between image sequences self.cur_texture = 0 self.animation_finished = False self.death_time = 0 self.death_gunner_r, self.death_gunner_l = load_spritesheet_pair("robot_rumble.assets.gunner_assets", "death1.png", 7, 64, 32) self.death_swordster_r, self.death_swordster_l = load_spritesheet_pair("robot_rumble.assets.swordster_assets", "death1.png", 7, 64, 32) self.death_fighter_r, self.death_fighter_l = load_spritesheet_pair("robot_rumble.assets.fighter_assets", "death1.png", 7, 64, 32) self.scale = constants.ENEMY_SCALING self.death_r = self.death_gunner_r self.death_l = self.death_gunner_l if self.character_face_direction == constants.RIGHT_FACING: self.death = self.death_r else: self.death = self.death_l self.texture = self.death[1] def center(self, x, y, scale, direction): self.center_x = x self.center_y = y self.scale = scale self.face_direction(direction) def face_direction(self, direction): self.character_face_direction = direction if self.character_face_direction == constants.RIGHT_FACING: self.death = self.death_r else: self.death = self.death_l self.texture = self.death[1] def change_player_type(self, player_type): match player_type: case "gunner": self.death_r = self.death_gunner_r self.death_l = self.death_gunner_l case "swordster": self.death_r = self.death_swordster_r self.death_l = self.death_swordster_l case "fighter": self.death_r = self.death_fighter_r self.death_l = self.death_fighter_l self.face_direction(self.character_face_direction) def die(self, delta_time): self.death_time += delta_time if self.death[0] + 1 >= len(self.death): self.death[0] = 1 self.animation_finished = True return True elif self.death_time > constants.DRONE_TIMER / 2: self.texture = self.death[self.death[0]] self.death[0] += 1 self.death_time = 0 return False
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/death.py
0.547706
0.272121
death.py
pypi
from robot_rumble.Characters.entities import Entity from robot_rumble.Characters.projectiles import TurretBullet from robot_rumble.Util import constants from robot_rumble.Util.spriteload import load_spritesheet class Turret(Entity): def __init__(self, x, y): # Setup parent class super().__init__() # Used for flipping between image sequences self.cur_texture = 0 self.cur_time_frame = 0 # set center x and y self.center_y = y self.center_x = x # Shot animation time, determine if it's shooting, and time between shots self.shoot_animate = 0 self.is_shooting = False self.time_to_shoot = 0 self.bullet_list = [] self.scale = constants.ENEMY_SCALING # Load sprite sheet self.look = \ load_spritesheet("robot_rumble.assets.enemies.enemy3", "enemy3attack-Sheet[32height32wide].png", 11, 32, 32) self.texture = self.look[1] def update(self): for bullet in self.bullet_list: bullet.move() bullet.update() def turret_bullet(self, delta_time): if self.turret_logic(delta_time): bullet = TurretBullet(self.center_x, self.center_y) self.bullet_list.append(bullet) return bullet else: return None def turret_logic(self, delta_time): if not self.is_shooting: self.time_to_shoot += delta_time else: self.shoot_animate += delta_time if self.time_to_shoot > constants.DRONE_TIMER * 7: self.is_shooting = True self.time_to_shoot = 0 if self.is_shooting: if self.look[0] + 1 >= len(self.look): self.look[0] = 1 self.is_shooting = False return True elif self.shoot_animate > constants.DRONE_TIMER / 2: self.texture = self.look[self.look[0]] self.look[0] += 1 self.shoot_animate = 0 return False
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/turret.py
0.710929
0.361418
turret.py
pypi
from importlib.resources import files import arcade from robot_rumble.Util import constants class Entity(arcade.Sprite): def __init__(self): super().__init__() # Used for image sequences self.cur_time_frame = 0 self.cur_texture = 0 self.scale = 1 self.character_face_direction = constants.RIGHT_FACING # General textures that will be in all player/boss classes self.idle_r = None self.idle_l = None self.running_r = None self.running_l = None self.jumping_r = None self.jumping_l = None self.damaged_r = None self.damaged_l = None self.dash_r = None self.dash_l = None self.attack_r = None self.attack_l = None self.idle = None self.running = None self.jumping = None self.damaged = None self.dash = None self.attack = None # Tracking the various states, which helps us smooth animations self.is_jumping = False self.is_attacking = False self.is_dashing = False self.is_damaged = False self.is_blocking = False self.fix_slash = False # 0 is for gunner, 1 is for swordster, 2 is for fighter self.character = 0 self.move_player = False self.walk_sound = arcade.load_sound(files("robot_rumble.assets.sounds.effects").joinpath("robot_step.wav")) def setup(self): pass def update(self): pass def update_animation(self, delta_time: float = 1 / 60): # Regardless of animation, determine if character is facing left or right if self.change_x < 0: self.character_face_direction = constants.LEFT_FACING self.idle[1] = self.idle_l self.running[1] = self.running_l self.jumping[1] = self.jumping_l self.damaged[1] = self.damaged_l self.dash[1] = self.dash_l self.attack[1] = self.attack_l elif self.change_x > 0: self.character_face_direction = constants.RIGHT_FACING self.idle[1] = self.idle_r self.running[1] = self.running_r self.jumping[1] = self.jumping_r self.damaged[1] = self.damaged_r self.dash[1] = self.dash_r self.attack[1] = self.attack_r # Should work regardless of framerate self.cur_time_frame += delta_time if self.is_damaged: self.change_x = 0 self.texture = self.damaged[1][self.damaged[0]] if self.damaged[0] == 0: self.change_y = 0 if self.cur_time_frame >= 3 / 60: if self.damaged[0] >= len(self.damaged[1]) - 1: self.damaged[0] = 0 self.is_damaged = False else: self.damaged[0] += 1 self.cur_time_frame = 0 return # Landing overrides the cur_time_frame counter (to prevent stuttery looking animation) # This condition must mean that the player WAS jumping but has landed if self.change_y == 0 and self.is_jumping and \ (self.texture == self.jumping[1][3]): # Update the tracker for future jumps self.is_jumping = False self.jumping[0] = 0 # Animation depending on whether facing left or right and moving or still if self.change_x == 0: if self.is_attacking: self.texture = self.attack[1][self.attack[0]] else: self.texture = self.idle[1][self.idle[0]] else: if not self.is_attacking: self.texture = self.running[1][self.running[0]] return # Idle animation if self.change_x == 0 and self.change_y == 0: # If the player is standing still and pressing the attack button, play the attack animation if self.is_attacking and self.cur_time_frame >= 1 / 60: # Designed this way to maintain consistency with other, multi-frame animation code self.texture = self.attack[1][self.attack[0]] if self.attack[0] >= len(self.attack[1]) - 1: self.attack[0] = 0 self.is_attacking = False self.fix_slash = True self.cur_time_frame = 1 / 3 self.move_player = True else: self.attack[0] += 1 self.cur_time_frame = 0 # Having the idle animation loop every .33 seconds elif self.cur_time_frame >= 1 / 3: ''' Load the correct idle animation based on most recent direction faced Basically, on startup, index 0 should hold a value of 1. So the first time we enter this branch, self.texture gets set to self.idle_r[1], which is the first animation frame. Then we either increment the value in the first index or loop it back around to a value of 1. ''' self.texture = self.idle[1][self.idle[0]] if self.move_player: self.move_player = False if self.character == 1: if self.character_face_direction == constants.RIGHT_FACING: self.center_x -= 32 else: self.center_x += 32 if self.character == 2: if self.character_face_direction == constants.RIGHT_FACING: self.center_x -= 16 else: self.center_x += 16 if self.idle[0] >= len(self.idle[1]) - 1: self.idle[0] = 0 else: self.idle[0] = self.idle[0] + 1 self.cur_time_frame = 0 return # Moving else: # Check to see if the player is jumping if self.change_y != 0 and not self.is_attacking: self.is_jumping = True self.texture = self.jumping[1][self.jumping[0]] # Check if the player is mid-jump or mid-fall, and adjust which sprite they're on accordingly if self.change_y > 0: # We DON'T loop back to 1 here because the character should hold the pose until they start falling. if self.jumping[0] >= 3: self.jumping[0] = 3 elif self.cur_time_frame > 10 / 60: self.jumping[0] = self.jumping[0] + 1 self.cur_time_frame = 0 elif self.change_y < 0: self.texture = self.jumping[1][3] self.jumping[0] = 3 # Have the running animation loop every .133 seconds elif self.cur_time_frame >= 8 / 60 and not self.is_attacking and not self.is_dashing: self.texture = self.running[1][self.running[0]] if self.running[0] >= len(self.running[1]) - 1: self.running[0] = 0 self.cur_time_frame = 0 else: if self.running[0] % 2 == 0: arcade.play_sound(self.walk_sound, volume=.5) self.running[0] = self.running[0] + 1 self.cur_time_frame = 0 return def on_key_press(self, key, modifiers=0): pass def on_key_release(self, key, modifiers=0): pass
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/entities.py
0.524395
0.217878
entities.py
pypi
import math from importlib.resources import files import arcade import robot_rumble.Util.constants as constants from robot_rumble.Characters.entities import Entity from robot_rumble.Util.spriteload import load_spritesheet_pair class BossProjectile(Entity): def __init__(self, timeToExist, radius, x, y, destx=0, desty=0, init_angle=0): # Set up parent class super().__init__() self.time_before_death = timeToExist self.timer = 0 self.radius = radius self.angle = math.radians(init_angle) self.omega = constants.BULLET_SPEED_ROTATION # angular velocity self.center_x = x + radius * math.cos(math.radians(init_angle)) self.center_y = y + radius * math.cos(math.radians(init_angle)) self.diff_x = destx - self.center_x self.diff_y = desty - self.center_y self.texture = arcade.load_texture(files("robot_rumble.assets.boss_assets").joinpath("projectile.png"), x=0, y=0, width=32, height=32) self.scale = constants.BULLET_SIZE def pathing(self, offset_x, offset_y, delta_time): self.angle = self.angle + math.radians(self.omega / 5) self.timer = self.timer + delta_time self.center_x = offset_x + self.radius * math.sin(self.angle) # New x self.center_y = offset_y + self.radius * math.cos(self.angle) # New y if self.timer >= self.time_before_death: super().kill() def homing(self, delta_time): self.timer = self.timer + delta_time angle = math.atan2(self.diff_y, self.diff_x) self.center_x = self.center_x + math.cos(angle) * constants.BULLET_SPEED_ROTATION self.center_y = self.center_y + math.sin(angle) * constants.BULLET_SPEED_ROTATION if self.timer >= self.time_before_death: super().kill() class PlayerBullet(Entity): def __init__(self, x, y, direction): # Setup parent class super().__init__() # Default to face-right self.character_face_direction = direction self.scale = 2 self.kill_timer = 0 self.bullet_r, self.bullet_l = load_spritesheet_pair("robot_rumble.assets.gunner_assets", "player_projectile.png", 1,32,32) if direction == constants.RIGHT_FACING: self.texture = self.bullet_r[1] self.center_x = x + 20 else: self.texture = self.bullet_l[1] self.center_x = x - 20 self.center_y = y - 7 def update(self, delta_time): if self.character_face_direction == constants.RIGHT_FACING: self.change_x += constants.PLAYER_BULLET_MOVEMENT_SPEED else: self.change_x += -constants.PLAYER_BULLET_MOVEMENT_SPEED self.kill_timer += delta_time self.center_x += self.change_x self.center_y += self.change_y if self.kill_timer > constants.PLAYER_BULLET_LIFE_TIME: self.kill() class DroneBullet(Entity): def __init__(self, x, y, direction): # Setup parent class super().__init__() # direction and position self.cur_time_frame = 0 self.character_face_direction = direction self.center_y = y if self.character_face_direction == constants.RIGHT_FACING: self.center_x = x + 5 else: self.center_x = x - 5 # Used for flipping between image sequences self.cur_texture = 0 self.scale = constants.ENEMY_SCALING self.bullet = arcade.load_texture(files("robot_rumble.assets.enemies").joinpath("enemy1bullet.png"), x=0, y=0, width=32, height=32, hit_box_algorithm="Simple") self.texture = self.bullet def move(self): if self.character_face_direction == constants.RIGHT_FACING: self.change_x += constants.DRONE_BULLET_MOVEMENT_SPEED else: self.change_x += -constants.DRONE_BULLET_MOVEMENT_SPEED def update(self): self.center_x += self.change_x self.center_y += self.change_y class CrawlerBullet(Entity): def __init__(self, x, y, direction): # Setup parent class super().__init__() # Direction and position self.cur_time_frame = 0 self.character_face_direction = direction if self.character_face_direction == constants.RIGHT_FACING: self.center_x = x + 30 else: self.center_x = x - 30 self.center_y = y - 20 # Used for flipping between image sequences self.cur_texture = 0 self.scale = constants.ENEMY_SCALING self.bullet = arcade.load_texture(files("robot_rumble.assets.enemies.enemy2").joinpath("enemy2bullet.png"), x=0, y=0, width=32, height=32, hit_box_algorithm="Simple") self.texture = self.bullet def move(self): if self.character_face_direction == constants.RIGHT_FACING: self.change_x += constants.DRONE_BULLET_MOVEMENT_SPEED else: self.change_x += -constants.DRONE_BULLET_MOVEMENT_SPEED def update(self): self.center_x += self.change_x self.center_y += self.change_y class TurretBullet(Entity): def __init__(self, x, y): # Setup parent class super().__init__() # Position self.center_x = x self.center_y = y - 35 # Used for flipping between image sequences self.cur_time_frame = 0 self.cur_texture = 0 self.scale = constants.ENEMY_SCALING self.bullet = arcade.load_texture(files("robot_rumble.assets.enemies.enemy3").joinpath("enemy3bullet.png"), x=0, y=0, width=32, height=32, hit_box_algorithm="Simple") self.texture = self.bullet def move(self): self.change_y += -constants.DRONE_BULLET_MOVEMENT_SPEED def update(self): self.center_x += self.change_x self.center_y += self.change_y class Sword(Entity): def __init__(self): # Setup parent class super().__init__() # Default to face-right self.cur_time_frame = 0 self.character_face_direction = constants.RIGHT_FACING # Used for flipping between image sequences self.cur_texture = 0 self.scale = constants.ENEMY_SCALING self.sword = arcade.load_texture(files("robot_rumble.assets.boss_assets").joinpath("swords.png"), x=0, y=64, width=32, height=32, hit_box_algorithm="Simple") self.texture = self.sword self.angle += 135
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/projectiles.py
0.631253
0.336944
projectiles.py
pypi
import arcade from robot_rumble.Characters.entities import Entity from robot_rumble.Characters.projectiles import DroneBullet from robot_rumble.Util import constants from robot_rumble.Util.spriteload import load_spritesheet_pair class Drone(Entity): def __init__(self, x, y, direction): # Setup parent class super().__init__() # Used for flipping between image sequences self.cur_texture = 0 self.cur_time_frame = 0 # Time to bob the other direction (up/down) self.bob = 0 self.move_up = True self.limit_drone = 1 # set center x and y and direction self.character_face_direction = direction self.center_y = y self.center_x = x # Shot animation time, determine if it's shooting, and time between shots self.shoot_animate = 0 self.is_shooting = False self.time_to_shoot = 0 self.bullet_list = [] self.scale = constants.ENEMY_SCALING # Need a variable to track the center of the drone's path self.start_y = y # Load textures self.look_l, self.look_r = load_spritesheet_pair("robot_rumble.assets.enemies", "enemy1.png", 3, 32, 32) self.shoot_l, self.shoot_r = load_spritesheet_pair("robot_rumble.assets.enemies", "enemy1_attack_effect.png", 6, 32, 32) self.fire_l, self.fire_r = load_spritesheet_pair("robot_rumble.assets.enemies", "enemy1_flying.png", 2, 32, 32) if self.character_face_direction == constants.RIGHT_FACING: self.look = self.look_r self.fire = self.fire_r self.shoot = self.shoot_r else: self.look = self.look_l self.fire = self.fire_l self.shoot = self.shoot_l self.thrusters = arcade.Sprite() self.shooting = arcade.Sprite() self.thrusters.scale = constants.ENEMY_SCALING self.shooting.scale = constants.ENEMY_SCALING self.thrusters.texture = self.fire[1] self.shooting.texture = self.shoot[1] self.shooting.visible = False self.texture = self.look[1] def update(self): self.center_x += self.change_x self.center_y += self.change_y self.thrusters.center_x = self.center_x self.thrusters.center_y = self.center_y # change the ten to be negative if left if self.character_face_direction == constants.RIGHT_FACING: self.shooting.center_x = self.center_x + 10 else: self.shooting.center_x = self.center_x - 10 self.shooting.center_y = self.center_y for bullet in self.bullet_list: bullet.move() bullet.update() def kill_all(self): for bullet in self.bullet_list: bullet.kill() self.thrusters.kill() self.shooting.kill() def drone_bullet(self, delta_time): if self.drone_logic(delta_time): bullet = DroneBullet(self.shooting.center_x, self.shooting.center_y, self.character_face_direction) self.bullet_list.append(bullet) return bullet else: return None def drone_logic(self, delta_time): if not self.is_shooting: self.time_to_shoot += delta_time else: self.shoot_animate += delta_time if self.time_to_shoot > constants.DRONE_TIMER * 10: self.is_shooting = True self.time_to_shoot = 0 self.change_y = 0 if self.is_shooting: if self.shoot[0] + 1 >= len(self.shoot): self.shoot[0] = 1 self.is_shooting = False self.shooting.visible = False return True elif self.shoot_animate > constants.DRONE_TIMER / 2: self.shooting.visible = True self.shooting.texture = self.shoot[self.shoot[0]] self.shoot[0] += 1 self.shoot_animate = 0 else: if self.center_y >= self.start_y + self.limit_drone or self.center_y <= self.start_y - self.limit_drone: self.move_up = not self.move_up if self.move_up: self.change_y = constants.DRONE_MOVEMENT_SPEED self.thrusters.texture = self.fire[1] else: self.change_y = -constants.DRONE_MOVEMENT_SPEED self.thrusters.texture = self.fire[2] return False def face_direction(self, direction): self.character_face_direction = direction if self.character_face_direction == constants.RIGHT_FACING: self.look = self.look_r self.fire = self.fire_r self.shoot = self.shoot_r else: self.look = self.look_l self.fire = self.fire_l self.shoot = self.shoot_l self.thrusters.texture = self.fire[1] self.shooting.texture = self.shoot[1] self.texture = self.look[1]
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/drone.py
0.666062
0.307498
drone.py
pypi
import arcade from robot_rumble.Characters.entities import Entity from robot_rumble.Characters.projectiles import CrawlerBullet from robot_rumble.Util import constants from robot_rumble.Util.spriteload import load_spritesheet_pair class Crawler(Entity): def __init__(self, x, y, direction): # Setup parent class super().__init__() # Used for flipping between image sequences (i.e., animation logic) self.cur_texture = 0 self.cur_time_frame = 1 / 10 # set center x, y, and direction self.character_face_direction = direction self.center_y = y self.center_x = x # Copy center x and y into start variables that won't change # These track the center of the crawler's path and let us set boundaries on the walking self.start_x = x self.start_y = y # these guys walk, they don't bob up and down. initialize walking logic variables (+- horizontal boundaries) self.right_walk_limit = self.start_x + 100 self.left_walk_limit = self.start_x - 100 if self.character_face_direction == constants.RIGHT_FACING: self.change_x = 0.75 else: self.change_x = -0.75 # Shot animation time, determine if it's shooting, time between shots, and a list of all the bullets self.shoot_animate = 0 self.is_shooting = False self.time_to_shoot = 0 self.bullet_list = [] self.scale = constants.ENEMY_SCALING # Load textures self.walk_l, self.walk_r = \ load_spritesheet_pair("robot_rumble.assets.enemies.enemy2", "enemy2walk[32height48wide].png", 5, 48, 32) self.shoot_pose_l, self.shoot_pose_r = \ load_spritesheet_pair("robot_rumble.assets.enemies.enemy2", "enemy2attack[32height48wide].png", 5, 48, 32) self.shoot_effect_l, self. shoot_effect_r = \ load_spritesheet_pair("robot_rumble.assets.enemies.enemy2", "enemy2attackeffect[32height48wide].png", 10, 48, 32) # Pick appropriate one for direction (remember this is still just on init) if self.character_face_direction == constants.RIGHT_FACING: self.walk = self.walk_r self.shoot_pose = self.shoot_pose_r self.shoot_effect = self.shoot_effect_r else: self.walk = self.walk_l self.shoot_pose = self.shoot_pose_l self.shoot_effect = self.shoot_effect_l # create the actual sprites for the attack and assign them the appropriate loaded textures self.shooting_pose = arcade.Sprite() self.shooting_effect = arcade.Sprite() self.shooting_pose.scale = constants.ENEMY_SCALING self.shooting_effect.scale = constants.ENEMY_SCALING self.shooting_pose.texture = self.shoot_pose[1] self.shooting_effect.texture = self.shoot_effect[1] self.shooting_pose.visible = False self.shooting_effect.visible = False # Since crawler is an entity is a sprite, it can hold the walk texture without its own call to arcade.Sprite() self.texture = self.walk[1] def update(self): self.center_x += self.change_x self.center_y += self.change_y self.shooting_pose.center_x = self.center_x self.shooting_pose.center_y = self.center_y # Offset the shooting effect horizontally since the end of the gun barrel isn't the center of the sprite if self.character_face_direction == constants.RIGHT_FACING: self.shooting_effect.center_x = self.center_x + 10 else: self.shooting_effect.center_x = self.center_x - 10 self.shooting_effect.center_y = self.center_y # Bullet logic for bullet in self.bullet_list: bullet.move() bullet.update() def kill_all(self): for bullet in self.bullet_list: bullet.kill() self.kill() self.shooting_pose.kill() self.shooting_effect.kill() def crawler_bullet(self, delta_time): if self.crawler_logic(delta_time): bullet = CrawlerBullet( self.shooting_effect.center_x, self.shooting_effect.center_y, self.character_face_direction) self.bullet_list.append(bullet) return bullet else: return None def crawler_logic(self, delta_time): # update either the time between shots or how long it's been since the shoot animation started if not self.is_shooting: self.time_to_shoot += delta_time else: self.shoot_animate += delta_time # If the timer reaches this time, then the crawler should fire; reassign vars as needed if self.time_to_shoot > constants.DRONE_TIMER * 15: self.is_shooting = True self.time_to_shoot = 0 self.change_x = 0 self.change_y = 0 # shooting animation logic (joined with the movement logic, so that the crawler stops to shoot) if self.is_shooting: if self.shoot_pose[0] + 1 >= len(self.shoot_pose): self.shoot_pose[0] = 1 self.shoot_effect[0] = 1 self.is_shooting = False self.shooting_pose.visible = False self.shooting_effect.visible = False if self.character_face_direction == constants.RIGHT_FACING: self.change_x = 0.75 else: self.change_x = -0.75 return True elif self.shoot_animate > constants.DRONE_TIMER / 2: self.shooting_pose.visible = True self.shooting_effect.visible = True self.shooting_pose.texture = self.shoot_pose[self.shoot_pose[0]] self.shooting_effect.texture = self.shoot_effect[self.shoot_effect[0]] self.shoot_pose[0] += 1 self.shoot_effect[0] += 1 self.shoot_animate = 0 else: self.cur_time_frame += delta_time if self.center_x >= self.right_walk_limit or self.center_x <= self.left_walk_limit: self.change_direction() elif self.cur_time_frame >= 1 / 10: if self.walk[0] + 1 >= len(self.walk): self.walk[0] = 1 else: self.walk[0] = self.walk[0] + 1 self.texture = self.walk[self.walk[0]] self.cur_time_frame = 0 return False def change_direction(self): if self.character_face_direction == constants.RIGHT_FACING: self.character_face_direction = constants.LEFT_FACING self.walk = self.walk_l self.shoot_pose = self.shoot_pose_l self.shoot_effect = self.shoot_effect_l else: self.character_face_direction = constants.RIGHT_FACING self.walk = self.walk_r self.shoot_pose = self.shoot_pose_r self.shoot_effect = self.shoot_effect_r self.shooting_pose.texture = self.shoot_pose[1] self.shooting_effect.texture = self.shoot_effect[1] self.texture = self.walk[1] self.change_x = -1 * self.change_x
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/crawler.py
0.622574
0.285998
crawler.py
pypi
import random from robot_rumble.Characters.Boss.bossBase import BossBase from robot_rumble.Characters.projectiles import Sword from robot_rumble.Util import constants from robot_rumble.Util.spriteload import load_spritesheet_pair_nocount class BossTwo(BossBase): def __init__(self, target): # Set up parent class super().__init__(target) self.boss_logic_timer = 0 self.once_jump = True # Load textures self.idle_r, self.idle_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "idle2.png", 2, 32, 32) self.running_r, self.running_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "run_masked.png", 8, 32, 32) self.jumping_r, self.jumping_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "jump_masked.png", 7, 32, 32) self.damaged_r, self.damaged_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "damaged_masked.png", 6, 32, 32) self.dash_r, self.dash_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "dash_masked.png", 7, 32, 32) self.attack_r, self.attack_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "attack_masked.png", 22, 64, 32) self.jumping_attack_r, self.jumping_attack_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "jump_attack_masked.png", 7, 48, 32) self.damaged_r, self.damaged_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "damaged_masked.png", 6, 32, 32) self.secondslash = 8 self.thirdslash = 14 self.idle = [0, self.idle_r] self.running = [0, self.running_r] self.jumping = [0, self.jumping_r] self.damaged = [0, self.damaged_r] self.dash = [0, self.dash_r] self.attack = [0, self.attack_r] self.jumping_attack = [0, self.jumping_attack_r] # Tracking the various states, which helps us smooth animations self.is_jumping = False self.is_attacking = False self.slash_can_hit = [True, True, True] self.jump_can_hit = True self.sword_list = [] self.sword_timer = 1 self.texture = self.idle_r[1] # Some variables used in boss logic self.time_to_run_away = random.randint(0,10) self.total_evade_time = 10 / random.randint(15,20) self.evading = False self.center_x = 830 self.center_y = 120 self.death.change_player_type("swordster") def boss_logic(self, delta_time): self.is_attacking = False self.is_jumping = False self.boss_form_swap_timer += delta_time # Check if the form needs to be changed if self.boss_form_swap_timer > constants.FORM_TIMER: self.boss_form_swap_timer = 0 self.boss_first_form = not self.boss_first_form self.time_to_run_away = 0 # First form logic if self.boss_first_form: # dash when far away from player if abs(self.center_x - self.target.center_x) > 200: self.is_dashing = True else: self.is_dashing = False # attack when close enough if self.target.center_x < self.center_x + 24*constants.ENEMY_SCALING and self.target.center_x > self.center_x - 24*constants.ENEMY_SCALING\ and self.target.center_y < self.center_y + 50 and self.target.center_y > self.center_y - 50: if not self.is_attacking: # need to adjust the sprite centering due to the difference in sprite size if self.change_x != 0: if self.character_face_direction == constants.RIGHT_FACING and self.center_x < 1100: self.center_x += 16*constants.ENEMY_SCALING else: self.center_x -= 16*constants.ENEMY_SCALING self.change_x = 0 self.is_attacking = True if self.boss_form_swap_timer > self.time_to_run_away: self.evading = True if self.evading: self.is_dashing = False self.run_from_player() if self.boss_form_swap_timer >= self.time_to_run_away + self.total_evade_time: self.time_to_run_away = self.boss_form_swap_timer + random.randint(0,10) self.total_evade_time = 10 / random.randint(15,20) self.evading = False else: self.run_to_player() # Second form logic else: # spawn sword based on timer self.sword_timer += delta_time if self.sword_timer > constants.SWORD_SPAWN_TIME: self.make_sword() self.sword_timer = 0 # dash when close to player if abs(self.center_x - self.target.center_x) < 200: self.is_dashing = True else: self.is_dashing = False # Check if the boss should patrol if self.center_x - self.target.center_x > 0 and self.target.center_x <= 523 and self.center_y == 134.75 and self.center_x > 660: if self.center_x < 1010 and self.center_x > 660: if self.center_x > 995: self.character_face_direction = constants.LEFT_FACING elif self.center_x < 690: self.character_face_direction = constants.RIGHT_FACING if self.character_face_direction == constants.RIGHT_FACING: self.change_x = constants.BOSS2_MOVE_SPEED elif self.character_face_direction == constants.LEFT_FACING: self.change_x = -constants.BOSS2_MOVE_SPEED elif self.center_x - self.target.center_x < 0 and self.target.center_x >= 508 and self.center_y == 134.75 and self.center_x < 475: if self.center_x < 450 and self.center_x > 340: if self.center_x > 445: self.character_face_direction = constants.LEFT_FACING elif self.center_x < 360: self.character_face_direction = constants.RIGHT_FACING if self.character_face_direction == constants.RIGHT_FACING: self.change_x = constants.BOSS2_MOVE_SPEED elif self.character_face_direction == constants.LEFT_FACING: self.change_x = -constants.BOSS2_MOVE_SPEED else: # Check proximity to wall and if close to wall run past player if (self.center_x < 225 and self.center_y == 269 and self.change_x == 0)\ or (self.center_x < 300 and self.character_face_direction == constants.RIGHT_FACING): self.change_x = constants.BOSS2_MOVE_SPEED self.character_face_direction = constants.RIGHT_FACING elif (self.center_x > 1135 and self.center_y == 314 and self.change_x == 0)\ or (self.center_x > 830 and self.character_face_direction == constants.LEFT_FACING): self.change_x = -constants.BOSS2_MOVE_SPEED self.character_face_direction = constants.LEFT_FACING else: self.run_from_player() if (self.center_x > 1020 and self.center_y == 269 and self.character_face_direction == constants.LEFT_FACING)\ or (self.center_x > 290 and self.center_x < 440 and self.center_y == 269 and self.character_face_direction == constants.RIGHT_FACING): self.change_y = constants.BOSS2_JUMP_SPEED * 1.5 # checks if the boss needs to jump if self.change_x != 0 and not self.is_jumping and not self.is_attacking: if (self.center_x > 610 and self.center_x < 670 and self.character_face_direction == constants.LEFT_FACING and (self.center_y == 134.75 or self.center_y == 179.5))\ or (self.center_x > 455 and self.center_x < 523 and self.character_face_direction == constants.RIGHT_FACING and (self.center_y == 134.75 or self.center_y == 179.5))\ or (self.center_x > 995 and self.center_x < 1016 and self.center_y == 134.75 and self.character_face_direction == constants.RIGHT_FACING)\ or (self.center_x > 1065 and self.center_x < 1105 and self.center_y == 269 and self.character_face_direction == constants.RIGHT_FACING): self.change_y = constants.BOSS2_JUMP_SPEED self.is_jumping = True elif (self.center_x > 340 and self.center_x < 380 and self.character_face_direction == constants.LEFT_FACING and self.center_y == 134.75) \ or (self.center_x > 1040 and self.center_x < 1060 and self.center_y == 179.5 and self.character_face_direction == constants.RIGHT_FACING): self.change_y = constants.BOSS2_JUMP_SPEED * 1.5 self.is_jumping = True # Check if the boss is running into the wall if self.center_x < 225 and self.center_y == 269 and self.change_x < 0: self.change_x = 0 self.character_face_direction = constants.RIGHT_FACING elif self.center_x > 1135 and self.center_y == 314 and self.change_x > 0: self.change_x = 0 self.character_face_direction = constants.LEFT_FACING if self.is_attacking or self.is_damaged: self.change_x = 0 def update_animation(self, delta_time): super().update_animation(delta_time) if not self.is_damaged: # The sword fighter can't move and slash at the same time if self.is_attacking: self.change_x = 0 # Landing overrides the cur_time_frame counter (to prevent stuttery looking animation) # This condition must mean that the player WAS jumping but has landed if self.change_y == 0 and self.is_jumping and \ (self.texture == self.jumping[1][4] or self.texture == self.jumping_attack[1][4]): # Update the tracker for future jumps self.is_jumping = False # Animation depending on whether facing left or right and moving or still if self.change_x == 0: if self.is_attacking: self.texture = self.attack[1][self.attack[0]] else: self.texture = self.idle[1][self.idle[0]] else: self.texture = self.running[1][self.running[0]] return # Moving if self.change_x != 0 or self.change_y != 0: # Check to see if the player is jumping (while moving right) if self.change_y != 0: if self.is_attacking: self.texture = self.jumping_attack[1][self.jumping_attack[0]] # Check if the player is mid-jump or mid-fall, and adjust which sprite they're on accordingly if self.change_y > 0: if self.is_attacking: if self.jumping_attack[0] >= 3: self.jumping_attack[0] = 3 else: self.jumping_attack[0] = self.jumping_attack[0] + 1 elif self.change_y < 0: if self.is_attacking: self.jumping_attack[0] = 0 self.texture = self.jumping_attack[1][4] elif self.is_dashing and self.cur_time_frame >= 8 / 60 and not self.is_attacking: self.texture = self.dash[1][self.dash[0]] if self.dash[0] >= len(self.dash[1]) - 1: self.dash[0] = 0 else: self.dash[0] = self.dash[0] + 1 self.cur_time_frame = 0 return if self.texture == self.attack[1][0]: self.slash_can_hit = [True, True, True] if self.texture == self.jumping_attack[1][0]: self.jump_can_hit = True def run_from_player(self): # Move away from player if self.change_y == 0: if self.target.center_x < self.center_x: self.change_x = constants.BOSS2_MOVE_SPEED if self.is_dashing: self.change_x = constants.BOSS2_MOVE_SPEED * 2.5 elif self.target.center_x > self.center_x: self.change_x = -constants.BOSS2_MOVE_SPEED if self.is_dashing: self.change_x = -constants.BOSS2_MOVE_SPEED * 2.5 else: self.change_x = 0 def run_to_player(self): # Move toward player if self.change_y == 0: if self.target.center_x < self.center_x: self.change_x = -constants.BOSS2_MOVE_SPEED if self.is_dashing: self.change_x = -constants.BOSS2_MOVE_SPEED * 2 elif self.target.center_x > self.center_x: self.change_x = constants.BOSS2_MOVE_SPEED if self.is_dashing: self.change_x = constants.BOSS2_MOVE_SPEED * 2 else: self.change_x = 0 def make_sword(self): sword = Sword() sword.center_x = self.target.center_x sword.center_y = 800 self.sword_list.append(sword) def kill_all(self): for sword in self.sword_list: sword.kill() sword.remove_from_sprite_lists() def update(self, delta_time): if self.is_attacking: self.change_x = 0 super().update(delta_time) self.boss_logic(delta_time)
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/Boss/bossTwo.py
0.526586
0.208139
bossTwo.py
pypi
from importlib.resources import files import arcade import robot_rumble.Util.constants as constants from robot_rumble.Characters.death import Player_Death from robot_rumble.Characters.entities import Entity from robot_rumble.Util.spriteload import load_spritesheet_nocount from robot_rumble.Util.spriteload import load_spritesheet class BossHealthBar(arcade.Sprite): def __init__(self): # Set up parent class super().__init__() # Load Sprite sheet self.red_bar = load_spritesheet_nocount("robot_rumble.assets.boss_assets", "boss_red.png", 40, 85, 8) self.red_bar.append( arcade.load_texture(files("robot_rumble.assets.boss_assets").joinpath("boss_red.png"), x=3400, y=0, width=85, height=8)) self.green_bar = load_spritesheet_nocount("robot_rumble.assets.boss_assets", "boss_green.png", 40, 85, 8) self.texture = self.red_bar[0] class BossBase(Entity): def __init__(self, target): # Target is a sprite, specifically the player super().__init__() self.target = target self.health = 40 # TODO CHANGE # Rest of Health Bar Creation and Setup self.hp_bar = BossHealthBar() self.hp_bar.scale = 5 self.hp_bar.center_x = constants.SCREEN_WIDTH // 2 self.hp_bar.center_y = constants.SCREEN_HEIGHT // 2 # Additional Boss Sprite Setup self.character_face_direction = constants.LEFT_FACING self.scale = constants.ENEMY_SCALING self.sprite_lists_weapon = [] # Logic Variable self.current_state = 0 self.boss_form_swap_timer = 0 self.boss_form_pos_timer = [0, 0] self.boss_first_form = True self.center_x = constants.SCREEN_WIDTH // 2 self.center_y = constants.SCREEN_HEIGHT // 2 + 200 self.is_alive = True self.death = Player_Death() def drawing(self): pass def boss_logic(self, delta_time): pass def update(self, delta_time): if self.health <= 0: if self.death.die(delta_time): self.death.kill() else: if self.health >= 80: self.health = 80 elif self.health <= 0: self.health = 0 # Player Movement self.center_x += self.change_x self.center_y += self.change_y def ranged_attack(self): pass def reset_boss(self): pass def return_sprite_lists(self): return self.sprite_lists_weapon def return_health_sprite(self): return self.hp_bar def hit(self): # Fighter double damage if self.target.character == 2: self.health -= 1 self.health -= 1 if self.health < 0: self.health = 0 self.is_damaged = True if self.health == 0: self.is_alive = False self.death.center(self.center_x, self.center_y, self.scale, self.character_face_direction) self.change_x = 0 self.change_y = 0 self.kill_all() self.kill() self.hp_bar.texture = self.hp_bar.red_bar[40 - self.health] def kill_all(self): pass def return_death_sprite(self): return self.death
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/Boss/bossBase.py
0.486332
0.226784
bossBase.py
pypi
from robot_rumble.Characters.Player.playerBase import PlayerBase from robot_rumble.Util import constants from robot_rumble.Util.spriteload import load_spritesheet_pair_nocount class PlayerFighter(PlayerBase): def __init__(self): super().__init__() # Load textures self.idle_r, self.idle_l = load_spritesheet_pair_nocount("robot_rumble.assets.fighter_assets", "idle.png", 2, 32, 32) self.attack_r, self.attack_l = load_spritesheet_pair_nocount("robot_rumble.assets.fighter_assets", "attack_unmasked.png", 37, 48, 32) self.running_r, self.running_l = load_spritesheet_pair_nocount("robot_rumble.assets.fighter_assets", "run_unmasked.png", 8, 32, 32) self.running_attack_r, self.running_attack_l = load_spritesheet_pair_nocount( "robot_rumble.assets.fighter_assets", "attack_unmasked.png", 37, 48, 32) self.jumping_r, self.jumping_l = load_spritesheet_pair_nocount("robot_rumble.assets.fighter_assets", "jump_unmasked.png", 7, 32, 32) self.jumping_attack_r, self.jumping_attack_l = load_spritesheet_pair_nocount( "robot_rumble.assets.fighter_assets", "attack_unmasked.png", 7, 48, 32) self.damaged_r, self.damaged_l = load_spritesheet_pair_nocount("robot_rumble.assets.fighter_assets", "damaged_masked.png", 6, 32, 32) self.blocking_r, self.blocking_l = load_spritesheet_pair_nocount("robot_rumble.assets.fighter_assets", "flashing.png", 2, 32, 32) self.sparkle_r, self.sparkle_l = load_spritesheet_pair_nocount("robot_rumble.assets.fighter_assets", "sparkle.png", 13, 32, 32) self.sparkle = [0, self.sparkle_r] self.idle = [0, self.idle_r] self.running = [0, self.running_r] self.jumping = [0, self.jumping_r] self.damaged = [0, self.damaged_r] self.dash = [0, self.dash_r] self.attack = [0, self.attack_r] self.running_attack = [0, self.running_attack_r] self.jumping_attack = [0, self.jumping_attack_r] self.blocking = [0, self.blocking_r] self.PLAYER_MOVEMENT_SPEED = constants.MOVE_SPEED_PLAYER * 1.1 # Set an initial texture. Required for the code to run. self.texture = self.idle_r[0] self.slash_can_hit = [True, True, True, True] self.jump_can_hit = True self.slashes = [7, 14, 24] self.character = 2 self.death.change_player_type("fighter") def update(self, delta_time): super().update(delta_time) def update_animation(self, delta_time): super().update_animation(delta_time) if self.fix_slash: self.slash_can_hit = [True, True, True, True] self.fix_slash = False self.jump_can_hit = True if not self.is_blocking and not self.is_damaged: # This condition must mean that the player WAS jumping but has landed if self.change_y == 0 and self.is_jumping and \ (self.texture == self.jumping[1][4] or self.texture == self.jumping_attack[1][6]): # Update the tracker for future jumps self.is_jumping = False self.jumping_attack[0] = 0 # Animation depending on whether facing left or right and moving or still if self.change_x == 0: if self.is_attacking: self.texture = self.attack[1][self.attack[0]] else: self.texture = self.idle[1][self.idle[0]] else: if self.is_attacking: self.texture = self.running_attack[1][self.running_attack[0]] else: self.texture = self.running[1][self.running[0]] return # Moving if self.change_x != 0 or self.change_y != 0: # Check to see if the player is jumping (while moving right) if self.change_y != 0: self.is_jumping = True if self.is_attacking: self.texture = self.jumping_attack[1][self.jumping_attack[0]] # Check if the player is mid-jump or mid-fall, and adjust which sprite they're on accordingly # We DON'T loop back to 1 here because the character should hold the pose until they start falling. if self.is_attacking: if self.jumping_attack[0] >= 6: self.jumping_attack[0] = 0 self.is_attacking = False self.jumping[0] = 3 else: self.jumping_attack[0] = self.jumping_attack[0] + 1 return
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/Player/playerFighter.py
0.717507
0.299566
playerFighter.py
pypi
from importlib.resources import files import arcade from robot_rumble.Characters.death import Player_Death from robot_rumble.Characters.entities import Entity from robot_rumble.Util import constants from robot_rumble.Util.spriteload import load_spritesheet, load_spritesheet_pair_nocount class PlayerBase(Entity): def __init__(self): super().__init__() # Set health self.health = 20 self.health_bar = PlayerHealthBar() self.death = Player_Death() self.is_alive = True # Used for flipping between image sequences self.scale = constants.PLAYER_SCALING # Tracking the various states, which helps us smooth animations self.sparkle_r, self.sparkle_l = load_spritesheet_pair_nocount("robot_rumble.assets.gunner_assets", "sparkle.png", 13, 32, 32) self.sparkle = [0, self.sparkle_r] self.blocking_r, self.blocking_l = load_spritesheet_pair_nocount("robot_rumble.assets.gunner_assets", "flashing.png", 2, 32, 32) self.blocking = [0, self.blocking_r] self.is_jumping = False self.is_attacking = False self.left_pressed = False self.right_pressed = False self.PLAYER_MOVEMENT_SPEED = 0 # Weapons self.weapons_list = [] self.sparkle_sprite = arcade.Sprite() self.sparkle_sprite.texture = self.sparkle[1][self.sparkle[0]] self.sparkle_sprite.center_x = self.center_x self.sparkle_sprite.center_y = self.center_y self.sparkle_sprite.scale = self.scale # Walking sound self.walk_sound = \ arcade.load_sound(files("robot_rumble.assets.sounds.effects").joinpath("robot_step.wav")) # Damage sound self.take_damage_sound = \ arcade.load_sound(files("robot_rumble.assets.sounds.effects").joinpath("robot_take_damage.wav")) def update_animation(self, delta_time): super().update_animation(delta_time) # Regardless of animation, determine if character is facing left or right if self.change_x < 0: self.running_attack[1] = self.running_attack_l self.jumping_attack[1] = self.jumping_attack_l self.blocking[1] = self.blocking_l elif self.change_x > 0: self.running_attack[1] = self.running_attack_r self.jumping_attack[1] = self.jumping_attack_r self.blocking[1] = self.blocking_r if not self.is_damaged: if self.is_blocking: self.change_x = 0 self.texture = self.blocking[1][self.blocking[0]] self.sparkle_sprite.texture = self.sparkle[1][self.sparkle[0]] if self.sparkle[0] == 0: self.change_y = 0 if self.cur_time_frame >= 3 / 60: if self.sparkle[0] >= len(self.sparkle[1]) - 1: self.sparkle[0] = 0 else: self.sparkle[0] += 1 if self.cur_time_frame >= 5 / 60: if self.blocking[0] >= len(self.blocking[1]) - 1: self.blocking[0] = 0 else: self.blocking[0] += 1 self.cur_time_frame = 0 return else: self.blocking[0] = 0 self.sparkle[0] = 0 # Moving if self.change_x != 0 or self.change_y != 0: if self.cur_time_frame >= 1 / 60 and self.change_y == 0 and self.is_attacking: self.texture = self.running_attack[1][self.running_attack[0]] if self.running_attack[0] >= len(self.running_attack[1]) - 1: self.running_attack[0] = 0 self.is_attacking = False self.fix_slash = True self.cur_time_frame = 1/3 else: if self.running_attack[0] == 3 or self.running_attack[0] == 6: arcade.play_sound(self.walk_sound) self.running_attack[0] = self.running_attack[0] + 1 self.cur_time_frame = 0 return def update(self, delta_time): if self.health > 0: self.update_animation(delta_time) self.sparkle_sprite.center_x = self.center_x self.sparkle_sprite.center_y = self.center_y if not self.is_blocking: self.sparkle_sprite.remove_from_sprite_lists() self.update_player_speed() for weapon in self.weapons_list: weapon.update(delta_time) else: if self.death.die(delta_time): self.is_alive = False def drawing(self): pass def update_player_speed(self): self.change_x = 0 if not self.is_blocking: # Using the key pressed variables lets us create more responsive x-axis movement if self.left_pressed and not self.right_pressed: self.change_x = -self.PLAYER_MOVEMENT_SPEED elif self.right_pressed and not self.left_pressed: self.change_x = self.PLAYER_MOVEMENT_SPEED def hit(self): if not self.is_damaged and not self.is_blocking: arcade.play_sound(self.take_damage_sound) self.is_damaged = True self.health -= 1 if self.health == 0: self.is_alive = False self.death.center(self.center_x, self.center_y, self.scale, self.character_face_direction) self.change_x = 0 self.change_y = 0 self.kill() if self.health_bar.hp_list[0] < 21: self.health_bar.hp_list[0] = self.health_bar.hp_list[0] + 1 self.health_bar.texture = self.health_bar.hp_list[self.health_bar.hp_list[0]] def heal(self): self.health = 20 self.health_bar.hp_list[0] = 1 self.health_bar.texture = self.health_bar.hp_list[self.health_bar.hp_list[0]] def spawn_attack(self): pass def on_key_press(self, key, modifiers=0): if self.is_alive: if key == arcade.key.LEFT or key == arcade.key.A: self.left_pressed = True elif key == arcade.key.RIGHT or key == arcade.key.D: self.right_pressed = True def on_key_release(self, key, modifiers): """Called when the user releases a key.""" if key == arcade.key.LEFT or key == arcade.key.A: self.left_pressed = False elif key == arcade.key.RIGHT or key == arcade.key.D: self.right_pressed = False def return_health_sprite(self): return self.health_bar def return_death_sprite(self): return self.death class PlayerHealthBar(arcade.Sprite): def __init__(self): # Set up parent class super().__init__() # Load Sprite Sheet self.hp_list = load_spritesheet("robot_rumble.assets.ui", "health_bar.png", 21, 61, 19) self.texture = self.hp_list[self.hp_list[0]] self.scale = 3 self.center_x = 100 self.center_y = 770
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/Player/playerBase.py
0.608594
0.224395
playerBase.py
pypi
from robot_rumble.Characters.Player.playerBase import PlayerBase from robot_rumble.Util import constants from robot_rumble.Util.spriteload import load_spritesheet_pair_nocount class PlayerSwordster(PlayerBase): def __init__(self): super().__init__() # Load textures self.idle_r, self.idle_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "idle2.png", 2, 32, 32) self.attack_r, self.attack_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "attack_unmasked.png", 22, 64, 32) self.running_r, self.running_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "run_unmasked.png", 8, 32, 32) self.running_attack_r, self.running_attack_l = load_spritesheet_pair_nocount( "robot_rumble.assets.swordster_assets", "attack_unmasked.png", 22, 64, 32) self.jumping_r, self.jumping_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "jump_unmasked.png", 7, 32, 32) self.jumping_attack_r, self.jumping_attack_l = load_spritesheet_pair_nocount( "robot_rumble.assets.swordster_assets", "jump_attack_unmasked.png", 7, 48, 32) self.damaged_r, self.damaged_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "damaged_masked.png", 6, 32, 32) self.blocking_r, self.blocking_l = load_spritesheet_pair_nocount("robot_rumble.assets.swordster_assets", "flashing.png", 2, 32, 32) self.idle = [0, self.idle_r] self.running = [0, self.running_r] self.jumping = [0, self.jumping_r] self.damaged = [0, self.damaged_r] self.dash = [0, self.dash_r] self.attack = [0, self.attack_r] self.running_attack = [0, self.running_attack_r] self.jumping_attack = [0, self.jumping_attack_r] self.blocking = [0, self.blocking_r] self.PLAYER_MOVEMENT_SPEED = constants.MOVE_SPEED_PLAYER * 1.05 # Set an initial texture. Required for the code to run. self.texture = self.idle_r[0] self.slash_can_hit = [True, True, True] self.jump_can_hit = True self.slashes = [8, 14] self.character = 1 self.death.change_player_type("swordster") def update(self, delta_time): super().update(delta_time) def update_animation(self, delta_time): super().update_animation(delta_time) if self.fix_slash: self.slash_can_hit = [True, True, True] self.fix_slash = False self.jump_can_hit = True if not self.is_blocking and not self.is_damaged: # This condition must mean that the player WAS jumping but has landed if self.change_y == 0 and self.is_jumping and \ (self.texture == self.jumping[1][4] or self.texture == self.jumping_attack[1][6]): # Update the tracker for future jumps self.is_jumping = False self.jumping_attack[0] = 0 # Animation depending on whether facing left or right and moving or still if self.change_x == 0: if self.is_attacking: self.texture = self.attack[1][self.attack[0]] else: self.texture = self.idle[1][self.idle[0]] else: if self.is_attacking: self.texture = self.running_attack[1][self.running_attack[0]] else: self.texture = self.running[1][self.running[0]] return # Moving if self.change_x != 0 or self.change_y != 0: # Check to see if the player is jumping (while moving right) if self.change_y != 0: self.is_jumping = True if self.is_attacking: self.texture = self.jumping_attack[1][self.jumping_attack[0]] # Check if the player is mid-jump or mid-fall, and adjust which sprite they're on accordingly # We DON'T loop back to 1 here because the character should hold the pose until they start falling. if self.is_attacking: if self.jumping_attack[0] >= 6: self.jumping_attack[0] = 0 self.is_attacking = False self.jumping[0] = 3 else: self.jumping_attack[0] = self.jumping_attack[0] + 1 return
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/Player/playerSwordster.py
0.712432
0.260378
playerSwordster.py
pypi
from robot_rumble.Characters.Player.playerBase import PlayerBase from robot_rumble.Characters.projectiles import PlayerBullet from robot_rumble.Util import constants from robot_rumble.Util.spriteload import load_spritesheet_pair_nocount class PlayerGunner(PlayerBase): def __init__(self): super().__init__() # Load textures self.idle_r, self.idle_l = load_spritesheet_pair_nocount("robot_rumble.assets.gunner_assets", "idle1.png", 2, 32, 32) self.attack_r, self.attack_l = load_spritesheet_pair_nocount("robot_rumble.assets.gunner_assets", "run_attack1.png", 8, 32, 32) self.running_r, self.running_l = load_spritesheet_pair_nocount("robot_rumble.assets.gunner_assets", "run_unmasked.png", 8, 32, 32) self.running_attack_r, self.running_attack_l = load_spritesheet_pair_nocount("robot_rumble.assets.gunner_assets", "run_attack1.png", 8, 32, 32) # Load jumping textures by iterating through each sprite in the sheet and adding them to the correct list self.jumping_r, self.jumping_l = load_spritesheet_pair_nocount("robot_rumble.assets.gunner_assets", "jump_unmasked.png", 7, 32, 32) self.jumping_attack_r , self.jumping_attack_l = load_spritesheet_pair_nocount("robot_rumble.assets.gunner_assets", "jump_unmasked_attack.png", 7, 32, 32) self.damaged_r, self.damaged_l = load_spritesheet_pair_nocount("robot_rumble.assets.gunner_assets", "teleport.png", 6, 32, 32) # [0] is the animation frame, [1] is which list-> RIGHT or LEFT, access with self.idle[1][self.idle[0]] self.idle = [0, self.idle_r] self.running = [0, self.running_r] self.jumping = [0, self.jumping_r] self.attack = [0, self.attack_r] self.damaged = [0, self.damaged_r] self.dash = [0, self.dash_r] self.running_attack = [0, self.running_attack_r] self.jumping_attack = [0, self.jumping_attack_r] # Set an initial texture. Required for the code to run. self.texture = self.idle_r[1] self.PLAYER_MOVEMENT_SPEED = constants.MOVE_SPEED_PLAYER # MOVESPEED KAYLEE U CAN CHANGE self.character = 0 def setup(self): super().setup() def update(self,delta_time): super().update(delta_time) def spawn_attack(self): # this implementation should be done in its own way per character self.is_attacking = True bullet = PlayerBullet(self.center_x, self.center_y, self.character_face_direction) self.weapons_list.append(bullet) return bullet def update_animation(self, delta_time: float = 1 / 60): super().update_animation(delta_time) if not self.is_blocking and not self.is_damaged: # Landing overrides the cur_time_frame counter (to prevent stuttery looking animation) # This condition must mean that the player WAS jumping but has landed if self.change_y == 0 and self.is_jumping and \ (self.texture == self.jumping[1][3] or self.texture == self.jumping_attack[1][3]): # Update the tracker for future jumps self.is_jumping = False self.jumping[0] = 0 # Animation depending on whether facing left or right and moving or still if self.change_x == 0: if self.is_attacking: self.texture = self.attack[1][self.attack[0]] else: self.texture = self.idle[1][self.idle[0]] else: if self.is_attacking: self.texture = self.running_attack[1][self.running_attack[0]] else: self.texture = self.running[1][self.running[0]] return # Idle animation (this is different from entity because the gunner doesn't need to play an animation when attacking while idle) if self.change_x == 0 and self.change_y == 0: # If the player is standing still and pressing the attack button, play the attack animation if self.is_attacking: # Designed this way to maintain consistency with other, multi-frame animation code self.texture = self.attack[1][self.attack[0]] if self.attack[0] >= len(self.attack[1]) - 1: self.attack[0] = 0 self.is_attacking = False else: self.attack[0] += 1 self.cur_time_frame = 0 # Moving elif self.change_x != 0 or self.change_y != 0: # Check to see if the player is jumping (while moving right) if self.change_y != 0: self.is_jumping = True if self.is_attacking: self.texture = self.jumping_attack[1][self.jumping[0]] return def on_key_press(self, key, modifiers=0): super().on_key_press(key,modifiers) def on_key_release(self, key, modifiers=0): super().on_key_release(key,modifiers)
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble/Characters/Player/playerGunner.py
0.67405
0.310655
playerGunner.py
pypi
import arcade import os from importlib.resources import files SPRITE_SCALING = 0.5 SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SCREEN_TITLE = "Move Sprite with Keyboard Example" MOVEMENT_SPEED = 5 RIGHT_FACING = 0 LEFT_FACING = 1 CHARACTER_SCALING = 0.3 FRAMES_PER_SECOND = 60 def load_texture_pair(filename): """ Load a texture pair, with the second being a mirror image. """ return [ arcade.load_texture(filename), arcade.load_texture(filename, flipped_horizontally=True) ] class Player(arcade.Sprite): """ Player Class """ def __init__(self): # Set up parent class super().__init__() # Default to face-right self.cur_time_frame = 0 self.character_face_direction = RIGHT_FACING # Used for flipping between image sequences self.cur_texture = 0 self.scale = CHARACTER_SCALING #Load textures self.idle_r = [1] self.idle_l = [1] self.running_r = [1] self.running_l = [1] for i in range(2): texture_r = arcade.load_texture(files("robot_rumble.sprites").joinpath("Robot_idle.png"), x=i * 1000, y=0, width=1000, height=1000) texture_l = arcade.load_texture(files("robot_rumble.sprites").joinpath("Robot_idle.png"), x=i * 1000, y=0, width=1000, height=1000, flipped_horizontally=True) self.idle_r.append(texture_r) self.idle_l.append(texture_l) for i in range(8): texture_r = arcade.load_texture(files("robot_rumble.sprites").joinpath("Robot_run.png"), x=i * 1000, y=0, width=1000, height=1000) texture_l = arcade.load_texture(files("robot_rumble.sprites").joinpath("Robot_run.png"), x=i * 1000, y=0, width=1000, height=1000, flipped_horizontally=True) self.running_r.append(texture_r) self.running_l.append(texture_l) def update_animation(self, delta_time): #frames per second -> 60 self.cur_time_frame += delta_time #print("change x: ", self.change_x) #print("cur_time_frame time: ", self.cur_time_frame) if self.change_x == 0 and self.change_y == 0: if self.cur_time_frame >= 1/4: self.texture = self.idle_r[self.idle_r[0]] if self.idle_r[0] >= len(self.idle_r) - 1: self.idle_r[0] = 1 else: self.idle_r[0] = self.idle_r[0] + 1 self.cur_time_frame = 0 return if self.change_x > 0: if self.cur_time_frame >= 8/60: self.texture = self.running_r[self.running_r[0]] if self.running_r[0] >= len(self.running_r) - 1: self.running_r[0] = 1 else: self.running_r[0] = self.running_r[0] + 1 self.cur_time_frame = 0 if self.change_x < 0: if self.cur_time_frame >= 8/60: self.texture = self.running_l[self.running_l[0]] if self.running_l[0] >= len(self.running_l) - 1: self.running_l[0] = 1 else: self.running_l[0] = self.running_l[0] + 1 self.cur_time_frame = 0 def update(self): """ Move the player """ # Move player. # Remove these lines if physics engine is moving player. self.center_x += self.change_x self.center_y += self.change_y # Check for out-of-bounds if self.left < 0: self.left = 0 elif self.right > SCREEN_WIDTH - 1: self.right = SCREEN_WIDTH - 1 if self.bottom < 0: self.bottom = 0 elif self.top > SCREEN_HEIGHT - 1: self.top = SCREEN_HEIGHT - 1 class MyGame(arcade.Window): """ Main application class. """ def update_player_speed(self): # Calculate speed based on the keys pressed self.player.change_x = 0 if self.left_pressed and not self.right_pressed: self.player.change_x = -MOVEMENT_SPEED elif self.right_pressed and not self.left_pressed: self.player.change_x = MOVEMENT_SPEED def __init__(self, width, height, title): """ Initializer """ # Call the parent class initializer super().__init__(width, height, title) # Variables that will hold sprite lists self.player_list = None # Set up the player info self.player = None self.left_pressed = False self.right_pressed = False self.up_pressed = False self.down_pressed = False # Set the background color arcade.set_background_color(arcade.color.AMAZON) def setup(self): """ Set up the game and initialize the variables. """ # Sprite lists self.player_list = arcade.SpriteList() self.player = Player() self.player.center_x = SCREEN_WIDTH // 2 self.player.center_y = SCREEN_HEIGHT // 2 self.player.scale = 0.3 self.player_list.append(self.player) def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing self.clear() # Draw all the sprites. self.player_list.draw() def on_update(self, delta_time): """ Movement and game logic """ # Move the player self.player_list.update_animation() def on_key_press(self, key, modifiers): """Called whenever a key is pressed. """ if key == arcade.key.W: self.up_pressed = True self.update_player_speed() elif key == arcade.key.S: self.down_pressed = True self.update_player_speed() elif key == arcade.key.A: self.left_pressed = True self.update_player_speed() elif key == arcade.key.D: self.right_pressed = True self.update_player_speed() def on_key_release(self, key, modifiers): if key == arcade.key.W: self.up_pressed = False self.update_player_speed() elif key == arcade.key.S: self.down_pressed = False self.update_player_speed() elif key == arcade.key.A: self.left_pressed = False self.update_player_speed() elif key == arcade.key.D: self.right_pressed = False self.update_player_speed() def main(): """ Main function """ print(os.getcwd()) print(files("robot_rumble.sprites").joinpath("Robot_idle.png")) window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) window.setup() arcade.run() if __name__ == "__main__": main()
/robot_rumble-0.2.0-py3-none-any.whl/robot_rumble_package/main.py
0.505859
0.194177
main.py
pypi
import time import numpy as np import cv2 import logging from . import constants import os from . import utils os.environ["OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS"] = "0" class Field: """ Handle the field calibration and coordinates """ def __init__(self): self.logger: logging.Logger = logging.getLogger("field") self.focal = None # Should we (re-)calibrate the field ? self.should_calibrate: bool = True self.corner_field_positions = {} for (c, sx, sy) in (["c1", 1, 1], ["c2", 1, -1], ["c3", -1, 1], ["c4", -1, -1]): cX = sx * (constants.field_length / 2 + (constants.corner_tag_size / 2) + constants.corner_tag_border) cY = sy * (constants.field_width / 2 + (constants.corner_tag_size / 2) + constants.corner_tag_border) self.corner_field_positions[c] = [ # Top left ( cX + constants.corner_tag_size / 2, cY + constants.corner_tag_size / 2, ), # Top right ( cX + constants.corner_tag_size / 2, cY - constants.corner_tag_size / 2, ), # Bottom right ( cX - constants.corner_tag_size / 2, cY - constants.corner_tag_size / 2, ), # Bottom left ( cX - constants.corner_tag_size / 2, cY + constants.corner_tag_size / 2, ), ] # Position of corners on the image self.corner_gfx_positions: dict = {} # Is the field calibrated ? self.is_calibrated = False # Do we see the whole field ? self.see_whole_field = False # Extrinsic (4x4) transformations self.extrinsic = None self.extrinsic_inv = None # Camera intrinsic and distortion self.intrinsic = None self.distortion = None self.errors = 0 def calibrated(self) -> bool: """ Is the field calibrated ? :return bool: True if the field is calibrated properly """ return self.is_calibrated def tag_position(self, corners: list, front=False) -> tuple: """ Returns the position of a tag :param list corners: tag's corners :param bool front: tag front ? (else, center), defaults to False :return tuple: position of the tag """ if front: pX = (corners[0][0] + corners[1][0]) / 2.0 pY = (corners[0][1] + corners[1][1]) / 2.0 else: pX = (corners[0][0] + corners[2][0]) / 2.0 pY = (corners[0][1] + corners[2][1]) / 2.0 return pX, pY def set_corner_position(self, corner: str, corners: list): """ Sets the position of a corner :param str corner: the corner name (c1, c2, c3 or c4) :param list corners: the corner position """ self.corner_gfx_positions[corner] = corners def update_calibration(self, image): """ If the field should be calibrated, compute a calibration from the detected corners. This will use corner positions previously passed with set_corner_positions. :param image: the (OpenCV) image used for calibration """ if len(self.corner_gfx_positions) >= 4 and self.should_calibrate and self.focal is not None: # Computing point-to-point correspondance object_points = [] graphics_positions = [] for key in self.corner_gfx_positions: k = 0 for gfx, real in zip(self.corner_gfx_positions[key], self.corner_field_positions[key]): graphics_positions.append(gfx) object_points.append([*real, 0.0]) object_points = np.array(object_points, dtype=np.float32) graphics_positions = np.array(graphics_positions, dtype=np.float32) # Intrinsic parameters are fixed intrinsic = [ [self.focal, 0, image.shape[1] / 2], [0, self.focal, image.shape[0] / 2], [0, 0, 1], ] # Calibrating camera flags = cv2.CALIB_USE_INTRINSIC_GUESS + cv2.CALIB_FIX_FOCAL_LENGTH + cv2.CALIB_FIX_PRINCIPAL_POINT # No distortion flags += cv2.CALIB_FIX_TANGENT_DIST flags += cv2.CALIB_FIX_K1 + cv2.CALIB_FIX_K2 + cv2.CALIB_FIX_K3 + cv2.CALIB_FIX_K4 + cv2.CALIB_FIX_K5 ret, self.intrinsic, self.distortion, rvecs, tvecs = cv2.calibrateCamera( [object_points], [graphics_positions], image.shape[:2][::-1], np.array(intrinsic, dtype=np.float32), None, flags=flags, ) # Computing extrinsic matrices transformation = np.eye(4) transformation[:3, :3], _ = cv2.Rodrigues(rvecs[0]) transformation[:3, 3] = tvecs[0].T # transformation[:3, 3] = [0, 0, 2] self.extrinsic = transformation self.extrinsic_inv = np.linalg.inv(self.extrinsic) # We are now calibrated self.is_calibrated = True self.should_calibrate = False self.errors = 0 # Checking if we can see the whole fields image_height, image_width, _ = image.shape image_points = [] self.see_whole_field = True for sx, sy in [(-1, 1), (1, 1), (1, -1), (-1, -1)]: x = sx * ((constants.field_length / 2) + constants.border_size) y = sy * ((constants.field_width / 2) + constants.border_size) img = self.position_to_pixel([x, y, 0.0]) image_points.append((int(img[0]), int(img[1]))) if img[0] < 0 or img[0] > image_width or img[1] < 0 or img[1] > image_height: self.see_whole_field = False # We check that calibration is consistent, this can happen be done with only a few corners # The goal is to avoid recalibrating everytime for performance reasons if len(self.corner_gfx_positions) >= 3: if self.is_calibrated: has_error = False for key in self.corner_gfx_positions: for gfx, real in zip(self.corner_gfx_positions[key], self.corner_field_positions[key]): projected_position = self.pixel_to_position(gfx) reprojection_distance = np.linalg.norm(np.array(real) - np.array(projected_position)) if reprojection_distance > 0.025: has_error = True if not has_error: self.errors = 0 else: self.errors += 1 if self.errors > 8: self.logger.warning("Calibration seems wrong, re-calibrating") self.should_calibrate = True self.corner_gfx_positions = {} def field_to_camera(self, point: list) -> np.ndarray: """ Transforms a point from field frame to camera frame :param list point: point in field frame (3d) :return np.ndarray: point in camera frame (3d) """ return (self.extrinsic @ np.array([*point, 1.0]))[:3] def camera_to_field(self, point: list) -> np.ndarray: """ Transforms a point from camera frame to field frame :param list point: point in camera frame (3d) :return np.ndarray: point in field frame (3d) """ return (self.extrinsic_inv @ np.array([*point, 1.0]))[:3] def pixel_to_position(self, pixel: list, z: float = 0) -> list: """ Transforms a pixel on the image to a 3D point on the field, given a z :param list pos: pixel :param float z: the height to intersect with, defaults to 0 :return list: point coordinates (x, y) """ # Computing the point position in camera frame point_position_camera = cv2.undistortPoints(np.array(pixel), self.intrinsic, self.distortion)[0][0] # Computing the point position in the field frame and solving for given z point_position_field = self.camera_to_field([*point_position_camera, 1.0]) camera_center_field = self.camera_to_field(np.array([0.0, 0.0, 0.0])) delta = point_position_field - camera_center_field l = (z - camera_center_field[2]) / delta[2] return list(camera_center_field + l * delta)[:2] def position_to_pixel(self, pos: list) -> list: """ Given a position (3D, will be assumed on the ground if 2D), find its position on the screen :param list pos: position in field frame (2D or 3D) :return list: position on the screen """ if len(pos) == 2: # If no z is provided, assume it is a ground position pos = [*pos, 0.0] point_position_camera = self.field_to_camera(pos) position, J = cv2.projectPoints( point_position_camera, np.zeros(3), np.zeros(3), self.intrinsic, self.distortion, ) position = position[0][0] return [int(position[0]), int(position[1])] def pose_of_tag(self, corners: list): """ Returns the position and orientation of a detected tag :param list corners: tag's corners :return dict|None: a dict with position and orientation or None if not calibrated """ if self.calibrated(): center = self.pixel_to_position(self.tag_position(corners), constants.robot_height) front = self.pixel_to_position(self.tag_position(corners, front=True), constants.robot_height) return { "position": center, "orientation": float(np.arctan2(front[1] - center[1], front[0] - center[0])), } else: return None
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/field.py
0.766992
0.312239
field.py
pypi
import numpy as np import threading import time import serial from serial.tools import list_ports import logging from . import robot, robots # Constants for binary protocol PACKET_ACK = 0 PACKET_MONITOR = 1 PACKET_HOLO = 80 PACKET_HOLO_CONTROL = 2 PACKET_HOLO_BEEP = 3 PACKET_HOLO_LEDS_CUSTOM = 7 PACKET_HOLO_LEDS_BREATH = 8 PACKET_HOLO_KICK = 12 PACKET_MONITOR_DATA = 5 logger: logging.Logger = logging.getLogger("robot") class Packet: """ Represents a physical packet that is sent or received (binary protocol) """ def __init__(self, type_: int, payload=bytearray()): self.type: int = type_ self.payload = payload.copy() def available(self): return len(self.payload) def append_byte(self, char): char = char & 0xFF if type(char) == int: self.payload += bytearray((char,)) else: self.payload += bytearray(char) def append_short(self, short): b1 = (short >> 8) & 0xFF b2 = short & 0xFF self.payload += bytearray((b1, b2)) def append_int(self, short): b1 = (short >> 24) & 0xFF b2 = (short >> 16) & 0xFF b3 = (short >> 8) & 0xFF b4 = short & 0xFF self.payload += bytearray((b1, b2, b3, b4)) def appendFloat(self, f): self.append_int(f * 1000.0) def appendSmallFloat(self, f): self.append_short(f * 10.0) def readByte(self): byte = self.payload[0] self.payload = self.payload[1:] return byte def read_int(self): n = self.readByte() << 24 n = n | (self.readByte() << 16) n = n | (self.readByte() << 8) n = n | (self.readByte() << 0) return int(np.int32(n)) def read_short(self): n = (self.readByte() << 8) | self.readByte() return int(np.int16(n)) def read_float(self): return self.read_int() / 1000.0 def read_small_float(self): return self.read_short() / 10.0 def to_raw(self): raw = bytearray() raw += bytearray((0xFF, 0xAA, self.type, len(self.payload))) raw += self.payload raw += bytearray((self.checksum(),)) return raw def checksum(self): return sum(self.payload) % 256 class RobotSerial(robot.Robot): """ Connection with a physical robot """ def __init__(self, url: str): super().__init__(url) # Instance of serial connection self.bt = None # Is the connection initialized ? self.init: bool = True # Is the thread running ? self.running: bool = True # Last message timestamps self.last_sent_message = None # Last initialization tinestamp self.last_init = None # State retrieved from the packets self.state = {} # Starting the threads self.thread = threading.Thread(target=lambda: self.run_thread()) self.thread.start() # Pending packets queued self.pending_packets = {} self.lock = threading.Lock() def available_urls() -> list: devs = [entry.device for entry in list_ports.comports()] return [entry.device for entry in list_ports.comports()] def monitor(self, frequency: int) -> None: """ Send a monitor command to the robot :param int frequency: monitor frequency (Hz) """ packet = Packet(PACKET_MONITOR) packet.append_int(frequency) self.add_packet("monitor", packet) def blink(self) -> None: """ Gets the robot blinking for a while """ for _ in range(5): self.leds(255, 255, 255) time.sleep(0.25) self.leds(0, 0, 0) time.sleep(0.25) self.leds_dirty = True def process(self, packet: Packet) -> None: """ Processes a packet :param Packet packet: packet to process """ if packet.type == PACKET_MONITOR_DATA: self.last_message = time.time() state = {} version = packet.readByte() state["version"] = version if version == 11: # Version 11, old robots state["time"] = packet.read_float() state["distance"] = packet.read_small_float() state["optics"] = [packet.readByte() for optic in range(7)] state["wheels"] = [packet.read_small_float() for w in range(3)] state["yaw"] = packet.read_small_float() state["gyro_yaw"] = packet.read_small_float() state["pitch"] = packet.read_small_float() state["roll"] = packet.read_small_float() state["odometry"] = { "x": packet.read_short() / 1000.0, "y": packet.read_short() / 1000.0, "yaw": packet.read_small_float(), } state["battery"] = [packet.readByte() / 40.0, packet.readByte() / 40.0] elif version == 2: # Version 2, new robots state["time"] = packet.read_float() state["battery"] = [packet.readByte() / 10.0] else: logger.error(f"Unknown firmware version {version}") self.state = state def add_packet(self, name: str, packet: Packet) -> None: """ Adds a packet to the pending packets :param str name: the name of the packet, if such a name is in used, it will be overwritten :param Packet packet: packet to send """ self.lock.acquire() self.pending_packets[name] = packet self.lock.release() def pop_packet(self): """ Gets the next pending packet to be sent if any :return Packet|None: a packet, or None """ packet = None self.lock.acquire() if len(self.pending_packets) > 0: name = next(iter(self.pending_packets)) packet = self.pending_packets[name] del self.pending_packets[name] self.lock.release() return packet def beep(self, frequency: int, duration: int): """ Gets the robot beeping :param int frequency: frequency (Hz) :param int duration: duration (ms) """ packet = Packet(PACKET_HOLO) packet.append_byte(PACKET_HOLO_BEEP) packet.append_short(frequency) packet.append_short(duration) self.add_packet("beep", packet) def kick(self, power: float = 1.0): """ Gets the robot kicking :param float power: kick intensity (0 to 1), defaults to 1. """ packet = Packet(PACKET_HOLO) packet.append_byte(PACKET_HOLO_KICK) packet.append_byte(int(100 * power)) self.add_packet("kick", packet) def control(self, dx: float, dy: float, dturn: float): """ Sends some chassis speed order fo the robot :param float dx: x speed (m/s) :param float dy: y speed (m/s) :param float dturn: rotational speed (rad/s) """ packet = Packet(PACKET_HOLO) packet.append_byte(PACKET_HOLO_CONTROL) packet.append_short(int(1000 * dx)) packet.append_short(int(1000 * dy)) packet.append_short(int(np.rad2deg(dturn))) self.add_packet("control", packet) def leds(self, r: int, g: int, b: int) -> None: """ Sets the robot LEDs :param int r: R intensity (0-255) :param int g: G intensity (0-255) :param int b: B intensity (0-255) """ packet = Packet(PACKET_HOLO) packet.append_byte(PACKET_HOLO_LEDS_CUSTOM) packet.append_byte(r) packet.append_byte(g) packet.append_byte(b) self.add_packet("leds", packet) def stop(self): """ Stops the robot from moving """ self.control(0, 0, 0) def close(self): """ Stops the robot's thread """ self.running = False def run_thread(self): """ Process the main thread """ while self.running: try: if self.init: logger.info(f"Opening connection with {self.url}") self.init = False if self.bt is not None: self.bt.close() self.bt = None self.bt = serial.Serial(self.url, timeout=0.02) time.sleep(0.1) self.bt.write(b"rhock\r\nrhock\r\nrhock\r\n") time.sleep(0.1) self.monitor(5) self.control(0, 0, 0) self.beep(880, 250) self.last_init = time.time() self.last_sent_message = None state = 0 type_, length, payload = 0, 0, bytearray() # Receiving data byte = self.bt.read(1) if len(byte): byte = ord(byte) if state == 0: # First header if byte == 0xFF: state += 1 else: state = 0 elif state == 1: # Second header if byte == 0xAA: state += 1 else: state = 0 elif state == 2: # Packet type type_ = byte state += 1 elif state == 3: # Packet length length = byte state += 1 elif state == 4: # Payload payload += bytearray((byte,)) if len(payload) >= length: state += 1 elif state == 5: # Checksum if sum(payload) % 256 == byte: self.process(Packet(type_, payload)) type_, length, payload = 0, 0, bytearray() state = 0 # Asking periodically for robot monitor status if self.last_sent_message is None or time.time() - self.last_sent_message > 1.0: self.monitor(1) # Sending pending packets packet = self.pop_packet() while packet is not None: self.last_sent_message = time.time() self.last_sent_message = time.time() if self.bt is not None and self.bt.is_open: self.bt.write(packet.to_raw()) packet = self.pop_packet() except (OSError, serial.serialutil.SerialException) as e: # In case of exception, we re-init the connection logger.error(f"Error: {e}") if "FileNotFoundError" in str(e): time.sleep(1.0) self.init = True # If we didn't receive a message for more than 5s, we re-init the connection no_message = (self.last_message is None) or (time.time() - self.last_message > 5) if self.last_init is None: old_init = False else: old_init = time.time() - self.last_init > 5 if no_message and old_init: self.init = True if self.bt is not None: self.bt.close() if __name__ == "__main__": r = RobotSerial("/dev/rfcomm0") while True: print(r.state) time.sleep(5)
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/robot_serial.py
0.689201
0.185596
robot_serial.py
pypi
from concurrent.futures import thread import copy from multiprocessing.dummy.connection import Client import zmq import time import uuid import threading import logging from . import robots, utils, client, constants, tasks from .robot import RobotError class Control: """ This class is responsible for publishing the API allowing to control the robots. It also runs its own internal client to preempt the robots, for instance to stop them or to force them to be placed somewhere on the field. """ def __init__(self): self.logger: logging.Logger = logging.getLogger("control") # type: ignore[annotation-unchecked] self.robots: robots.Robots = None # Publishing server self.context = zmq.Context() self.socket = self.context.socket(zmq.REP) self.socket.bind("tcp://*:7558") self.socket.RCVTIMEO = 1000 self.master_key = str(uuid.uuid4()) # Allowing "extra" features (LEDs, buzzer etc.) self.allow_extra_features: bool = True # Target for client self.targets = {robot: None for robot in utils.all_robots()} self.targets_buffer: dict = {} self.lock: threading.Lock = threading.Lock() self.tasks: dict = {} self.robots_color: dict = {} self.teams = {team: {"allow_control": True, "key": "", "packets": 0} for team in utils.robot_teams()} def available_robots(self) -> list: """ Returns a list of the available robots :return list: list of (str) available robots """ return self.robots.robots_by_marker.keys() def add_task(self, task: tasks.ControlTask): """ Adds a task to the controller, this will preempt the concerned robots :param tasks.ControlTask task: the task """ self.lock.acquire() self.tasks[task.name] = task self.lock.release() def has_task(self, task_name: str) -> bool: """ Checks if a task exists :param str task_name: the task name :return bool: True if the tasks exists """ return task_name in self.tasks def remove_task(self, name: str) -> None: """ Removes a task :param str name: the task name """ self.lock.acquire() if name in self.tasks: del self.tasks[name] self.lock.release() def process_command(self, marker: str, command: list, is_master: bool) -> list: response: list = [False, "Unknown error"] try: if marker in self.robots.robots_by_marker: if type(command) == list: robot = self.robots.robots_by_marker[marker] if command[0] == "kick" and len(command) == 2: robot.kick(float(command[1])) response = [True, "ok"] elif command[0] == "control" and len(command) == 4: robot.control(float(command[1]), float(command[2]), float(command[3])) response = [True, "ok"] elif command[0] == "teleport" and len(command) == 4: robot.teleport(float(command[1]), float(command[2]), float(command[3])) response = [True, "ok"] elif command[0] == "leds" and len(command) == 4: if is_master or self.allow_extra_features: robot.leds(int(command[1]), int(command[2]), int(command[3])) response = [True, "ok"] else: response[0] = 2 response[1] = "Only master can set the LEDs" elif command[0] == "beep" and len(command) == 3: if is_master or self.allow_extra_features: robot.beep(int(command[1]), int(command[2])) response = [True, "ok"] else: response[0] = 2 response[1] = "Only master can set the LEDs" else: response[0] = 2 response[1] = "Unknown command" elif marker == "ball": self.robots.ball.teleport(float(command[1]), float(command[2]), float(command[3])) response = [True, "ok"] else: response[1] = f"Unknown robot: {marker}" except RobotError as e: response = [False, str(e)] except (TypeError, ValueError) as e: response = [False, "ArgumentError: "+str(e)] return response def thread(self): """ Main control loop, process commands received from the API """ while self.running: try: json = self.socket.recv_json() response = [False, "Unknown error"] if type(json) == list and len(json) == 4: key, team, number, command = json if team in self.teams: allow_control = True is_master = key == self.master_key if not is_master: tasks = [task.name for task in self.robot_tasks(team, number)] if self.teams[team]["key"] != key: response[1] = f"Bad key for team {team}" allow_control = False elif not self.teams[team]["allow_control"]: response[0] = 2 response[1] = f"You are not allowed to control the robots of team {team}" allow_control = False elif len(tasks): reasons = str(tasks) response[0] = 2 response[1] = f"Robot {number} of team {team} is preempted: {reasons}" allow_control = False if allow_control: marker = utils.robot_list2str(team, number) response = self.process_command(marker, command, is_master) self.teams[team]["packets"] += 1 if team == "ball": is_master = key == self.master_key response = self.process_command("ball", command, is_master) self.socket.send_json(response) except zmq.error.Again: pass def start(self): """ Starts the control's threads """ self.running = True control_thread = threading.Thread(target=lambda: self.thread()) control_thread.start() client_thread = threading.Thread(target=lambda: self.client_thread()) client_thread.start() def stop(self): """ Stops the threads from running (to do at the end of the program) """ self.running = False def robot_tasks(self, team: str, number: int) -> list: """ Gather all current tasks about a given robot :param str team: robot's team :param int number: robot's number :return list: list of tasks concerning this robot """ tasks = [] for task in self.tasks.values(): for task_team, task_number in task.robots(): if (team, number) == (task_team, task_number): tasks.append(task) return tasks def status(self) -> dict: """ Create the status structure for the control :return dict: a dictionary containing control's status """ state = copy.deepcopy(self.teams) for team in utils.robot_teams(): state[team]["preemption_reasons"] = {number: [] for number in utils.robot_numbers()} for task in self.tasks.values(): for team, number in task.robots(): state[team]["preemption_reasons"][number].append(task.name) return state def allow_team_control(self, team: str, allow: bool) -> None: """ Sets the team allowance flag :param str team: team :param bool allow: is the team allowed to control its robots? """ self.teams[team]["allow_control"] = allow def emergency(self) -> None: """ Performs an emergency stop """ # Clearing all the tasks, and creating a one-time stop all task. This can prevent # races conditions when the client thread is actually ticking tasks and might send # orders to the robots anyway. self.tasks.clear() self.add_task(tasks.StopAllTask("emergency", forever=False)) # Disallowing teams to control robots for team in utils.robot_teams(): self.allow_team_control(team, False) # Sending a stop moving order to all robots for port in self.robots.robots: self.robots.robots[port].control(0, 0, 0) def set_key(self, team: str, key: str): """ Sets a team's key :param str team: the team name :param str key: the team's key """ self.teams[team]["key"] = key def ensure_robots_on_field(self): """ Ensure that the robots don't leave the field. If they go outside a given area, they will be sent back inside the field using goto. """ [limit_up_right, _, limit_down_left, _] = constants.field_corners(0.25) for team, number in utils.all_robots(): robot = self.client.robots[team][number] if robot.position is not None: out_of_field = not utils.in_rectangle(robot.position, limit_down_left, limit_up_right) task_name = "out-of-game-%s" % utils.robot_list2str(team, number) if out_of_field: # Creating a top priority task to recover the robot task = tasks.GoToTask( task_name, team, number, (0.0, 0.0, 0.0), skip_old=False, priority=100, ) self.add_task(task) else: # If the robot is recovered, creating a one-time task to make it stop moving if self.has_task(task_name): task = tasks.StopTask(task_name, team, number, forever=False, priority=100) self.add_task(task) def tick_tasks(self) -> set: """ Ticks all the current tasks to be run :return set: the robots that were updated during this tick """ self.lock.acquire() tasks_to_tick = list(self.tasks.values()).copy() self.lock.release() # Sorting tasks by priority tasks_to_tick = sorted(tasks_to_tick, key=lambda task: -task.priority) robots_ticked = set() to_delete = [] available_robots = self.available_robots() # Ticking all the tasks for task in tasks_to_tick: for team, number in task.robots(): if (team, number) not in robots_ticked and utils.robot_list2str(team, number) in available_robots: # Robot was not ticked yet by an higher-priority task robots_ticked.add((team, number)) try: task.tick(self.client.robots[team][number]) except client.ClientError as e: self.logger.error(f"Error in control's client: {e}") if task.finished(self.client, available_robots): to_delete.append(task.name) # Removing finished tasks self.lock.acquire() for task_name in to_delete: if task_name in self.tasks: del self.tasks[task_name] self.lock.release() return robots_ticked def update_robots_colors(self, robots_ticked: set) -> None: """ Ensure robot LEDs colors, either their team or the preempted color :param set robots_ticked: robots that were ticked """ try: new_robots_color = {} for robot_id in self.robots.robots_by_marker: robot = utils.robot_str2list(robot_id) color = "preempted" if robot in robots_ticked else robot[0] if ( (robot not in self.robots_color) or self.robots_color[robot] != color or self.robots.should_restore_leds(robot_id) ): self.client.robots[robot[0]][robot[1]].leds(*utils.robot_leds_color(color)) new_robots_color[robot] = color self.robots_color = new_robots_color except client.ClientError as e: self.logger.error(f"Error while setting leds: {e}") def client_thread(self) -> None: """ This thread is used to control the robot, it connects to the local API using the master key """ self.client = client.Client(key=self.master_key, wait_ready=False) while self.running: self.ensure_robots_on_field() robots_ticked = self.tick_tasks() self.update_robots_colors(robots_ticked) time.sleep(0.01)
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/control.py
0.634996
0.304804
control.py
pypi
import numpy as np """ This file contains all relevant constants. It can be dimension of items or values from the rules. """ # Field dimension field_length: float = 1.84 # [m] (x axis) field_width: float = 1.23 # [m] (y axis) # Carpet dimension carpet_length: float = 2.45 # [m] (x axis) carpet_width: float = 1.84 # [m] (y axis) # Goals size goal_width: float = 0.6 # [m] goal_virtual_height: float = 0.1 # [m] # Side of the (green) border we should be able to see around the field border_size: float = 0.3 # [m] # Dots coordinates (x, y) dots_x: float = 0.45 # [m] dots_y: float = 0.305 # [m] # Defense area defense_area_width = 0.9 # [m] defense_area_length = 0.3 # [m] # Timed circle radius and maximum time before being penalized timed_circle_radius: float = 0.25 # [m] timed_circle_time: float = 3 # [s] # Margin for ball re-placement (on the center or on dots) place_ball_margin: float = 0.05 # [m] # Margins for being in and out the field field_in_margin: float = -0.08 # [m] field_out_margin: float = 0.02 # [m] # Tag sizes corner_tag_size: float = 0.16 # [m] corner_tag_border: float = 0.025 # [m] robot_tag_size: float = 0.08 # [m] # Heights robot_height: float = 0.076 # [m] ball_radius: float = 0.021 # [m] # We detect the center of the orange blog to see the ball, and not the top of the ball # that is why we use the radius here instead of the diameter ball_height: float = ball_radius # [m] # Durations game_duration: float = 300.0 # [s] halftime_duration: float = 120.0 # [s] default_penalty: float = 5.0 # [s] grace_time: float = 3.0 # [s] # Number of penalty spots penalty_spots: int = 8 penalty_spot_lock_time: int = 1 # Parameters referee_history_size: int = 3 # For simulation robot_mass: float = 0.710 # [kg] max_linear_acceleration: float = 3 # [m.s^-2] max_angular_accceleration: float = 50 # [rad.s^-2] ball_mass: float = 0.008 # [kg] ball_deceleration: float = 0.3 # [m.s^-2] kicker_x_tolerance: float = 0.03 # [m] kicker_y_tolerance: float = 0.065 # [m] # Wheel radius [m] wheel_radius: float = 0.035 # Distance between its center and wheels [m] wheel_center_spacing: float = 0.0595 # Robot radius [m] robot_radius: float = 0.088 # Goals coordinates def goal_posts(x_positive: bool = True) -> np.ndarray: sign = 1 if x_positive else -1 return np.array([[sign * field_length / 2, -goal_width / 2.0], [sign * field_length / 2, goal_width / 2]]) # Field coordinates with margins (For goals and sideline) def field_corners(margin: float = 0) -> np.ndarray: return [ np.array([sign1 * ((field_length / 2.0) + margin), sign2 * ((field_width / 2.0) + margin)]) for sign1, sign2 in [[1, 1], [1, -1], [-1, -1], [-1, 1]] ] # Returns the defense area rectangle def defense_area(x_positive: bool = True) -> np.ndarray: if x_positive: return [ [field_length / 2 - defense_area_length, -defense_area_width / 2], [field_length / 2 + defense_area_length, defense_area_width / 2], ] else: return [ [-field_length / 2 - defense_area_length, -defense_area_width / 2], [-field_length / 2 + defense_area_length, defense_area_width / 2], ]
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/constants.py
0.831588
0.636396
constants.py
pypi
import sys import threading import time import numpy as np from numpy.linalg import norm from math import dist from . import kinematics, utils, constants, state, robot, robots from collections.abc import Callable class SimulatedObject: def __init__(self, marker: str, position: np.ndarray, radius: int, deceleration: float = 0, mass: float = 1) -> None: self.marker: str = marker self.radius: int = radius self.mass: float = mass self.position: np.ndarray = np.array([float(i) for i in position]) self.velocity: np.ndarray = np.array([0.0, 0.0, 0.0]) self.deceleration: float = deceleration self.pending_actions: list(Callable) = [] self.sim: Simulator = None def execute_actions(self) -> None: for action in self.pending_actions: action() self.pending_actions = [] def teleport(self, x: float, y: float, turn: float): self.position = np.array((x, y, turn)) self.velocity = np.array([0.0, 0.0, 0.0]) def update_velocity(self, dt) -> None: self.velocity[:2] = utils.update_limit_variation(self.velocity[:2], np.array([0.0, 0.0]), self.deceleration * dt) def collision_R(self, obj): """ Given another object, computes the collision frame. It returns R_collision_world """ # Computing unit vectors normal and tangent to contact (self to obj) normal = obj.position[:2] - self.position[:2] normal = (normal / norm(normal)) if norm(normal) != 0 else (0, 0) tangent = np.array([[0, -1], [1, 0]]) @ normal return np.vstack((normal, tangent)) def collision(self, obj) -> None: R_collision_world = self.collision_R(obj) # Velocities expressed in the collision frame self_velocity_collision = R_collision_world @ self.velocity[:2] obj_velocity_collision = R_collision_world @ obj.velocity[:2] # Updating velocities using elastic collision u1 = self_velocity_collision[0] u2 = obj_velocity_collision[0] m1 = self.mass m2 = obj.mass Cr = 0.25 # If the objects are not getting closer to each other, don't proceed if u2 - u1 > 0: return self_velocity_collision[0] = (m1 * u1 + m2 * u2 + m2 * Cr * (u2 - u1)) / (m1 + m2) obj_velocity_collision[0] = (m1 * u1 + m2 * u2 + m1 * Cr * (u1 - u2)) / (m1 + m2) # Velocities back in the world frame self.velocity[:2] = R_collision_world.T @ self_velocity_collision obj.velocity[:2] = R_collision_world.T @ obj_velocity_collision class SimulatedRobot(SimulatedObject): def __init__(self, name: str, position: np.ndarray) -> None: super().__init__(name, position, constants.robot_radius, 0, constants.robot_mass) self.control_cmd: np.ndarray = np.array([0.0, 0.0, 0.0]) self.leds = None # [R,G,B] (0-255) None for off def compute_kick(self, power: float) -> None: # Robot to ball vector, expressed in world ball_world = self.sim.objects["ball"].position[:2] T_world_robot = utils.frame(tuple(self.position)) T_robot_world = utils.frame_inv(T_world_robot) ball_robot = utils.frame_transform(T_robot_world, ball_world) if utils.in_rectangle( ball_robot, [self.radius + constants.ball_radius - constants.kicker_x_tolerance, -constants.kicker_y_tolerance], [self.radius + constants.ball_radius + constants.kicker_x_tolerance, constants.kicker_y_tolerance], ): # TODO: Move the ball kicking velocity to constants # TODO: We should not set the ball velocity to 0 in the y direction but keep its velocity ball_speed_robot = [np.clip(power, 0, 1) * np.random.normal(0.8, 0.1), 0] self.sim.objects["ball"].velocity[:2] = T_world_robot[:2, :2] @ ball_speed_robot def update_velocity(self, dt: float) -> None: target_velocity_robot = self.control_cmd T_world_robot = utils.frame(tuple(self.position)) target_velocity_world = T_world_robot[:2, :2] @ target_velocity_robot[:2] self.velocity[:2] = utils.update_limit_variation( self.velocity[:2], target_velocity_world, constants.max_linear_acceleration * dt ) self.velocity[2:] = utils.update_limit_variation( self.velocity[2:], target_velocity_robot[2:], constants.max_angular_accceleration * dt ) def control_leds(self, r: int, g: int, b: int) -> None: self.leds = [r, g, b] class RobotSim(robot.Robot): def __init__(self, url: str): super().__init__(url) self.set_marker(url) self.object: SimulatedRobot = None def initialize(self, position: np.ndarray) -> None: self.object = SimulatedRobot(self.marker, position) def teleport(self, x: float, y: float, turn: float) -> None: """ Teleports the robot to a given position/orientation :param float x: x position [m] :param float y: y position [m] :param float turn: orientation [rad] """ self.object.teleport(x, y, turn) def control(self, dx: float, dy: float, dturn: float) -> None: self.object.control_cmd = kinematics.clip_target_order(np.array([dx, dy, dturn])) def kick(self, power: float = 1.0) -> None: self.object.pending_actions.append(lambda: self.object.compute_kick(power)) def leds(self, red: int, green: int, blue: int) -> None: """ Controls the robot LEDs :param int red: red brightness (0-255) :param int green: green brightness (0-255) :param int blue: blue brightness (0-255) """ self.object.pending_actions.append(lambda: self.object.control_leds(red, green, blue)) class Simulator: def __init__(self, robots: robots.Robots, state: state.State = None, run_thread=True): self.state: state.State = state self.robots: robots.Robots = robots for marker, position in zip( ["green1", "green2", "blue1", "blue2"], [[-0.5, 0.5, 0], [-0.5, -0.5, 0], [0.5, 0.5, 0], [0.5, -0.5, 0]], ): robot: RobotSim = self.robots.add_robot(f"sim://{marker}") robot.initialize(position) self.robots.update() self.objects: dict = {} # Creating the ball self.add_object( SimulatedObject("ball", [0, 0, 0], constants.ball_radius, constants.ball_deceleration, constants.ball_mass) ) self.add_robot_objects() self.robots.ball = self.objects["ball"] self.fps_limit = 100 if run_thread: self.run_thread() def run_thread(self): self.run = True self.simu_thread: threading.Thread = threading.Thread(target=lambda: self.thread()) self.simu_thread.start() self.lock: threading.Lock = threading.Lock() def add_object(self, object: SimulatedObject) -> None: self.objects[object.marker] = object object.sim = self def add_robot_objects(self) -> None: for robot in self.robots.robots_by_marker.values(): self.add_object(robot.object) def thread(self) -> None: last_time = time.time() while self.run: self.dt = -last_time + (last_time := time.time()) self.loop(self.dt) while (self.fps_limit is not None) and (time.time() - last_time < 1 / self.fps_limit): time.sleep(1e-3) def loop(self, dt): # Simulator proceed in two steps: # 1) We handle future collisions as elastic collisions and change the velocity vectors # accordingly. # 2) We apply the object velocities, removing all the components in the velocities that would # create collision. for obj in self.objects.values(): # Execute actions (e.g: kick) # Update object velocity (e.g: deceleration, taking commands in account) obj.update_velocity(dt) if norm(obj.velocity) > 0: # Where the object would arrive without collisions future_pos = obj.position + obj.velocity * dt # Check for collisions for marker in self.objects: if marker != obj.marker: check_obj = self.objects[marker] if dist(future_pos[:2], check_obj.position[:2]) < (obj.radius + check_obj.radius): obj.collision(check_obj) for obj in self.objects.values(): # Check for collisions for marker in self.objects: if marker != obj.marker: check_obj = self.objects[marker] future_pos = obj.position + obj.velocity * dt if dist(future_pos[:2], check_obj.position[:2]) < (obj.radius + check_obj.radius): R_collision_world = obj.collision_R(check_obj) velocity_collision = R_collision_world @ obj.velocity[:2] velocity_collision[0] = min(0, velocity_collision[0]) obj.velocity[:2] = R_collision_world.T @ velocity_collision obj.position = obj.position + (obj.velocity * dt) obj.execute_actions() if "ball" in self.objects and not utils.in_rectangle( self.objects["ball"].position[:2], [-constants.carpet_length / 2, -constants.carpet_width / 2], [constants.carpet_length / 2, constants.carpet_width / 2], ): self.objects["ball"].position[:3] = [0.0, 0.0, 0.0] self.objects["ball"].velocity[:3] = [0.0, 0.0, 0.0] self.push() def push(self) -> None: if self.state is not None: for marker in self.objects: pos = self.objects[marker].position if marker == "ball": self.state.set_ball(pos[:2].tolist()) else: self.state.set_marker(marker, pos[:2].tolist(), pos[2]) self.state.set_leds(marker, self.objects[marker].leds)
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/simulator.py
0.63307
0.559531
simulator.py
pypi
import signal import numpy as np import zmq import sys import threading import logging import time from . import constants, utils configurations = { "dots": [ ["green", 1, (constants.field_length / 4, -constants.field_width / 4, np.pi)], ["green", 2, (constants.field_length / 4, constants.field_width / 4, np.pi)], ["blue", 1, (-constants.field_length / 4, constants.field_width / 4, 0)], ["blue", 2, (-constants.field_length / 4, -constants.field_width / 4, 0)], ], "game": [ ["green", 1, (constants.field_length / 4, 0, np.pi)], ["green", 2, (constants.field_length / 2, 0, np.pi)], ["blue", 1, (-constants.field_length / 4, 0, 0)], ["blue", 2, (-constants.field_length / 2, 0, 0)], ], "game_green_positive": [ ["green", 1, (constants.field_length / 4, 0, np.pi)], ["green", 2, (constants.field_length / 2, 0, np.pi)], ["blue", 1, (-constants.field_length / 4, 0, 0)], ["blue", 2, (-constants.field_length / 2, 0, 0)], ], "game_blue_positive": [ ["green", 1, (-constants.field_length / 4, 0, 0)], ["green", 2, (-constants.field_length / 2, 0, 0)], ["blue", 1, (constants.field_length / 4, 0, np.pi)], ["blue", 2, (constants.field_length / 2, 0, np.pi)], ], "side": [ ["green", 1, (0.2, constants.field_width / 2, -np.pi / 2)], ["green", 2, (0.6, constants.field_width / 2, -np.pi / 2)], ["blue", 1, (-0.2, constants.field_width / 2, -np.pi / 2)], ["blue", 2, (-0.6, constants.field_width / 2, -np.pi / 2)], ], "swap_covers_green_positive": [ ["green", 1, (0.15, -0.2, np.pi)], ["green", 2, (0.15, 0.2, np.pi)], ["blue", 1, (-0.15, -0.2, 0)], ["blue", 2, (-0.15, 0.2, 0)], ], "swap_covers_blue_positive": [ ["green", 1, (-0.15, -0.2, 0)], ["green", 2, (-0.15, 0.2, 0)], ["blue", 1, (0.15, -0.2, np.pi)], ["blue", 2, (0.15, 0.2, np.pi)], ], "gently_swap_side": [ ["green", 1, (0, -0.15, 0)], ["green", 2, (0, 0.5, 0)], ["blue", 1, (0, -0.5, np.pi)], ["blue", 2, (0, 0.15, np.pi)], ], } class ClientError(Exception): pass class ClientTracked: def __init__(self): self.position = None self.pose = None self.orientation = None self.last_update = None class ClientRobot(ClientTracked): def __init__(self, color, number, client): super().__init__() self.moved = False self.color = color self.team = color self.number = number self.client = client self.x_max = constants.field_length / 2 + constants.border_size / 2.0 self.x_min = -self.x_max self.y_max = constants.field_width / 2 + constants.border_size / 2.0 self.y_min = -self.y_max def ball(self): return self.client.ball def has_position(self, skip_old): seen = (self.position is not None) and (self.orientation is not None) if skip_old: seen = seen and self.age() < 1 return seen def age(self): if self.last_update is None: return None return time.time() - self.last_update def kick(self, power=1): return self.client.command(self.color, self.number, "kick", [power]) def control(self, dx, dy, dturn): self.moved = True return self.client.command(self.color, self.number, "control", [dx, dy, dturn]) def teleport(self, x, y, turn): return self.client.command(self.color, self.number, "teleport", [x, y, turn]) def beep(self, frequency: int, duration: int): return self.client.command(self.color, self.number, "beep", [frequency, duration]) def leds(self, r, g, b): return self.client.command(self.color, self.number, "leds", [r, g, b]) def goto_compute_order(self, target, skip_old=True): if not self.has_position(skip_old): return False, (0.0, 0.0, 0.0) if callable(target): target = target() x, y, orientation = target x = min(self.x_max, max(self.x_min, x)) y = min(self.y_max, max(self.y_min, y)) Ti = utils.frame_inv(utils.robot_frame(self)) target_in_robot = Ti @ np.array([x, y, 1]) error_x = target_in_robot[0] error_y = target_in_robot[1] error_orientation = utils.angle_wrap(orientation - self.orientation) arrived = np.linalg.norm([error_x, error_y, error_orientation]) < 0.05 order = 1.5 * error_x, 1.5 * error_y, 1.5 * error_orientation return arrived, order def goto(self, target, wait=True, skip_old=True): if wait: while not self.goto(target, wait=False): time.sleep(0.05) self.control(0, 0, 0) return True arrived, order = self.goto_compute_order(target, skip_old) self.control(*order) return arrived class Client: def __init__(self, host="127.0.0.1", key="", wait_ready=True): logging.basicConfig(format="[%(levelname)s] %(asctime)s - %(name)s - %(message)s", level=logging.INFO) self.logger: logging.Logger = logging.getLogger("client") self.error_management = "raise" # "ignore", "print", "raise" self.running = True self.key = key self.lock = threading.Lock() self.robots = {} # Declaring stubs for auto completion self.green1: ClientRobot self.green2: ClientRobot self.blue1: ClientRobot self.blue2: ClientRobot # Creating self.green1, self.green2 etc. for color, number in utils.all_robots(): robot_id = utils.robot_list2str(color, number) robot = ClientRobot(color, number, self) self.__dict__[robot_id] = robot if color not in self.robots: self.robots[color] = {} self.robots[color][number] = robot # Custom objects to track self.objs = {n: ClientTracked() for n in range(1, 9)} self.ball = None # ZMQ Context self.context = zmq.Context() # Creating subscriber connection self.sub = self.context.socket(zmq.SUB) self.sub.set_hwm(1) self.sub.connect("tcp://" + host + ":7557") self.sub.subscribe("") self.on_update = None self.sub_packets = 0 self.sub_thread = threading.Thread(target=lambda: self.sub_process()) self.sub_thread.start() # Informations from referee self.referee = None # Creating request connection self.req = self.context.socket(zmq.REQ) self.req.connect("tcp://" + host + ":7558") if threading.current_thread() is threading.main_thread(): signal.signal(signal.SIGINT, self.sigint) # Waiting for the first packet to be received, guarantees to have robot state after # client creation dt = 0.05 t = 0 warning_showed = False while wait_ready and self.sub_packets < 1 and self.running: t += dt time.sleep(dt) if t > 3 and not warning_showed: warning_showed = True self.logger.warning("Still no message from vision after 3s") self.logger.warning("if you want to operate without vision, pass wait_ready=False to the client") def sigint(self, signal_received, frame): self.stop() sys.exit(0) def __enter__(self): return self def __exit__(self, type, value, tb): self.stop() def update_position(self, tracked, infos): tracked.position = np.array(infos["position"]) tracked.orientation = infos["orientation"] tracked.pose = np.array(list(tracked.position) + [tracked.orientation]) tracked.last_update = time.time() def sub_process(self): self.sub.RCVTIMEO = 1000 last_t = time.time() while self.running: try: json = self.sub.recv_json() ts = time.time() dt = ts - last_t last_t = ts if "ball" in json: self.ball = None if json["ball"] is None else np.array(json["ball"]) if "markers" in json: for entry in json["markers"]: team = entry[:-1] number = int(entry[-1]) if team == "obj": self.update_position(self.objs[number], json["markers"][entry]) else: self.update_position(self.robots[team][number], json["markers"][entry]) if "referee" in json: self.referee = json["referee"] if self.on_update is not None: self.on_update(self, dt) self.sub_packets += 1 except zmq.error.Again: pass def stop_motion(self): for color in self.robots: robots = self.robots[color] for index in robots: if robots[index].moved: try: robots[index].control(0.0, 0.0, 0.0) except ClientError: pass def em(self): self.stop_motion() def stop(self): self.stop_motion() self.running = False def teleport_ball(self, x: float, y: float): return self.command("ball", 0, "teleport", [x, y, 0]) def command(self, color, number, name, parameters): if threading.current_thread() is threading.main_thread(): sigint_handler = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, signal.SIG_IGN) self.lock.acquire() self.req.send_json([self.key, color, number, [name, *parameters]]) success, message = self.req.recv_json() self.lock.release() if threading.current_thread() is threading.main_thread(): signal.signal(signal.SIGINT, sigint_handler) time.sleep(0.01) if success != 1: if self.error_management == "raise" or not success: raise ClientError('Command "' + name + '" failed: ' + message) elif self.error_management == "print": self.logger.warning('Command "' + name + '" failed: ' + message) def goto_configuration(self, configuration_name="side", wait=False): targets = configurations[configuration_name] arrived = False while not arrived: arrived = True for color, index, target in targets: robot = self.robots[color][index] try: arrived = robot.goto(target, wait=wait) and arrived except ClientError: pass self.stop_motion()
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/client.py
0.433262
0.476823
client.py
pypi
import numpy as np import time import copy import math import logging from . import config, control, robot, utils, state class Robots: """ This class contains the instance of robots, each of them being a separate connection to a physical robot. """ def __init__(self, state=None): self.logger: logging.Logger = logging.getLogger("robots") self.state: state.State = state # Robots (indexed by urls) self.robots: dict = {} # Robots (indexed by marker strings) self.robots_by_marker: dict = {} def load_config(self) -> None: # Loading robots from the configuration if "robots" in config.config: for url, marker in config.config["robots"]: config_robot = self.add_robot(url) if config_robot and marker != "": config_robot.set_marker(marker) self.update() # Registered protocols protocols: dict = {} def update(self): """ Updates robots_by_marker for it to be consistent with robots """ new_robots_by_marker = {} for url in self.robots: if self.robots[url].marker is not None: new_robots_by_marker[self.robots[url].marker] = self.robots[url] self.robots_by_marker = new_robots_by_marker def should_restore_leds(self, robot: str) -> bool: """ Checking if a robot should have its LEDs resetted :param str robot: robot name :return bool: True if the LEDs should be restored """ if robot in self.robots_by_marker and self.robots_by_marker[robot].leds_dirty: self.robots_by_marker[robot].leds_dirty = False return True return False def identify(self): """ Starts the identification procedure, to detect markers on the top of each robots """ for url in self.robots: self.logger.info(f"Identifying {url}...") # Detection before the robot moves before = copy.deepcopy(self.state.get_state())["markers"] after = copy.deepcopy(before) # Makes the robot rotating at 50°/s for 1s self.set_marker(url, None) self.robots[url].beep(200, 100) self.robots[url].control(0, 0, math.radians(50)) for _ in range(100): markers = copy.deepcopy(self.state.get_state())["markers"] before = {**markers, **before} after = {**after, **markers} time.sleep(0.01) self.robots[url].control(0, 0, 0) # We assign the marker to the robot that moved for marker in before: a = before[marker]["orientation"] b = after[marker]["orientation"] delta = np.rad2deg(utils.angle_wrap(b - a)) self.logger.info(f"marker={marker}, url={url}, delta={delta}") if delta > 25 and delta < 90: logging.info(f"Identified robot {url} to be {marker}") self.set_marker(url, marker) def available_urls(self) -> list: """ Retrieve a list of available URLs :return list: a list of (str) urls """ urls: list = [] for protocol in self.protocols: urls += [f"{protocol}://{url}" for url in self.protocols[protocol].available_urls()] return urls def save_config(self) -> None: """ Save the configuration file """ config.config["robots"] = [] for url in self.robots: config.config["robots"].append([url, self.robots[url].marker]) config.save() def add_robot(self, full_url: str): """ Adds an url to the robots list :param str url: the robot's url """ if full_url not in self.robots: result = full_url.split("://", 1) if len(result) == 2: protocol, url = result if protocol in self.protocols: self.robots[full_url] = self.protocols[protocol](url) self.save_config() return self.robots[full_url] else: print(f'Unknown protocol: {protocol} in robot URL "{full_url}"') else: print(f"Bad url: {full_url}") return None def get_robots(self) -> dict: """ Gets robots informations. :return dict: information about robots """ data = {} for entry in self.robots: last_detection = None if self.robots[entry].marker in self.state.last_updates: last_detection = time.time() - self.state.last_updates[self.robots[entry].marker] data[entry] = { "state": self.robots[entry].state, "marker": self.robots[entry].marker, "last_detection": last_detection, "last_message": time.time() - self.robots[entry].last_message if self.robots[entry].last_message is not None else None, } return data def set_marker(self, url: str, marker: str) -> None: """ Sets the marker for a robot on a given url :param str url: the url :param str marker: the marker """ if url in self.robots: self.robots[url].set_marker(marker) self.save_config() self.update() def remove(self, url: str) -> None: """ Removes a url from :param str url: the url """ if url in self.robots: self.robots[url].close() del self.robots[url] self.save_config() self.update() def stop(self): """ Stops execution and closes all the connections """ self.control.stop() for url in self.robots: self.robots[url].close()
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/robots.py
0.772144
0.305425
robots.py
pypi
import math import copy import numpy as np import threading import logging from . import constants, utils, config, control, tasks, state from .field import Field import time class Referee: """ Handles the referee """ def __init__(self, state: state.State): self.logger: logging.Logger = logging.getLogger("referee") self.control: control.Control = control.Control() # Info from detection self._state_info = None self.state: state.State = state # Last actions self.referee_history = [] # Timestamp when the timer started self.chrono_is_running: bool = False self.start_timer = 0.0 # Set when a goal validation is pending self.goal_validated = None # Position where we wait for the ball to be before we self.wait_ball_position = None # Timers to penalize robots staying in te self.timed_circle_timers = {robot: 0 for robot in utils.all_robots()} # Game state structure self.game_state = { "game_is_running": False, "game_paused": True, "halftime_is_running": False, "timer": 0, "game_state_msg": "", "teams": { team: { "name": "", "score": 0, "x_positive": team == utils.robot_teams()[0], } for team in utils.robot_teams() }, } # Robots Penalties self.penalties = {} self.penalty_spot = [ {"robot": None, "last_use": 0, "pos": (x, side * constants.field_width / 2, side * np.pi / 2)} for x in np.linspace(-constants.field_length / 2, constants.field_length / 2, constants.penalty_spots // 2 + 2)[ 1:-1 ] for side in (-1, 1) ] self.reset_penalties() # Starting the Referee thread self.lock = threading.Lock() self.referee_thread = threading.Thread(target=lambda: self.thread()) self.referee_thread.start() def set_state_info(self, info: dict) -> None: """ Sets internal detection info :param dict info: detection infos """ self.lock.acquire() self._state_info = info self.lock.release() def get_game_state(self, full: bool = True) -> dict: game_state = copy.deepcopy(self.game_state) # Updating robot statuses control_status = self.control.status() for team, number in utils.all_robots(): robot_state = { "penalized": False, "penalized_remaining": None, "penalized_reason": None, "preempted": False, "preemption_reasons": [], } robot_id = utils.robot_list2str(team, number) robot_state["penalized"] = self.penalties[robot_id]["remaining"] is not None if robot_state["penalized"]: robot_state["penalized_remaining"] = math.ceil(self.penalties[robot_id]["remaining"]) else: robot_state["penalized_remaining"] = None robot_state["penalized_reason"] = self.penalties[robot_id]["reason"] preempted_reasons = control_status[team]["preemption_reasons"][number] robot_state["preempted"] = len(preempted_reasons) > 0 robot_state["preemption_reasons"] = preempted_reasons if "robots" not in game_state["teams"][team]: game_state["teams"][team]["robots"] = {} game_state["teams"][team]["robots"][number] = robot_state if full: game_state["referee_history_sliced"] = self.referee_history[-constants.referee_history_size :] else: del game_state["game_state_msg"] # Updating timer game_state["timer"] = math.ceil(game_state["timer"]) return game_state def wait_for_ball_placement(self, target_position=(0.0, 0.0)): """ Waits for the ball to be placed somewhere, pauses the game until then :param tuple target_position: the target position for the ball, defaults to (0.0, 0.0) """ self.wait_ball_position = target_position self.game_state["game_paused"] = True self.game_state["game_state_msg"] = "Place the ball on the dot" def start_game(self): """ Starts the game """ self.logger.info("Game started") self.game_state["timer"] = constants.game_duration self.game_state["game_is_running"] = True self.referee_history = [] self.reset_score() self.pause_game("game-start") self.start_timer = 0 self.chrono_is_running = False self.wait_for_ball_placement() def pause_game(self, reason: str = "manually-paused"): """ Pause the game :param str reason: the reason for this pause, defaults to "manually-paused" """ self.logger.info(f"Game paused, reason: {reason}") self.game_state["game_paused"] = True task = tasks.StopAllTask(reason) self.control.add_task(task) self.game_state["game_state_msg"] = "Game has been manually paused" def resume_game(self): """ Resume the game """ self.logger.info("Game resumed") self.game_state["game_paused"] = False self.game_state["game_state_msg"] = "Game is running..." self.wait_ball_position = None if self.control.has_task("game-start"): self.chrono_is_running = True self.control.remove_task("manually-paused") self.control.remove_task("sideline-crossed") self.control.remove_task("goal") self.control.remove_task("force-place") self.control.remove_task("game-start") self.control.remove_task("half-time") # Ensuring all robots are stopped self.control.add_task(tasks.StopAllTask("stop-all", forever=False)) def stop_game(self): """ Stop the game (end) """ self.logger.info("Game stopped") self.game_state["game_paused"] = True self.game_state["game_is_running"] = False self.chrono_is_running = False self.wait_ball_position = None self.start_timer = 0.0 self.reset_penalties() self.control.remove_task("manually-paused") self.control.remove_task("sideline-crossed") self.control.remove_task("goal") self.control.remove_task("game-start") self.control.remove_task("force-place") self.control.remove_task("half-time") self.game_state["game_state_msg"] = "Game is ready to start" def start_half_time(self): """ Start an half time break """ self.game_state["timer"] = constants.halftime_duration self.chrono_is_running = True self.game_state["game_is_running"] = False self.game_state["halftime_is_running"] = True self.game_state["game_paused"] = True self.game_state["game_state_msg"] = "Half Time" task = tasks.StopAllTask("half-time") self.control.add_task(task) self.reset_penalties() self.control.remove_task("sideline-crossed") self.control.remove_task("goal") def start_second_half_time(self): """ Resume after an half time break """ self.pause_game("game-start") self.chrono_is_running = False self.game_state["timer"] = constants.game_duration self.game_state["halftime_is_running"] = False self.game_state["game_is_running"] = True self.game_state["game_state_msg"] = "Game is running..." self.wait_for_ball_placement() def force_place(self, configuration: str): """ Force the robots to be placed somewhere :param str configuration: the name of the target configuration """ task = tasks.GoToConfigurationTask("force-place", configuration, priority=50) self.control.add_task(task) def place_game(self, configuration: str): """ Place the robot for the current game setup :param str configuration: the target configuration """ if configuration == "standard": if self.game_state["teams"][utils.robot_teams()[1]]["x_positive"]: configuration = "game_blue_positive" else: configuration = "game_green_positive" self.reset_penalties() elif configuration == "swap_covers": if self.game_state["teams"][utils.robot_teams()[1]]["x_positive"]: configuration = "swap_covers_blue_positive" else: configuration = "swap_covers_green_positive" self.force_place(configuration) def increment_score(self, team: str, increment: int): """ Increments a team score :param str team: team name :param int increment: how much should be incremented """ self.game_state["teams"][team]["score"] += increment def reset_score(self): """ Reset team scores """ for team in utils.robot_teams(): self.game_state["teams"][team]["score"] = 0 def add_referee_history(self, team: str, action: str) -> list: """ Adds an entry to the referee history :param str team: the team :param str action: action :return list: the referee history entry created """ timestamp = math.ceil(self.game_state["timer"]) i = len(self.referee_history) new_history_line = [i, timestamp, team, action] self.referee_history.append(new_history_line) return self.referee_history def reset_penalties(self): """ Resets all robot penalties """ for robot_id in utils.all_robots_id(): self.cancel_penalty(robot_id) def add_penalty(self, duration: float, robot: str, reason: str = "manually_penalized"): """ Adds some penalty to a r obot :param float duration: the penalty duration :param str robot: the target robot :param str reason: penalty reason, defaults to "manually_penalized" """ self.penalties[robot]["reason"] = reason if self.penalties[robot]["remaining"] is None: self.penalties[robot]["remaining"] = float(duration) team, number = utils.robot_str2list(robot) task_name = "penalty-" + robot self.logger.info(f"Adding penalty for robot {robot}, reason: {reason}") if robot in self.state_info["markers"]: x, y = self.state_info["markers"][robot]["position"] # Find the nearest free penalty spot distance = [ math.dist((x, y), penalty_spot["pos"][:2]) if penalty_spot["robot"] is None and time.time() - penalty_spot["last_use"] > constants.penalty_spot_lock_time else math.inf for penalty_spot in self.penalty_spot ] free_penaltly_spot_index = distance.index(min(distance)) target = self.penalty_spot[free_penaltly_spot_index]["pos"] self.penalty_spot[free_penaltly_spot_index]["robot"] = robot self.logger.info(f"---- Penalty Spot : {free_penaltly_spot_index}") task = tasks.GoToTask(task_name, team, number, target, forever=True) else: task = tasks.StopTask(task_name, team, number) self.control.add_task(task) else: self.penalties[robot]["remaining"] += float(duration) def cancel_penalty(self, robot: str): """ Cancels a robot's penalty :param str robot: the robot """ self.penalties[robot] = {"remaining": None, "reason": None, "grace": constants.grace_time} penalty_spot = [spot for spot in self.penalty_spot if spot["robot"] == robot] if penalty_spot != []: penalty_spot[0]["last_use"] = time.time() penalty_spot[0]["robot"] = None # Replacing the control task with a one-time stop to ensure the robot is not moving team, number = utils.robot_str2list(robot) task = tasks.StopTask("penalty-" + robot, team, number, forever=False) self.control.add_task(task) def tick_penalties(self, elapsed: float): """ Update robot penalties and grace time :param float elapsed: time elapsed since last tick """ for robot in self.penalties: if self.penalties[robot]["remaining"] is not None: self.penalties[robot]["remaining"] -= elapsed if self.penalties[robot]["remaining"] < 0: self.cancel_penalty(robot) if self.penalties[robot]["grace"] is not None: self.penalties[robot]["grace"] -= elapsed if self.penalties[robot]["grace"] < 0: self.penalties[robot]["grace"] = None def can_be_penalized(self, robot: str) -> bool: """ Can a given robot be penalized? It can be penalized if: * It is not already penalized * Its grace time is not expired * It has no other tasks to do (it is not preempted) :param str robot: robot :return bool: True if the robot can be penalized """ tasks = self.control.robot_tasks(*utils.robot_str2list(robot)) return ( len(tasks) == 0 and (self.penalties[robot]["remaining"] is None) and (self.penalties[robot]["grace"] is None) ) def set_team_name(self, team: str, name: str): self.game_state["teams"][team]["name"] = name def swap_team_sides(self): """ Swap team sides (x positive referring to the team defending goals on the positive x axis of field) """ for team in self.game_state["teams"]: self.game_state["teams"][team]["x_positive"] = not self.game_state["teams"][team]["x_positive"] def validate_goal(self, yes_no: bool): """ Handles goal validation by user :param bool yes_no: whether the goal is validated or canceller """ if yes_no: if self.game_state["teams"]["blue"]["x_positive"]: self.force_place("game_blue_positive") else: self.force_place("game_green_positive") self.wait_for_ball_placement() self.goal_validated = True else: self.increment_score(self.referee_history[-1][2], -1) self.goal_validated = False self.resume_game() def check_line_crosses(self, ball_coord: np.ndarray, ball_coord_old: np.ndarray): """ Checks for line crosses (sideline crosses and goals) :param np.ndarray ball_coord: ball position (now) :param np.ndarray ball_coord_old: ball position on previous frame """ [x_pos_goals_low, x_pos_goals_high] = constants.goal_posts(x_positive=True) [x_neg_goals_high, x_neg_goals_low] = constants.goal_posts(x_positive=False) [field_UpRight_in, _, field_DownLeft_in, _] = constants.field_corners(margin=constants.field_in_margin) [field_UpRight_out, field_DownRight_out, field_DownLeft_out, field_UpLeft_out] = constants.field_corners( margin=constants.field_out_margin ) # Goals and ball trajectory intersection (Goal detection) intersect_x_neg_goal, _ = utils.intersect(ball_coord_old, ball_coord, x_neg_goals_low, x_neg_goals_high) intersect_x_pos_goal, _ = utils.intersect(ball_coord_old, ball_coord, x_pos_goals_low, x_pos_goals_high) intersect_goal = intersect_x_neg_goal or intersect_x_pos_goal if intersect_goal and not self.ball_out_field: goal_team = self.positive_team if intersect_x_neg_goal else self.negative_team self.logger.info(f"Goal for team {goal_team}") self.ball_out_field = True self.increment_score(goal_team, 1) self.add_referee_history(goal_team, "Goal") self.reset_penalties() self.pause_game("goal") self.game_state["game_state_msg"] = "Waiting for Goal Validation" # Sideline (field+margin) and ball trajectory intersection (Sideline fool detection) intersect_field_Upline_out = utils.intersect(ball_coord_old, ball_coord, field_UpLeft_out, field_UpRight_out) intersect_field_DownLine_out = utils.intersect(ball_coord_old, ball_coord, field_DownLeft_out, field_DownRight_out) intersect_field_LeftLine_out = utils.intersect(ball_coord_old, ball_coord, field_UpLeft_out, field_DownLeft_out) intersect_field_RightLine_out = utils.intersect(ball_coord_old, ball_coord, field_UpRight_out, field_DownRight_out) intersect_field_out = bool( intersect_field_Upline_out[0] or intersect_field_RightLine_out[0] or intersect_field_DownLine_out[0] or intersect_field_LeftLine_out[0] ) if intersect_field_out and not intersect_goal and not self.ball_out_field: for intersection in ( intersect_field_Upline_out, intersect_field_DownLine_out, intersect_field_LeftLine_out, intersect_field_RightLine_out, ): has_intersection, point = intersection if has_intersection: target = ( (1 if point[0] > 0 else -1) * constants.dots_x, (1 if point[1] > 0 else -1) * constants.dots_y, ) self.wait_for_ball_placement(target) self.ball_out_field = True self.add_referee_history("neutral", "Sideline crossed") self.pause_game("sideline-crossed") # Verification that the ball has been inside a smaller field (field-10cm margin) at least once before a new goal or a sideline foul is detected if self.ball_out_field and utils.in_rectangle(ball_coord, field_DownLeft_in, field_UpRight_in): self.ball_out_field = False def penalize_fools(self, elapsed: float): """ Penalize robots that are not respecting some rules :param float elapsed: elapsed time (s) since last tick """ # Checking the robot respect timed circle and defense area rules defender = {} for marker in self.state_info["markers"]: team, number = utils.robot_str2list(marker) robot_position = np.array(self.state_info["markers"][marker]["position"]) if team in utils.robot_teams(): robot = (team, number) # Penalizing robots that are staying close to the ball if self.state_info["ball"] is not None and self.can_be_penalized(marker): ball_position = np.array(self.state_info["ball"]) distance = np.linalg.norm(ball_position - robot_position) if distance < constants.timed_circle_radius: if self.timed_circle_timers[(team, number)] is None: self.timed_circle_timers[robot] = 0 else: self.timed_circle_timers[robot] += elapsed if self.timed_circle_timers[robot] > constants.timed_circle_time: self.add_penalty(constants.default_penalty, marker, "ball_abuse") else: self.timed_circle_timers[(team, number)] = None else: self.timed_circle_timers[(team, number)] = None # Penalizing extra robots that are entering the defense area if self.can_be_penalized(marker): my_defense_area = constants.defense_area(self.positive_team == team) opponent_defense_area = constants.defense_area(self.positive_team != team) # This is penalizing robots for abusive attack (suspended) if utils.in_rectangle(robot_position, *opponent_defense_area): self.add_penalty(constants.default_penalty, marker, "abusive_attack") if utils.in_rectangle(robot_position, *my_defense_area): if team in defender: other_robot, other_robot_position = defender[team] robot_to_penalize = marker if abs(other_robot_position[0]) < abs(robot_position[0]): robot_to_penalize = other_robot self.add_penalty(constants.default_penalty, robot_to_penalize, "abusive_defense") else: defender[team] = [marker, robot_position] def thread(self): """ Referee thread """ self.ball_out_field = False wait_ball_timestamp = None ball_coord_old = np.array([0, 0]) self.game_state["game_state_msg"] = "Game is ready to start" last_tick = time.time() while True: self.state_info = copy.deepcopy(self.state.get_state()) self.state.set_referee(self.get_game_state()) self.control.allow_extra_features = not self.game_state["game_is_running"] elapsed = time.time() - last_tick if self.chrono_is_running: self.game_state["timer"] -= elapsed last_tick = time.time() # Updating positive and negative teams all_teams = utils.robot_teams() if self.game_state["teams"][all_teams[0]]["x_positive"]: self.positive_team, self.negative_team = all_teams else: self.negative_team, self.positive_team = all_teams if not self.game_state["game_paused"]: if self.state_info is not None: if self.state_info["ball"] is not None: ball_coord = np.array(self.state_info["ball"]) if (ball_coord != ball_coord_old).any(): self.check_line_crosses(ball_coord, ball_coord_old) ball_coord_old = ball_coord self.penalize_fools(elapsed) self.tick_penalties(elapsed) else: # Waiting for the ball to be at a specific position to resume the game if ( (self.wait_ball_position is not None) and (self.state_info is not None) and (self.state_info["ball"] is not None) ): distance = np.linalg.norm(np.array(self.wait_ball_position) - np.array(self.state_info["ball"])) if distance < constants.place_ball_margin: if wait_ball_timestamp is None: wait_ball_timestamp = time.time() elif time.time() - wait_ball_timestamp >= 1: self.game_state["game_state_msg"] = "Game is running..." self.goal_validated = None self.resume_game() else: wait_ball_timestamp = None time.sleep(0.1)
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/referee.py
0.537284
0.239683
referee.py
pypi
class RobotError(Exception): ... class Robot: def __init__(self, url: str): # Port name self.url: str = url # Robot state (e.g: battery level) self.state: dict = {} # Should leds be re-set self.leds_dirty: bool = False # Timestamp of the last received packet from the robot self.last_message = None # Marker on the top of this robot self.marker = None def available_urls() -> list: return [] def set_marker(self, marker: str) -> None: """ Sets the robot's marker :param str marker: the robot marker """ self.marker = marker def kick(self, power: float) -> None: """ Kicks :param float power: kick power (0-1) :raises RobotError: if the operation is not supported """ raise RobotError("This robot can't kick") def control(self, dx: float, dy: float, dturn: float) -> None: """ Controls the robot velocity :param float dx: x axis (robot frame) velocity [m/s] :param float dy: y axis (robot frame) velocity [m/s] :param float dturn: rotation (robot frame) velocity [rad/s] :raises RobotError: if the operation is not supported """ raise RobotError("This robot can't move") def leds(self, red: int, green: int, blue: int) -> None: """ Controls the robot LEDs :param int red: red brightness (0-255) :param int green: green brightness (0-255) :param int blue: blue brightness (0-255) :raises RobotError: if the operation is not supported """ ... def beep(self, frequency: int, duration: int) -> None: """ Gets the robot beeping :param int frequency: frequency (Hz) :param int duration: duration (ms) :raises RobotError: if the operation is not supported """ ... def teleport(self, x: float, y: float, theta: float) -> None: """ Teleports the robot to a given position/orientation :param float x: x position [m] :param float y: y position [m] :param float theta: orientation [rad] :raises RobotError: if the operation is not supported """ raise RobotError("This robot can't be teleported")
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/robot.py
0.912539
0.629006
robot.py
pypi
import time import numpy as np import cv2 import os import base64 import threading from . import detection, config resolutions = [ (320, 240), (352, 288), (640, 360), (640, 480), (800, 600), (800, 448), (864, 480), (848, 480), (960, 544), (960, 720), (1024, 576), (1024, 768), (1280, 720), (1600, 896), (1920, 1080), ] is_windows = os.name == "nt" class Video: """ Handles video capture from the camera """ def __init__(self): # Limitting the output period self.min_period = 1 / 60 # Image retrieve and processing duration self.period = None # Current capture self.capture = None # The last retrieved image self.image = None # Debug output self.debug = False # Ask main thread to stop capture self.should_stop_capture = False self.detection = detection.Detection() self.settings = { "brightness": 0, "contrast": 0, "saturation": 100, "gain": 0, "crop_x": 100, "crop_y": 100, "rescale": 100, "exposure": -7 if is_windows else 100, "focal": 885, } self.favourite_index = None self.resolution = len(resolutions) - 1 if "camera" in config.config: if "favourite_index" in config.config["camera"]: self.favourite_index = config.config["camera"]["favourite_index"] if "resolution" in config.config["camera"]: self.resolution = config.config["camera"]["resolution"] for entry in config.config["camera"]["settings"]: self.settings[entry] = config.config["camera"]["settings"][entry] # Starting the video processing thread self.running = True self.video_thread = threading.Thread(target=lambda: self.thread()) self.video_thread.start() def cameras(self) -> list: """ Build a list of available cameras :return list: a list containing possible indexes and favourite one (None if no favourite) """ if self.capture is None: indexes = [] for index in range(10): cap = cv2.VideoCapture(index, cv2.CAP_DSHOW if is_windows else None) if cap.read()[0]: if self.favourite_index is None: self.favourite_index = index indexes.append(index) cap.release() return [indexes, self.favourite_index] else: return [[], None] def resolutions(self) -> list: """ Returns all possible resolutions :return list: a list of possible resolutions """ res = ["%d x %d" % res for res in resolutions] return [self.resolution, res] def save_config(self): """ Save the configuration """ config.config["camera"] = { "favourite_index": self.favourite_index, "resolution": self.resolution, "settings": self.settings, } config.save() def start_capture(self, index: int, resolution: int) -> bool: """ Starts video capture :param int index: the camera index to use :param int resolution: the resolution index to use :return bool: whether the capture started """ self.capture = cv2.VideoCapture(index) w, h = resolutions[resolution] self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, w) self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, h) self.capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc("M", "J", "P", "G")) self.favourite_index = index self.resolution = resolution self.apply_camera_settings() self.save_config() time.sleep(0.1) return self.image is not None def stop_capture(self) -> None: """ Stop video capture """ self.should_stop_capture = True def stop(self) -> None: """ Stop execution of threads """ self.running = False self.stop_capture() def apply_camera_settings(self) -> None: """ Use camera settings to set OpenCV properties on capture stream """ if self.capture is not None: self.capture.set(cv2.CAP_PROP_BRIGHTNESS, self.settings["brightness"]) self.capture.set(cv2.CAP_PROP_CONTRAST, self.settings["contrast"]) self.capture.set(cv2.CAP_PROP_SATURATION, self.settings["saturation"]) self.capture.set(cv2.CAP_PROP_GAIN, self.settings["gain"]) self.capture.set(cv2.CAP_PROP_AUTOFOCUS, 0) self.capture.set(cv2.CAP_PROP_FOCUS, 0) self.capture.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1.0) self.capture.set(cv2.CAP_PROP_EXPOSURE, self.settings["exposure"]) if self.resolution is not None: w, h = resolutions[self.resolution] self.detection.field.focal = self.settings["focal"] * (h / 1080) * (self.settings["rescale"] / 100.0) def set_camera_settings(self, settings: dict): """ Set camera settings, save and apply them :param dict settings: settings """ self.settings = settings self.save_config() self.apply_camera_settings() def thread(self): """ Main video capture thread """ if self.favourite_index is not None and self.resolution is not None: self.start_capture(self.favourite_index, self.resolution) while self.running: if self.capture is not None: try: t0 = time.time() grabbed, image_captured = self.capture.read() image_debug = None if image_captured is not None: height, width, channels = image_captured.shape frame_size = np.array([width, height]) if "crop_x" in self.settings and "crop_y" in self.settings: if self.settings["crop_x"] < 100 or self.settings["crop_y"] < 100: frame_size[0] = round(frame_size[0] * self.settings["crop_x"] / 100.0) frame_size[1] = round(frame_size[1] * self.settings["crop_y"] / 100.0) x_offset = round((width - frame_size[0]) / 2.0) y_offset = round((height - frame_size[1]) / 2.0) image_captured = image_captured[ y_offset : y_offset + frame_size[1], x_offset : x_offset + frame_size[0] ] if "rescale" in self.settings and self.settings["rescale"] < 100 and self.settings["rescale"] > 0: new_size = frame_size * self.settings["rescale"] / 100.0 image_captured = cv2.resize(image_captured, (int(new_size[0]), int(new_size[1])), cv2.INTER_LINEAR) # Process the image if self.debug: image_debug = image_captured.copy() self.detection.detect_markers(image_captured, image_debug) self.detection.detect_ball(image_captured, image_debug) self.detection.draw_annotations(image_debug) # Computing time current_period = time.time() - t0 if current_period < self.min_period: time.sleep(self.min_period - current_period) current_period = time.time() - t0 if self.period is None: self.period = current_period else: self.period = self.period * 0.9 + current_period * 0.1 self.image = image_debug if image_debug is not None else image_captured if self.should_stop_capture: self.should_stop_capture = False self.capture.release() del self.capture self.capture = None self.image = None except cv2.error as e: print("OpenCV error") print(e) else: time.sleep(0.1) def get_image(self) -> str: """ Get the current image :return str: the image contents (base64 encoded) """ if self.image is not None: data = cv2.imencode(".jpg", self.image) return base64.b64encode(data[1]).decode("utf-8") else: return "" def get_video(self, with_image: bool) -> dict: """ Get the video status :param bool with_image: whether to include the image :return dict: a dictionnary containing current status of video service """ data = { "running": self.capture is not None, "fps": round(1 / self.period, 1) if self.period is not None else 0, "detection": self.detection.get_detection(), } if with_image: data["image"] = self.get_image() return data
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/video.py
0.635562
0.234905
video.py
pypi
import numpy as np import re def frame(x, y=0, orientation=0): """ Given a position and an orientation of a body "b" in a frame "a", builds the 3x3 2D transformation matrix T_a_b: T_a_b = [ cos(alpha) -sin(alpha) x ] [ sin(alpha) cos(alpha) y ] [ 0 0 1 ] """ if type(x) is tuple or type(x) is list: x, y, orientation = x cos, sin = np.cos(orientation), np.sin(orientation) return np.array([[cos, -sin, x], [sin, cos, y], [0.0, 0.0, 1.0]]) def frame_inv(frame): """ Given a 3x3 2D transformation matrix T_a_b, computes T_b_a """ frame_inv = np.eye(3) R = frame[:2, :2] frame_inv[:2, :2] = R.T frame_inv[:2, 2] = -R.T @ frame[:2, 2] return frame_inv def frame_transform(frame, vector): return (frame @ [*vector, 1])[:2] def robot_frame(robot): pos = robot.position return frame(pos[0], pos[1], robot.orientation) def angle_wrap(alpha): return (alpha + np.pi) % (2 * np.pi) - np.pi def update_limit_variation(current_value: np.ndarray, target_value: np.ndarray, max_variation: float): variation = np.linalg.norm(target_value - current_value) if variation > 0: accepted_variation = min(variation, max_variation) return current_value + (target_value - current_value) * accepted_variation / variation else: return target_value def intersect(A, B, C, D): u = B - A v = D - C uv = np.vstack((u, -v)).T if np.linalg.det(uv) == 0: return (False, None) else: lambdas = np.linalg.inv(uv) @ (C - A) V = np.all(0 <= lambdas) and np.all(lambdas <= 1) if V: P = A + lambdas[0] * u return (True, P) else: return (False, None) def robot_max_number() -> int: """ The maximum number of robots :return int: Maximum number of robots per team on the field """ return 2 def robot_numbers() -> list: """ List all possible robot numbers (starting at 1) :return list: robot numbers """ return range(1, robot_max_number() + 1) def robot_teams() -> list: """ List of possible robot team (colors) :return list: possible robot team (colors) """ return ["green", "blue"] def robot_leds_color(name: str) -> list: """ Returns the LEDs color for a given name :param str name: color name :return list: list of [r, g, b] values for this color """ if name == "preempted": return [50, 0, 50] elif name == "blue": return [0, 0, 50] elif name == "green": return [0, 50, 0] else: raise NotImplemented(f"Unknown color: {name}") def all_robots() -> list: """ List of all possible robots (eg: ['blue', 1]) :return list: robots """ return [(team, number) for team in robot_teams() for number in robot_numbers()] def robot_list2str(team: str, number: int) -> str: """ Transforms a robot tuple (eg: ['blue', 1]) to a robot string (eg: 'blue1') :param str team: robot team (eg: "blue") :param int number: robot number (eg: 1) :return str: robot id (eg: blue1) """ return "%s%d" % (team, number) def robot_str2list(robot: str) -> list: """ Transforms a robot string (eg: 'blue1') to a robot list (eg: ['blue', 1]) :param str robot: string robot name (eg: 'blue1') :return list: robot id (eg: ['blue', 1]) """ matches = re.match("([^\d]+)([0-9]+)", robot) return matches[1], int(matches[2]) def all_robots_id() -> list: """ Returns all possible robot id (eg "blue1") :return list: robot ids """ return [robot_list2str(*robot) for robot in all_robots()] def in_rectangle(point: list, bottom_left: list, top_right: list) -> bool: """ Checks if a point is in a rectangle :param list point: the point (x, y) :param list bottom_left point :param list top_right point :return bool: True if the point is in the rectangle """ return (np.array(point) >= np.array(bottom_left)).all() and (np.array(point) <= np.array(top_right)).all()
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/utils.py
0.899456
0.78014
utils.py
pypi
import zmq import time class State: def __init__(self, frequency_pub=30, simulated=False): """Summary Args: frequency_pub (int, optional): publication frequency [Hz] """ self.markers: dict = {} self.ball = None self.last_updates: dict = {} self.referee: dict = {} self.simulated = simulated self.context = None self.last_time = None self.frequency_pub = frequency_pub self.leds: dict = {} def get_state(self): return { "markers": self.markers, "ball": self.ball, "referee": self.referee, "leds": self.leds, "simulated": self.simulated, } def start_pub(self): # Publishing server self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) self.socket.set_hwm(1) self.socket.bind("tcp://*:7557") def publish(self) -> None: """ Publish the detection informations on the network """ info = self.get_state() self.socket.send_json(info, flags=zmq.NOBLOCK) def _refresh(function): def inner_publish(self, *args, **kwargs): function(self, *args, **kwargs) if self.context is not None: if self.last_time is None or (time.time() - self.last_time) > (1 / self.frequency_pub): self.last_time = time.time() self.publish() return inner_publish @_refresh def set_markers(self, markers): self.markers = markers for marker in markers: self.last_updates[marker] = time.time() @_refresh def set_leds(self, marker, leds): self.leds[marker] = leds @_refresh def set_marker(self, marker, position, orientation): if marker not in self.markers: self.markers[marker] = {"position": position, "orientation": orientation} else: self.markers[marker]["position"] = position self.markers[marker]["orientation"] = orientation self.last_updates[marker] = time.time() @_refresh def set_ball(self, position): self.ball = position @_refresh def set_referee(self, referee): self.referee = referee
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/state.py
0.874319
0.280068
state.py
pypi
import numpy as np from . import constants """ This file provide IK/FK kinematics for the robot. Note that there is an equivalent code embedded in the robots themselfs, allowing them to compute their own kinematics. This is only intended in the case we need to do some simulations. """ # Maxium wheel RPM [rotation/min] max_wheel_rpm: float = 150 # Wheel drive direction orientations [deg] wheel_alphas: list = [-90, 30, 150] # Wheel drive vectors drive_vectors = np.array([[np.cos(np.deg2rad(alpha)), np.sin(np.deg2rad(alpha))] for alpha in wheel_alphas]) # Inverse Kinematics matrix IK: np.ndarray = (1 / constants.wheel_radius) * np.hstack( (drive_vectors, np.array([[constants.wheel_center_spacing] * len(wheel_alphas)]).T) ) # Forward Kinematics matrix FK: np.ndarray = np.linalg.pinv(IK) # Maximum wheel speed [rad/s] max_wheel_speed: float = max_wheel_rpm * 2 * np.pi / 60 def forward_kinematics(w: np.ndarray) -> np.ndarray: """ Computes the forward kinematics (given wheel velocities [rad/s], compute the chassis velocity (xd [m/s], yd [m/s], thetad [rad/s])) Args: w (np.ndarray): wheel velocities (list of [rad/s]) Returns: np.ndarray: chassis frame speed (xd [m/s], yd [m/s], thetad [rad/s]) """ return FK @ w def inverse_kinematics(s: np.ndarray) -> np.ndarray: """ Computes the inverse kinematics (given the target chassis velocity (xd [m/s], yd [m/s], thetad [rad/s]), compute the wheel velocities [rad/s]) Args: s (np.ndarray): (xd [m/s], yd [m/s], thetad [rad/s]) Returns: np.ndarray: wheel velocities (list of [rad/s]) """ return IK @ s def clip_target_order(s: np.ndarray) -> np.ndarray: """ Clips the target order to a feasible one according to the maximum wheel velocities Args: s (np.ndarray): a chassis velocity (xd [m/s], yd [m/s], thetad [rad/s]) Returns: np.ndarray: the clipped chassis velocity (xd [m/s], yd [m/s], thetad [rad/s]) """ # Compute the wheel velocities that would be needed to reach the target chassis velocity w = inverse_kinematics(s) # Computes the highest max_wheel_speed/wheel_speed ratio that would require to resize w to make it # feasible, while preserving the vector direction ratio = max(1, max(abs(w) / max_wheel_speed)) # Since the IK/FK are linear, we can apply the same ratio to the chassis velocity return np.array(s) / ratio
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/kinematics.py
0.930513
0.624923
kinematics.py
pypi
from . import control, client, utils class ControlTask: """ A task to be managed by the control """ def __init__(self, name: str, priority: int = 0): self.name: str = name self.priority: int = priority # Available robots (passed by control) self.robots_filter = [] def robots(self) -> list: return [] def tick(self, robot: client.ClientRobot) -> None: raise NotImplemented("Task not implemented") def finished(self, client: client.Client, available_robots: list) -> bool: return False class SpeedTask: """ Gets the robot rotating """ def __init__(self, name: str, team: str, number: int, dx: float = 0, dy: float = 0, dturn: float = 0, **kwargs): super().__init__(name, **kwargs) self.team: str = team self.number: int = number self.dx: float = dx self.dy: float = dy self.dturn: float = dturn def robots(self): return [(self.team, self.number)] def tick(self, robot: client.ClientRobot): robot.control(self.dx, self.dy, self.dturn) def finished(self, client: client.Client, available_robots: list) -> bool: return False class StopAllTask(ControlTask): """ Stops all robots from moving, can be done once or forever """ def __init__(self, name: str, forever=True, **kwargs): super().__init__(name, **kwargs) self.forever = forever def robots(self): return utils.all_robots() def tick(self, robot: client.ClientRobot): robot.control(0.0, 0.0, 0.0) def finished(self, client: client.Client, available_robots: list) -> bool: return not self.forever class StopTask(StopAllTask): """ Stops one robot from moving """ def __init__(self, name: str, team: str, number: int, **kwargs): super().__init__(name, **kwargs) self.team: str = team self.number: int = number def robots(self): return [(self.team, self.number)] class GoToConfigurationTask(ControlTask): """ Send all robots to a given configuration """ def __init__(self, name: str, configuration=None, skip_old=True, robots_filter=None, forever=False, **kwargs): super().__init__(name, **kwargs) self.targets = {} self.skip_old: bool = skip_old self.forever: bool = forever if configuration is not None: for team, number, target in client.configurations[configuration]: if robots_filter is None or (team, number) in robots_filter: self.targets[(team, number)] = target def robots(self): return list(self.targets.keys()) def tick(self, robot: client.ClientRobot): robot.goto(self.targets[(robot.team, robot.number)], False, skip_old=self.skip_old) def finished(self, client: client.Client, available_robots: list) -> bool: if self.forever: return False for robot in available_robots: team, number = utils.robot_str2list(robot) if (team, number) in self.targets: arrived, _ = client.robots[team][number].goto_compute_order( self.targets[(team, number)], skip_old=self.skip_old ) if not arrived: return False for robot in available_robots: if (team, number) in self.targets: team, number = utils.robot_str2list(robot) client.robots[team][number].control(0.0, 0.0, 0.0) return True class GoToTask(GoToConfigurationTask): """ Send one robot to a position """ def __init__(self, name: str, team: str, number: int, target, skip_old=True, **kwargs): super().__init__(name, **kwargs) self.targets[(team, number)] = target
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/tasks.py
0.813794
0.336808
tasks.py
pypi
import numpy as np import cv2 import zmq import time from .field import Field from . import constants, config import os os.environ["OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS"] = "0" class Detect: def __init__(self): # Video attribute self.detection = self self.capture = None self.period = None self.referee = None # Publishing server self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) self.socket.set_hwm(1) self.socket.bind("tcp://*:7557") self.field = Field() class Detection: def __init__(self): self.state = None self.referee = None # ArUco parameters if self.is_new_aruco_api(): dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50) parameters = cv2.aruco.DetectorParameters() self.detector = cv2.aruco.ArucoDetector(dictionary, parameters) else: self.arucoDict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_50) self.arucoParams = cv2.aruco.DetectorParameters_create() # arucoParams.cornerRefinementMethod = cv2.aruco.CORNER_REFINE_APRILTAG # Goals Colors self.team_colors = {"green": (0, 255, 0), "blue": (255, 0, 0)} self.canceled_goal_side = None self.displaySettings = { "aruco": {"label": "ArUco Markers", "default": True}, "ball": {"label": "Ball", "default": True}, "goals": {"label": "Goals", "default": True}, "landmark": {"label": "Center Landmark", "default": True}, "penalty_spot": {"label": "Penalty Spot", "default": False}, "sideline": {"label": "Sideline Delimitations", "default": False}, "timed_circle": {"label": "Timed Circle", "default": False}, } self.reset_display_settings() if "display_settings" in config.config: for entry in config.config["display_settings"]: self.displaySettings[entry]["value"] = config.config["display_settings"][entry] self.arucoItems = { # Corners 0: ["c1", (128, 128, 0)], 1: ["c2", (128, 128, 0)], 2: ["c3", (128, 128, 0)], 3: ["c4", (128, 128, 0)], # Green 4: ["green1", (0, 128, 0)], 5: ["green2", (0, 128, 0)], # Blue 6: ["blue1", (128, 0, 0)], 7: ["blue2", (128, 0, 0)], # Generic objects 8: ["obj1", (128, 128, 0)], 9: ["obj2", (128, 128, 0)], 10: ["obj3", (128, 128, 0)], 11: ["obj4", (128, 128, 0)], 12: ["obj5", (128, 128, 0)], 13: ["obj6", (128, 128, 0)], 14: ["obj7", (128, 128, 0)], 15: ["obj8", (128, 128, 0)], } # Ball detection parameters (HSV thresholds) self.lower_orange = np.array([0, 150, 150]) self.upper_orange = np.array([25, 255, 255]) # Detection output self.markers = {} self.last_updates = {} self.ball = None self.no_ball = 0 self.field = Field() def is_new_aruco_api(self) -> bool: """ Aruco API changed slightly in opencv >= 4.7, see: https://stackoverflow.com/questions/74964527/attributeerror-module-cv2-aruco-has-no-attribute-dictionary-get We check OpenCV version and assume """ (major, minor, _) = cv2.__version__.split(".") if int(major) < 4 or (int(major) == 4 and int(minor) <= 6): # OpenCV <= 4.6 return False else: # OpenCV > 4.6 return True def should_display(self, entry: list) -> bool: return self.displaySettings[entry]["value"] def set_display_setting(self, entry: str, value: bool): self.displaySettings[entry]["value"] = value self.save_display_settings() def reset_display_settings(self): for entry in self.displaySettings: self.displaySettings[entry]["value"] = self.displaySettings[entry]["default"] def get_display_settings(self, reset=False): if reset: self.reset_display_settings() self.save_display_settings() return self.displaySettings def save_display_settings(self): config.config["display_settings"] = {key: self.displaySettings[key]["value"] for key in self.displaySettings} config.save() def calibrate_camera(self): self.field.should_calibrate = True self.field.is_calibrated = False def draw_point2square(self, image, center: list, margin: int, color: tuple, thickness: int): """ Helper to draw a square on the image """ pointA = self.field.position_to_pixel([center[0] - margin, center[1] + margin]) pointB = self.field.position_to_pixel([center[0] + margin, center[1] + margin]) pointC = self.field.position_to_pixel([center[0] + margin, center[1] - margin]) pointD = self.field.position_to_pixel([center[0] - margin, center[1] - margin]) cv2.line(image, pointA, pointB, color, thickness) cv2.line(image, pointB, pointC, color, thickness) cv2.line(image, pointC, pointD, color, thickness) cv2.line(image, pointD, pointA, color, thickness) def draw_circle( self, image, center: list, radius: float, color: tuple, thickness: int, points: int = 32, dashed: bool = False, ): """ Helper to draw a circle on the image """ first_point = None last_point = None k = 0 for alpha in np.linspace(0, 2 * np.pi, points): new_point = [ center[0] + np.cos(alpha) * radius, center[1] + np.sin(alpha) * radius, 0, ] if last_point: A = self.field.position_to_pixel(last_point) B = self.field.position_to_pixel(new_point) k += 1 if not dashed or k % 2 == 0: cv2.line(image, A, B, color, thickness) last_point = new_point if first_point is None: first_point = new_point def draw_annotations(self, image_debug): """ Draw extra annotations (lines, circles etc.) to check visually that the informations are matching the real images """ if self.field.calibrated() and (image_debug is not None) and (self.referee is not None): if self.should_display("sideline"): [ field_UpRight, field_DownRight, field_DownLeft, field_UpLeft, ] = constants.field_corners(constants.field_in_margin) A = self.field.position_to_pixel(field_UpRight) B = self.field.position_to_pixel(field_DownRight) C = self.field.position_to_pixel(field_DownLeft) D = self.field.position_to_pixel(field_UpLeft) cv2.line(image_debug, A, B, (0, 255, 0), 1) cv2.line(image_debug, B, C, (0, 255, 0), 1) cv2.line(image_debug, C, D, (0, 255, 0), 1) cv2.line(image_debug, D, A, (0, 255, 0), 1) [ field_UpRight, field_DownRight, field_DownLeft, field_UpLeft, ] = constants.field_corners(constants.field_out_margin) A = self.field.position_to_pixel(field_UpRight) B = self.field.position_to_pixel(field_DownRight) C = self.field.position_to_pixel(field_DownLeft) D = self.field.position_to_pixel(field_UpLeft) cv2.line(image_debug, A, B, (0, 0, 255), 1) cv2.line(image_debug, B, C, (0, 0, 255), 1) cv2.line(image_debug, C, D, (0, 0, 255), 1) cv2.line(image_debug, D, A, (0, 0, 255), 1) if self.should_display("goals"): for sign, color in [ (-1, self.team_colors[self.referee.negative_team]), (1, self.team_colors[self.referee.positive_team]), ]: C = self.field.position_to_pixel( [ sign * (constants.field_length / 2.0), -sign * constants.goal_width / 2.0, ] ) D = self.field.position_to_pixel( [ sign * (constants.field_length / 2.0), sign * constants.goal_width / 2.0, ] ) E = self.field.position_to_pixel( [ sign * (constants.field_length / 2.0), -sign * constants.goal_width / 2.0, constants.goal_virtual_height, ] ) F = self.field.position_to_pixel( [ sign * (constants.field_length / 2.0), sign * constants.goal_width / 2.0, constants.goal_virtual_height, ] ) cv2.line(image_debug, C, D, color, 3) cv2.line(image_debug, E, F, color, 2) cv2.line(image_debug, C, E, color, 2) cv2.line(image_debug, D, F, color, 2) for post in [-1, 1]: A = self.field.position_to_pixel( [ sign * (0.05 + constants.field_length / 2.0), post * constants.goal_width / 2.0, ] ) B = self.field.position_to_pixel( [ sign * (constants.field_length / 2.0), post * constants.goal_width / 2.0, ] ) cv2.line(image_debug, A, B, color, 3) if self.should_display("landmark"): A = self.field.position_to_pixel([0, 0]) B = self.field.position_to_pixel([0.2, 0]) cv2.line(image_debug, A, B, (0, 0, 255), 1) A = self.field.position_to_pixel([0, 0]) B = self.field.position_to_pixel([0, 0.2]) cv2.line(image_debug, A, B, (0, 255, 0), 1) A = self.field.position_to_pixel([0, 0, 0]) B = self.field.position_to_pixel([0, 0, 0.2]) cv2.line(image_debug, A, B, (255, 0, 0), 1) if self.should_display("timed_circle") and self.ball is not None: self.draw_circle( image_debug, self.ball, constants.timed_circle_radius, (0, 0, 255), 1, dashed=True, ) if self.should_display("penalty_spot"): for penalty_spot in self.referee.penalty_spot: color = (0, 255, 0) if penalty_spot["robot"] is not None: color = (0, 0, 255) elif time.time() - penalty_spot["last_use"] < constants.penalty_spot_lock_time: color = (0, 128, 255) self.draw_point2square( image_debug, penalty_spot["pos"][:-1], 0.1, color, 5, ) if self.referee.wait_ball_position is not None: self.draw_circle( image_debug, self.referee.wait_ball_position, constants.place_ball_margin, (0, 165, 255), 2, 16, ) def detect_markers(self, image, image_debug=None): """ Detect the fiducial markers on the image, they are passed to the field for calibration """ if self.is_new_aruco_api(): (corners, ids, rejected) = self.detector.detectMarkers(image) else: (corners, ids, rejected) = cv2.aruco.detectMarkers(image, self.arucoDict, parameters=self.arucoParams) new_markers = {} if len(corners) > 0: for markerCorner, markerID in zip(corners, ids.flatten()): if markerID not in self.arucoItems: continue corners = markerCorner.reshape((4, 2)) # Draw the bounding box of the ArUCo detection item = self.arucoItems[markerID][0] if item[0] == "c": self.field.set_corner_position(item, corners) if image_debug is not None: (topLeft, topRight, bottomRight, bottomLeft) = corners topRight = (int(topRight[0]), int(topRight[1])) bottomRight = (int(bottomRight[0]), int(bottomRight[1])) bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1])) topLeft = (int(topLeft[0]), int(topLeft[1])) itemColor = self.arucoItems[markerID][1] if self.should_display("aruco"): cv2.line(image_debug, topLeft, topRight, itemColor, 2) cv2.line(image_debug, topRight, bottomRight, itemColor, 2) cv2.line(image_debug, bottomRight, bottomLeft, itemColor, 2) cv2.line(image_debug, bottomLeft, topLeft, itemColor, 2) # Compute and draw the center (x, y)-coordinates of the # ArUco marker cX = int((topLeft[0] + bottomRight[0]) / 2.0) cY = int((topLeft[1] + bottomRight[1]) / 2.0) cv2.circle(image_debug, (cX, cY), 4, (0, 0, 255), -1) fX = int((topLeft[0] + topRight[0]) / 2.0) fY = int((topLeft[1] + topRight[1]) / 2.0) cv2.line( image_debug, (cX, cY), (cX + 2 * (fX - cX), cY + 2 * (fY - cY)), (0, 0, 255), 2, ) text = item if item.startswith("blue") or item.startswith("green"): text = item[-1] cv2.putText( image_debug, text, (cX - 4, cY + 4), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 6, ) cv2.putText( image_debug, text, (cX - 4, cY + 4), cv2.FONT_HERSHEY_SIMPLEX, 0.5, itemColor, 2, ) if self.field.calibrated() and item[0] != "c": new_markers[item] = self.field.pose_of_tag(corners) self.last_updates[item] = time.time() self.field.update_calibration(image) self.state.set_markers(new_markers) def detect_ball(self, image, image_debug): """ Detects the ball in the image """ # Converts the image to HSV and apply a threshold hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, self.lower_orange, self.upper_orange) # Detect connected components output = cv2.connectedComponentsWithStats(mask, 8, cv2.CV_32S) num_labels = output[0] stats = output[2] centroids = output[3] # Walk through candidates candidates = [] for k in range(1, num_labels): if stats[k][4] > 3: candidates.append(list(centroids[k])) if len(candidates) > 16: break # For each candidate, we will then check which one is the best (closest to previous estimation) if len(candidates): best = None bestPx = None bestDist = None self.no_ball = 0 for point in candidates: if self.field.calibrated(): pos = self.field.pixel_to_position(point, constants.ball_height) else: pos = point if self.ball: dist = np.linalg.norm(np.array(pos) - np.array(self.ball)) else: dist = 0 if best is None or dist < bestDist: bestDist = dist best = pos bestPx = point if self.should_display("ball"): if image_debug is not None and best: cv2.circle( image_debug, (int(bestPx[0]), int(bestPx[1])), 3, (255, 255, 0), 3, ) if self.field.calibrated(): self.ball = best else: self.no_ball += 1 if self.no_ball > 10: self.ball = None self.state.set_ball(self.ball) def get_detection(self, foo=None): while True: try: return { "ball": self.ball, "markers": self.markers, "calibrated": self.field.calibrated(), "see_whole_field": self.field.see_whole_field, "referee": None if self.referee is None else self.referee.get_game_state(full=False), } except Exception as err: print("Thread init error : ", err)
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/detection.py
0.544801
0.183777
detection.py
pypi
from . import api from . import ( state, video, robots, robot_serial, control, referee, detection, utils, constants, simulator, ) class Backend: def __init__(self, simulated=False, competition=False): super().__init__() robots.Robots.protocols["serial"] = robot_serial.RobotSerial self.simulated = simulated self.competition = competition self.state: state.State = state.State(30, self.simulated) self.state.start_pub() self.referee: referee.Referee = referee.Referee(self.state) self.control: control.Control = self.referee.control self.robots: robots.Robots = robots.Robots(self.state) if simulated: robots.Robots.protocols["sim"] = simulator.RobotSim self.simulator: simulator.Simulator = simulator.Simulator(self.robots, self.state) else: self.robots.load_config() self.video: video.Video = video.Video() self.detection: detection.Detection = self.video.detection self.detection.state = self.state self.detection.referee = self.referee self.control.robots = self.robots self.control.start() def is_competition(self): return self.competition def is_simulated(self): return self.simulated def cameras(self): return self.video.cameras() def constants(self) -> dict: # Retrieving all values declared in constants.py values: dict = {} constant_variables = vars(constants) for name in constant_variables: if type(constant_variables[name]) in [int, bool, float]: values[name] = constant_variables[name] # Adding team colors values["team_colors"] = utils.robot_teams() return values def get_state(self): return self.state.get_state() def resolutions(self): return self.video.resolutions() def getCameraSettings(self): return self.video.settings def start_capture(self, index: int, res: int) -> bool: return self.video.start_capture(index, res) def stop_capture(self): self.video.stop_capture() def get_image(self) -> str: image = self.video.get_image() return image def get_video(self, with_image: bool) -> dict: return self.video.get_video(with_image) def enableVideoDebug(self, enable=True) -> bool: self.video.debug = enable def cameraSettings(self, settings): self.video.set_camera_settings(settings) return True def available_urls(self): return self.robots.available_urls() def add_robot(self, url: str): self.robots.add_robot(url) def get_robots(self): return self.robots.get_robots() def set_marker(self, url: str, marker): self.robots.set_marker(url, marker) def removeRobot(self, url: str): self.robots.remove(url) def blink(self, url: str): if url in self.robots.robots: self.robots.robots[url].blink() def kick(self, url: str): if url in self.robots.robots: self.robots.robots[url].kick() def teleport(self, marker: str, x: float, y: float, turn: float): if marker in self.robots.robots_by_marker or marker == "ball": self.simulator.objects[marker].teleport(x, y, turn) def control_status(self): return self.control.status() def allow_team_control(self, team: str, allow: bool): self.control.allow_team_control(team, allow) def emergency(self): self.control.emergency() def set_key(self, team: str, key: str): self.control.set_key(team, key) def identify(self): self.robots.identify() def startReferee(self): self.referee.startReferee() def stopReferee(self): self.referee.stopReferee() def increment_score(self, team: str, increment: int): self.referee.increment_score(team, increment) def reset_score(self): self.referee.reset_score() def set_display_setting(self, entry: str, value: bool): self.detection.set_display_setting(entry, value) def get_display_settings(self, reset: bool = False) -> list: return self.detection.get_display_settings(reset) def start_game(self): self.referee.start_game() def pause_game(self): self.referee.pause_game() def resume_game(self): self.referee.resume_game() def stop_game(self): self.referee.stop_game() def calibrate_camera(self): self.detection.calibrate_camera() def place_game(self, configuration: str): self.referee.place_game(configuration) def set_team_name(self, team: str, name: str): self.referee.set_team_name(team, name) def swap_team_sides(self) -> str: self.referee.swap_team_sides() def start_half_time(self): self.referee.start_half_time() def start_second_half_time(self): self.referee.start_second_half_time() def add_penalty(self, duration: int, robot: str): self.referee.add_penalty(duration, robot) def cancel_penalty(self, robot) -> str: self.referee.cancel_penalty(robot) def get_game_state(self) -> dict: return self.referee.get_game_state() def get_wait_ball_position(self): return self.referee.wait_ball_position def validate_goal(self, yes_no: bool): self.referee.validate_goal(yes_no)
/robot-soccer-kit-2.1.1.tar.gz/robot-soccer-kit-2.1.1/rsk/backend.py
0.780788
0.330417
backend.py
pypi
# Robot soccer Python ![Version](https://img.shields.io/static/v1?label=Version&message=1.0.4&color=7159c1?style=for-the-badge) ![Version](https://img.shields.io/static/v1?label=Dependence&message=pygame&color=red) ![](https://user-images.githubusercontent.com/50979367/125829618-9f371d88-ff18-4107-8a0d-60ede54bb0e6.PNG) **robot_soccer_python** is a robot soccer simulation 2D environment for python. I create this project to study AI applied to robot. With this project, you will need only programming the robots' brain. Lets take a look bellow how to install and use this open-source project! ## Installation To install this project is very simple, you only need to write the command bellow in your prompt terminal: ```bash pip install robot_soccer_python ``` And that's it! Very simple, isn't it? ## Usage To use, I need to explain the classes and methods that you will need. #### Pose This class is used to write a position on the environment. To import you have to write: ```python from robot_soccer_python.agents Pose ``` And you have to pass the position x, y and rotation in the plane xy for this class, like ```Pose(x,y,rotation)```, remember, rotation is zero when the robot is turn to the positive sense of axis x and π in the negative sense. #### Player This class is used to get and set all the information about the robots. To import this class and initialize a player you have to do: ```python from robot_soccer_python.agents import Player player = Player(Pose(3, 3, 0), 2, 2, 0.2) ``` The **first argument** is the initial position of the player, the **second** is maximum linear speed that this player will achieve, the **third** is the maximum angular speed and the **last parameter** is the radius of the robot (because the robots are circles and you can change the size). #### simulation2D This class is the most important class that you will need. In this class you will configure the parameters of the simulation, like the list of players and you will get the information about the sensors of the robots. To configure the simulation, you have to do: ```python from robot_soccer_python.simulation2D import simulation2D simulation = simulation2D([ Player(Pose(3, 3, 0), 2, 2, 0.2), Player(Pose(6, 3, 0), 2, 2, 0.2)], shockable=True, full_vision=False) ``` The first argument is the list of players, the second is if you want that the robots can shock with each other (Like the Pauli exclusion principle "two bodies cannot occupy the same space") or if you don't want this physic principle. The last argument is if you want that the robots will see all in the environment, or if they will see only the the field and players in their field vision. To get the information about the sensors of all the players, you have to do: ```python simulation.get_sensors() ``` #### init_simulation To pass the frames of the simulation you only need to call this class. Like demonstrad bellow: ```python from robot_soccer_python.simulation2D import init_simulation init_simulation(simulation) ``` # Example A example of a simple simulation is: ```python from robot_soccer_python.simulation2D import simulation2D, init_simulation from robot_soccer_python.agents import Player, Pose import time simulation = simulation2D( [Player(Pose(3, 3, 0), 2, 2, 0.2), Player(Pose(6, 3, 0), 2, 2, 0.2)], shockable=True, full_vision=False) now = time.time() now2 = time.time() command1 = (0, 0) command2 = (0, 0) while True: if time.time() - now > 2: command1 = (1 + command1[0], 1 + command1[1]) command2 = (1 + command2[0], - 1 + command2[1]) now = time.time() if time.time() - now2 < 3: simulation.set_commands([command1, command2]) else: simulation.set_commands([command2, command1]) if time.time() - now2 > 5: now2 = time.time() init_simulation(simulation) player_sensors = simulation.get_sensors() ``` Just copy and past after the installation and see what happen! # Sensors There are 40 points in the soccer field in the contour and the robots can calculate the distance between they and those points, that is the sensors. They can calculate the distance beetween they and other players too, if they are in their field od vision, of course. I draw the line of vision of the robot to explain how they can see. Below I draw black lines for vision of points on the field and write line for vision of other robot. If the robot cannot see, the data will be infinite. On the image bellow the red robot cannot see the yellow robot, so there aren't a write line and when you run ```simulation.get_sensors()``` the data for the other player's distance will be infinite. ![](https://user-images.githubusercontent.com/50979367/125828076-6223c7e9-e41a-411b-9f0d-000c18aa7e79.PNG) But on the image bellow the red robot can see the yellow robot and there are write line. ![](https://user-images.githubusercontent.com/50979367/125828708-9c63c38e-7486-48ab-ad90-ae7c21c122d8.PNG) # Goal Like the real soccer, if the ball achieve the crossbar, the scoreboard will update and the robots and the ball will replace to the init position. # Did you have any problem? If you get any problem, please contact me: jonysalgadofilho@gmail.com If you like to contribute, please do it! I will like so much, I did this project to help me to study AI and I think that can help you, as well.
/robot_soccer_python-1.0.4.tar.gz/robot_soccer_python-1.0.4/README.md
0.464416
0.946695
README.md
pypi
from robot_soccer_python.constants import * from robot_soccer_python.utils import Pose from robot_soccer_python.agents import Ball from robot_soccer_python.simulation import * from robot_soccer_python.state_machine_ball import FiniteStateMachineBall, MoveForwardStateBall import datetime # ______________________________________________________________________________ # simulation2D function def simulation2D(players, shockable = True, full_vision = False): """ This function initialize the simulation and return a object that the user can pass the controls and get the sensors information. :param players: a list of Players for simulation :type: list of Player :param shockable: parameter that informs if players will collide with themselves :type shockable: bool :param full_vision: parameter that informs if player will see every thing even if it’s not in the vision cone. :type full_vision: bool """ behavierBall = FiniteStateMachineBall(MoveForwardStateBall(False)) poseBall = Pose(PIX2M * SCREEN_WIDTH*1/4.0, PIX2M * SCREEN_HEIGHT / 2.0, 0) ball = Ball(poseBall, 1.0, 100, RADIUS_BALL, behavierBall) for player in players: player.sensors.set_full_vision(full_vision) return Simulation(np.array(players), ball, shockable, full_vision) def init_simulation(simulation): now = datetime.datetime.now() pygame.init() window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Robot soccer 2D environment") icon = pygame.image.load('robot_soccer_python\icon.PNG') pygame.display.set_icon(icon) clock = pygame.time.Clock() environment = Environment(window) while (datetime.datetime.now() - now).seconds < 1: clock.tick(FREQUENCY) for event in pygame.event.get(): if event.type == pygame.QUIT: end_simulation() simulation.update() draw(simulation, window, environment) def end_simulation(): pygame.quit()
/robot_soccer_python-1.0.4.tar.gz/robot_soccer_python-1.0.4/robot_soccer_python/simulation2D.py
0.613815
0.512815
simulation2D.py
pypi
from RfInterface import RfInterface # This allows acccess to robotFramework calls and data from DebugUI import DebugUI # This is the pop up UI # This is the main library function used in robotFramework scripts class DebugUiLibrary: """ This test library provides a single keyword 'Debug' to allow debugging of robotFramework scripts *Before running tests* Prior to running tests, DebugUiLibrary be added as an imported library in your Robot test suite. Example: | Library | DebugUiLibrary | """ def Debug(self): """The command "Debug" surfaces the debugger user interface. This suggests possible commands and lets you edit and try them. The commands use valid xpaths found from the page by the debugger. The debugger also lists the current variables in case you want to use them. Add "Library Debug.py" to your project settings section. Add "Debug" in your script where you want to start debugging test steps (the line before a problem). Experiment with commands until you fix the problem. You can manually interact with the page and use browser tools to view xpaths and page source while you debug. When a command works "Save" it When you are finished paste the saved commands into your script. NOTES: Paste buffer content vanishes when the Debugger closes so paste your new commands into your script before exiting it. The debugger may take around 15-30 seconds to surface or update while it searches the page content. Not all controls are found by the debugger - you may have to add or tinker with the command you try. """ # create an interface to robbotFramework - so we can send commands rfInterface=RfInterface() # Open up the debug UI debugUI=DebugUI(rfInterface) # Print a message on exiting the debugger print "Debug complete" # Testing for this code if __name__=='__main__': DebugUiLibrary().Debug() # ------------------ End of File ------------------
/robotFramework-DebugUiLibrary-0.9.0.zip/robotFramework-DebugUiLibrary-0.9.0/DebugUiLibrary/DebugUiLibrary.py
0.643777
0.268654
DebugUiLibrary.py
pypi
import Tkinter as tk listHeight=30 listWidth=100 import tkMessageBox commandComboLabel='EXAMPLE commands - Click any command to use it' historyComboLabel='HISTORY of commands tried - Click any command to use it' programComboLabel='SAVED commands - these are now on the clipboard ready to use' varsComboLabel ='VARIABLES - robotFramework variables and their values' helpText =''' RobotFramework Script Debug UI: The entryfield near the top takes commands to try. You can edit or type into it or select commands from the page below. Three commands are on buttons on the right and in the 'menu' at the left: Try - tries out whatever command you have in the entryfield. Save - saves the current command to the saved page Exit - quits the debugger and continues your program with the next line after the 'Debug' line Three views are available depending on which menu item you click: Commands - shows a list of suggested available commands. History - shows a list of all commands you try. Saved - shows a list of commands you previously saved. To use the Debug UI : Click on any command to put it into the entryfield. Edit the command, then try it by clicking the Try button or menu item. Double click will load and execute in one go if you are feeling lucky. After a command is executed the list of available commands is refreshed. This may take some time where there are lots of controls. When a command works click save to put it on the saved page You can step through several commands and save them. Go to the saved page to get the commands into the paste buffer. Paste them into your robotframework script (you need do this before exiting) When you have finished debugging click exit and robotframework resumes running your testcase on the line after 'Debug'. You can interact with the browser between tries to get the page ready or back to it's original state. You may need to experiment with editing the command to make it work correctly. When you open the 'Saved' page the list of saved commands is put on the clipboard ready to paste into your script. You can use the debugger alongside checkXpath and firebug. It has been tested with firefox and Chrome. Check the robotFramework log in RIDE to see the current status. You will get far faster response time if you use Chrome ... If you want to add controls to search for edit controlsList.py Good luck !!! ''' class DebugUI: def __init__(self,rfInterface): self.savedCommands=[] self.rfInterface=rfInterface self.root = tk.Tk() self.root.title('RobotFramework DebugUI') self.root.bind('<Return>', self.tryCommand) # Put 'focus' on the try command button # Add a menu to select the different history lists - afraid it has to go at the top as far as I can see menubar = tk.Menu(self.root) menubar.add_command(label="Try", command=self.tryCommand) menubar.add_command(label="Save", command=self.saveCommand) menubar.add_command(label="Exit", command=self.fini) menubar.add_command(label="||") menubar.add_command(label="Commands", command=self.showCommands) menubar.add_command(label="History", command=self.showHistory) menubar.add_command(label="Saved", command=self.showProgram) menubar.add_command(label="||") menubar.add_command(label="Variables", command=self.showVars) menubar.add_command(label="||") menubar.add_command(label="Help", command=self.showHelp) self.root.config(menu=menubar) # A button panel at the top buttonPanel = tk.Frame(self.root) buttonPanel.pack(side=tk.TOP) # Add the buttons panel to the UI # Add an entry field for rf commands self.commandEntryfield=tk.Entry(buttonPanel, width=listWidth) self.commandEntryValue=tk.StringVar() self.commandEntryfield["textvariable"]=self.commandEntryValue self.commandEntryValue.set('Click link //a[contains(text(),"YOUR_TEXT_HERE")]') self.commandEntryfield.pack(side=tk.LEFT) self.commandEntryfield.bind('<Double-Button-1>',self.tryCommand) # Double click trys the command # Add a Try command button to the panel PB1 = tk.Button(buttonPanel, text ="Try", command = self.tryCommand, bg="GREEN") PB1.pack(side=tk.LEFT) PB1.focus_set() # Set focus on the try command button # Add a save command button to the panel PB2 = tk.Button(buttonPanel, text ="Save", command = self.saveCommand, bg="Yellow") PB2.pack(side=tk.LEFT) # Add an exit button to the panel EB = tk.Button(buttonPanel, text ="Exit", command=self.fini, bg="Red") EB.pack(side=tk.LEFT) # ---------- Add a combo panel for commands ---------- self.comboPanel=tk.Frame(self.root) self.comboPanel.pack(side=tk.BOTTOM, expand=tk.YES) # Add the combo panel to the UI # Add a label to it self.comboLabelText=tk.StringVar() self.comboLabelText.set(commandComboLabel) comboLabel=tk.Label(self.comboPanel, textvariable=self.comboLabelText) comboLabel.pack(side=tk.TOP, expand=tk.YES) # ---------- Add a combo panel for history - not packed initially ---------- self.historyCombo=tk.Listbox(self.comboPanel,width=listWidth,height=listHeight) self.historyCombo.bind('<Double-Button-1>',self.listSelect) # Make double clicks run the list select function # ---------- Add a combo panel for variables ---------- self.varsScroll = tk.Scrollbar(self.comboPanel) self.varsCombo = tk.Listbox(self.comboPanel, yscrollcommand=self.varsScroll.set, width=listWidth, height=listHeight) self.varsScroll.config(command=self.varsCombo.yview) self.varsCombo.bind('<Double-Button-1>',self.listSelect) # Make double clicks run the list select function # ---------- Add a list of stored program steps ---------- self.programList=tk.StringVar() # Create a variable to hold the program steps # Diplayed program list self.progScroll = tk.Scrollbar(self.comboPanel) self.programCombo = tk.Text(self.comboPanel, yscrollcommand=self.progScroll.set, height=listHeight, borderwidth=0) self.progScroll.config(command=self.programCombo.yview) self.programCombo.configure(bg=self.root.cget('bg'), relief=tk.FLAT) self.programCombo.configure(state="disabled") # Make the program combo non editable # ---------- Make text selectable in the program panel ---------- self.programCombo.bind('<Double-Button-1>',self.select_all) self.programCombo.bind("<Control-Key-a>", self.select_all) self.programCombo.bind("<Control-Key-A>", self.select_all) # just in case caps lock is on # Add a listbox with the commands in self.commandScroll = tk.Scrollbar(self.comboPanel) self.commandCombo=tk.Listbox(self.comboPanel, selectmode=tk.BROWSE, yscrollcommand=self.commandScroll.set, width=listWidth, height=listHeight) self.commandScroll.config(command=self.commandCombo.yview) self.updateCommandsList() # Put the available commands into the commands list - can take ages self.commandScroll.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES) # Make this one show on startup self.commandCombo.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES) self.commandCombo.bind('<<ListboxSelect>>',self.listSelect) # Clicks select from the list self.commandCombo.bind('<Double-Button-1>',self.listSelectRun) # Double clicks select from the list and run the command self.root.mainloop() # This sits in this loop forever running the UI until you exit # ---------------- Command entryfield functions ---------------- def select_all(self,event): # Select all the text in textbox self.programCombo.tag_add("sel", "1.0", "end") self.programCombo.mark_set("insert", "1.0") self.programCombo.see("insert") return 'break' def updateCommandsList(self): # Refresh the contents of the list of commands available self.root.config(cursor="watch") # Show an hourglass while selenium reads the controls self.root.update() commandsList=self.rfInterface.getAllPageControls() self.commandCombo.delete(0,tk.END) for command in commandsList: self.commandCombo.insert(tk.END,command) self.commandCombo.selection_set(first=0) self.root.config(cursor="") def tryCommand(self,event=None): # (Safely) try out the command from the entry field # The event parameter because clicking the enter key passes in an enter event - which we ignore self.command=self.commandEntryfield.get() self.commands=self.command.split(' ') self.commands=[c.strip() for c in self.commands if c!=''] self.rfInterface.runCommand(tuple(self.commands)) self.historyCombo.insert(0,' '.join(self.commands)) self.updateCommandsList() # Put the available commands into the commands list def saveCommand(self): # Save the entry field command in saved commands command=self.commandEntryfield.get() self.savedCommands.append(command) self.programList.set("\n".join(self.savedCommands)) def listSelect(self,event): # Select an item from a list - put it into the entryfield widget = event.widget selection=widget.curselection() # Timing problems when people click around # should really poll but that seems like overkill ... if len(selection)>0: value = widget.get(selection[0]) else: value='Log Drat - click it again...' self.commandEntryValue.set(value) def listSelectRun(self,event): # Select and run an item from a list self.listSelect(event) # put it into the entryfield self.tryCommand() # Try the command # ---------------- Show contents ---------------- def clearView(self,label): # Clear the panel and set the label self.programCombo.pack_forget() self.progScroll.pack_forget() self.commandCombo.pack_forget() self.commandScroll.pack_forget() self.varsCombo.pack_forget() self.varsScroll.pack_forget() self.historyCombo.pack_forget() self.comboLabelText.set(label) def showCommands(self): # Show the available commands self.clearView(commandComboLabel) self.commandScroll.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES) # Add the scrollbar self.commandCombo.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES) # Add the commands def showProgram(self): # Show the saved program self.clearView(programComboLabel) progText=self.programList.get() # Set the text - ie list of steps self.programCombo.configure(state="normal") self.programCombo.delete(1.0, "end") self.programCombo.insert(1.0,progText) self.programCombo.configure(state="disabled") self.root.clipboard_clear() # Put the commands on the clipboard automagically self.root.clipboard_append(progText) # when the page is opened - (probably not sensible) self.progScroll.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES) # Add the scroll bar self.programCombo.pack(side=tk.LEFT, expand=tk.YES) # Show the program steps list def showVars(self): # Show the list of available variables varsDict=self.rfInterface.getVars() # Get the values varsList=dictAsList(varsDict) # Convert to a displayable list self.varsCombo.delete(0, tk.END) # Add the values to the control for v in varsList: self.varsCombo.insert(tk.END, v) self.clearView(varsComboLabel) # Show the list self.varsScroll.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES) # Add the scrollbar self.varsCombo.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES) # Show the list def showHistory(self): # Show the command history self.clearView(historyComboLabel) self.historyCombo.pack(side=tk.BOTTOM, expand=tk.YES) def showHelp(self): # Show the help text self.clearView(helpText) def fini(self): # Quit the program print "KTHXBYE" self.root.destroy() return # Convert a dictionary into a list of strings to display def dictAsList(varsDict): varsList=[] for key in varsDict.keys(): varsList.append(str(key)+' '+str(varsDict[key])) return varsList # ------------------ # Testing for this code # ------------------ class FakeRfInterface: def getVars(self): varsDict={1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9, } return varsDict def runCommand(self,args): return def getAllPageControls(self): return [] if __name__ == '__main__': print "TESTING" fakeRfInterface=FakeRfInterface() app = DebugUI(fakeRfInterface) #DebugUI.showVars() # -------- End of file --------
/robotFramework-DebugUiLibrary-0.9.0.zip/robotFramework-DebugUiLibrary-0.9.0/DebugUiLibrary/DebugUI.py
0.403214
0.213787
DebugUI.py
pypi
# Robot descriptions in Python [![Build](https://img.shields.io/github/actions/workflow/status/robot-descriptions/robot_descriptions.py/test.yml?branch=master)](https://github.com/robot-descriptions/robot_descriptions.py/actions) [![Coverage](https://coveralls.io/repos/github/robot-descriptions/robot_descriptions.py/badge.svg?branch=master)](https://coveralls.io/github/robot-descriptions/robot_descriptions.py?branch=master) [![PyPI version](https://img.shields.io/pypi/v/robot_descriptions)](https://pypi.org/project/robot_descriptions/) [![Conda Version](https://img.shields.io/conda/vn/conda-forge/robot_descriptions.svg)](https://anaconda.org/conda-forge/robot_descriptions) [![Contributing](https://img.shields.io/badge/PRs-welcome-green.svg)](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/CONTRIBUTING.md) Import open source robot descriptions as Python modules. Importing a description for the first time automatically downloads and caches files for future imports. Most [Awesome Robot Descriptions](https://github.com/robot-descriptions/awesome-robot-descriptions) are available. All of them [load successfully](https://github.com/robot-descriptions/robot_descriptions.py#loaders) in respectively MuJoCo (MJCF) or Pinocchio, iDynTree, PyBullet and yourdfpy (URDF). ## Installation ### Install from pip ```console pip install robot_descriptions ``` ### Install from conda ```console conda install -c conda-forge robot_descriptions ``` ## Usage The library provides `load_robot_description` functions that return an instance of a robot description directly usable in the corresponding software. For example: ```python from robot_descriptions.loaders.pinocchio import load_robot_description robot = load_robot_description("upkie_description") ``` Loaders are implemented for the following robotics software: | Software | Loader | |--------------------------------------------------------------|------------------------------------------| | [iDynTree](https://github.com/robotology/idyntree) | `robot_descriptions.loaders.idyntree` | | [MuJoCo](https://github.com/deepmind/mujoco) | `robot_descriptions.loaders.mujoco` | | [Pinocchio](https://github.com/stack-of-tasks/pinocchio) | `robot_descriptions.loaders.pinocchio` | | [PyBullet](https://pybullet.org/) | `robot_descriptions.loaders.pybullet` | | [RoboMeshCat](https://github.com/petrikvladimir/RoboMeshCat) | `robot_descriptions.loaders.robomeshcat` | | [yourdfpy](https://github.com/clemense/yourdfpy/) | `robot_descriptions.loaders.yourdfpy` | Loading will automatically download the robot description if needed, and cache it to a local directory. ### Import as submodule You can also import a robot description directly as a submodule of ``robot_descriptions``: ```python from robot_descriptions import my_robot_description ``` The import will automatically download the robot description if you don't have it already, and cache it to a local directory. The submodule then provides the following paths: <dl> <dt> <code>URDF_PATH</code> / <code>MJCF_PATH</code> </dt> <dd> Path to the main URDF/MJCF file of the robot description. </dd> <dt> <code>PACKAGE_PATH</code> </dt> <dd> Path to the root of the robot description package. </dd> <dt> <code>REPOSITORY_PATH</code> </dt> <dd> Path to the working directory of the git repository hosting the robot description. </dd> </dl> Some robot descriptions include additional fields. For instance, the ``iiwa_description`` exports ``URDF_PATH_POLYTOPE_COLLISION`` with more detailed collision meshes. ## Examples Loading a robot description: - [iDynTree](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/load_in_idyntree.py) - [MuJoCo](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/load_in_mujoco.py) - [Pinocchio](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/load_in_pinocchio.py) - [PyBullet](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/load_in_pybullet.py) - [RoboMeshCat](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/load_in_robomeshcat.py) - [yourdfpy](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/load_in_yourdfpy.py) Visualizing a robot description: - [MeshCat](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/show_in_meshcat.py) - [MuJoCo](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/show_in_mujoco.py) - [PyBullet](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/show_in_pybullet.py) - [RoboMeshCat](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/show_in_robomeshcat.py) - [yourdfpy](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/examples/show_in_yourdfpy.py) ## Command line tool The command line tool can be used to visualize any of the robot descriptions below. For example: ```console robot_descriptions show solo_description ``` ## Descriptions Available robot descriptions ([gallery](https://github.com/robot-descriptions/awesome-robot-descriptions#gallery)) are listed in the following categories: * [Arms](#arms) * [Bipeds](#bipeds) * [Dual arms](#dual-arms) * [Drones](#drones) * [Educational](#educational) * [End effectors](#end-effectors) * [Mobile manipulators](#mobile-manipulators) * [Humanoids](#humanoids) * [Quadrupeds](#quadrupeds) * [Wheeled](#wheeled) The DOF column denotes the number of actuated degrees of freedom. ### Arms | Name | Robot | Maker | DOF | Format | |-------------------------------|-----------------------|--------------------------|-----|------------| | `edo_description` | e.DO | Comau | 6 | URDF | | `fanuc_m710ic_description` | M-710iC | Fanuc | 6 | URDF | | `gen2_description` | Gen2 (Jaco) | Kinova | 6 | URDF | | `gen3_description` | Gen3 (Jaco) | Kinova | 6 | URDF | | `gen3_mj_description` | Gen3 (Jaco) | Kinova | 7 | MJCF | | `iiwa_description` | iiwa | KUKA | 7 | URDF | | `panda_description` | Panda | Franka Emika | 8 | URDF | | `panda_mj_description` | Panda | Franka Emika | 8 | MJCF | | `poppy_ergo_jr_description` | Poppy Ergo Jr | Poppy Project | 6 | URDF | | `ur10_description` | UR10 | Universal Robots | 6 | URDF | | `ur3_description` | UR3 | Universal Robots | 6 | URDF | | `ur5_description` | UR5 | Universal Robots | 6 | URDF | | `ur5e_mj_description` | UR5e | Universal Robots | 6 | MJCF | | `z1_description` | Z1 | UNITREE Robotics | 6 | URDF | ### Bipeds | Name | Robot | Maker | DOF | Format | |-------------------------------|-----------------------|--------------------------|-----|------------| | `bolt_description` | Bolt | ODRI | 6 | URDF | | `cassie_description` | Cassie | Agility Robotics | 16 | URDF | | `cassie_mj_description` | Cassie | Agility Robotics | 16 | MJCF | | `rhea_description` | Rhea | Gabrael Levine | 7 | URDF | | `spryped_description` | Spryped | Benjamin Bokser | 8 | URDF | | `upkie_description` | Upkie | Tast's Robots | 6 | URDF | ### Dual arms | Name | Robot | Maker | DOF | Format | |-------------------------------|-----------------------|--------------------------|-----|------------| | `baxter_description` | Baxter | Rethink Robotics | 15 | URDF | | `nextage_description` | NEXTAGE | Kawada Robotics | 15 | URDF | | `poppy_torso_description` | Poppy Torso | Poppy Project | 13 | URDF | | `yumi_description` | YuMi | ABB | 16 | URDF | ### Drones | Name | Robot | Maker | DOF | Format | |-------------------------------|-----------------------|--------------------------|-----|------------| | `cf2_description` | Crazyflie 2.0 | Bitcraze | 0 | URDF | ### Educational | Name | Robot | DOF | Format | |-------------------------------|-----------------------|-----|------------| | `double_pendulum_description` | Double Pendulum | 2 | URDF | | `finger_edu_description` | FingerEdu | 3 | URDF | | `simple_humanoid_description` | Simple Humanoid | 29 | URDF | | `trifinger_edu_description` | TriFingerEdu | 9 | URDF | ### End effectors | Name | Robot | Maker | DOF | Format | |-------------------------------|-----------------------|--------------------------|-----|------------| | `allegro_hand_description` | Allegro Hand | Wonik Robotics | 16 | URDF | | `barrett_hand_description` | BarrettHand | Barrett Technology | 8 | URDF | | `robotiq_2f85_description` | Robotiq 2F-85 | Robotiq | 1 | URDF | | `robotiq_2f85_mj_description` | Robotiq 2F-85 | Robotiq | 1 | MJCF | | `shadow_hand_mj_description` | Shadow Hand | The Shadow Robot Company | 24 | MJCF | ### Humanoids | Name | Robot | Maker | DOF | Format | |-------------------------------|-----------------------|--------------------------|-----|------------| | `atlas_drc_description` | Atlas DRC (v3) | Boston Dynamics | 30 | URDF | | `atlas_v4_description` | Atlas v4 | Boston Dynamics | 30 | URDF | | `draco3_description` | Draco3 | Apptronik | 25 | URDF | | `ergocub_description` | ergoCub | IIT | 57 | URDF | | `icub_description` | iCub | IIT | 32 | URDF | | `jaxon_description` | JAXON | JSK | 38 | URDF | | `jvrc_description` | JVRC-1 | AIST | 34 | URDF | | `jvrc_mj_description` | JVRC-1 | AIST | 34 | MJCF | | `r2_description` | Robonaut 2 | NASA JSC Robotics | 56 | URDF | | `romeo_description` | Romeo | Aldebaran Robotics | 37 | URDF | | `sigmaban_description` | SigmaBan | Rhoban | 20 | URDF | | `talos_description` | TALOS | PAL Robotics | 32 | URDF | | `valkyrie_description` | Valkyrie | NASA JSC Robotics | 59 | URDF | ### Mobile manipulators | Name | Robot | Maker | DOF | Format | |-------------------------------|-----------------------|--------------------------|-----|------------| | `eve_r3_description` | Eve R3 | Halodi | 23 | URDF | | `fetch_description` | Fetch | Fetch Robotics | 14 | URDF | | `ginger_description` | Ginger | Paaila Technology | 49 | URDF | | `pepper_description` | Pepper | SoftBank Robotics | 17 | URDF | | `pr2_description` | PR2 | Willow Garage | 32 | URDF | | `reachy_description` | Reachy | Pollen Robotics | 21 | URDF | | `stretch_description` | Stretch RE1 | Hello Robot | 14 | URDF | | `tiago_description` | TIAGo | PAL Robotics | 48 | URDF | ### Quadrupeds | Name | Robot | Maker | DOF | Format | |-------------------------------|-----------------------|--------------------------|-----|------------| | `a1_mj_description` | A1 | UNITREE Robotics | 12 | MJCF | | `a1_description` | A1 | UNITREE Robotics | 12 | URDF | | `b1_description` | B1 | UNITREE Robotics | 12 | URDF | | `aliengo_description` | Aliengo | UNITREE Robotics | 12 | MJCF, URDF | | `anymal_b_mj_description` | ANYmal B | ANYbotics | 12 | MJCF | | `anymal_b_description` | ANYmal B | ANYbotics | 12 | URDF | | `anymal_c_mj_description` | ANYmal C | ANYbotics | 12 | MJCF | | `anymal_c_description` | ANYmal C | ANYbotics | 12 | URDF | | `go1_mj_description` | Go1 | UNITREE Robotics | 12 | MJCF | | `go1_description` | Go1 | UNITREE Robotics | 12 | URDF | | `hyq_description` | HyQ | IIT | 12 | URDF | | `laikago_description` | Laikago | UNITREE Robotics | 12 | MJCF, URDF | | `mini_cheetah_description` | Mini Cheetah | MIT | 12 | URDF | | `minitaur_description` | Minitaur | Ghost Robotics | 16 | URDF | | `solo_description` | Solo | ODRI | 12 | URDF | ## Contributing New robot descriptions are welcome! Check out the [guidelines](https://github.com/robot-descriptions/robot_descriptions.py/tree/master/CONTRIBUTING.md) then open a PR. ## Thanks Thanks to the maintainers of all the git repositories that made these robot descriptions available. ## See also Robot descriptions in other languages: | ![C++](https://img.shields.io/badge/C%2B%2B-00599C?logo=c%2B%2B&logoColor=white) | [robot\_descriptions.cpp](https://github.com/mayataka/robot_descriptions.cpp) | |--|--|
/robot_descriptions-1.6.0.tar.gz/robot_descriptions-1.6.0/README.md
0.645567
0.957912
README.md
pypi
import argparse import datetime from loguru import logger import os import pathlib from typing import List import dateutil.parser import jinja2 import robota_core.config_readers as config_readers from robota_core.data_server import DataServer from robota_common_errors.common_errors import get_error_descriptions, CommonError from robota_common_errors.common_errors import assess_common_errors from robota_common_errors.output_templates.build_webpages import build_webpages def count_errors(common_errors: List[CommonError]) -> int: """Count how many different common error types were detected.""" error_count = 0 for error in common_errors: if error.detail_titles: error_count += 1 return error_count def identify_common_errors(robota_config: dict, start: datetime.datetime, end: datetime.datetime) -> List[CommonError]: """The main function which gets the common errors.""" # Set up data source data_server = DataServer(robota_config, start, end) # Obtain info on common errors from YAML files common_errors = get_error_descriptions(robota_config) # Identify common errors. return assess_common_errors(data_server, common_errors) def output_html_report(common_errors: List[CommonError], data_source_info: dict, common_error_summary: dict, output_dir: str): # Construct the marking report based on determined performance update_template(common_errors, data_source_info, common_error_summary) # Build the webpages copying from templates to the live directory template_dir = pathlib.Path(__file__).parent / "output_templates" build_webpages(template_dir, pathlib.Path(output_dir)) def update_template(common_errors: List[CommonError], data_source_info: dict, common_error_summary: dict): """Produce the HTML report by writing the marking results to a HTML template. :param common_errors: A list of common errors and feedback on them. :param data_source_info: A dictionary of information about the data sources that were used. :param common_error_summary: A dictionary of stats about the common errors that is printed in the report. """ logger.info("Writing common error report.") template_loader = jinja2.FileSystemLoader( searchpath=f"robota_common_errors/output_templates/") template_env = jinja2.Environment(loader=template_loader, trim_blocks=True, lstrip_blocks=True, undefined=jinja2.StrictUndefined) jinja_template = template_env.get_template("common_error_report/report_template.html") rendered_page = jinja_template.render(common_errors=common_errors, common_error_summary=common_error_summary, data_source_info=data_source_info) # prepare the output directory output_directory = pathlib.Path("webpages/").resolve() os.makedirs(output_directory, exist_ok=True) # Write the generated report to a file output_name = "common-error-report.html" report_path = output_directory / pathlib.Path(output_name) with open(report_path, "w", encoding='utf-8') as result_html: result_html.write(rendered_page) logger.info(f"Common error report written to {report_path}.") def summarise_data_sources(robota_config: dict, start: datetime.datetime, end: datetime.datetime) -> dict: data_source_summary = {"start": start, "end": end} desired_sources = ["issues", "remote_provider", "repository", "ci"] for source in desired_sources: source_info = config_readers.get_data_source_info(robota_config, source) if source_info: source_info.pop("token", None) source_info.pop("username", None) data_source_summary[source] = source_info return data_source_summary def summarise_common_errors(common_errors: List[CommonError]): error_summary = {"num_tested_errors": len(common_errors), "num_detected_errors": 0} for error in common_errors: if error.count_errors() > 1: error_summary["num_detected_errors"] += 1 return error_summary def run_html_error_report(start: str, end: str, config_path: str, output_dir: str, substitution_variables: dict): """Get common errors and output them in the form of a HTML report.""" start = dateutil.parser.parse(start) end = dateutil.parser.parse(end) # Get robota config from local config file robota_config = config_readers.get_robota_config(config_path, substitution_variables) common_errors = identify_common_errors(robota_config, start, end) data_source_info = summarise_data_sources(robota_config, start, end) common_error_summary = summarise_common_errors(common_errors) output_html_report(common_errors, data_source_info, common_error_summary, output_dir) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-c", "--config_path", help="The path to the robota-config.yaml file.", default="robota-config.yaml") parser.add_argument("-o", "--output_dir", help="The output directory to place the report.", default="webpages/") parser.add_argument("-s", "--start", help="The start date of the first commit to consider in YYYY-MM-DD format.", default="2020-01-01") parser.add_argument("-e", "--end", help="The end date of the last commit to consider in YYYY-MM-DD format.", default=datetime.date.today().isoformat()) parsed, unknown_args = parser.parse_known_args() KNOWN_ARGS = vars(parsed) if len(unknown_args) % 2 != 0: raise SyntaxError("Malformed command line arguments. " "Each flag must be followed by a single argument.") while unknown_args: flag = unknown_args.pop(0).lstrip("-") value = unknown_args.pop(0) KNOWN_ARGS[flag] = value run_html_error_report(KNOWN_ARGS.pop("start"), KNOWN_ARGS.pop("end"), KNOWN_ARGS.pop("config_path"), KNOWN_ARGS.pop("output_dir"), KNOWN_ARGS)
/robota_common_errors-1.1.1-py3-none-any.whl/robota_common_errors/report.py
0.771542
0.27486
report.py
pypi
import importlib from loguru import logger from typing import List from robota_core import config_readers from robota_core.config_readers import get_config, RobotaConfigParseError from robota_core.string_processing import markdownify from robota_core.data_server import DataServer class CommonError: """Representation of a common error that could be identified :ivar name: The name of the common error. :ivar marking_function: The name of the function used to assess the common error. :ivar description: A textual description of the common error. :ivar detail_titles: Titles of a table to be printed on the marking report. :ivar error_details: Rows of a table to be printed on the marking report. """ def __init__(self, common_error: dict): self.name = common_error["name"] self.marking_function = common_error["marking_function"] self.description = markdownify(common_error["text"]) self.required_data_sources: List[str] = common_error["required_data_sources"] self.detail_titles: List[str] = [] self.error_details: List[List[str]] = [] def __getstate__(self) -> dict: return {"name": self.name, "detail_titles": self.detail_titles, "error_details": self.error_details} def add_feedback(self, feedback: List[List[str]]): self.error_details = feedback def add_feedback_titles(self, feedback_titles: List[str]): self.detail_titles = feedback_titles def count_errors(self) -> int: """Sum the occurrences of this error by checking error details.""" if not self.error_details: return 0 else: return len(self.error_details[0]) def assess_common_errors(data_source: DataServer, common_errors: List[CommonError]) -> List[CommonError]: """Go through all of the possible common errors, running the assessment function for each one.""" if common_errors is None: return [] completed_errors = [] logger.info("Begun assessment of common errors.") common_errors_module = importlib.import_module('robota_common_errors.common_error_functions') for error in common_errors: logger.info(f"Assessing common error {error.name}.") if validate_data_sources(data_source, error): marking_function = getattr(common_errors_module, error.marking_function, None) if marking_function: completed_errors.append(marking_function(data_source, error)) else: logger.warning(f"Common error function '{error.marking_function}' specified in " f"common error: '{error.name}' but not found in " f"'common_error_functions.py'. RoboTA will not assess this error.") logger.success("Completed assessment of common errors.") return completed_errors def validate_data_sources(data_source: DataServer, common_error: CommonError): """Check the data sources that are available from the DataServer.""" valid_sources = data_source.get_valid_sources() for source in common_error.required_data_sources: if source not in valid_sources: logger.warning(f"Common error {common_error.name} cannot be assessed as it requires " f"the data source {source} which has not been provided in the " f"robota config file.") return False return True def get_error_descriptions(robota_config: dict) -> List[CommonError]: """Get the textual description of common errors to identify.""" common_error_source = config_readers.get_data_source_info(robota_config, "common_errors") if not common_error_source: raise KeyError(f"common_errors data source not found in robota config. Must specify a " f"source of common errors.") if "file_name" in common_error_source: error_file = common_error_source["file_name"] else: raise RobotaConfigParseError("Could not find key 'file_name' in 'common_error' data type " "in RoboTA config.") logger.info(f"Getting error config from {error_file}") error_config = get_config([error_file], common_error_source)[0] if error_config is None: raise KeyError(f"Failed to load common errors from file {error_file}.") else: return [CommonError(error_info) for error_info in error_config]
/robota_common_errors-1.1.1-py3-none-any.whl/robota_common_errors/common_errors.py
0.784443
0.277644
common_errors.py
pypi
import datetime from typing import List, Union from robota_core.commit import Commit def is_date_before_other_dates(query_date: datetime.datetime, deadline: datetime.datetime, key_date: datetime.datetime) -> bool: """Determine whether an action was before the deadline and another key date. :param query_date: The date of the action in question, e.g. when was an issue assigned, time estimate set, or due date set. :param deadline: The deadline of the action :param key_date: The query date should be before this significant date, as well as the deadline e.g. branch creation date :return: True if issue query_date was before deadline and key_date else False. """ if query_date is not None and key_date is not None: assert key_date is not query_date if not query_date: return False if query_date < deadline: if not key_date: return True elif query_date < key_date: return True else: return False else: return False def get_first_feature_commit(base_commits: List[Commit], feature_commits: List[Commit]) -> Union[Commit, None]: """Get the first commit on a feature branch. Determine first commit by looking for branching points, described by the parent commits. All parameters are lists of commit IDs ordered from newest to oldest :param base_commits: commits from base branch (usually master) :param feature_commits: commits from feature branch :return first_feature_commit: commit ID of first commit on feature """ # No feature branch commits in specified time range if not feature_commits: return None # To be certain that we have the first commit on feature, # there must be a commit common to both lists. if feature_commits[-1] != base_commits[-1]: raise AssertionError('The oldest commit in each list must be common to both branches.') # First check for unmerged feature branch # If last feature commit is not in base commits then the feature branch is unmerged if feature_commits[0] not in base_commits: # Now loop through commits and look at their parents. # The parent that is in base is the branching point for commit in feature_commits: if Commit({"id": commit.parent_ids[0]}, "dict") in base_commits: # If a parent is found in base then the commit is the first on the feature branch. return commit raise AssertionError("Feature branch not connected to master branch.") # Feature commit is in both feature and base, so feature parent must be # parent to a base commit too. Test for merged feature by looking for merge commit: for feature_commit in feature_commits: if find_feature_parent(feature_commit, base_commits): return feature_commit # All feature commits have been tested and neither an unmerged feature # branch, nor a merged feature with merge commit were found. # This is a FAST-FORWARD MERGE, so return the second commit on the feature branch # (the two lists of feature branch commits contains one extra, # earlier commit each so that we can always find a common commit). return feature_commits[-2] def find_feature_parent(feature_commit: Commit, base_commits: List[Commit]) -> bool: """Determine whether the provided feature commit has a commit in the base branch with a common parent. :param feature_commit: The feature commit being checked. :param base_commits: A list of the base commits, most recent first. :returns: True if feature_commit has a common parent with a commit in the base branch else False. """ base_commit = base_commits[0] while True: try: feature_parent = feature_commit.parent_ids[0] except IndexError: feature_parent = None if feature_parent in base_commit.parent_ids and base_commit != feature_commit: return True # The first parent is always the branch being merged into - the base branch try: base_commit = find_commit_in_list(base_commit.parent_ids[0], base_commits) except IndexError: base_commit = None if not base_commit: # If we have gone through all of the base commits and not found feature_parent then # this feature commit is not the first in the feature branch return False def find_commit_in_list(commit_id: str, commits: List[Commit]) -> Union[None, Commit]: """Find a Commit in a list of Commits by its ID. :param commit_id: The id of the commit to find. :param commits: The list of Commits to search. :return: Commit if found, else None. """ for commit in commits: if commit.id == commit_id: return commit return None def fixup_first_feature_commit(feature_branch_commits: List[Commit], initial_guess_of_first_commit: Commit, merge_commits: List[Commit]): """Fix-up function to look for merge commits on master branch before the tip of the feature branch. Any commits up to and including a merge commit in the history of a feature branch cannot be the first commit on the feature branch. :param feature_branch_commits: :return: """ # next_commit means next chronologically, rather than next in the list of commits, # which is ordered newest to oldest. branch_tip = feature_branch_commits[0] next_commit = None for commit in feature_branch_commits: if commit in merge_commits and commit is not branch_tip: if next_commit: return next_commit else: return commit next_commit = commit else: return initial_guess_of_first_commit def date_is_before(date1: datetime.datetime, date2: datetime.datetime) -> bool: """If date1 and date2 are provided and date1 is before date2 return True, else return False.""" if date1 and date2 and date1 < date2: return True else: return False def logical_and_lists(list1: List[bool], list2: List[bool]) -> List[bool]: """For two lists of booleans of length N, return a list of length N where output[i] is True if list1[i] is True and list2[i] is True, else output[i] is False. """ assert len(list1) == len(list2) return [a and b for a, b in zip(list1, list2)] def are_list_items_in_other_list(reference_list: List, query_list: List) -> List[bool]: """Check whether items in query_list exist in correct_list. :param reference_list: The reference list of items :param query_list: The items to check - does this list contain items in reference_list? :return items_present: Whether items in the correct list are in query_list (bool) >>> are_list_items_in_other_list([1, 2, 3], [3, 1, 1]) [True, False, True] """ items_present = [True if item in query_list else False for item in reference_list] return items_present def are_lists_equal(list_1: list, list_2: list) -> List[bool]: """Elementwise comparison of lists. Return list of booleans, one for each element in the input lists, True if element N in list 1 is equal to element N in list 2, else False.""" return [i == j for i, j in zip(list_1, list_2)] def fraction_of_lists_equal(list_1: list, list_2: list) -> float: """Returns the fraction of list elements are equal when compared elementwise.""" boolean_equals = are_lists_equal(list_1, list_2) return boolean_equals.count(True) / len(boolean_equals) def get_value_from_list_of_dicts(list_of_dicts: List[dict], search_key: str, search_value: int, return_key: str): """Given a list of dictionaries, identify the required dictionary which contains the *search_key*: *search_value* pair. Return the value in that dictionary associated with *return_key*.""" assert(search_key != return_key) for d in list_of_dicts: for k in d: if k == search_key and d[k] == search_value: return d[return_key]
/robota_core-2.2.2.tar.gz/robota_core-2.2.2/robota_core/logic.py
0.864796
0.427337
logic.py
pypi
import datetime import re from typing import Union, Dict import bleach import markdown def string_to_datetime(date: Union[str, None], datetime_format: str = '%Y-%m-%dT%H:%M:%S.%fZ') -> Union[datetime.datetime, None]: """Convert time string (output from GitLab project attributes) to datetime. :param date: A string representing the datetime. :param datetime_format: The format of 'date'. :return date: The converted datetime. >>> string_to_datetime('2017-12-06T08:28:32.000Z', "%Y-%m-%dT%H:%M:%S.%fZ") datetime.datetime(2017, 12, 6, 8, 28, 32) """ if date is None: return None if isinstance(date, str): return datetime.datetime.strptime(date, datetime_format) else: raise TypeError("Unknown date type. Cannot convert.") def markdownify(text: str) -> str: """Take text in markdown format and output the formatted text with HTML markup.""" return markdown.markdown(text, extensions=['attr_list']) def clean(text: str) -> str: """Convert any HTML tags to a string representation so HTML cannot be executed.""" return bleach.clean(text) def html_newlines(text: str) -> str: """Replace any newline characters in a string with html newline characters.""" html = re.sub('(\n)+', '<br>', text) return html def list_to_html_rows(list_of_strings: list) -> str: """Join list items with html new lines.""" return '<br>'.join(list_of_strings) def sublist_to_html_rows(list_of_lists: list, empty='-') -> list: """Separate items in a sub-list by html new lines instead of commas.""" for item in list_of_lists: assert item is None or isinstance(item, list) return [list_to_html_rows(list_items) if list_items else empty for list_items in list_of_lists] def get_link(url: str, link_text: Union[str, int, float]) -> str: """Create link (e.g. to a commit).""" return f'<a target="_parent" href="{url}">{link_text}</a>' def build_regex_string(string: str) -> str: """Escape some characters and replace * and ? wildcard characters with the python regex equivalents.""" string.replace(".", r"\.") string.replace("*", ".+") string.replace("?", ".") return string def replace_none(input_list: list, replacement='-') -> list: """Sanitise list for display purposes.""" return [item if item is not None else replacement for item in input_list] def append_list_to_dict(dictionary: Dict[str, list], key: str, value: list): """If key exists in dictionary then append value to it, else add a new key with value. :param dictionary: A dictionary to add key and value to. :param key: Dictionary key. :param value: A value to append to the dictionary list. """ if key in dictionary: dictionary[key].extend(value) else: dictionary[key] = value
/robota_core-2.2.2.tar.gz/robota_core-2.2.2/robota_core/string_processing.py
0.879121
0.276965
string_processing.py
pypi
import datetime import io import sys from abc import abstractmethod from typing import List, Union import github import github.Branch from github.File import File import gitlab import gitlab.v4.objects import git from loguru import logger from robota_core import gitlab_tools, config_readers from robota_core.commit import CommitCache, Tag, Commit, get_tags_at_date from robota_core.github_tools import GithubServer from robota_core.string_processing import string_to_datetime class Branch: """An abstract object representing a git branch. :ivar id: Name of branch. :ivar id: Commit id that branch points to. """ def __init__(self, branch, source: str): self.name = None self.id = None if source == "gitlab": self._branch_from_gitlab(branch) elif source == "github": self._branch_from_github(branch) elif source == "dict": self._branch_from_dict(branch) elif source == "local": self._branch_from_local(branch) else: TypeError("Unknown branch type.") def _branch_from_gitlab(self, branch: gitlab.v4.objects.ProjectBranch): self.name = branch.attributes["name"] self.id = branch.attributes["commit"]["id"] def _branch_from_dict(self, branch: dict): self.name = branch["name"] self.id = branch["commit_id"] def _branch_from_github(self, branch: github.Branch.Branch): self.name = branch.name self.id = branch.commit.sha def _branch_from_local(self, branch: git.Head): self.name = branch.name self.id = branch.commit.hexsha class Event: """A repository event. :ivar date: The date and time of the event. :ivar type: 'deleted', 'pushed to' or 'pushed new' :ivar ref_type: The thing the event concerns, 'tag', 'branch', 'commit' etc. :ivar ref_name: The name of the thing the event concerns (branch name or tag name) :ivar commit_id: A commit id associated with ref """ def __init__(self, event_data): self.date = None self.type = None self.ref_type = None self.ref_name = None self.commit_id = None self.commit_count = None if isinstance(event_data, gitlab.v4.objects.ProjectEvent): self._event_from_gitlab(event_data) elif isinstance(event_data, dict): self._event_from_dict(event_data) def _event_from_gitlab(self, event_data: gitlab.v4.objects.ProjectEvent): self.date = string_to_datetime(event_data.attributes['created_at']) self.type = event_data.attributes["action_name"] if "push_data" in event_data.attributes: push_data = event_data.attributes['push_data'] self.ref_type = push_data['ref_type'] self.ref_name = push_data['ref'] self.commit_count = push_data['commit_count'] if self.type == "deleted": self.commit_id = push_data['commit_from'] else: self.commit_id = push_data['commit_to'] def _event_from_dict(self, event_data: dict): self.date = string_to_datetime(event_data['date']) self.type = event_data["type"] if "push_data" in event_data: push_data = event_data['push_data'] self.ref_type = push_data['ref_type'] self.ref_name = push_data['ref_name'] self.commit_id = push_data['commit_id'] self.commit_count = push_data['commit_count'] class Diff: """A representation of a git diff between two points in time for a single file in a git repository.""" def __init__(self, diff_info, diff_source: str): self.old_path: str self.new_path: str self.new_file: bool self.diff: str if diff_source == "gitlab": self._diff_from_gitlab(diff_info) elif diff_source == "github": self._diff_from_github(diff_info) elif diff_source == "local_repo": self._diff_from_local(diff_info) else: raise TypeError(f"Unknown diff source: '{diff_source}'") def _diff_from_gitlab(self, diff_info: dict): """Populate a diff using the dictionary of diff information returned by gitlab.""" self.old_path = diff_info["old_path"] self.new_path = diff_info["new_path"] self.new_file = diff_info["new_file"] self.diff = diff_info["diff"] def _diff_from_local(self, diff_info: git.Diff): self.old_path = diff_info.a_path self.new_path = diff_info.b_path self.new_file = diff_info.new_file self.diff = diff_info.diff def _diff_from_github(self, diff_info: github.File.File): self.new_path = diff_info.filename if diff_info.previous_filename is None: self.old_path = self.new_path else: self.old_path = diff_info.previous_filename if diff_info.status == "added": self.new_file = True else: self.new_file = False self.diff = diff_info.patch class Repository: """A place where commits, tags, events, branches and files come from. :ivar _branches: A list of Branches associated with this repository. :ivar _events: A list of Events associated with this repository. :ivar _diffs: A dictionary of cached diffs associated with this repository. They are labelled in the form key = point_1 + point_2 where point_1 and point_2 are the commit SHAs or branch names that the diff describes. """ def __init__(self, project_url: str): self._branches: Union[None, List[Branch]] = None self._events: List[Event] = [] self._diffs = {} self._stored_commits: List[CommitCache] = [] self._tags: List[Tag] = [] self.project_url = project_url @abstractmethod def list_files(self, identifier: str) -> List[str]: """Returns a list of file paths with file names in a repository. Identifier can be a commit or branch name. File paths are relative to the repository root.""" raise NotImplementedError("Not implemented in base class.") def get_branches(self) -> List[Branch]: """Get all of the Branches in the repository.""" if not self._branches: self._branches = self._fetch_branches() return self._branches def get_branch(self, name: str) -> Union[Branch, None]: """Get a Branch from the repository by name. If Branch does not exist, return None.""" if not self._branches: self._branches = self._fetch_branches() for branch in self._branches: if branch.name == name: return branch return None @abstractmethod def _fetch_branches(self) -> List[Branch]: """Retrieve all branches from the server.""" raise NotImplementedError("Not implemented in base class.") @abstractmethod def get_events(self) -> List[Event]: """Return a list of Events associated with this repository.""" raise NotImplementedError("Not implemented in base class.") @abstractmethod def get_file_contents(self, file_path: str, branch: str = "master") -> Union[bytes, None]: """Get the decoded contents of a file from the repository. Works well for text files. Might explode for other file types.""" raise NotImplementedError("Not implemented in base class.") @abstractmethod def compare(self, point_1: str, point_2: str) -> List[Diff]: """Compare the state of the repository at two points in time. The points may be branch names, tags or commit ids. """ raise NotImplementedError("Not implemented in base class.") def get_commits(self, start: datetime.datetime = None, end: datetime.datetime = None, branch: str = None) -> List[Commit]: """Get issues from the issue provider between the start date and end date.""" cached_commits = self._get_cached_commits(start, end, branch) if cached_commits: return list(cached_commits.commits) new_commits = self._fetch_commits(start, end, branch) self._stored_commits.append(CommitCache(start, end, branch, new_commits)) return new_commits def get_commit_by_id(self, commit_id: str) -> Union[Commit, None]: """Get a Commit by its unique ID number""" if commit_id is None: return None for cache in self._stored_commits: for commit in cache: if commit.id.startswith(commit_id): return commit new_commit = self._fetch_commit_by_id(commit_id) # Add the new commit to a cache of its own. fake_date = datetime.datetime.fromtimestamp(1) new_cache = CommitCache(fake_date, fake_date, "", [new_commit]) self._stored_commits.append(new_cache) return new_commit def get_tags(self): """Get all tags from the server.""" if not self._tags: self._tags = self._fetch_tags() return self._tags def get_tag(self, name: str, deadline: datetime.datetime = None, events: List["Event"] = None) -> Union[Tag, None]: """Get a git Tag by name. :param name: The name of the tag to get. :param deadline: If provided, filters tags such that tags are only returned if they existed at deadline. :param events: Events corresponding to the repository, required if deadline is specified. :returns: The Tag if found else returns None. """ if not self._tags: self._tags = self._fetch_tags() tags_to_search = self._tags if deadline: if not events: raise SyntaxError("Must provide list of events if deadline is specified.") tags_to_search = get_tags_at_date(deadline, tags_to_search, events) for tag in tags_to_search: if tag.name == name: return tag return None def _get_cached_commits(self, start: datetime.datetime, end: datetime.datetime, branch: str) -> Union[CommitCache, None]: """Check whether commits with the specified start, end and branch are already stored.""" for cache in self._stored_commits: if cache.start == start and cache.end == end and cache.branch == branch: return cache return None @abstractmethod def _fetch_tags(self) -> List[Tag]: """Fetch tags from a the server.""" raise NotImplementedError("Not implemented in base class.") @abstractmethod def _fetch_commit_by_id(self, commit_id: str) -> Union[Commit, None]: """Fetch a single commit from the server.""" raise NotImplementedError("Not implemented in base class.") @abstractmethod def _fetch_commits(self, start: Union[datetime.datetime, None], end: Union[datetime.datetime, None], branch: Union[str, None]) -> List[Commit]: """Fetch a list of commits from the server.""" raise NotImplementedError("Not implemented in base class.") class LocalRepository(Repository): def __init__(self, commit_source: dict): super().__init__(commit_source["path"]) self.repo = git.Repo(commit_source["path"]) def list_files(self, identifier: str) -> List[str]: files = self.repo.tree(identifier).traverse() file_paths = [file.path for file in files if file.type == "blob"] return file_paths def get_file_contents(self, file_path: str, branch: str = "master") -> Union[bytes, None]: file = self.repo.heads[branch].commit.tree / file_path with io.BytesIO(file.data_stream.read()) as f: return f.read() def compare(self, point_1: str, point_2: str) -> List[Diff]: commit_1 = self._get_commit(point_1) commit_2 = self._get_commit(point_2) diffs = commit_1.diff(commit_2, create_patch=True) robota_diffs = [Diff(diff, "local_repo") for diff in diffs] return robota_diffs def _get_commit(self, ref: str) -> git.Commit: """Get a commit object from a ref which is a branch, tag or commit SHA.""" try: commit = self.repo.heads[ref].commit return commit except IndexError: pass try: commit = self.repo.tags[ref].commit return commit except IndexError: pass try: commit = self.repo.commit(ref) return commit except IndexError: logger.error(f"Can't find object {ref} in Local repository. Object must be branch name," f"tag or commit SHA.") sys.exit(1) def get_events(self) -> List[Event]: # TODO: Can events be mined from the reflog? raise NotImplementedError("Get events not implemented for LocalRepository") def _fetch_branches(self) -> List[Branch]: return [Branch(branch, "local") for branch in self.repo.branches] def _fetch_commits(self, start: Union[datetime.datetime, None], end: Union[datetime.datetime, None], branch: Union[str, None]) -> List[Commit]: rev_list_args = {} if start: rev_list_args["since"] = start.isoformat() if end: rev_list_args["until"] = end.isoformat() rev = None if branch: rev = branch commits = self.repo.iter_commits(rev, "", **rev_list_args) return [Commit(commit, "local") for commit in commits] def _fetch_commit_by_id(self, commit_id: str) -> Union[Commit, None]: return Commit(self.repo.commit(commit_id), "local") def _fetch_tags(self) -> List[Tag]: return [Tag(tag, "local") for tag in self.repo.tags] class GithubRepository(Repository): def __init__(self, repository_source: dict): super().__init__(repository_source['url']) server = GithubServer(repository_source) self.repo = server.open_github_repo(repository_source["project"]) def list_files(self, identifier: str) -> List[str]: files = self.repo.get_git_tree(identifier, recursive=True) file_paths = [file.path for file in files.tree if file.type == "blob"] return file_paths def _fetch_branches(self) -> List[Branch]: return [Branch(branch, "github") for branch in self.repo.get_branches()] def get_events(self) -> List[Event]: raise NotImplementedError("Method not implemented for Github Repository") def get_file_contents(self, file_path: str, branch: str = "master") -> Union[bytes, None]: try: file = self.repo.get_contents(file_path, branch) except github.UnknownObjectException: return None return file.decoded_content def compare(self, point_1: str, point_2: str) -> List[Diff]: comparison = self.repo.compare(point_1, point_2) return [Diff(diff, "github") for diff in comparison.files] def _fetch_commit_by_id(self, commit_id: str) -> Union[Commit, None]: try: commit_data = self.repo.get_commit(commit_id) except github.GithubException as e: if e.status == 422: return None else: raise e return Commit(commit_data, "github") def _fetch_commits(self, start: Union[datetime.datetime, None], end: Union[datetime.datetime, None], branch: Union[str, None]) -> List[Commit]: if not start: start = github.GithubObject.NotSet if not end: end = github.GithubObject.NotSet if not branch: branch = github.GithubObject.NotSet github_commits = self.repo.get_commits(sha=branch, since=start, until=end) return [Commit(github_commit, "github") for github_commit in github_commits] def _fetch_tags(self) -> List[Tag]: github_tags = self.repo.get_tags() return [Tag(github_tag, "github") for github_tag in github_tags] class GitlabRepository(Repository): """A Gitlab flavour of a repository. :ivar project: A connection to the gitlab repository """ def __init__(self, data_source: dict): if "token" in data_source: token = data_source["token"] else: token = None server = gitlab_tools.GitlabServer(data_source["url"], token) self.project = server.open_gitlab_project(data_source["project"]) super().__init__(self.project.attributes["web_url"]) def list_files(self, identifier: str) -> List[str]: files = [] page_num = 1 while True: file_page = self.project.repository_tree(ref=identifier, per_page=100, page=page_num, recursive=True) if file_page: files.extend(file_page) page_num += 1 else: break file_paths = [file["path"] for file in files if file["type"] == "blob"] return file_paths def _fetch_branches(self) -> List[Branch]: return [Branch(branch, "gitlab") for branch in self.project.branches.list(all=True)] def get_events(self) -> List[Event]: """Return a list of Events associated with this repository.""" if not self._events: # API requires date in ISO 8601 format gitlab_events = self.project.events.list(all=True, action="pushed") for gitlab_event in gitlab_events: self._events.append(Event(gitlab_event)) return self._events def get_file_contents(self, file_path: str, branch: str = "master") -> Union[bytes, None]: """Get a file directly from the repository.""" try: file = self.project.files.get(file_path, branch) except gitlab.GitlabGetError: return None else: return file.decode() def compare(self, point_1: str, point_2: str) -> List[Diff]: """Compare the state of the repository at two points in time. The points may be branch names, tags or commit ids. Point 1 must be chronologically before point 2. """ if not point_1 + point_2 in self._diffs: gitlab_diffs = self.project.repository_compare(point_1, point_2) robota_diffs = [Diff(diff, "gitlab") for diff in gitlab_diffs["diffs"]] self._diffs[point_1 + point_2] = robota_diffs return self._diffs[point_1 + point_2] def _fetch_commits(self, start: Union[datetime.datetime, None], end: Union[datetime.datetime, None], branch: Union[str, None]) -> List[Commit]: """ Function to return commits falling withing a certain time window. :param start: The start of the time window for included commits. :param end: The end of the time window for included commits. :param branch: Filters commits by branch name. If None, get commits from all branches. :return: A list of Commit object. """ request_parameters = {} if start is not None: request_parameters['since'] = start.isoformat() if end is not None: request_parameters['until'] = end.isoformat() if branch is None: request_parameters['all'] = True else: request_parameters['ref_name'] = branch gitlab_commits = self.project.commits.list(all=True, query_parameters=request_parameters) return [Commit(commit, "gitlab", self.project_url) for commit in gitlab_commits] def _fetch_commit_by_id(self, commit_id: str) -> Union[Commit, None]: try: gitlab_commit = self.project.commits.get(commit_id) except gitlab.exceptions.GitlabGetError: return None return Commit(gitlab_commit, "gitlab", self.project_url) def _fetch_tags(self) -> List[Tag]: """Method for getting tags from the gitlab server.""" gitlab_tags = self.project.tags.list(all=True) return [Tag(gitlab_tag, "gitlab") for gitlab_tag in gitlab_tags] def new_repository(robota_config: dict) -> Union[Repository, None]: """Factory method for Repositories.""" repo_config = config_readers.get_data_source_info(robota_config, "repository") if not repo_config: return None repo_type = repo_config["type"] logger.debug(f"Initialising {repo_type} repository.") if repo_type == "gitlab": return GitlabRepository(repo_config) elif repo_type == "github": return GithubRepository(repo_config) elif repo_type == 'local_repository': return LocalRepository(repo_config) else: raise TypeError(f"Unknown repository type {repo_config['type']}.")
/robota_core-2.2.2.tar.gz/robota_core-2.2.2/robota_core/repository.py
0.554712
0.172067
repository.py
pypi
import json from loguru import logger import time import requests from robota_core import config_readers class AttendanceError(Exception): """An error in collecting attendance data.""" class StudentAttendance: """The student attendance class collects data from an external API about student attendance.""" def __init__(self, robota_config: dict, mock: bool = False): """ :param robota_config: A dictionary of information about data sources read from the robota config file. :param mock: If True, return mock data instead of getting real data from the data source. """ data_source_name = "attendance" attendance_source = config_readers.get_data_source_info(robota_config, data_source_name) if not attendance_source: raise KeyError(f"Data source '{data_source_name}' not found in robota config.") self.data = None self.mock = mock self._get_course_attendance(attendance_source) self.total_sessions = self._get_number_of_sessions() def _get_course_attendance(self, attendance_source: dict): """Get student attendance using the specified data source. :param attendance_source: Information about where to get attendance data from. """ if self.mock: logger.warning("Attendance mocking specified - providing mocked attendance data.") return if attendance_source["type"] == "benchmark": logger.info("Connecting to Benchmark to retrieve attendance data.") self._get_benchmark_attendance(attendance_source) else: raise KeyError(f"Student attendance of type: " f"{attendance_source['type']} not implemented.") def _get_benchmark_attendance(self, attendance_source: dict): """Collect data from the UoM CS Benchmark API. To simplify the API requests, all of the attendance data for a particular course is downloaded at once. This means that StudentAttendance should be instantiated at the beginning and then data collected student by student by accessing the process_benchmark_data method. :param attendance_source: Information about where to get attendance data from. """ headers = {'Private-Token': attendance_source["token"]} data = requests.get(attendance_source["url"], headers=headers).text self.data = json.loads(data) def get_student_attendance(self, student_id: str) -> int: """For an individual student, get their attendance from the list of all attendances. :param student_id: The university ID name of the student to get attendance of. :return student_attendance: The number of sessions attended in the current year. """ if self.mock: return 8 student_attendance = 0 current_time = time.time() for week in self.data: # Only collect attendance data for weeks that have passed. if week["finish"] < current_time: try: if week["events"][student_id][0]["data"] == "present": student_attendance += 1 except KeyError: pass return student_attendance def _get_number_of_sessions(self) -> int: """Get the total number of sessions that a student could have attended in the current year.""" if self.mock: return 10 else: num_sessions = 0 current_time = time.time() for week in self.data: if week["finish"] < current_time: num_sessions += 1 return num_sessions
/robota_core-2.2.2.tar.gz/robota_core-2.2.2/robota_core/attendance.py
0.658088
0.312816
attendance.py
pypi
from loguru import logger import os import pathlib import re import shutil import stat import tempfile import tarfile import csv from typing import List, Tuple, Union import gitlab import yaml from robota_core import gitlab_tools as gitlab_tools class RobotaConfigLoadError(Exception): """The error raised when there is a problem loading the configuration""" class RobotaConfigParseError(Exception): """The error raised when there is a problem parsing the configuration""" def get_config(file_names: Union[str, List[str]], data_source: dict) -> list: """The base method of the class. Calls different methods to get the config depending on the config type. :param file_names: The names of one or more config files to open. :param data_source: Information about the source of the config data. The 'type' key specifies the source of the data and other keys are extra information about the source like url or API token. :return: a list of parsed file contents, one list element for each file specified in `file_names`. If a file is not found, the corresponding list element is set to None. """ if isinstance(file_names, str): file_names = [file_names] if not isinstance(data_source, dict): raise TypeError("Config variables must be a dictionary of variables.") source_type = data_source["type"] if source_type == "local_path": parsed_variables = _config_from_local_path(data_source, file_names) elif source_type == "gitlab": parsed_variables = _config_from_gitlab(data_source, file_names) else: raise RobotaConfigLoadError(f"Source type: {source_type} is not a valid data source for" f" the 'get_config' method.") return parsed_variables def _config_from_gitlab(data_source, file_names) -> List[dict]: parsed_variables = [] config_file_directory, commit_id = get_gitlab_config(data_source) for name in file_names: config_path = config_file_directory / pathlib.Path(name) if config_path.is_file(): file_contents = parse_config(config_path) if isinstance(file_contents, dict): file_contents["config_commit_id"] = commit_id parsed_variables.append(file_contents) else: parsed_variables.append(None) if config_file_directory: shutil.rmtree(config_file_directory, onerror=rmtree_error) return parsed_variables def _config_from_local_path(data_source, file_names) -> List[dict]: parsed_variables = [] for name in file_names: config_path = pathlib.Path(data_source["path"]) / pathlib.Path(name) if config_path.exists(): config = parse_config(config_path) parsed_variables.append(config) else: logger.warning(f"Attempted to load config from path: '{config_path}', " f"but path does not exist.") parsed_variables.append(None) return parsed_variables def get_gitlab_config(config_variables: dict) -> Tuple[pathlib.Path, str]: """Get config from a Gitlab repository by logging in using an access token and downloading the files from the repository. :param config_variables: required keys/value pairs are: gitlab_url: The URL of the gitlab repository gitlab_project: The full project name of the project containing the config files. gitlab_token: The gitlab access token. :return: the temporary directory containing the config files. """ # Read GitLab authentication token stored as environment variable if "token" in config_variables: token = config_variables["token"] else: token = None gitlab_server = gitlab_tools.GitlabServer(config_variables["url"], token) if "branch" in config_variables: branch_name = config_variables["branch"] else: branch_name = "master" project = gitlab_server.open_gitlab_project(config_variables["project"]) try: commit_id = project.commits.get(branch_name).attributes["short_id"] except gitlab.exceptions.GitlabGetError: raise gitlab.exceptions.GitlabGetError(f"Error fetching config. " f"Branch {branch_name} not found in " f"repository: {config_variables['project']}.") temp_path = pathlib.Path(tempfile.mkdtemp()) tar_path = temp_path / pathlib.Path("tar") with open(tar_path, 'wb') as output_dir: output_dir.write(project.repository_archive(branch_name)) with tarfile.TarFile.open(tar_path, mode='r') as input_tar: input_tar.extractall(temp_path) for file in temp_path.iterdir(): if file.name != "tar": return file, commit_id def read_csv_file(csv_path: Union[str, pathlib.Path]) -> dict: """Parse a two column csv file. Return dict with first column as keys and second column as values. """ data = {} with open(csv_path, newline='') as f: reader = csv.reader(f, skipinitialspace=True) for row in reader: if row: data[row[0]] = row[1] return data def process_yaml(yaml_content: dict) -> dict: """Do custom string substitution to the dictionary produced from reading a YAML file. This is not part of the core YAML spec. This function replaces instances of ${key_name} in strings nested as values in dicts or lists with the value of the key "key_name" if "key_name" occurs in the root of the dictionary. """ if isinstance(yaml_content, dict): # Collect all of the highest level values in the dict - these can be used for substitution # elsewhere root_keys = {} for key, value in yaml_content.items(): if not isinstance(value, list) and not isinstance(value, dict): root_keys.update({key: value}) for key, value in yaml_content.items(): yaml_content[key] = substitute_dict(value, root_keys) return yaml_content def substitute_dict(input_value: object, root_keys: dict) -> object: """If `input_value` is a list or dict, recurse into it trying to find strings. If `input_value` is a string then substitute any variables that occur as keys in `root_keys` with the values in `root_keys`. Variables to be substituted are indicated by a bash like syntax, e.g. ${variable_name}.""" if isinstance(input_value, list): for item in input_value: input_value[input_value.index(item)] = substitute_dict(item, root_keys) if isinstance(input_value, dict): for key, value in input_value.items(): input_value[key] = substitute_dict(value, root_keys) if isinstance(input_value, str): sub_keys = re.findall(r"(?<=\${)([^}]*)(?=})", input_value) for key in sub_keys: if key in root_keys: input_value = input_value.replace(f"${{{key}}}", str(root_keys[key])) return input_value def parse_config(config_path: pathlib.Path) -> dict: """Parses a config file to extract the configuration variables from it. :param config_path: the full file path to the config file. :return: the config variables read from the file. Return type depends on the file type. """ config_file_type = config_path.suffix if config_file_type in [".yaml", ".yml"]: config = read_yaml_file(config_path) config = process_yaml(config) elif config_file_type == ".csv": config = read_csv_file(config_path) else: raise RobotaConfigParseError(f"Cannot parse file of type: {type}.") return config def read_yaml_file(config_location: pathlib.Path) -> dict: """ Read a YAML file into a dictionary :param config_location: the path of the config file :return: Key-value pairs from the config file """ # noinspection PyTypeChecker with open(config_location, encoding='utf8') as yaml_file: try: config = yaml.load(yaml_file.read(), Loader=yaml.FullLoader) except yaml.YAMLError as e: logger.error(f"YAML Parsing of file {config_location.absolute()} failed.") raise e return config def get_robota_config(config_path: str, substitution_vars: dict) -> dict: """The robota config specifies the source for each data type used by RoboTA. The RoboTA config is always stored locally since it contains API tokens. :param config_path: The path of the robota config file to read. :param substitution_vars: An optional dictionary of values to substitute into the config file. """ config_path = pathlib.Path(config_path) # Load RoboTA config from file. robota_config = get_config([config_path.name], {"type": "local_path", "path": config_path.parent})[0] if robota_config is None: raise RobotaConfigLoadError(f"Unable to load robota config from {config_path.absolute()}") logger.debug(f"robota-config loaded from {config_path.absolute()}") return substitute_keys(robota_config, substitution_vars) def substitute_keys(robota_config: dict, command_line_args: dict) -> dict: """Go through all of the data sources replacing any curly bracketed strings by named variables provided to roboTA as command line arguments. This allows substitution of things like a team name or exercise number into the robota config. :param robota_config: The dictionary of data sources loaded from robota-config.yaml. :param command_line_args: Command line arguments given to RoboTA. """ for top_key in ["data_types", "data_sources"]: for source_name, data_source in robota_config[top_key].items(): for key, value in data_source.items(): if not value: raise KeyError(f"Key '{key}' in robota config has no value.") for name, arg in command_line_args.items(): if f"{{{name}}}" in value: robota_config[top_key][source_name][key] = robota_config[top_key][source_name][key].replace(f"{{{name}}}", arg) return robota_config def get_data_source_info(robota_config: dict, key: str) -> Union[dict, None]: """Get the information about the data source specified by 'key' from the robota_config dictionary.""" config_error = "Error in RoboTA config file." if "data_types" not in robota_config: raise RobotaConfigParseError(f"{config_error} 'data_types' section not found in " f"robota-config.") if key not in robota_config["data_types"]: logger.debug(f"'{key}' not found in 'data_types' config section. Not initialising " f"this data source.") return None data_type_info = robota_config["data_types"][key] if "data_source" not in data_type_info: raise RobotaConfigParseError(f"{config_error} 'data_source' key not found in details " f"of '{key}' data type in robota_config.") data_source = data_type_info["data_source"] if "data_sources" not in robota_config: raise RobotaConfigParseError(f"{config_error} 'data_sources section not found.") if data_source not in robota_config["data_sources"]: raise RobotaConfigParseError(f"{config_error} Data source '{data_source}' specified in " f"'data_types' section, but no details provided in " f"'data_sources' section.") data_source_info = robota_config["data_sources"][data_source] if "type" not in data_source_info: raise RobotaConfigParseError(f"Error in RoboTA config file. 'type' not specified in " f"data source: '{data_source}'.") return {**data_source_info, **data_type_info} def rmtree_error(func, path, _): """Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. """ if not os.access(path, os.W_OK): os.chmod(path, stat.S_IWUSR) func(path)
/robota_core-2.2.2.tar.gz/robota_core-2.2.2/robota_core/config_readers.py
0.699973
0.254668
config_readers.py
pypi
from abc import abstractmethod import datetime from typing import List, Union, Tuple import re import github.Issue import github.IssueComment from gitlab.v4.objects import ProjectIssueNote, ProjectIssue from loguru import logger from robota_core import gitlab_tools, config_readers from robota_core.github_tools import GithubServer from robota_core.string_processing import string_to_datetime, get_link, clean class Issue: """An Issue :ivar created_at: (datetime) The time at which the issue was created. :ivar assignee: (string) The person to whom the issue was assigned. :ivar closed_at: (datetime) The time at which the issue was closed. :ivar closed_by: (string) The person who closed the issue. :ivar time_stats: (dict) Estimates and reported time taken to work on the issue. :ivar due_date: (datetime) The time at which issue is due to be completed. :ivar title: (string) The title of the issue. :ivar comments: (List[Comment]) A list of Comments associated with the Issue. :ivar state: (string) Whether the issue is open or closed. :ivar milestone: (string) Any milestone the issue is associated with. :ivar url: (string) A link to the Issue on GitLab. """ def __init__(self, issue, issue_source: str, get_comments=True): self.created_at = None self.assignee = None self.closed_at = None self.closed_by = None self.time_stats = None self.due_date = None self.title = "" self.comments: List[IssueComment] = [] self.state = None self.milestone = None self.url = "" self.number = None if issue_source == "gitlab": self._issue_from_gitlab(issue, get_comments) elif issue_source == "github": self._issue_from_github(issue, get_comments) elif issue_source == "test data": self._issue_from_test_data(issue) else: raise TypeError(f"Unknown issue type: '{issue_source}'") self.link = get_link(self.url, self.title) def __eq__(self, other_issue: Union[None, "Issue"]) -> bool: if other_issue is None: return False elif self.created_at == other_issue.created_at and self.title == other_issue.title: return True else: return False def __repr__(self) -> str: return f"Issue: {self.title}" def _issue_from_github(self, github_issue: github.Issue.Issue, get_comments: bool): self.created_at = github_issue.created_at if github_issue.assignee: self.assignee = github_issue.assignee.name else: self.assignee = None if github_issue.closed_by: self.closed_by = github_issue.closed_by.name else: self.closed_by = None self.title = github_issue.title self.state = github_issue.state if github_issue.milestone: self.milestone = {"title": github_issue.milestone.title, 'web_url': github_issue.milestone.url} else: self.milestone = None self.url = github_issue.html_url self.number = github_issue.number if get_comments: comments = github_issue.get_comments() for comment in comments: self.comments.append(IssueComment(comment, "github")) def _issue_from_gitlab(self, gitlab_issue: ProjectIssue, get_comments: bool): """Convert a GitLabIssue to a RoboTA issue.""" self.created_at = string_to_datetime(gitlab_issue.attributes["created_at"]) self.assignee = gitlab_issue.attributes["assignee"] self.closed_at = string_to_datetime(gitlab_issue.attributes["closed_at"]) self.closed_by = gitlab_issue.attributes["closed_by"] self.time_stats = gitlab_issue.attributes["time_stats"] self.due_date = string_to_datetime(gitlab_issue.attributes["due_date"], '%Y-%m-%d') self.title = gitlab_issue.attributes["title"] if gitlab_issue.state == "opened": self.state = "open" else: self.state = gitlab_issue.state gitlab_milestone = gitlab_issue.attributes["milestone"] if gitlab_milestone: self.milestone = {"title": gitlab_milestone['title'], 'web_url': gitlab_milestone['web_url']} self.url = gitlab_issue.attributes["web_url"] self.number = gitlab_issue.attributes["iid"] # Returns comments in descending order of creation date (oldest first) if get_comments: all_notes = gitlab_issue.notes.list(all=True) for note in all_notes: self.comments.append(IssueComment(note, "gitlab")) def _issue_from_test_data(self, issue_data): (number, title) = issue_data self.number = number self.title = title def get_assignee(self) -> Union[str, None]: """ Return name of issue assignee :return If issue has an assignee, returns their name else returns None. """ if self.assignee: return self.assignee['name'] return None def get_assignment_date(self) -> Union[datetime.datetime, None]: """Get assignment date for an issue. First checks comments for assignment date and if none is found, returns the issue creation date. If there is more than one assignment date, this method will always return the most recent. :return: The date at which the issue was assigned. """ if not self.assignee: return None # Looking for most recent comment first so reverse comment list. for comment in reversed(self.comments): if comment.text.startswith('assigned to'): return comment.created_at return self.created_at def get_time_estimate_date(self) -> Union[datetime.datetime, None]: """Gets the date a time estimate was added to an issue. This only works for issues made after 05/02/19 as this was a feature added in Gitlab 11.4. :return: Date of the first time estimate, None if no time estimate was found. """ # Comments are stored oldest first. for comment in reversed(self.comments): if comment.text.startswith('changed time estimate to'): return comment.created_at return None def get_time_estimate(self) -> datetime.timedelta: """Gets estimate of time it will take to close issue.""" time_estimate = self.time_stats['time_estimate'] return datetime.timedelta(seconds=time_estimate) def get_comment_timestamp(self, key_phrase: str, earliest=False) -> Union[datetime.datetime, None]: """Search for a phrase in the comments of an issue If the phrase exists, return creation time of the comment. :param key_phrase: a phrase to search for in a comment on the issue. :param earliest: If True, return the earliest comment matching key_phrase, else return most recent comment matching key_phrase. :return: If phrase is present in a comment, return the the time of the comment, else return None """ # Since we can't guarantee that all Git hosting sites will return comments in the same order # we specifically search for the one we want comments = self.comments matching_comments = [c.created_at for c in comments if key_phrase in c.text] if matching_comments: matching_comments.sort(reverse=not earliest) return matching_comments[0] return None def get_recorded_team_member(self, key_phrase: str) -> Union[None, List[str]]: """Report whether a team member has been recorded using a key phrase for issue. Key phrase should appear at the start of a comment to indicate assignment of sub-team member, code reviewer (etc). :param key_phrase: Phrase to search for :return team_member_recorded: Str """ # Strings we're searching for are: # - key_phrase @username # - key_phrase https://gitlab.cs.man.ac.uk/username # - key_phrase https://gitlab.cs.man.ac.uk/user.name # Also permit the team member to be quoted or in angle brackets # Also permit the url to be in square brackets as this is markdown for a link regex = r"\s*(<|\"|\'|\[)*(@|https://gitlab.cs.man.ac.uk/)(\w+\.*\w*)(>|\"|\'|\])*" regex = key_phrase + regex recorded_team_member = [] for comment in self.comments: match = re.findall(regex, comment.text) if match: for match_contents in match: recorded_team_member.append(match_contents[2]) if recorded_team_member: return recorded_team_member return None def get_date_of_time_spent_record(self, key_phrase: str) -> Union[datetime.datetime, str]: """Determine whether a time spent category has been recorded. The key phrase should appear in a comment to indicate what the time has been spent on. :param key_phrase: Phrase to search for, which should have a time record associated with it :return: Last edited time of comment recording time spent """ # The order of the comments is most recent (i.e. last) first. # Start with the most recent comment, where the key phrases are most likely to appear. for n, comment in enumerate(self.comments): if key_phrase in comment.text: # A `/spend` command in a key phrase comment generates a subsequent comment in # the web interface. In the API, the generated 'time spent' comment shows before # the key phrase comment in time, i.e. comment index + 1! # Furthermore, students might not use the `/spend` command in a comment and # add the time separately. As such, we look for 'time spent' in both the # previous (`/spend`) and next (manual) comment. # 'Previous' and 'next' are used below in the temporal sense, # rather than relating to indices. previous_comment = self.comments[n + 1] next_comment = self.comments[n - 1] if 'time spent' in next_comment.text or 'time spent' in previous_comment.text: return comment.updated_at else: return "No time record found" return "Key phrase not found" def is_assignee_contributing(self, team) -> Union[bool, str]: """Determine whether the Student assigned to work on an Issue is contributing to the exercise.""" if self.assignee is None: return "No issue assignee." else: assigned_student = team.get_student_by_name(self.assignee["name"]) if assigned_student is None: # This will happen if a student leaves the team after the exercise. return "Assignee is not a team member" else: return assigned_student.is_contributing def get_status(self, deadline: datetime.datetime): """Get current status of issue if deadline hasn't passed, otherwise get last status of issue before the deadline, and save in the issue.state attribute so that it is only calculated once. :param deadline: :return: """ if datetime.datetime.now() < deadline: return self.state else: for comment in self.comments: # Has the issue status changed since the deadline? if comment.system and comment.created_at < deadline: if comment.text.startswith('closed'): self.state = 'closed' break elif comment.text == 'reopened': self.state = 'open' break else: # No status change before the deadline self.state = 'open' return self.state class IssueCache: """A cache of Issue objects from a specific date range.""" def __init__(self, start: datetime.datetime = None, end: datetime.datetime = None, get_comments=True, milestone=None): self.start = start self.end = end self.get_comments = get_comments self.issues: List[Issue] = [] self.milestone = milestone def __iter__(self): yield from self.issues def add_issue(self, issue: Issue): """Add an Issue to an IssueCache.""" self.issues.append(issue) class IssueServer: """An IssueServer is a service from which Issues are extracted.""" def __init__(self): self._stored_issues: List[IssueCache] = [] def get_issues(self, start: datetime.datetime = datetime.datetime.fromtimestamp(1), end: datetime.datetime = datetime.datetime.now(), get_comments: bool = True) -> List[Issue]: """Get issues from the issue provider between the start date and end date.""" cached_issues = self._get_cached_issues(start, end) if cached_issues: return cached_issues.issues new_issues = self._fetch_issues(start, end, get_comments) cached_issues = IssueCache(start, end, get_comments) for issue in new_issues: cached_issues.add_issue(issue) self._stored_issues.append(cached_issues) return new_issues def get_issues_by_milestone(self, milestone_name: str) -> Union[List[Issue], None]: """Get a list of issues associated with a milestone.""" for issue_cache in self._stored_issues: if issue_cache.milestone == milestone_name: return issue_cache.issues new_issues = self._fetch_issues_by_milestone(milestone_name) new_cache = IssueCache(milestone=milestone_name) for issue in new_issues: new_cache.add_issue(issue) self._stored_issues.append(new_cache) return new_issues @abstractmethod def _fetch_issues(self, start: datetime.datetime, end: datetime.datetime, get_comments: bool) -> List[Issue]: """Get issues from the issue provider between the start date and end date.""" raise NotImplementedError("Not implemented in base class.") @abstractmethod def _fetch_issues_by_milestone(self, milestone_name: str) -> List[Issue]: """Get issues associated with the given milestone from the issue provider.""" raise NotImplementedError("Not implemented in base class.") def _get_cached_issues(self, start: datetime.datetime, end: datetime.datetime) -> Union[IssueCache, None]: """Check whether issues with the specified start and end date are already stored.""" for cache in self._stored_issues: if cache.start and cache.end: if cache.start == start and cache.end == end: return cache else: return None class GitLabIssueServer(IssueServer): """An IssueServer with GitLab as the server.""" def __init__(self, issue_source: dict): super().__init__() if "token" in issue_source: token = issue_source["token"] else: token = None gitlab_server = gitlab_tools.GitlabServer(issue_source["url"], token) self.project = gitlab_server.open_gitlab_project(issue_source["project"]) def _fetch_issues(self, start: datetime.datetime, end: datetime.datetime, get_comments=True) -> List[Issue]: """Function to return issues falling withing a certain time window. :param start: The start of the time window for included issues :param end: The end of the time window for included issues. :param get_comments: Whether or not to download issue comments from the server. This may take some time if there are a large number of issues so should be disabled if the comments are not needed. :return: A list of Issue objects. """ request_parameters = {} if start is not None: request_parameters['created_after'] = start.isoformat() if end is not None: request_parameters['created_before'] = end.isoformat() gitlab_issues = self.project.issues.list(all=True, query_parameters=request_parameters) return [Issue(gitlab_issue, "gitlab", get_comments) for gitlab_issue in gitlab_issues] def _fetch_issues_by_milestone(self, milestone_name: str) -> List[Issue]: """Get all gitlab issues associated with a particular milestone. :param milestone_name: The name of the milestone to find. """ project_milestones = self.project.milestones.list() for milestone in project_milestones: if milestone.attributes["title"] == milestone_name: milestone_issues = list(milestone.issues()) return [Issue(issue, "gitlab") for issue in milestone_issues] # If the milestone exists but there are no issues associated with it. return [] class GitHubIssueServer(IssueServer): def __init__(self, issue_server_source: dict): super().__init__() server = GithubServer(issue_server_source) self.repo = server.open_github_repo(issue_server_source["project"]) def _fetch_issues(self, start: datetime.datetime, end: datetime.datetime, get_comments: bool) -> List[Issue]: # TODO: This method does not check issue [opening] end date issues = self.repo.get_issues(state="all", since=start) return [Issue(issue, "github") for issue in issues if not issue.pull_request] def _fetch_issues_by_milestone(self, milestone_name: str) -> List[Issue]: milestones = self.repo.get_milestones() for milestone in milestones: if milestone.title == milestone_name: issues = self.repo.get_issues(milestone=milestone, state="all") return [Issue(issue, "github") for issue in issues] # If milestone not found return [] class IssueComment: """A comment is a textual field attached to an Issue :ivar text: (string) The content of the comment message. :ivar created_at: (datetime) The time a comment was made. :ivar updated_at: (datetime) The most recent time the content of a comment was updated. """ def __init__(self, comment, source: str): self.text = None self.created_at = None self.updated_at = None self.system = None if source == "gitlab": self._comment_from_gitlab(comment) elif source == "github": self._comment_from_github(comment) elif source == "test data": self._comment_from_test_data(comment) else: raise TypeError(f"Unknown commit comment source: '{source}'.") def _comment_from_gitlab(self, comment: ProjectIssueNote): """Populate an instance of a comment from a GitLab note.""" self.text = clean(comment.attributes["body"]) self.created_at = string_to_datetime(comment.attributes["created_at"]) self.updated_at = string_to_datetime(comment.attributes["updated_at"]) self.system = comment.attributes["system"] def _comment_from_github(self, comment: github.IssueComment): self.text = comment.body self.created_at = comment.created_at self.updated_at = comment.updated_at def _comment_from_test_data(self, comment: Tuple[str, datetime.datetime, datetime.datetime, str]): (text, created_at, updated_at, system) = comment self.text = text self.created_at = created_at self.updated_at = updated_at self.system = system def get_issue_by_title(issues: List[Issue], title: str) -> Union[Issue, None]: """If issue with 'title' exists in 'issues', return the issue, else return None. :param issues: A list of Issue objects. :param title: An issue title :returns: Issue with title == title, else None. """ for issue in issues: if issue.title == title: return issue return None def new_issue_server(robota_config: dict) -> Union[None, IssueServer]: """A factory method for IssueServers.""" issue_server_source = config_readers.get_data_source_info(robota_config, 'issues') if not issue_server_source: return None server_type = issue_server_source["type"] logger.debug(f"Initialising {server_type} issue server.") if server_type == 'gitlab': return GitLabIssueServer(issue_server_source) if server_type == 'github': return GitHubIssueServer(issue_server_source) else: raise TypeError(f"Unknown issue server type {server_type}.")
/robota_core-2.2.2.tar.gz/robota_core-2.2.2/robota_core/issue.py
0.727104
0.183484
issue.py
pypi
import sys from loguru import logger import urllib.request from typing import List import gitlab.v4.objects class GitlabGroup: """ A group is distinct from a project, a group may contain many projects. Projects contained in a group inherit the members of the containing project. """ def __init__(self, gitlab_connection: gitlab.Gitlab, group_name: str): self.group_name = group_name self.group = gitlab_connection.groups.get(group_name) def get_group_members(self) -> List[str]: """ Get a list of members in a group. :return member_list: Names of members of group. """ member_list = [] for member in self.group.members.list(): member_list.append(member.attributes['name']) return member_list class GitlabServer: """A connection to the Gitlab server. Contains methods for interfacing with the API. This is held distinct from the Repository object because it can also be used to interface with an Issue server.""" def __init__(self, url: str, token: str): """ Initialise the connection to the server, getting credentials from the credentials file. :param url: url of GitLab server :param token: Authentication token for gitlab server. """ self.url = url self.token = token self.gitlab_connection: gitlab.Gitlab = self._open_gitlab_connection() def _open_gitlab_connection(self) -> gitlab.Gitlab: """Open a connection to the GitLab server using authentication token.""" if not self.token: logger.error("Must provide an authentication token in robota config to use the " "gitlab API.") raise KeyError() server = gitlab.Gitlab(self.url, private_token=self.token) try: server.auth() except gitlab.exceptions.GitlabAuthenticationError: logger.error("Incorrect authentication token provided. Unable to connect to GitLab.") # Exit to prevent really long gitlab stack trace. sys.exit(1) except gitlab.exceptions.GitlabHttpError: logger.error(f"Unable to find gitlab server '{self.url}.") sys.exit(1) logger.info(f"Logged in to gitlab: '{server.url}' as {server.user.attributes['name']}") return server def open_gitlab_project(self, project_path: str) -> gitlab.v4.objects.Project: """Open a GitLab project. :param project_path: The path of the project to open. Includes namespace. :return: A GitLab project object. """ if "/" not in project_path: raise gitlab.exceptions.GitlabGetError("Must provide namespace " "when opening gitlab project.") try: url_encoded_path = urllib.request.pathname2url(project_path) project = self.gitlab_connection.projects.get(url_encoded_path) except gitlab.exceptions.GitlabGetError as error_type: logger.error(f"Unable to find project: {project_path}. It either does not exist or " f"the current user {self.gitlab_connection.user.attributes['name']} does " f"not have access to this project.") sys.exit(1) logger.info(f"Connected to gitlab project {project.attributes['path_with_namespace']}") return project def open_gitlab_group(self, group_name: str) -> GitlabGroup: return GitlabGroup(self.gitlab_connection, group_name)
/robota_core-2.2.2.tar.gz/robota_core-2.2.2/robota_core/gitlab_tools.py
0.648466
0.180107
gitlab_tools.py
pypi
import json from loguru import logger from datetime import datetime from enum import Enum from typing import Union, List, Dict, TypeVar from abc import ABC, abstractmethod import jenkins import requests from robota_core.string_processing import string_to_datetime, get_link from robota_core import config_readers class Test: """A representation of the result of a Test. :ivar name: The name of the test. :ivar result: The result of the test, PASSED or FAILED. :ivar time: The time that the test ran. :ivar branch: The branch of commit the test was run upon. This is not populated on object creation.""" def __init__(self, suite: dict, case: dict): self.name = f"{suite['name']}.{case['name']}" self.result = case["status"] self.time = string_to_datetime(suite["timestamp"], "%Y-%m-%dT%H:%M:%S") self.branch = None def __eq__(self, test_result: "Test"): if self.name == test_result.name: return True return False def __hash__(self): return hash(self.name) class BuildResult(Enum): """Represents the result of a Jenkins build.""" Success = 1 Unstable = 2 Failure = 3 Aborted = 4 Not_Built = 5 Gitlab_Timeout = 6 def __str__(self): return self.name class Build: """A Build is the result of executing a CI job. :ivar number: The number of the build. :ivar result: The result of the build :ivar timestamp: The time at which the build started. :ivar commit_id: The ID of the git commit the build was run on. :ivar branch_name: The git branch of the commit the build was run on. :ivar link: A HTML string linking to the web-page that displays the build on Jenkins. :ivar instruction_coverage: A code coverage result from JaCoCo. """ def __init__(self, jenkins_build): self.number: str = "" self.result: BuildResult = None self.timestamp: datetime = None self.commit_id: str = "" self.branch_name: str = "" self.link: str = "" self.instruction_coverage: dict = {} self.test_coverage_url: str = "" self.build_from_jenkins(jenkins_build) def build_from_jenkins(self, jenkins_build): """Create a Robota Build object from a Jenkins build object.""" self.number = jenkins_build["number"] self.result = self._assign_build_result(jenkins_build["result"]) self.timestamp = datetime.fromtimestamp(jenkins_build["timestamp"] / 1000) self.link = get_link(jenkins_build["url"], self.result.name) self.test_coverage_url = f'{jenkins_build["url"]}jacoco/' for action in jenkins_build["actions"]: if "_class" in action: if action["_class"] == "hudson.plugins.git.util.BuildData": self.commit_id = action["lastBuiltRevision"]["SHA1"] self.branch_name = action["lastBuiltRevision"]["branch"][0]["name"] if action["_class"] == "hudson.plugins.jacoco.JacocoBuildAction": if "instructionCoverage" in action: self.instruction_coverage = action['instructionCoverage'] if "FailureCauseBuildAction" in action["_class"]: for cause in action["foundFailureCauses"]: if cause["name"] == 'Connection time-out while accessing GitLab': self.result = BuildResult.Gitlab_Timeout @staticmethod def _assign_build_result(build_result: str) -> BuildResult: """Convert the build result string from Jenkins into a BuildResult representation.""" if build_result == "SUCCESS": return BuildResult.Success elif build_result == "UNSTABLE": return BuildResult.Unstable elif build_result == "FAILURE": return BuildResult.Failure elif build_result == "ABORTED": return BuildResult.Aborted elif build_result == "NOT_BUILT" or build_result is None: return BuildResult.Failure else: raise KeyError(f"Build result of type {build_result} not known.") class Job: """A job is a series of CI checks. Each time a job is executed it stores the result in a build. """ def __init__(self, job_data, project_root): self.name = None self.short_name = None self.url = None # Builds are ordered most recent first. self.last_build_number = None self.last_completed_build_number = None self.last_successful_build_number = None self._builds: List[Build] = [] self.job_from_jenkins(job_data, project_root) def job_from_jenkins(self, jenkins_job: dict, project_root: str): """Create a Robota Job object from a Jenkins Job object.""" self.name = jenkins_job["fullName"].replace(project_root + "/", "") self.short_name = jenkins_job["name"] self.url = jenkins_job["url"] if jenkins_job["lastBuild"]: self.last_build_number = jenkins_job["lastBuild"]["number"] if jenkins_job["lastCompletedBuild"]: self.last_completed_build_number = jenkins_job["lastCompletedBuild"]["number"] if jenkins_job["lastSuccessfulBuild"]: self.last_successful_build_number = jenkins_job["lastSuccessfulBuild"]["number"] for jenkins_build in jenkins_job["builds"]: self._builds.append(Build(jenkins_build)) def get_builds(self) -> List[Build]: """Get all builds of a job.""" return self._builds def get_build_by_number(self, number) -> Union[Build, None]: """Get build of this job by number, where 1 is the chronologically earliest build of a job. If build is not found, returns None.""" for build in self._builds: if build.number == number: return build return None def get_last_completed_build(self) -> Union[Build, None]: """"Get the last completed build of a job.""" try: return self.get_build_by_number(self.last_completed_build_number) except AttributeError: return None def get_last_build(self, start: datetime, end: datetime) -> Union[None, Build]: """Get most recent job build status between start and end. :param start: Build must occur after this time :param end: Build must occur before this time :return: Last build in time window, None if no job in time window. """ if start is None or end is None: raise TypeError # Start with most recent build, looking for the last build before *end* builds = self.get_builds() for build in builds: if start < build.timestamp < end: return build return None def get_first_successful_build(self, start: datetime, end: datetime) -> Union[None, Build]: """Return the first (oldest) successful build in the time window.""" for build in reversed(self.get_builds()): if start < build.timestamp < end and build.result == BuildResult.Success: return build return None def get_first_build(self, start: datetime, end: datetime) -> Union[None, Build]: """Return the first (oldest) build in the time window.""" for build in reversed(self.get_builds()): if start < build.timestamp < end: return build return None def get_build_by_commit_id(self, commit_id) -> Union[Build, None]: """Get a job triggered by commit_id""" builds = self.get_builds() for build in builds: if commit_id == build.commit_id: return build return None class CIServer(ABC): """A CIServer is a service from which test results are fetched. All of these are abstract methods implemented by subclasses. """ def __init__(self): self._jobs: List[Job] = [] self.tests: Dict[str, List[Test]] = {} @abstractmethod def get_jobs_by_folder(self, folder_name: str) -> List[Job]: """Get all jobs located in a particular folder.""" raise NotImplementedError("Not implemented in base class.") @abstractmethod def get_job_by_name(self, job_name: str) -> Union[Job, None]: """Get a job by its name. Return None if job not found.""" raise NotImplementedError("Not implemented in base class.") @abstractmethod def get_tests(self, job_path: str) -> Union[None, List[Test]]: """Get all Tests that were run for a job.""" raise NotImplementedError("Not implemented in base class.") @abstractmethod def get_package_coverage(self, job_path: str, package_name: str) -> Union[None, float]: """Get the percentage test coverage for a particular package.""" raise NotImplementedError("Not implemented in base class.") class JenkinsCIServer(CIServer): """With Jenkins it is possible to download all of the jobs from a whole project at once. This is much quicker than getting each job one by one as the API requests are slow. For this reason the JenkinsCIServer class downloads all jobs from a project and then helper methods get jobs from the local cache.""" def __init__(self, ci_source: dict): """Connects to Jenkins and downloads all jobs. If the jobs are heavily nested in folders, it may be necessary to increase the depth parameter to iteratively fetch the lower level jobs. :param ci_source: A dictionary of config info for setting up the JenkinsCIServer. """ super().__init__() self.url = ci_source["url"] token = ci_source["token"] username = ci_source["username"] self.project_name = ci_source["project_name"] self.folder_name = ci_source["folder_name"] self.base_request_string = f"{self.url}job/{self.project_name}/job/{self.folder_name}/" logger.info("Logging in to Jenkins to get CI information.") self.server = jenkins.Jenkins(self.url, username=username, password=token) # Populate the CIServer object with Jobs request_string = self._build_request_string(folder_depth=4) job_data = self.server.jenkins_open(requests.Request('GET', request_string)) all_jobs = json.loads(job_data) self._populate_jobs(all_jobs) def _populate_jobs(self, nested_jobs): """Iteratively unfolds jobs from any containing folders, and stores all jobs as a flat list.""" for child in nested_jobs["jobs"]: if child["_class"].endswith("Folder"): self._populate_jobs(child) else: self._add_job(child) def _add_job(self, jenkins_job: dict): """Adds a single job to the list of jobs in the CIJobServer instance.""" self._jobs.append(Job(jenkins_job, f"{self.project_name}/{self.folder_name}")) def get_jobs_by_folder(self, folder_name: str) -> List[Job]: """Get all jobs that were located in a particular folder.""" jobs = [] for job in self._jobs: if job.name.startswith(folder_name): jobs.append(job) return jobs def get_job_by_name(self, job_name: str) -> Union[Job, None]: """Get a job by its name. Return None if job not found.""" for job in self._jobs: if job.name == job_name: return job return None def _build_request_string(self, folder_depth=4) -> str: """Returns the request string for all of the Jenkins build results in a folder. The string is formed recursively since the jobs may be in nested folders. :param folder_depth: The number of folders deep to nest the xtree request. """ jobs = "jobs[fullName,name,url,lastBuild[number],lastCompletedBuild[number]," \ "lastSuccessfulBuild[number],BUILDS,JOBS]" builds = "builds[number,result,timestamp,url,actions" \ "[_class,lastBuiltRevision[SHA1,branch[*]],instructionCoverage[*]," \ "foundFailureCauses[*]]]" tree_string = jobs for i in range(folder_depth): tree_string = tree_string.replace("JOBS", jobs) if i == (folder_depth - 1): tree_string = tree_string.replace(",JOBS", "") tree_string = tree_string.replace("BUILDS", builds) return f"{self.base_request_string}/api/json?depth={folder_depth}&tree={tree_string}" def get_tests(self, job_path: str) -> Union[None, List[Test]]: """Get Tests for a job - this is a separate API request to the main job info.""" if job_path in self.tests: return self.tests[job_path] job_name = job_path.replace('/', '/job/') job_name = f'job/{job_name}' request_string = f"{self.base_request_string}{job_name}/lastCompletedBuild/testReport/" \ f"api/json?tree=suites[cases[name,status],name,timestamp]" response = self._jenkins_get(request_string) if not response: return None data = json.loads(response) tests = self._process_test_names(data) self.tests[job_path] = tests return tests def get_package_coverage(self, job_path: str, package_name: str) -> Union[None, float]: """Get the percentage test coverage for a particular package. :param job_path: The tag or job name to query. :param package_name: The name of the package to get coverage for. """ job_name = job_path.replace('/', '/job/') job_name = f'job/{job_name}' request_string = f"{self.base_request_string}{job_name}/lastCompletedBuild/jacoco/" \ f"{package_name}/api/json?tree=instructionCoverage[percentageFloat]" response = self._jenkins_get(request_string) if response is None: return None coverage = json.loads(response) return coverage["instructionCoverage"]["percentageFloat"] def _jenkins_get(self, request_string: str) -> Union[None, str]: """Send a direct API request to the open Jenkins server. :param request_string: The API request string to send. """ request = requests.Request('GET', request_string) try: response = self.server.jenkins_open(request) except jenkins.NotFoundException: # If the job has not generated data corresponding to the request string # then the API request will fail. return None return response @staticmethod def _process_test_names(data: dict) -> List[Test]: """Get a list of test names from the nested JSON in the test report.""" tests = [] for suite in data["suites"]: for case in suite["cases"]: tests.append(Test(suite, case)) return tests # This type refers to any of the subclasses of CIServer - it is used for typing the return of the # CIServer factory method. CIType = TypeVar('CIType', bound=CIServer) def new_ci_server(robota_config: dict) -> Union[None, CIType]: """Factory method for creating CIServers""" ci_server_source = config_readers.get_data_source_info(robota_config, 'ci') if not ci_server_source: return None ci_type = ci_server_source["type"] logger.debug(f"Initialising {ci_type} ci server.") if ci_server_source["type"] == 'jenkins': return JenkinsCIServer(ci_server_source) else: raise TypeError(f"Unknown CI server type {ci_server_source['type']}.")
/robota_core-2.2.2.tar.gz/robota_core-2.2.2/robota_core/ci.py
0.850033
0.229676
ci.py
pypi
import datetime from abc import abstractmethod from typing import List, Union, Dict from loguru import logger from robota_core import gitlab_tools, config_readers from robota_core.github_tools import GithubServer from robota_core.merge_request import MergeRequest, MergeRequestCache class RemoteProvider: """A remote provider is a cloud provider that a git repository can be synchronised to. Remote providers have some features that a basic git Repository does not including merge requests and teams. """ def __init__(self): self._stored_merge_requests: List[MergeRequestCache] = [] def get_merge_requests(self, start: datetime.datetime = datetime.datetime.fromtimestamp(1), end: datetime.datetime = datetime.datetime.now()) -> List[MergeRequest]: cached_merge_requests = self._get_cached_merge_requests(start, end) if cached_merge_requests: return cached_merge_requests.merge_requests new_merge_requests = self._fetch_merge_requests(start, end) cache = MergeRequestCache(start, end, new_merge_requests) self._stored_merge_requests.append(cache) return new_merge_requests @abstractmethod def _fetch_merge_requests(self, start: datetime.datetime, end: datetime.datetime) -> List[MergeRequest]: raise NotImplementedError("Not implemented in base class") def _get_cached_merge_requests(self, start: datetime.datetime, end: datetime.datetime) -> Union[MergeRequestCache, None]: """Check whether merge requests with the specified start and end date are already stored.""" for cache in self._stored_merge_requests: if cache.start == start and cache.end == end: return cache else: return None @abstractmethod def get_members(self) -> Dict[str, str]: """Get a dictionary of names and corresponding usernames of members of this repository.""" raise NotImplementedError("Not implemented in base class.") class GithubRemoteProvider(RemoteProvider): def __init__(self, provider_source: dict): super().__init__() server = GithubServer(provider_source) self.repo = server.open_github_repo(provider_source["project"]) def _fetch_merge_requests(self, start: datetime.datetime, end: datetime.datetime) -> List[MergeRequest]: all_pulls = self.repo.get_pulls() filtered_pulls = [pull for pull in all_pulls if start < pull.created_at < end] return [MergeRequest(pull, "github") for pull in filtered_pulls] def get_members(self) -> Dict[str, str]: """This method returns names and usernames of repo collaborators since github doesn't have the idea of members in the same way as gitlab.""" members = self.repo.get_collaborators() member_names = {member.name: member.login for member in members} return member_names class GitlabRemoteProvider(RemoteProvider): def __init__(self, provider_source: dict): super().__init__() if "token" in provider_source: token = provider_source["token"] else: token = None server = gitlab_tools.GitlabServer(provider_source["url"], token) self.project = server.open_gitlab_project(provider_source["project"]) super().__init__() def _fetch_merge_requests(self, start: datetime.datetime, end: datetime.datetime) -> List[MergeRequest]: """Get merge requests within a time period""" merge_requests = self.project.mergerequests.list(created_after=start, created_before=end) return [MergeRequest(merge_request, "gitlab") for merge_request in merge_requests] def get_members(self) -> Dict[str, str]: members = self.project.members.list() member_names = {member.attributes['name']: member.attributes['username'] for member in members} return member_names def new_remote_provider(robota_config: dict) -> Union[RemoteProvider, None]: """Factory method for RemoteProvider.""" provider_config = config_readers.get_data_source_info(robota_config, "remote_provider") if not provider_config: return None provider_type = provider_config["type"] logger.debug(f"Initialising {provider_type} remote provider.") if provider_type == "gitlab": return GitlabRemoteProvider(provider_config) elif provider_type == "github": return GithubRemoteProvider(provider_config) else: raise TypeError(f"Unknown remote provider type {provider_config['type']}.")
/robota_core-2.2.2.tar.gz/robota_core-2.2.2/robota_core/remote_provider.py
0.73848
0.270516
remote_provider.py
pypi
import time import math from abc import ABC, abstractmethod import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import rps.utilities.misc as misc # RobotariumABC: This is an interface for the Robotarium class that # ensures the simulator and the robots match up properly. # THIS FILE SHOULD NEVER BE MODIFIED OR SUBMITTED! class RobotariumABC(ABC): def __init__(self, number_of_robots=-1, show_figure=True, sim_in_real_time=True, initial_conditions=np.array([])): #Check user input types assert isinstance(number_of_robots,int), "The number of robots used argument (number_of_robots) provided to create the Robotarium object must be an integer type. Recieved type %r." % type(number_of_robots).__name__ assert isinstance(initial_conditions,np.ndarray), "The initial conditions array argument (initial_conditions) provided to create the Robotarium object must be a numpy ndarray. Recieved type %r." % type(initial_conditions).__name__ assert isinstance(show_figure,bool), "The display figure window argument (show_figure) provided to create the Robotarium object must be boolean type. Recieved type %r." % type(show_figure).__name__ assert isinstance(sim_in_real_time,bool), "The simulation running at 0.033s per loop (sim_real_time) provided to create the Robotarium object must be boolean type. Recieved type %r." % type(show_figure).__name__ #Check user input ranges/sizes assert (number_of_robots >= 0 and number_of_robots <= 50), "Requested %r robots to be used when creating the Robotarium object. The deployed number of robots must be between 0 and 50." % number_of_robots if (initial_conditions.size > 0): assert initial_conditions.shape == (3, number_of_robots), "Initial conditions provided when creating the Robotarium object must of size 3xN, where N is the number of robots used. Expected a 3 x %r array but recieved a %r x %r array." % (number_of_robots, initial_conditions.shape[0], initial_conditions.shape[1]) self.number_of_robots = number_of_robots self.show_figure = show_figure self.initial_conditions = initial_conditions # Boundary stuff -> lower left point / width / height self.boundaries = [-1.6, -1, 3.2, 2] self.file_path = None self.current_file_size = 0 # Constants self.time_step = 0.033 self.robot_diameter = 0.11 self.wheel_radius = 0.016 self.base_length = 0.105 self.max_linear_velocity = 0.2 self.max_angular_velocity = 2*(self.wheel_radius/self.robot_diameter)*(self.max_linear_velocity/self.wheel_radius) self.max_wheel_velocity = self.max_linear_velocity/self.wheel_radius self.robot_radius = self.robot_diameter/2 self.velocities = np.zeros((2, number_of_robots)) self.poses = self.initial_conditions if self.initial_conditions.size == 0: self.poses = misc.generate_initial_conditions(self.number_of_robots, spacing=0.2, width=2.5, height=1.5) self.left_led_commands = [] self.right_led_commands = [] # Visualization self.figure = [] self.axes = [] self.left_led_patches = [] self.right_led_patches = [] self.chassis_patches = [] self.right_wheel_patches = [] self.left_wheel_patches = [] if(self.show_figure): self.figure, self.axes = plt.subplots() self.axes.set_axis_off() for i in range(number_of_robots): p = patches.RegularPolygon(self.poses[:2, i], 4, math.sqrt(2)*self.robot_radius, self.poses[2,i]+math.pi/4, facecolor='#FFD700', edgecolor = 'k') rled = patches.Circle(self.poses[:2, i]+0.75*self.robot_radius*np.array((np.cos(self.poses[2, i]), np.sin(self.poses[2, i]))+\ 0.04*np.array((-np.sin(self.poses[2, i]+math.pi/2), np.cos(self.poses[2, i]+math.pi/2)))),\ self.robot_radius/5, fill=False) lled = patches.Circle(self.poses[:2, i]+0.75*self.robot_radius*np.array((np.cos(self.poses[2, i]), np.sin(self.poses[2, i]))+\ 0.015*np.array((-np.sin(self.poses[2, i]+math.pi/2), np.cos(self.poses[2, i]+math.pi/2)))),\ self.robot_radius/5, fill=False) rw = patches.Circle(self.poses[:2, i]+self.robot_radius*np.array((np.cos(self.poses[2, i]+math.pi/2), np.sin(self.poses[2, i]+math.pi/2)))+\ 0.04*np.array((-np.sin(self.poses[2, i]+math.pi/2), np.cos(self.poses[2, i]+math.pi/2))),\ 0.02, facecolor='k') lw = patches.Circle(self.poses[:2, i]+self.robot_radius*np.array((np.cos(self.poses[2, i]-math.pi/2), np.sin(self.poses[2, i]-math.pi/2)))+\ 0.04*np.array((-np.sin(self.poses[2, i]+math.pi/2))),\ 0.02, facecolor='k') #lw = patches.RegularPolygon(self.poses[:2, i]+self.robot_radius*np.array((np.cos(self.poses[2, i]-math.pi/2), np.sin(self.poses[2, i]-math.pi/2)))+\ # 0.035*np.array((-np.sin(self.poses[2, i]+math.pi/2), np.cos(self.poses[2, i]+math.pi/2))),\ # 4, math.sqrt(2)*0.02, self.poses[2,i]+math.pi/4, facecolor='k') self.chassis_patches.append(p) self.left_led_patches.append(lled) self.right_led_patches.append(rled) self.right_wheel_patches.append(rw) self.left_wheel_patches.append(lw) self.axes.add_patch(rw) self.axes.add_patch(lw) self.axes.add_patch(p) self.axes.add_patch(lled) self.axes.add_patch(rled) # Draw arena self.boundary_patch = self.axes.add_patch(patches.Rectangle(self.boundaries[:2], self.boundaries[2], self.boundaries[3], fill=False)) self.axes.set_xlim(self.boundaries[0]-0.1, self.boundaries[0]+self.boundaries[2]+0.1) self.axes.set_ylim(self.boundaries[1]-0.1, self.boundaries[1]+self.boundaries[3]+0.1) plt.ion() plt.show() plt.subplots_adjust(left=-0.03, right=1.03, bottom=-0.03, top=1.03, wspace=0, hspace=0) def set_velocities(self, ids, velocities): # Threshold linear velocities idxs = np.where(np.abs(velocities[0, :]) > self.max_linear_velocity) velocities[0, idxs] = self.max_linear_velocity*np.sign(velocities[0, idxs]) # Threshold angular velocities idxs = np.where(np.abs(velocities[1, :]) > self.max_angular_velocity) velocities[1, idxs] = self.max_angular_velocity*np.sign(velocities[1, idxs]) self.velocities = velocities @abstractmethod def get_poses(self): raise NotImplementedError() @abstractmethod def step(self): raise NotImplementedError() #Protected Functions def _threshold(self, dxu): dxdd = self._uni_to_diff(dxu) to_thresh = np.absolute(dxdd) > self.max_wheel_velocity dxdd[to_thresh] = self.max_wheel_velocity*np.sign(dxdd[to_thresh]) dxu = self._diff_to_uni(dxdd) def _uni_to_diff(self, dxu): r = self.wheel_radius l = self.base_length dxdd = np.vstack((1/(2*r)*(2*dxu[0,:]-l*dxu[1,:]),1/(2*r)*(2*dxu[0,:]+l*dxu[1,:]))) return dxdd def _diff_to_uni(self, dxdd): r = self.wheel_radius l = self.base_length dxu = np.vstack((r/(2)*(dxdd[0,:]+dxdd[1,:]),r/l*(dxdd[1,:]-dxdd[0,:]))) return dxu def _validate(self, errors = {}): # This is meant to be called on every iteration of step. # Checks to make sure robots are operating within the bounds of reality. p = self.poses b = self.boundaries N = self.number_of_robots for i in range(N): x = p[0,i] y = p[1,i] if(x < b[0] or x > (b[0] + b[2]) or y < b[1] or y > (b[1] + b[3])): if "boundary" in errors: errors["boundary"] += 1 else: errors["boundary"] = 1 errors["boundary_string"] = "iteration(s) robots were outside the boundaries." for j in range(N-1): for k in range(j+1,N): if(np.linalg.norm(p[:2,j]-p[:2,k]) <= self.robot_diameter): if "collision" in errors: errors["collision"] += 1 else: errors["collision"] = 1 errors["collision_string"] = "iteration(s) where robots collided." dxdd = self._uni_to_diff(self.velocities) exceeding = np.absolute(dxdd) > self.max_wheel_velocity if(np.any(exceeding)): if "actuator" in errors: errors["actuator"] += 1 else: errors["actuator"] = 1 errors["actuator_string"] = "iteration(s) where the actuator limits were exceeded." return errors
/robotarium_python_simulator-0.0.0-py3-none-any.whl/rps/robotarium_abc.py
0.406273
0.560553
robotarium_abc.py
pypi
import numpy as np from rps.utilities.transformations import * def create_si_position_controller(x_velocity_gain=1, y_velocity_gain=1, velocity_magnitude_limit=0.15): """Creates a position controller for single integrators. Drives a single integrator to a point using a propoertional controller. x_velocity_gain - the gain impacting the x (horizontal) velocity of the single integrator y_velocity_gain - the gain impacting the y (vertical) velocity of the single integrator velocity_magnitude_limit - the maximum magnitude of the produce velocity vector (should be less than the max linear speed of the platform) -> function """ #Check user input types assert isinstance(x_velocity_gain, (int, float)), "In the function create_si_position_controller, the x linear velocity gain (x_velocity_gain) must be an integer or float. Recieved type %r." % type(x_velocity_gain).__name__ assert isinstance(y_velocity_gain, (int, float)), "In the function create_si_position_controller, the y linear velocity gain (y_velocity_gain) must be an integer or float. Recieved type %r." % type(y_velocity_gain).__name__ assert isinstance(velocity_magnitude_limit, (int, float)), "In the function create_si_position_controller, the velocity magnitude limit (y_velocity_gain) must be an integer or float. Recieved type %r." % type(y_velocity_gain).__name__ #Check user input ranges/sizes assert x_velocity_gain > 0, "In the function create_si_position_controller, the x linear velocity gain (x_velocity_gain) must be positive. Recieved %r." % x_velocity_gain assert y_velocity_gain > 0, "In the function create_si_position_controller, the y linear velocity gain (y_velocity_gain) must be positive. Recieved %r." % y_velocity_gain assert velocity_magnitude_limit >= 0, "In the function create_si_position_controller, the velocity magnitude limit (velocity_magnitude_limit) must not be negative. Recieved %r." % velocity_magnitude_limit gain = np.diag([x_velocity_gain, y_velocity_gain]) def si_position_controller(xi, positions): """ xi: 2xN numpy array (of single-integrator states of the robots) points: 2xN numpy array (of desired points each robot should achieve) -> 2xN numpy array (of single-integrator control inputs) """ #Check user input types assert isinstance(xi, np.ndarray), "In the si_position_controller function created by the create_si_position_controller function, the single-integrator robot states (xi) must be a numpy array. Recieved type %r." % type(xi).__name__ assert isinstance(positions, np.ndarray), "In the si_position_controller function created by the create_si_position_controller function, the robot goal points (positions) must be a numpy array. Recieved type %r." % type(positions).__name__ #Check user input ranges/sizes assert xi.shape[0] == 2, "In the si_position_controller function created by the create_si_position_controller function, the dimension of the single-integrator robot states (xi) must be 2 ([x;y]). Recieved dimension %r." % xi.shape[0] assert positions.shape[0] == 2, "In the si_position_controller function created by the create_si_position_controller function, the dimension of the robot goal points (positions) must be 2 ([x_goal;y_goal]). Recieved dimension %r." % positions.shape[0] assert xi.shape[1] == positions.shape[1], "In the si_position_controller function created by the create_si_position_controller function, the number of single-integrator robot states (xi) must be equal to the number of robot goal points (positions). Recieved a single integrator current position input array of size %r x %r and desired position array of size %r x %r." % (xi.shape[0], xi.shape[1], positions.shape[0], positions.shape[1]) _,N = np.shape(xi) dxi = np.zeros((2, N)) # Calculate control input dxi[0][:] = x_velocity_gain*(positions[0][:]-xi[0][:]) dxi[1][:] = y_velocity_gain*(positions[1][:]-xi[1][:]) # Threshold magnitude norms = np.linalg.norm(dxi, axis=0) idxs = np.where(norms > velocity_magnitude_limit) if norms[idxs].size != 0: dxi[:, idxs] *= velocity_magnitude_limit/norms[idxs] return dxi return si_position_controller def create_clf_unicycle_position_controller(linear_velocity_gain=0.8, angular_velocity_gain=3): """Creates a unicycle model pose controller. Drives the unicycle model to a given position and orientation. (($u: \mathbf{R}^{3 \times N} \times \mathbf{R}^{2 \times N} \to \mathbf{R}^{2 \times N}$) linear_velocity_gain - the gain impacting the produced unicycle linear velocity angular_velocity_gain - the gain impacting the produced unicycle angular velocity -> function """ #Check user input types assert isinstance(linear_velocity_gain, (int, float)), "In the function create_clf_unicycle_position_controller, the linear velocity gain (linear_velocity_gain) must be an integer or float. Recieved type %r." % type(linear_velocity_gain).__name__ assert isinstance(angular_velocity_gain, (int, float)), "In the function create_clf_unicycle_position_controller, the angular velocity gain (angular_velocity_gain) must be an integer or float. Recieved type %r." % type(angular_velocity_gain).__name__ #Check user input ranges/sizes assert linear_velocity_gain >= 0, "In the function create_clf_unicycle_position_controller, the linear velocity gain (linear_velocity_gain) must be greater than or equal to zero. Recieved %r." % linear_velocity_gain assert angular_velocity_gain >= 0, "In the function create_clf_unicycle_position_controller, the angular velocity gain (angular_velocity_gain) must be greater than or equal to zero. Recieved %r." % angular_velocity_gain def position_uni_clf_controller(states, positions): """ A position controller for unicycle models. This utilized a control lyapunov function (CLF) to drive a unicycle system to a desired position. This function operates on unicycle states and desired positions to return a unicycle velocity command vector. states: 3xN numpy array (of unicycle states, [x;y;theta]) poses: 3xN numpy array (of desired positons, [x_goal;y_goal]) -> 2xN numpy array (of unicycle control inputs) """ #Check user input types assert isinstance(states, np.ndarray), "In the function created by the create_clf_unicycle_position_controller function, the single-integrator robot states (xi) must be a numpy array. Recieved type %r." % type(states).__name__ assert isinstance(positions, np.ndarray), "In the function created by the create_clf_unicycle_position_controller function, the robot goal points (positions) must be a numpy array. Recieved type %r." % type(positions).__name__ #Check user input ranges/sizes assert states.shape[0] == 3, "In the function created by the create_clf_unicycle_position_controller function, the dimension of the unicycle robot states (states) must be 3 ([x;y;theta]). Recieved dimension %r." % states.shape[0] assert positions.shape[0] == 2, "In the function created by the create_clf_unicycle_position_controller function, the dimension of the robot goal positions (positions) must be 2 ([x_goal;y_goal]). Recieved dimension %r." % positions.shape[0] assert states.shape[1] == positions.shape[1], "In the function created by the create_clf_unicycle_position_controller function, the number of unicycle robot states (states) must be equal to the number of robot goal positions (positions). Recieved a current robot pose input array (states) of size %r states %r and desired position array (positions) of size %r states %r." % (states.shape[0], states.shape[1], positions.shape[0], positions.shape[1]) _,N = np.shape(states) dxu = np.zeros((2, N)) pos_error = positions - states[:2][:] rot_error = np.arctan2(pos_error[1][:],pos_error[0][:]) dist = np.linalg.norm(pos_error, axis=0) dxu[0][:]=linear_velocity_gain*dist*np.cos(rot_error-states[2][:]) dxu[1][:]=angular_velocity_gain*dist*np.sin(rot_error-states[2][:]) return dxu return position_uni_clf_controller def create_clf_unicycle_pose_controller(approach_angle_gain=1, desired_angle_gain=2.7, rotation_error_gain=1): """Returns a controller ($u: \mathbf{R}^{3 \times N} \times \mathbf{R}^{3 \times N} \to \mathbf{R}^{2 \times N}$) that will drive a unicycle-modeled agent to a pose (i.e., position & orientation). This control is based on a control Lyapunov function. approach_angle_gain - affects how the unicycle approaches the desired position desired_angle_gain - affects how the unicycle approaches the desired angle rotation_error_gain - affects how quickly the unicycle corrects rotation errors. -> function """ gamma = approach_angle_gain k = desired_angle_gain h = rotation_error_gain def R(theta): return np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta),np.cos(theta)]]) def pose_uni_clf_controller(states, poses): N_states = states.shape[1] dxu = np.zeros((2,N_states)) for i in range(N_states): translate = R(-poses[2,i]).dot((poses[:2,i]-states[:2,i])) e = np.linalg.norm(translate) theta = np.arctan2(translate[1],translate[0]) alpha = theta - (states[2,i]-poses[2,i]) alpha = np.arctan2(np.sin(alpha),np.cos(alpha)) ca = np.cos(alpha) sa = np.sin(alpha) print(gamma) print(e) print(ca) dxu[0,i] = gamma* e* ca dxu[1,i] = k*alpha + gamma*((ca*sa)/alpha)*(alpha + h*theta) return dxu return pose_uni_clf_controller def create_hybrid_unicycle_pose_controller(linear_velocity_gain=1, angular_velocity_gain=2, velocity_magnitude_limit=0.15, angular_velocity_limit=np.pi, position_error=0.05, position_epsilon=0.02, rotation_error=0.05): '''Returns a controller ($u: \mathbf{R}^{3 \times N} \times \mathbf{R}^{3 \times N} \to \mathbf{R}^{2 \times N}$) that will drive a unicycle-modeled agent to a pose (i.e., position & orientation). This controller is based on a hybrid controller that will drive the robot in a straight line to the desired position then rotate to the desired position. linear_velocity_gain - affects how much the linear velocity is scaled based on the position error angular_velocity_gain - affects how much the angular velocity is scaled based on the heading error velocity_magnitude_limit - threshold for the max linear velocity that will be achieved by the robot angular_velocity_limit - threshold for the max rotational velocity that will be achieved by the robot position_error - the error tolerance for the final position of the robot position_epsilon - the amount of translational distance that is allowed by the rotation before correcting position again. rotation_error - the error tolerance for the final orientation of the robot ''' si_to_uni_dyn = create_si_to_uni_dynamics(linear_velocity_gain=linear_velocity_gain, angular_velocity_limit=angular_velocity_limit) def pose_uni_hybrid_controller(states, poses, input_approach_state = np.empty([0,0])): N=states.shape[1] dxu = np.zeros((2,N)) #This is essentially a hack since default arguments are evaluated only once we will mutate it with each call if input_approach_state.shape[1] != N: approach_state = np.ones((1,N))[0] for i in range(N): wrapped = poses[2,i] - states[2,i] wrapped = np.arctan2(np.sin(wrapped),np.cos(wrapped)) dxi = poses[:2,[i]] - states[:2,[i]] #Normalize Vector norm_ = np.linalg.norm(dxi) if(norm_ > (position_error - position_epsilon) and approach_state[i]): if(norm_ > velocity_magnitude_limit): dxi = velocity_magnitude_limit*dxi/norm_ dxu[:,[i]] = si_to_uni_dyn(dxi, states[:,[i]]) elif(np.absolute(wrapped) > rotation_error): approach_state[i] = 0 if(norm_ > position_error): approach_state = 1 dxu[0,i] = 0 dxu[1,i] = angular_velocity_gain*wrapped else: dxu[:,[i]] = np.zeros((2,1)) return dxu return pose_uni_hybrid_controller
/robotarium_python_simulator-0.0.0-py3-none-any.whl/rps/utilities/controllers.py
0.914792
0.786664
controllers.py
pypi
import numpy as np import matplotlib.pyplot as plt def generate_initial_conditions(N, spacing=0.3, width=3, height=1.8): """Generates random initial conditions in an area of the specified width and height at the required spacing. N: int (number of agents) spacing: double (how far apart positions can be) width: double (width of area) height: double (height of area) -> 3xN numpy array (of poses) """ #Check user input types assert isinstance(N, int), "In the function generate_initial_conditions, the number of robots (N) to generate intial conditions for must be an integer. Recieved type %r." % type(N).__name__ assert isinstance(spacing, (float,int)), "In the function generate_initial_conditions, the minimum spacing between robots (spacing) must be an integer or float. Recieved type %r." % type(spacing).__name__ assert isinstance(width, (float,int)), "In the function generate_initial_conditions, the width of the area to place robots randomly (width) must be an integer or float. Recieved type %r." % type(width).__name__ assert isinstance(height, (float,int)), "In the function generate_initial_conditions, the height of the area to place robots randomly (width) must be an integer or float. Recieved type %r." % type(height).__name__ #Check user input ranges/sizes assert N > 0, "In the function generate_initial_conditions, the number of robots to generate initial conditions for (N) must be positive. Recieved %r." % N assert spacing > 0, "In the function generate_initial_conditions, the spacing between robots (spacing) must be positive. Recieved %r." % spacing assert width > 0, "In the function generate_initial_conditions, the width of the area to initialize robots randomly (width) must be positive. Recieved %r." % width assert height >0, "In the function generate_initial_conditions, the height of the area to initialize robots randomly (height) must be positive. Recieved %r." % height x_range = int(np.floor(width/spacing)) y_range = int(np.floor(height/spacing)) assert x_range != 0, "In the function generate_initial_conditions, the space between robots (space) is too large compared to the width of the area robots are randomly initialized in (width)." assert y_range != 0, "In the function generate_initial_conditions, the space between robots (space) is too large compared to the height of the area robots are randomly initialized in (height)." assert x_range*y_range > N, "In the function generate_initial_conditions, it is impossible to place %r robots within a %r x %r meter area with a spacing of %r meters." % (N, width, height, spacing) choices = (np.random.choice(x_range*y_range, N, replace=False)+1) poses = np.zeros((3, N)) for i, c in enumerate(choices): x,y = divmod(c, y_range) poses[0, i] = x*spacing - width/2 poses[1, i] = y*spacing - height/2 poses[2, i] = np.random.rand()*2*np.pi - np.pi return poses def at_pose(states, poses, position_error=0.05, rotation_error=0.2): """Checks whether robots are "close enough" to poses states: 3xN numpy array (of unicycle states) poses: 3xN numpy array (of desired states) -> 1xN numpy index array (of agents that are close enough) """ #Check user input types assert isinstance(states, np.ndarray), "In the at_pose function, the robot current state argument (states) must be a numpy ndarray. Recieved type %r." % type(states).__name__ assert isinstance(poses, np.ndarray), "In the at_pose function, the checked pose argument (poses) must be a numpy ndarray. Recieved type %r." % type(poses).__name__ assert isinstance(position_error, (float,int)), "In the at_pose function, the allowable position error argument (position_error) must be an integer or float. Recieved type %r." % type(position_error).__name__ assert isinstance(rotation_error, (float,int)), "In the at_pose function, the allowable angular error argument (rotation_error) must be an integer or float. Recieved type %r." % type(rotation_error).__name__ #Check user input ranges/sizes assert states.shape[0] == 3, "In the at_pose function, the dimension of the state of each robot must be 3 ([x;y;theta]). Recieved %r." % states.shape[0] assert poses.shape[0] == 3, "In the at_pose function, the dimension of the checked pose of each robot must be 3 ([x;y;theta]). Recieved %r." % poses.shape[0] assert states.shape == poses.shape, "In the at_pose function, the robot current state and checked pose inputs must be the same size (3xN, where N is the number of robots being checked). Recieved a state array of size %r x %r and checked pose array of size %r x %r." % (states.shape[0], states.shape[1], poses.shape[0], poses.shape[1]) # Calculate rotation errors with angle wrapping res = states[2, :] - poses[2, :] res = np.abs(np.arctan2(np.sin(res), np.cos(res))) # Calculate position errors pes = np.linalg.norm(states[:2, :] - poses[:2, :], 2, 0) # Determine which agents are done done = np.nonzero((res <= rotation_error) & (pes <= position_error)) return done def at_position(states, points, position_error=0.02): """Checks whether robots are "close enough" to desired position states: 3xN numpy array (of unicycle states) points: 2xN numpy array (of desired points) -> 1xN numpy index array (of agents that are close enough) """ #Check user input types assert isinstance(states, np.ndarray), "In the at_position function, the robot current state argument (states) must be a numpy ndarray. Recieved type %r." % type(states).__name__ assert isinstance(points, np.ndarray), "In the at_position function, the desired pose argument (poses) must be a numpy ndarray. Recieved type %r." % type(points).__name__ assert isinstance(position_error, (float,int)), "In the at_position function, the allowable position error argument (position_error) must be an integer or float. Recieved type %r." % type(position_error).__name__ #Check user input ranges/sizes assert states.shape[0] == 3, "In the at_position function, the dimension of the state of each robot (states) must be 3. Recieved %r." % states.shape[0] assert points.shape[0] == 2, "In the at_position function, the dimension of the checked position for each robot (points) must be 2. Recieved %r." % points.shape[0] assert states.shape[1] == poses.shape[1], "In the at_position function, the number of checked points (points) must match the number of robot states provided (states). Recieved a state array of size %r x %r and desired pose array of size %r x %r." % (states.shape[0], states.shape[1], points.shape[0], points.shape[1]) # Calculate position errors pes = np.linalg.norm(states[:2, :] - points, 2, 0) # Determine which agents are done done = np.nonzero((pes <= position_error)) return done def determine_marker_size(robotarium_instance, marker_size_meters): # Get the x and y dimension of the robotarium figure window in pixels fig_dim_pixels = robotarium_instance.axes.transData.transform(np.array([[robotarium_instance.boundaries[2]],[robotarium_instance.boundaries[3]]])) # Determine the ratio of the robot size to the x-axis (the axis are # normalized so you could do this with y and figure height as well). marker_ratio = (marker_size_meters)/(robotarium_instance.boundaries[2]) # Determine the marker size in points so it fits the window. Note: This is squared # as marker sizes are areas. return (fig_dim_pixels[0,0] * marker_ratio)**2. def determine_font_size(robotarium_instance, font_height_meters): # Get the x and y dimension of the robotarium figure window in pixels y1, y2 = robotarium_instance.axes.get_window_extent().get_points()[:,1] # Determine the ratio of the robot size to the y-axis. font_ratio = (y2-y1)/(robotarium_instance.boundaries[2]) # Determine the font size in points so it fits the window. return (font_ratio*font_height_meters)
/robotarium_python_simulator-0.0.0-py3-none-any.whl/rps/utilities/misc.py
0.900797
0.785884
misc.py
pypi
import numpy as np def cycle_GL(N): """ Generates a graph Laplacian for a cycle graph N: int (number of agents) -> NxN numpy array (representing the graph Laplacian) """ #Check user input types assert isinstance(N, int), "In the cycle_GL function, the number of nodes (N) must be an integer. Recieved type %r." % type(N).__name__ #Check user input ranges/sizes assert N > 0, "In the cycle_GL function, number of nodes (N) must be positive. Recieved %r." % N ones = np.ones(N-1) L = 2*np.identity(N) - np.diag(ones, 1) - np.diag(ones, -1) L[N-1, 0] = -1 L[0, N-1] = -1 return L def lineGL(N): """ Generates a graph Laplacian for a line graph N: int (number of agents) -> NxN numpy array (representing the graph Laplacian) """ #Check user input types assert isinstance(N, int), "In the lineGL function, the number of nodes (N) must be an integer. Recieved type %r." % type(N).__name__ #Check user input ranges/sizes assert N > 0, "In the lineGL function, number of nodes (N) must be positive. Recieved %r." % N ones = np.ones(N-1) L = 2*np.identity(N) - np.diag(ones, 1) - np.diag(ones, -1) L[0,0] = 1 L[N-1,N-1] = 1 return L def completeGL(N): """ Generates a graph Laplacian for a complete graph N: int (number of agents) -> NxN numpy array (representing the graph Laplacian) """ #Check user input types assert isinstance(N, int), "In the completeGL function, the number of nodes (N) must be an integer. Recieved type %r." % type(N).__name__ #Check user input ranges/sizes assert N > 0, "In the completeGL function, number of nodes (N) must be positive. Recieved %r." % N L = N*np.identity(N)-np.ones((N,N)) return L def random_connectedGL(v, e): """ Generates a Laplacian for a random, connected graph with v verticies and (v-1) + e edges. v: int (number of nodes) e: number of additional edges -> vxv numpy array (representing the graph Laplacian) """ #Check user input types assert isinstance(v, int), "In the random_connectedGL function, the number of verticies (v) must be an integer. Recieved type %r." % type(v).__name__ assert isinstance(e, int), "In the random_connectedGL function, the number of additional edges (e) must be an integer. Recieved type %r." % type(e).__name__ #Check user input ranges/sizes assert v > 0, "In the random_connectedGL function, number of verticies (v) must be positive. Recieved %r." % v assert e >= 0, "In the random_connectedGL function, number of additional edges (e) must be greater than or equal to zero. Recieved %r." % e L = np.zeros((v,v)) for i in range(1, v): edge = np.random.randint(i,size=(1,1)) #Update adjancency relations L[i,edge] = -1 L[edge,i] = -1 #Update node degrees L[i,i] += 1 L[edge,edge] = L[edge,edge]+1 # Because all nodes have at least 1 degree, chosse from only upper diagonal portion iut = np.triu_indices(v) iul = np.tril_indices(v) Ltemp = np.copy(L) Ltemp[iul] = 1 potEdges = np.where(np.logical_xor(Ltemp, 1)==True) numEdges = min(e, len(potEdges[0])) if numEdges <= 0: return L #Indicies of randomly chosen extra edges edgeIndicies = np.random.permutation(len(potEdges[0]))[:numEdges] sz =L.shape for index in edgeIndicies: #Update adjacency relation L[potEdges[0][index],potEdges[1][index]] = -1 L[potEdges[1][index],potEdges[0][index]] = -1 #Update Degree Relation L[potEdges[0][index],potEdges[0][index]] += 1 L[potEdges[1][index],potEdges[1][index]] += 1 return L def randomGL(v, e): """ Generates a Laplacian for a random graph with v verticies and e edges. v: int (number of nodes) e: number of additional edges -> vxv numpy array (representing the graph Laplacian) """ L = np.tril(np.ones((v,v))) #This works because you can't select diagonals potEdges = np.where(L==0) L = L-L numEdges = min(e, len(potEdges[0])) #Indicies of randomly chosen extra edges edgeIndicies = np.random.permutation(len(potEdges[0]))[:numEdges] for index in edgeIndicies: #Update adjacency relation L[potEdges[0][index],potEdges[1][index]] = -1 L[potEdges[1][index],potEdges[0][index]] = -1 #Update Degree Relation L[potEdges[0][index],potEdges[0][index]] += 1 L[potEdges[1][index],potEdges[1][index]] += 1 return L def topological_neighbors(L, agent): """ Returns the neighbors of a particular agent using the graph Laplacian L: NxN numpy array (representing the graph Laplacian) agent: int (agent: 0 - N-1) -> 1xM numpy array (with M neighbors) """ #Check user input types assert isinstance(L, np.ndarray), "In the topological_neighbors function, the graph Laplacian (L) must be a numpy ndarray. Recieved type %r." % type(L).__name__ assert isinstance(agent, int), "In the topological_neighbors function, the agent number (agent) must be an integer. Recieved type %r." % type(agent).__name__ #Check user input ranges/sizes assert agent >= 0, "In the topological_neighbors function, the agent number (agent) must be greater than or equal to zero. Recieved %r." % agent assert agent <= L.shape[0], "In the topological_neighbors function, the agent number (agent) must be within the dimension of the provided Laplacian (L). Recieved agent number %r and Laplactian size %r by %r." % (agent, L.shape[0], L.shape[1]) row = L[agent, :] row[agent]=0 # Since L = D - A return np.where(row != 0)[0] def delta_disk_neighbors(poses, agent, delta): ''' Returns the agents within the 2-norm of the supplied agent (not including the agent itself) poses: 3xN numpy array (representing the unicycle statese of the robots) agent: int (agent whose neighbors within a radius will be returned) delta: float (radius of delta disk considered) -> 1xM numpy array (with M neighbors) ''' #Check user input types assert isinstance(poses, np.ndarray), "In the delta_disk_neighbors function, the robot poses (poses) must be a numpy ndarray. Recieved type %r." % type(poses).__name__ assert isinstance(agent, int), "In the delta_disk_neighbors function, the agent number (agent) must be an integer. Recieved type %r." % type(agent).__name__ assert isinstance(delta, (int,float)), "In the delta_disk_neighbors function, the agent number (agent) must be an integer. Recieved type %r." % type(agent).__name__ #Check user input ranges/sizes assert agent >= 0, "In the delta_disk_neighbors function, the agent number (agent) must be greater than or equal to zero. Recieved %r." % agent assert delta >=0, "In the delta_disk_neighbors function, the sensing/communication radius (delta) must be greater than or equal to zero. Recieved %r." % delta assert agent <= poses.shape[1], "In the delta_disk_neighbors function, the agent number (agent) must be within the dimension of the provided poses. Recieved agent number %r and poses for %r agents." % (agent, poses.shape[1]) N = poses.shape[1] agents = np.arange(N) within_distance = [np.linalg.norm(poses[:2,x]-poses[:2,agent])<=delta for x in agents] within_distance[agent] = False return agents[within_distance]
/robotarium_python_simulator-0.0.0-py3-none-any.whl/rps/utilities/graph.py
0.76856
0.763792
graph.py
pypi
import numpy as np def create_si_to_uni_dynamics(linear_velocity_gain=1, angular_velocity_limit=np.pi): """ Returns a function mapping from single-integrator to unicycle dynamics with angular velocity magnitude restrictions. linear_velocity_gain: Gain for unicycle linear velocity angular_velocity_limit: Limit for angular velocity (i.e., |w| < angular_velocity_limit) -> function """ #Check user input types assert isinstance(linear_velocity_gain, (int, float)), "In the function create_si_to_uni_dynamics, the linear velocity gain (linear_velocity_gain) must be an integer or float. Recieved type %r." % type(linear_velocity_gain).__name__ assert isinstance(angular_velocity_limit, (int, float)), "In the function create_si_to_uni_dynamics, the angular velocity limit (angular_velocity_limit) must be an integer or float. Recieved type %r." % type(angular_velocity_limit).__name__ #Check user input ranges/sizes assert linear_velocity_gain > 0, "In the function create_si_to_uni_dynamics, the linear velocity gain (linear_velocity_gain) must be positive. Recieved %r." % linear_velocity_gain assert angular_velocity_limit >= 0, "In the function create_si_to_uni_dynamics, the angular velocity limit (angular_velocity_limit) must not be negative. Recieved %r." % angular_velocity_limit def si_to_uni_dyn(dxi, poses): """A mapping from single-integrator to unicycle dynamics. dxi: 2xN numpy array with single-integrator control inputs poses: 2xN numpy array with single-integrator poses -> 2xN numpy array of unicycle control inputs """ #Check user input types assert isinstance(dxi, np.ndarray), "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics function, the single integrator velocity inputs (dxi) must be a numpy array. Recieved type %r." % type(dxi).__name__ assert isinstance(poses, np.ndarray), "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics function, the current robot poses (poses) must be a numpy array. Recieved type %r." % type(poses).__name__ #Check user input ranges/sizes assert dxi.shape[0] == 2, "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics function, the dimension of the single integrator velocity inputs (dxi) must be 2 ([x_dot;y_dot]). Recieved dimension %r." % dxi.shape[0] assert poses.shape[0] == 3, "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics function, the dimension of the current pose of each robot must be 3 ([x;y;theta]). Recieved dimension %r." % poses.shape[0] assert dxi.shape[1] == poses.shape[1], "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics function, the number of single integrator velocity inputs must be equal to the number of current robot poses. Recieved a single integrator velocity input array of size %r x %r and current pose array of size %r x %r." % (dxi.shape[0], dxi.shape[1], poses.shape[0], poses.shape[1]) M,N = np.shape(dxi) a = np.cos(poses[2, :]) b = np.sin(poses[2, :]) dxu = np.zeros((2, N)) dxu[0, :] = linear_velocity_gain*(a*dxi[0, :] + b*dxi[1, :]) dxu[1, :] = angular_velocity_limit*np.arctan2(-b*dxi[0, :] + a*dxi[1, :], dxu[0, :])/(np.pi/2) return dxu return si_to_uni_dyn def create_si_to_uni_dynamics_with_backwards_motion(linear_velocity_gain=1, angular_velocity_limit=np.pi): """ Returns a function mapping from single-integrator dynamics to unicycle dynamics. This implementation of the mapping allows for robots to drive backwards if that direction of linear velocity requires less rotation. linear_velocity_gain: Gain for unicycle linear velocity angular_velocity_limit: Limit for angular velocity (i.e., |w| < angular_velocity_limit) """ #Check user input types assert isinstance(linear_velocity_gain, (int, float)), "In the function create_si_to_uni_dynamics, the linear velocity gain (linear_velocity_gain) must be an integer or float. Recieved type %r." % type(linear_velocity_gain).__name__ assert isinstance(angular_velocity_limit, (int, float)), "In the function create_si_to_uni_dynamics, the angular velocity limit (angular_velocity_limit) must be an integer or float. Recieved type %r." % type(angular_velocity_limit).__name__ #Check user input ranges/sizes assert linear_velocity_gain > 0, "In the function create_si_to_uni_dynamics, the linear velocity gain (linear_velocity_gain) must be positive. Recieved %r." % linear_velocity_gain assert angular_velocity_limit >= 0, "In the function create_si_to_uni_dynamics, the angular velocity limit (angular_velocity_limit) must not be negative. Recieved %r." % angular_velocity_limit def si_to_uni_dyn(dxi, poses): """A mapping from single-integrator to unicycle dynamics. dxi: 2xN numpy array with single-integrator control inputs poses: 2xN numpy array with single-integrator poses -> 2xN numpy array of unicycle control inputs """ #Check user input types assert isinstance(dxi, np.ndarray), "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics_with_backwards_motion function, the single integrator velocity inputs (dxi) must be a numpy array. Recieved type %r." % type(dxi).__name__ assert isinstance(poses, np.ndarray), "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics_with_backwards_motion function, the current robot poses (poses) must be a numpy array. Recieved type %r." % type(poses).__name__ #Check user input ranges/sizes assert dxi.shape[0] == 2, "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics_with_backwards_motion function, the dimension of the single integrator velocity inputs (dxi) must be 2 ([x_dot;y_dot]). Recieved dimension %r." % dxi.shape[0] assert poses.shape[0] == 3, "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics_with_backwards_motion function, the dimension of the current pose of each robot must be 3 ([x;y;theta]). Recieved dimension %r." % poses.shape[0] assert dxi.shape[1] == poses.shape[1], "In the si_to_uni_dyn function created by the create_si_to_uni_dynamics_with_backwards_motion function, the number of single integrator velocity inputs must be equal to the number of current robot poses. Recieved a single integrator velocity input array of size %r x %r and current pose array of size %r x %r." % (dxi.shape[0], dxi.shape[1], poses.shape[0], poses.shape[1]) M,N = np.shape(dxi) a = np.cos(poses[2, :]) b = np.sin(poses[2, :]) dxu = np.zeros((2, N)) dxu[0, :] = linear_velocity_gain*(a*dxi[0, :] + b*dxi[1, :]) dxu[1, :] = angular_velocity_limit*np.arctan2(-b*dxi[0, :] + a*dxi[1, :], dxu[0, :])/(np.pi/2) return dxu return si_to_uni_dyn def create_si_to_uni_mapping(projection_distance=0.05, angular_velocity_limit = np.pi): """Creates two functions for mapping from single integrator dynamics to unicycle dynamics and unicycle states to single integrator states. This mapping is done by placing a virtual control "point" in front of the unicycle. projection_distance: How far ahead to place the point angular_velocity_limit: The maximum angular velocity that can be provided -> (function, function) """ #Check user input types assert isinstance(projection_distance, (int, float)), "In the function create_si_to_uni_mapping, the projection distance of the new control point (projection_distance) must be an integer or float. Recieved type %r." % type(projection_distance).__name__ assert isinstance(angular_velocity_limit, (int, float)), "In the function create_si_to_uni_mapping, the maximum angular velocity command (angular_velocity_limit) must be an integer or float. Recieved type %r." % type(angular_velocity_limit).__name__ #Check user input ranges/sizes assert projection_distance > 0, "In the function create_si_to_uni_mapping, the projection distance of the new control point (projection_distance) must be positive. Recieved %r." % projection_distance assert projection_distance >= 0, "In the function create_si_to_uni_mapping, the maximum angular velocity command (angular_velocity_limit) must be greater than or equal to zero. Recieved %r." % angular_velocity_limit def si_to_uni_dyn(dxi, poses): """Takes single-integrator velocities and transforms them to unicycle control inputs. dxi: 2xN numpy array of single-integrator control inputs poses: 3xN numpy array of unicycle poses -> 2xN numpy array of unicycle control inputs """ #Check user input types assert isinstance(dxi, np.ndarray), "In the si_to_uni_dyn function created by the create_si_to_uni_mapping function, the single integrator velocity inputs (dxi) must be a numpy array. Recieved type %r." % type(dxi).__name__ assert isinstance(poses, np.ndarray), "In the si_to_uni_dyn function created by the create_si_to_uni_mapping function, the current robot poses (poses) must be a numpy array. Recieved type %r." % type(poses).__name__ #Check user input ranges/sizes assert dxi.shape[0] == 2, "In the si_to_uni_dyn function created by the create_si_to_uni_mapping function, the dimension of the single integrator velocity inputs (dxi) must be 2 ([x_dot;y_dot]). Recieved dimension %r." % dxi.shape[0] assert poses.shape[0] == 3, "In the si_to_uni_dyn function created by the create_si_to_uni_mapping function, the dimension of the current pose of each robot must be 3 ([x;y;theta]). Recieved dimension %r." % poses.shape[0] assert dxi.shape[1] == poses.shape[1], "In the si_to_uni_dyn function created by the create_si_to_uni_mapping function, the number of single integrator velocity inputs must be equal to the number of current robot poses. Recieved a single integrator velocity input array of size %r x %r and current pose array of size %r x %r." % (dxi.shape[0], dxi.shape[1], poses.shape[0], poses.shape[1]) M,N = np.shape(dxi) cs = np.cos(poses[2, :]) ss = np.sin(poses[2, :]) dxu = np.zeros((2, N)) dxu[0, :] = (cs*dxi[0, :] + ss*dxi[1, :]) dxu[1, :] = (1/projection_distance)*(-ss*dxi[0, :] + cs*dxi[1, :]) #Impose angular velocity cap. dxu[1,dxu[1,:]>angular_velocity_limit] = angular_velocity_limit dxu[1,dxu[1,:]<-angular_velocity_limit] = -angular_velocity_limit return dxu def uni_to_si_states(poses): """Takes unicycle states and returns single-integrator states poses: 3xN numpy array of unicycle states -> 2xN numpy array of single-integrator states """ _,N = np.shape(poses) si_states = np.zeros((2, N)) si_states[0, :] = poses[0, :] + projection_distance*np.cos(poses[2, :]) si_states[1, :] = poses[1, :] + projection_distance*np.sin(poses[2, :]) return si_states return si_to_uni_dyn, uni_to_si_states def create_uni_to_si_dynamics(projection_distance=0.05): """Creates two functions for mapping from unicycle dynamics to single integrator dynamics and single integrator states to unicycle states. This mapping is done by placing a virtual control "point" in front of the unicycle. projection_distance: How far ahead to place the point -> function """ #Check user input types assert isinstance(projection_distance, (int, float)), "In the function create_uni_to_si_dynamics, the projection distance of the new control point (projection_distance) must be an integer or float. Recieved type %r." % type(projection_distance).__name__ #Check user input ranges/sizes assert projection_distance > 0, "In the function create_uni_to_si_dynamics, the projection distance of the new control point (projection_distance) must be positive. Recieved %r." % projection_distance def uni_to_si_dyn(dxu, poses): """A function for converting from unicycle to single-integrator dynamics. Utilizes a virtual point placed in front of the unicycle. dxu: 2xN numpy array of unicycle control inputs poses: 3xN numpy array of unicycle poses projection_distance: How far ahead of the unicycle model to place the point -> 2xN numpy array of single-integrator control inputs """ #Check user input types assert isinstance(dxu, np.ndarray), "In the uni_to_si_dyn function created by the create_uni_to_si_dynamics function, the unicycle velocity inputs (dxu) must be a numpy array. Recieved type %r." % type(dxi).__name__ assert isinstance(poses, np.ndarray), "In the uni_to_si_dyn function created by the create_uni_to_si_dynamics function, the current robot poses (poses) must be a numpy array. Recieved type %r." % type(poses).__name__ #Check user input ranges/sizes assert dxu.shape[0] == 2, "In the uni_to_si_dyn function created by the create_uni_to_si_dynamics function, the dimension of the unicycle velocity inputs (dxu) must be 2 ([v;w]). Recieved dimension %r." % dxu.shape[0] assert poses.shape[0] == 3, "In the uni_to_si_dyn function created by the create_uni_to_si_dynamics function, the dimension of the current pose of each robot must be 3 ([x;y;theta]). Recieved dimension %r." % poses.shape[0] assert dxu.shape[1] == poses.shape[1], "In the uni_to_si_dyn function created by the create_uni_to_si_dynamics function, the number of unicycle velocity inputs must be equal to the number of current robot poses. Recieved a unicycle velocity input array of size %r x %r and current pose array of size %r x %r." % (dxu.shape[0], dxu.shape[1], poses.shape[0], poses.shape[1]) M,N = np.shape(dxu) cs = np.cos(poses[2, :]) ss = np.sin(poses[2, :]) dxi = np.zeros((2, N)) dxi[0, :] = (cs*dxu[0, :] - projection_distance*ss*dxu[1, :]) dxi[1, :] = (ss*dxu[0, :] + projection_distance*cs*dxu[1, :]) return dxi return uni_to_si_dyn
/robotarium_python_simulator-0.0.0-py3-none-any.whl/rps/utilities/transformations.py
0.925949
0.802323
transformations.py
pypi
__author__ = "Gregorio Ambrosio" __contact__ = "gambrosio[at]uma.es" __copyright__ = "Copyright 2023, Gregorio Ambrosio" __date__ = "2023/02/20" __license__ = "MIT" import cv2 from robotathome import logger __all__ = ['filter_sensor_observations', 'get_frames_per_second', 'get_RGBD_image', 'RGBD_images', 'composed_RGBD_images'] def filter_sensor_observations(rh_dataset, df, home_session_name='alma-s1', home_subsession=0, room_name='alma_masterroom1', sensor_list=['RGBD_3', 'RGBD_4', 'RGBD_1', 'RGBD_2'] ): """Return a dictionary with an item per sensor. This function applies a filter to the dataframe to select data for a home session and home subsession, a room name, and a list of sensor names. Args: rh_dataset: a robotathome object to get the id associated to a name df: a Pandas dataframe with the data resulting from the execution of the RoboAtHome:get_sensor_observations method. home_session_name: a string with the home session name home_subsession: the subsession number (0 or 1) room_name: a string with the room name sensor_list: a list made up of the names of the sensors Returns: df_dict: a dictionary with a item per sensor. Keys are the sensor names, and values are the filtered dataframe for that sensor. """ # We need to get some ids from names because home_session_id = rh_dataset.name2id(home_session_name, 'hs') room_id = rh_dataset.name2id(room_name, 'r') qstr1 = f'home_session_id=={home_session_id}' qstr2 = f'home_subsession_id=={home_subsession}' qstr3 = f'room_id=={room_id}' df_dict = {} # Apply filter a get the corresponding subset for sensor_name in sensor_list: sensor_id = rh_dataset.name2id(sensor_name, 's') qstr4 = f'sensor_id=={sensor_id}' df_query_str = qstr1 + ' & ' + qstr2 + ' & ' + qstr3 + ' & ' + qstr4 df_dict[sensor_name] = df.query(df_query_str) return df_dict def get_frames_per_second(df): """Compute frames per second for a sensor observations dataframe. Args: df: a Pandas dataframe with the data resulting from the execution of the RoboAtHome:get_sensor_observations method. Returns: frames_per_second: the result of calculating the time between the first frame and the last frame divided by the number of frames """ # Computing frames per second num_of_frames = len(df.index) seconds = (df.iloc[-1]['timestamp'] - df.iloc[0]['timestamp']) / 10**7 frames_per_second = num_of_frames / seconds logger.debug("frames per second: {:.2f}", frames_per_second) return frames_per_second def get_RGBD_image(rh_dataset, row): """Return a tuple composed of RGB & D images.""" [rgb_f, d_f] = rh_dataset.get_RGBD_files(row['id']) RGBD_image = (cv2.imread(rgb_f, cv2.IMREAD_COLOR), cv2.imread(d_f, cv2.IMREAD_COLOR)) return RGBD_image def RGBD_images(rh_dataset, df): """ Return a generator function of images.""" for _, row in df.iterrows(): img = get_RGBD_image(rh_dataset, row) yield img def composed_RGBD_images(rh_dataset, df_dict): """ Return a generator function of composed images. Returns: A dictionary whose keys are sensor names (sensor_list) and values are tuples of RGB image list and D image list of the corresponding sensor. """ # Yield over df_dict, i.e. frame by frame df_list = list(df_dict.values()) # Get a list of dataframes sensor_list = list(df_dict.keys()) df_lengths = [len(df) for df in df_list] # Get a list of df's lengths number_of_rows = min(df_lengths) # Select the minumun length # For each row we will make a composed image for row_index in range(number_of_rows): # For each sensor we will append an image to img_list RGB_image_list = [] # initialization of img_list D_image_list = [] for df in df_list: row = df.iloc[row_index] RGBD_image = get_RGBD_image(rh_dataset, row) RGB_image_list.append(RGBD_image[0]) D_image_list.append(RGBD_image[1]) RGB_image_dict = dict(zip(sensor_list, RGB_image_list)) D_image_dict = dict(zip(sensor_list, D_image_list)) yield (RGB_image_dict, D_image_dict)
/robotathome-1.1.9-py3-none-any.whl/src/core/df.py
0.889132
0.448849
df.py
pypi
class Board: def __init__(self, framework): self._framework = framework self.send_message = "" self.key_status = 0 self.cpu_temperature = 0.00 self.mpu_pit = 0.000 self.mpu_yaw = 0.000 self.mpu_rol = 0.000 self.mpu_temperature = 0.000 self.mpu_altitude = 0.000 self.mpu_pressure = 0.000 def led_status(self, channel, status): message = {"type": "led-status", "channel": channel, "status": status} self.send_message = self._framework.utils.json.dumps(message) return self.send_message def io_mode(self, channel, mode): message = {"type": "io-mode", "channel": channel, "mode": mode} self.send_message = self._framework.utils.json.dumps(message) return self.send_message def io_status(self, channel, status): message = {"type": "io-status", "channel": channel, "status": status} self.send_message = self._framework.utils.json.dumps(message) return self.send_message def power_status(self, channel, channel_id, status): message = {"type": "power-status", "channel": channel, "id": channel_id, "status": status} self.send_message = self._framework.utils.json.dumps(message) return self.send_message def pwm_control(self, channel, width): message = {"type": "pwm", "channel": channel, "width": width} self.send_message = self._framework.utils.json.dumps(message) return self.send_message def key_status(self): message = {"type": "key-status"} self.send_message = self._framework.utils.json.dumps(message) return self.send_message def read_key_status(self): return self.key_status def cpu_temperature(self): message = {"type": "cpu-temperature"} self.send_message = self._framework.utils.json.dumps(message) return self.send_message def read_cpu_temperature(self): return self.cpu_temperature def mpu_data(self): message = {"type": "mpu"} self.send_message = self._framework.utils.json.dumps(message) return self.send_message def read_mpu_data(self, data): if data == "pit": return self.mpu_pit if data == "yaw": return self.mpu_yaw if data == "rol": return self.mpu_rol if data == "temperature": return self.mpu_temperature if data == "altitude": return self.mpu_altitude if data == "pressure": return self.mpu_pressure return 0.000
/robotchain_sdk-1.0.6-py3-none-any.whl/robotchain_sdk/board/__init__.py
0.721351
0.224087
__init__.py
pypi
import inspect from typing import ( AsyncIterable, AsyncIterator, Awaitable, Callable, Iterable, Optional, TypeVar, Union, cast, ) __all__ = ["async_chain", "async_chain_iterator", "async_takewhile", "async_dropwhile"] _T = TypeVar("_T") AnyIterable = Union[Iterable[_T], AsyncIterable[_T]] async def async_chain(*iterables: AnyIterable[_T]) -> AsyncIterator[_T]: for iterable in iterables: if isinstance(iterable, AsyncIterable): async for v in iterable: yield v else: for v in iterable: yield v async def async_chain_iterator(iterator: AsyncIterator[AnyIterable[_T]]) -> AsyncIterator[_T]: async for e in iterator: async for v in async_chain(e): yield v async def __call_predicate(predicate: Union[Callable[[_T], bool], Callable[[_T], Awaitable[bool]]], e: _T) -> bool: result = predicate(e) if inspect.isawaitable(result): return await cast(Awaitable[bool], result) return cast(bool, result) async def iter_any_iterable(iterable: AnyIterable[_T]) -> AsyncIterator[_T]: if isinstance(iterable, AsyncIterable): async for e in iterable: yield e else: for e in iterable: yield e async def async_takewhile( predicate: Union[Callable[[_T], bool], Callable[[_T], Awaitable[bool]]], iterable: AnyIterable[_T], ) -> AsyncIterator[_T]: async for e in iter_any_iterable(iterable): result = await __call_predicate(predicate, e) if result: yield e else: break async def async_dropwhile( predicate: Union[Callable[[_T], bool], Callable[[_T], Awaitable[bool]]], iterable: AnyIterable[_T], ) -> AsyncIterator[_T]: result: Union[bool, Awaitable[bool]] = True async for e in iter_any_iterable(iterable): if not result: yield e else: result = await __call_predicate(predicate, e) if not result: yield e class __NotSet: # noqa: N801 pass __NOT_SET = __NotSet() async def async_next(__i: AsyncIterator[_T], __default: Union[_T, None, __NotSet] = __NOT_SET) -> Optional[_T]: try: return await __i.__anext__() except StopAsyncIteration: if __default is __NOT_SET: raise return cast(_T, __default)
/robotcode_core-0.54.3-py3-none-any.whl/robotcode/core/async_itertools.py
0.701509
0.261466
async_itertools.py
pypi
from __future__ import annotations import functools import os import re from pathlib import Path, PurePath from typing import Any, Iterable, Iterator, Optional, Sequence, Union, cast def _glob_pattern_to_re(pattern: str) -> str: result = "(?ms)^" in_group = False i = 0 while i < len(pattern): c = pattern[i] if c in "\\/$^+.()=!|": result += "\\" + c elif c == "?": result += "." elif c in "[]": result += c elif c == "{": in_group = True result += "(" elif c == "}": in_group = False result += ")" elif c == ",": if in_group: result += "|" else: result += "\\" + c elif c == "*": prev_char = pattern[i - 1] if i > 0 else None star_count = 1 while (i + 1) < len(pattern) and pattern[i + 1] == "*": star_count += 1 i += 1 next_char = pattern[i + 1] if (i + 1) < len(pattern) else None is_globstar = ( star_count > 1 and (prev_char is None or prev_char == "/") and (next_char is None or next_char == "/") ) if is_globstar: result += "((?:[^/]*(?:/|$))*)" i += 1 else: result += "([^/]*)" else: result += c i += 1 result += "$" return result @functools.lru_cache(maxsize=256) def _compile_glob_pattern(pattern: str) -> re.Pattern[str]: return re.compile(_glob_pattern_to_re(pattern)) class Pattern: def __init__(self, pattern: str) -> None: pattern = pattern.strip() self.only_dirs = pattern.endswith("/") path = PurePath(pattern) if path.is_absolute(): self.pattern = path.relative_to(path.anchor).as_posix() else: self.pattern = path.as_posix() if "*" in self.pattern or "?" in self.pattern or "[" in self.pattern or "{" in self.pattern: self.re_pattern: Optional[re.Pattern[str]] = _compile_glob_pattern(self.pattern) else: self.re_pattern = None def matches(self, path: Union[PurePath, str, os.PathLike[str]]) -> bool: if isinstance(path, PurePath): path = path.as_posix() else: path = str(os.fspath(path)) if self.re_pattern is None: return path == self.pattern return self.re_pattern.fullmatch(path) is not None def __str__(self) -> str: return self.pattern def __repr__(self) -> str: return f"{type(self).__qualname__}(pattern={self.pattern!r}" def globmatches(pattern: str, path: Union[PurePath, str, os.PathLike[Any]]) -> bool: return Pattern(pattern).matches(path) FILE_ATTRIBUTE_HIDDEN = 2 def _is_hidden(entry: os.DirEntry[str]) -> bool: if entry.name.startswith("."): return True if os.name == "nt" and ( (not entry.is_symlink() and entry.stat().st_file_attributes & 2 != 0) # type: ignore[attr-defined] or entry.name.startswith("$") ): return True return False def iter_files( path: Union[PurePath, str, os.PathLike[str]], patterns: Union[Sequence[Union[Pattern, str]], Pattern, str, None] = None, ignore_patterns: Union[Sequence[Union[Pattern, str]], Pattern, str, None] = None, *, include_hidden: bool = False, absolute: bool = False, ) -> Iterator[Path]: if not isinstance(path, PurePath): path = PurePath(path or ".") if patterns is not None and isinstance(patterns, (str, Pattern)): patterns = [patterns] if ignore_patterns is not None and isinstance(ignore_patterns, (str, Pattern)): ignore_patterns = [ignore_patterns] yield from _iter_files_recursive_re( path=path, patterns=[] if patterns is None else [p if isinstance(p, Pattern) else Pattern(p) for p in patterns], ignore_patterns=[] if ignore_patterns is None else [p if isinstance(p, Pattern) else Pattern(p) for p in ignore_patterns], include_hidden=include_hidden, absolute=absolute, _base_path=path, ) def _iter_files_recursive_re( path: PurePath, patterns: Sequence[Pattern], ignore_patterns: Sequence[Pattern], include_hidden: bool, absolute: bool, _base_path: PurePath, ) -> Iterator[Path]: try: with os.scandir(path) as it: for f in it: if not include_hidden and _is_hidden(f): continue relative_path = (path / f.name).relative_to(_base_path) if not ignore_patterns or not any( p.matches(relative_path) and (not p.only_dirs or p.only_dirs and f.is_dir()) for p in cast(Iterable[Pattern], ignore_patterns) ): if f.is_dir(): yield from _iter_files_recursive_re( PurePath(f), patterns, ignore_patterns, include_hidden=include_hidden, absolute=absolute, _base_path=_base_path, ) if not patterns or any( p.matches(relative_path) and (not p.only_dirs or p.only_dirs and f.is_dir()) for p in cast(Iterable[Pattern], patterns) ): yield Path(f).absolute() if absolute else Path(f) except (OSError, PermissionError): pass
/robotcode_core-0.54.3-py3-none-any.whl/robotcode/core/utils/glob_path.py
0.701304
0.242172
glob_path.py
pypi
# ruff: noqa: E501 from __future__ import annotations import enum import functools from dataclasses import dataclass from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union from robotcode.core.dataclasses import CamelSnakeMixin __lsp_version__ = "3.17.0" DocumentUri = str URI = str @enum.unique class SemanticTokenTypes(str, enum.Enum): """A set of predefined token types. This set is not fixed an clients can specify additional token types via the corresponding client capabilities. @since 3.16.0""" # Since: 3.16.0 NAMESPACE = "namespace" TYPE = "type" """Represents a generic type. Acts as a fallback for types which can't be mapped to a specific type like class or enum.""" CLASS_ = "class" ENUM = "enum" INTERFACE = "interface" STRUCT = "struct" TYPE_PARAMETER = "typeParameter" PARAMETER = "parameter" VARIABLE = "variable" PROPERTY = "property" ENUM_MEMBER = "enumMember" EVENT = "event" FUNCTION = "function" METHOD = "method" MACRO = "macro" KEYWORD = "keyword" MODIFIER = "modifier" COMMENT = "comment" STRING = "string" NUMBER = "number" REGEXP = "regexp" OPERATOR = "operator" DECORATOR = "decorator" """@since 3.17.0""" # Since: 3.17.0 @enum.unique class SemanticTokenModifiers(str, enum.Enum): """A set of predefined token modifiers. This set is not fixed an clients can specify additional token types via the corresponding client capabilities. @since 3.16.0""" # Since: 3.16.0 DECLARATION = "declaration" DEFINITION = "definition" READONLY = "readonly" STATIC = "static" DEPRECATED = "deprecated" ABSTRACT = "abstract" ASYNC_ = "async" MODIFICATION = "modification" DOCUMENTATION = "documentation" DEFAULT_LIBRARY = "defaultLibrary" @enum.unique class DocumentDiagnosticReportKind(str, enum.Enum): """The document diagnostic report kinds. @since 3.17.0""" # Since: 3.17.0 FULL = "full" """A diagnostic report with a full set of problems.""" UNCHANGED = "unchanged" """A report indicating that the last returned report is still accurate.""" class ErrorCodes(enum.IntEnum): """Predefined error codes.""" PARSE_ERROR = -32700 INVALID_REQUEST = -32600 METHOD_NOT_FOUND = -32601 INVALID_PARAMS = -32602 INTERNAL_ERROR = -32603 SERVER_NOT_INITIALIZED = -32002 """Error code indicating that a server received a notification or request before the server has received the `initialize` request.""" UNKNOWN_ERROR_CODE = -32001 class LSPErrorCodes(enum.IntEnum): REQUEST_FAILED = -32803 """A request failed but it was syntactically correct, e.g the method name was known and the parameters were valid. The error message should contain human readable information about why the request failed. @since 3.17.0""" # Since: 3.17.0 SERVER_CANCELLED = -32802 """The server cancelled the request. This error code should only be used for requests that explicitly support being server cancellable. @since 3.17.0""" # Since: 3.17.0 CONTENT_MODIFIED = -32801 """The server detected that the content of a document got modified outside normal conditions. A server should NOT send this error code if it detects a content change in it unprocessed messages. The result even computed on an older state might still be useful for the client. If a client decides that a result is not of any use anymore the client should cancel the request.""" REQUEST_CANCELLED = -32800 """The client has canceled a request and a server as detected the cancel.""" @enum.unique class FoldingRangeKind(str, enum.Enum): """A set of predefined range kinds.""" COMMENT = "comment" """Folding range for a comment""" IMPORTS = "imports" """Folding range for an import or include""" REGION = "region" """Folding range for a region (e.g. `#region`)""" @enum.unique class SymbolKind(enum.IntEnum): """A symbol kind.""" FILE = 1 MODULE = 2 NAMESPACE = 3 PACKAGE = 4 CLASS = 5 METHOD = 6 PROPERTY = 7 FIELD = 8 CONSTRUCTOR = 9 ENUM = 10 INTERFACE = 11 FUNCTION = 12 VARIABLE = 13 CONSTANT = 14 STRING = 15 NUMBER = 16 BOOLEAN = 17 ARRAY = 18 OBJECT = 19 KEY = 20 NULL = 21 ENUM_MEMBER = 22 STRUCT = 23 EVENT = 24 OPERATOR = 25 TYPE_PARAMETER = 26 @enum.unique class SymbolTag(enum.IntEnum): """Symbol tags are extra annotations that tweak the rendering of a symbol. @since 3.16""" # Since: 3.16 DEPRECATED = 1 """Render a symbol as obsolete, usually using a strike-out.""" @enum.unique class UniquenessLevel(str, enum.Enum): """Moniker uniqueness level to define scope of the moniker. @since 3.16.0""" # Since: 3.16.0 DOCUMENT = "document" """The moniker is only unique inside a document""" PROJECT = "project" """The moniker is unique inside a project for which a dump got created""" GROUP = "group" """The moniker is unique inside the group to which a project belongs""" SCHEME = "scheme" """The moniker is unique inside the moniker scheme.""" GLOBAL_ = "global" """The moniker is globally unique""" @enum.unique class MonikerKind(str, enum.Enum): """The moniker kind. @since 3.16.0""" # Since: 3.16.0 IMPORT_ = "import" """The moniker represent a symbol that is imported into a project""" EXPORT = "export" """The moniker represents a symbol that is exported from a project""" LOCAL = "local" """The moniker represents a symbol that is local to a project (e.g. a local variable of a function, a class not visible outside the project, ...)""" @enum.unique class InlayHintKind(enum.IntEnum): """Inlay hint kinds. @since 3.17.0""" # Since: 3.17.0 TYPE = 1 """An inlay hint that for a type annotation.""" PARAMETER = 2 """An inlay hint that is for a parameter.""" @enum.unique class MessageType(enum.IntEnum): """The message type""" ERROR = 1 """An error message.""" WARNING = 2 """A warning message.""" INFO = 3 """An information message.""" LOG = 4 """A log message.""" @enum.unique class TextDocumentSyncKind(enum.IntEnum): """Defines how the host (editor) should sync document changes to the language server.""" NONE_ = 0 """Documents should not be synced at all.""" FULL = 1 """Documents are synced by always sending the full content of the document.""" INCREMENTAL = 2 """Documents are synced by sending the full content on open. After that only incremental updates to the document are send.""" @enum.unique class TextDocumentSaveReason(enum.IntEnum): """Represents reasons why a text document is saved.""" MANUAL = 1 """Manually triggered, e.g. by the user pressing save, by starting debugging, or by an API call.""" AFTER_DELAY = 2 """Automatic after a delay.""" FOCUS_OUT = 3 """When the editor lost focus.""" @enum.unique class CompletionItemKind(enum.IntEnum): """The kind of a completion entry.""" TEXT = 1 METHOD = 2 FUNCTION = 3 CONSTRUCTOR = 4 FIELD = 5 VARIABLE = 6 CLASS = 7 INTERFACE = 8 MODULE = 9 PROPERTY = 10 UNIT = 11 VALUE = 12 ENUM = 13 KEYWORD = 14 SNIPPET = 15 COLOR = 16 FILE = 17 REFERENCE = 18 FOLDER = 19 ENUM_MEMBER = 20 CONSTANT = 21 STRUCT = 22 EVENT = 23 OPERATOR = 24 TYPE_PARAMETER = 25 @enum.unique class CompletionItemTag(enum.IntEnum): """Completion item tags are extra annotations that tweak the rendering of a completion item. @since 3.15.0""" # Since: 3.15.0 DEPRECATED = 1 """Render a completion as obsolete, usually using a strike-out.""" @enum.unique class InsertTextFormat(enum.IntEnum): """Defines whether the insert text in a completion item should be interpreted as plain text or a snippet.""" PLAIN_TEXT = 1 """The primary text to be inserted is treated as a plain string.""" SNIPPET = 2 """The primary text to be inserted is treated as a snippet. A snippet can define tab stops and placeholders with `$1`, `$2` and `${3:foo}`. `$0` defines the final tab stop, it defaults to the end of the snippet. Placeholders with equal identifiers are linked, that is typing in one will update others too. See also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax""" @enum.unique class InsertTextMode(enum.IntEnum): """How whitespace and indentation is handled during completion item insertion. @since 3.16.0""" # Since: 3.16.0 AS_IS = 1 """The insertion or replace strings is taken as it is. If the value is multi line the lines below the cursor will be inserted using the indentation defined in the string value. The client will not apply any kind of adjustments to the string.""" ADJUST_INDENTATION = 2 """The editor adjusts leading whitespace of new lines so that they match the indentation up to the cursor of the line for which the item is accepted. Consider a line like this: <2tabs><cursor><3tabs>foo. Accepting a multi line completion item is indented using 2 tabs and all following lines inserted will be indented using 2 tabs as well.""" @enum.unique class DocumentHighlightKind(enum.IntEnum): """A document highlight kind.""" TEXT = 1 """A textual occurrence.""" READ = 2 """Read-access of a symbol, like reading a variable.""" WRITE = 3 """Write-access of a symbol, like writing to a variable.""" @enum.unique class CodeActionKind(str, enum.Enum): """A set of predefined code action kinds""" EMPTY = "" """Empty kind.""" QUICK_FIX = "quickfix" """Base kind for quickfix actions: 'quickfix'""" REFACTOR = "refactor" """Base kind for refactoring actions: 'refactor'""" REFACTOR_EXTRACT = "refactor.extract" """Base kind for refactoring extraction actions: 'refactor.extract' Example extract actions: - Extract method - Extract function - Extract variable - Extract interface from class - ...""" REFACTOR_INLINE = "refactor.inline" """Base kind for refactoring inline actions: 'refactor.inline' Example inline actions: - Inline function - Inline variable - Inline constant - ...""" REFACTOR_REWRITE = "refactor.rewrite" """Base kind for refactoring rewrite actions: 'refactor.rewrite' Example rewrite actions: - Convert JavaScript function to class - Add or remove parameter - Encapsulate field - Make method static - Move method to base class - ...""" SOURCE = "source" """Base kind for source actions: `source` Source code actions apply to the entire file.""" SOURCE_ORGANIZE_IMPORTS = "source.organizeImports" """Base kind for an organize imports source action: `source.organizeImports`""" SOURCE_FIX_ALL = "source.fixAll" """Base kind for auto-fix source actions: `source.fixAll`. Fix all actions automatically fix errors that have a clear fix that do not require user input. They should not suppress errors or perform unsafe fixes such as generating new types or classes. @since 3.15.0""" # Since: 3.15.0 @enum.unique class TraceValues(str, enum.Enum): OFF = "off" """Turn tracing off.""" MESSAGES = "messages" """Trace messages only.""" VERBOSE = "verbose" """Verbose message tracing.""" @enum.unique class MarkupKind(str, enum.Enum): """Describes the content type that a client supports in various result literals like `Hover`, `ParameterInfo` or `CompletionItem`. Please note that `MarkupKinds` must not start with a `$`. This kinds are reserved for internal usage.""" PLAIN_TEXT = "plaintext" """Plain text is supported as a content format""" MARKDOWN = "markdown" """Markdown is supported as a content format""" @enum.unique class PositionEncodingKind(str, enum.Enum): """A set of predefined position encoding kinds. @since 3.17.0""" # Since: 3.17.0 UTF8 = "utf-8" """Character offsets count UTF-8 code units.""" UTF16 = "utf-16" """Character offsets count UTF-16 code units. This is the default and must always be supported by servers""" UTF32 = "utf-32" """Character offsets count UTF-32 code units. Implementation note: these are the same as Unicode code points, so this `PositionEncodingKind` may also be used for an encoding-agnostic representation of character offsets.""" @enum.unique class FileChangeType(enum.IntEnum): """The file event type""" CREATED = 1 """The file got created.""" CHANGED = 2 """The file got changed.""" DELETED = 3 """The file got deleted.""" @enum.unique class WatchKind(enum.IntFlag): CREATE = 1 """Interested in create events.""" CHANGE = 2 """Interested in change events""" DELETE = 4 """Interested in delete events""" @enum.unique class DiagnosticSeverity(enum.IntEnum): """The diagnostic's severity.""" ERROR = 1 """Reports an error.""" WARNING = 2 """Reports a warning.""" INFORMATION = 3 """Reports an information.""" HINT = 4 """Reports a hint.""" @enum.unique class DiagnosticTag(enum.IntEnum): """The diagnostic tags. @since 3.15.0""" # Since: 3.15.0 UNNECESSARY = 1 """Unused or unnecessary code. Clients are allowed to render diagnostics with this tag faded out instead of having an error squiggle.""" DEPRECATED = 2 """Deprecated or obsolete code. Clients are allowed to rendered diagnostics with this tag strike through.""" @enum.unique class CompletionTriggerKind(enum.IntEnum): """How a completion was triggered""" INVOKED = 1 """Completion was triggered by typing an identifier (24x7 code complete), manual invocation (e.g Ctrl+Space) or via API.""" TRIGGER_CHARACTER = 2 """Completion was triggered by a trigger character specified by the `triggerCharacters` properties of the `CompletionRegistrationOptions`.""" TRIGGER_FOR_INCOMPLETE_COMPLETIONS = 3 """Completion was re-triggered as current completion list is incomplete""" @enum.unique class SignatureHelpTriggerKind(enum.IntEnum): """How a signature help was triggered. @since 3.15.0""" # Since: 3.15.0 INVOKED = 1 """Signature help was invoked manually by the user or by a command.""" TRIGGER_CHARACTER = 2 """Signature help was triggered by a trigger character.""" CONTENT_CHANGE = 3 """Signature help was triggered by the cursor moving or by the document content changing.""" @enum.unique class CodeActionTriggerKind(enum.IntEnum): """The reason why code actions were requested. @since 3.17.0""" # Since: 3.17.0 INVOKED = 1 """Code actions were explicitly requested by the user or by an extension.""" AUTOMATIC = 2 """Code actions were requested automatically. This typically happens when current selection in a file changes, but can also be triggered when file content changes.""" @enum.unique class FileOperationPatternKind(str, enum.Enum): """A pattern kind describing if a glob pattern matches a file a folder or both. @since 3.16.0""" # Since: 3.16.0 FILE = "file" """The pattern matches a file only.""" FOLDER = "folder" """The pattern matches a folder only.""" @enum.unique class NotebookCellKind(enum.IntEnum): """A notebook cell kind. @since 3.17.0""" # Since: 3.17.0 MARKUP = 1 """A markup-cell is formatted source that is used for display.""" CODE = 2 """A code-cell is source code.""" @enum.unique class ResourceOperationKind(str, enum.Enum): CREATE = "create" """Supports creating new files and folders.""" RENAME = "rename" """Supports renaming existing files and folders.""" DELETE = "delete" """Supports deleting existing files and folders.""" @enum.unique class FailureHandlingKind(str, enum.Enum): ABORT = "abort" """Applying the workspace change is simply aborted if one of the changes provided fails. All operations executed before the failing operation stay executed.""" TRANSACTIONAL = "transactional" """All operations are executed transactional. That means they either all succeed or no changes at all are applied to the workspace.""" TEXT_ONLY_TRANSACTIONAL = "textOnlyTransactional" """If the workspace edit contains only textual file changes they are executed transactional. If resource changes (create, rename or delete file) are part of the change the failure handling strategy is abort.""" UNDO = "undo" """The client tries to undo the operations already executed. But there is no guarantee that this is succeeding.""" @enum.unique class PrepareSupportDefaultBehavior(enum.IntEnum): IDENTIFIER = 1 """The client's default behavior is to select the identifier according the to language's syntax rule.""" @enum.unique class TokenFormat(str, enum.Enum): RELATIVE = "relative" LSPObject = object """LSP object definition. @since 3.17.0""" # Since: 3.17.0 @dataclass class TextDocumentPositionParams(CamelSnakeMixin): """A parameter literal used in requests to pass a text document and a position inside that document.""" text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" @dataclass class WorkDoneProgressParams(CamelSnakeMixin): work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class PartialResultParams(CamelSnakeMixin): partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class ImplementationParams(CamelSnakeMixin): text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class Location(CamelSnakeMixin): """Represents a location inside a resource, such as a line inside a text file.""" uri: DocumentUri range: Range def __hash__(self) -> int: return hash((self.uri, self.range)) @dataclass class TextDocumentRegistrationOptions(CamelSnakeMixin): """General text document registration options.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" @dataclass class WorkDoneProgressOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None @dataclass class ImplementationOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None @dataclass class StaticRegistrationOptions(CamelSnakeMixin): """Static registration options to be returned in the initialize request.""" id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class ImplementationRegistrationOptions(CamelSnakeMixin): document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class TypeDefinitionParams(CamelSnakeMixin): text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class TypeDefinitionOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None @dataclass class TypeDefinitionRegistrationOptions(CamelSnakeMixin): document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class WorkspaceFolder(CamelSnakeMixin): """A workspace folder inside a client.""" uri: URI """The associated URI for this workspace folder.""" name: str """The name of the workspace folder. Used to refer to this workspace folder in the user interface.""" @dataclass class DidChangeWorkspaceFoldersParams(CamelSnakeMixin): """The parameters of a `workspace/didChangeWorkspaceFolders` notification.""" event: WorkspaceFoldersChangeEvent """The actual workspace folder change event.""" @dataclass class ConfigurationParams(CamelSnakeMixin): """The parameters of a configuration request.""" items: List[ConfigurationItem] @dataclass class DocumentColorParams(CamelSnakeMixin): """Parameters for a {@link DocumentColorRequest}.""" text_document: TextDocumentIdentifier """The text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class ColorInformation(CamelSnakeMixin): """Represents a color range from a document.""" range: Range """The range in the document where this color appears.""" color: Color """The actual color value for this color range.""" @dataclass class DocumentColorOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None @dataclass class DocumentColorRegistrationOptions(CamelSnakeMixin): document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class ColorPresentationParams(CamelSnakeMixin): """Parameters for a {@link ColorPresentationRequest}.""" text_document: TextDocumentIdentifier """The text document.""" color: Color """The color to request presentations for.""" range: Range """The range where the color would be inserted. Serves as a context.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class ColorPresentation(CamelSnakeMixin): label: str """The label of this color presentation. It will be shown on the color picker header. By default this is also the text that is inserted when selecting this color presentation.""" text_edit: Optional[TextEdit] = None """An {@link TextEdit edit} which is applied to a document when selecting this presentation for the color. When `falsy` the {@link ColorPresentation.label label} is used.""" additional_text_edits: Optional[List[TextEdit]] = None """An optional array of additional {@link TextEdit text edits} that are applied when selecting this color presentation. Edits must not overlap with the main {@link ColorPresentation.textEdit edit} nor with themselves.""" @dataclass class FoldingRangeParams(CamelSnakeMixin): """Parameters for a {@link FoldingRangeRequest}.""" text_document: TextDocumentIdentifier """The text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class FoldingRange(CamelSnakeMixin): """Represents a folding range. To be valid, start and end line must be bigger than zero and smaller than the number of lines in the document. Clients are free to ignore invalid ranges. """ start_line: int """The zero-based start line of the range to fold. The folded area starts after the line's last character. To be valid, the end must be zero or larger and smaller than the number of lines in the document.""" end_line: int """The zero-based end line of the range to fold. The folded area ends with the line's last character. To be valid, the end must be zero or larger and smaller than the number of lines in the document.""" start_character: Optional[int] = None """The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line.""" end_character: Optional[int] = None """The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line.""" kind: Optional[Union[FoldingRangeKind, str]] = None """Describes the kind of the folding range such as `comment' or 'region'. The kind is used to categorize folding ranges and used by commands like 'Fold all comments'. See {@link FoldingRangeKind} for an enumeration of standardized kinds.""" collapsed_text: Optional[str] = None """The text that the client should show when the specified range is collapsed. If not defined or not supported by the client, a default will be chosen by the client. @since 3.17.0""" # Since: 3.17.0 @dataclass class FoldingRangeOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None @dataclass class FoldingRangeRegistrationOptions(CamelSnakeMixin): document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class DeclarationParams(CamelSnakeMixin): text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class DeclarationOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None @dataclass class DeclarationRegistrationOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class SelectionRangeParams(CamelSnakeMixin): """A parameter literal used in selection range requests.""" text_document: TextDocumentIdentifier """The text document.""" positions: List[Position] """The positions inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class SelectionRange(CamelSnakeMixin): """A selection range represents a part of a selection hierarchy. A selection range may have a parent selection range that contains it.""" range: Range """The {@link Range range} of this selection range.""" parent: Optional[SelectionRange] = None """The parent selection range containing this range. Therefore `parent.range` must contain `this.range`.""" @dataclass class SelectionRangeOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None @dataclass class SelectionRangeRegistrationOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class WorkDoneProgressCreateParams(CamelSnakeMixin): token: ProgressToken """The token to be used to report progress.""" @dataclass class WorkDoneProgressCancelParams(CamelSnakeMixin): token: ProgressToken """The token to be used to report progress.""" @dataclass class CallHierarchyPrepareParams(CamelSnakeMixin): """The parameter of a `textDocument/prepareCallHierarchy` request. @since 3.16.0""" # Since: 3.16.0 text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class CallHierarchyItem(CamelSnakeMixin): """Represents programming constructs like functions or constructors in the context of call hierarchy. @since 3.16.0""" # Since: 3.16.0 name: str """The name of this item.""" kind: SymbolKind """The kind of this item.""" uri: DocumentUri """The resource identifier of this item.""" range: Range """The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code.""" selection_range: Range """The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. Must be contained by the {@link CallHierarchyItem.range `range`}.""" tags: Optional[List[SymbolTag]] = None """Tags for this item.""" detail: Optional[str] = None """More detail for this item, e.g. the signature of a function.""" data: Optional[LSPAny] = None """A data entry field that is preserved between a call hierarchy prepare and incoming calls or outgoing calls requests.""" @dataclass class CallHierarchyOptions(CamelSnakeMixin): """Call hierarchy options used during static registration. @since 3.16.0""" # Since: 3.16.0 work_done_progress: Optional[bool] = None @dataclass class CallHierarchyRegistrationOptions(CamelSnakeMixin): """Call hierarchy options used during static or dynamic registration. @since 3.16.0""" # Since: 3.16.0 document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class CallHierarchyIncomingCallsParams(CamelSnakeMixin): """The parameter of a `callHierarchy/incomingCalls` request. @since 3.16.0""" # Since: 3.16.0 item: CallHierarchyItem work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class CallHierarchyIncomingCall(CamelSnakeMixin): """Represents an incoming call, e.g. a caller of a method or constructor. @since 3.16.0""" # Since: 3.16.0 from_: CallHierarchyItem """The item that makes the call.""" from_ranges: List[Range] """The ranges at which the calls appear. This is relative to the caller denoted by {@link CallHierarchyIncomingCall.from `this.from`}.""" @dataclass class CallHierarchyOutgoingCallsParams(CamelSnakeMixin): """The parameter of a `callHierarchy/outgoingCalls` request. @since 3.16.0""" # Since: 3.16.0 item: CallHierarchyItem work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class CallHierarchyOutgoingCall(CamelSnakeMixin): """Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc. @since 3.16.0""" # Since: 3.16.0 to: CallHierarchyItem """The item that is called.""" from_ranges: List[Range] """The range at which this item is called. This is the range relative to the caller, e.g the item passed to {@link CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls `provideCallHierarchyOutgoingCalls`} and not {@link CallHierarchyOutgoingCall.to `this.to`}.""" @dataclass class SemanticTokensParams(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 text_document: TextDocumentIdentifier """The text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class SemanticTokens(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 data: List[int] """The actual tokens.""" result_id: Optional[str] = None """An optional result id. If provided and clients support delta updating the client will include the result id in the next semantic token request. A server can then instead of computing all semantic tokens again simply send a delta.""" @dataclass class SemanticTokensPartialResult(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 data: List[int] @dataclass class SemanticTokensOptionsFullType1(CamelSnakeMixin): delta: Optional[bool] = None """The server supports deltas for full documents.""" @dataclass class SemanticTokensOptions(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 legend: SemanticTokensLegend """The legend used by the server""" range: Optional[Union[bool, Any]] = None """Server supports providing semantic tokens for a specific range of a document.""" full: Optional[Union[bool, SemanticTokensOptionsFullType1]] = None """Server supports providing semantic tokens for a full document.""" work_done_progress: Optional[bool] = None @dataclass class SemanticTokensRegistrationOptionsFullType1(CamelSnakeMixin): delta: Optional[bool] = None """The server supports deltas for full documents.""" @dataclass class SemanticTokensRegistrationOptions(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 legend: SemanticTokensLegend """The legend used by the server""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" range: Optional[Union[bool, Any]] = None """Server supports providing semantic tokens for a specific range of a document.""" full: Optional[Union[bool, SemanticTokensRegistrationOptionsFullType1]] = None """Server supports providing semantic tokens for a full document.""" work_done_progress: Optional[bool] = None id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class SemanticTokensDeltaParams(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 text_document: TextDocumentIdentifier """The text document.""" previous_result_id: str """The result id of a previous response. The result Id can either point to a full response or a delta response depending on what was received last.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class SemanticTokensDelta(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 edits: List[SemanticTokensEdit] """The semantic token edits to transform a previous result into a new result.""" result_id: Optional[str] = None @dataclass class SemanticTokensDeltaPartialResult(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 edits: List[SemanticTokensEdit] @dataclass class SemanticTokensRangeParams(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 text_document: TextDocumentIdentifier """The text document.""" range: Range """The range the semantic tokens are requested for.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class ShowDocumentParams(CamelSnakeMixin): """Params to show a document. @since 3.16.0""" # Since: 3.16.0 uri: URI """The document uri to show.""" external: Optional[bool] = None """Indicates to show the resource in an external program. To show for example `https://code.visualstudio.com/` in the default WEB browser set `external` to `true`.""" take_focus: Optional[bool] = None """An optional property to indicate whether the editor showing the document should take focus or not. Clients might ignore this property if an external program is started.""" selection: Optional[Range] = None """An optional selection range if the document is a text document. Clients might ignore the property if an external program is started or the file is not a text file.""" @dataclass class ShowDocumentResult(CamelSnakeMixin): """The result of a showDocument request. @since 3.16.0""" # Since: 3.16.0 success: bool """A boolean indicating if the show was successful.""" @dataclass class LinkedEditingRangeParams(CamelSnakeMixin): text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class LinkedEditingRanges(CamelSnakeMixin): """The result of a linked editing range request. @since 3.16.0""" # Since: 3.16.0 ranges: List[Range] """A list of ranges that can be edited together. The ranges must have identical length and contain identical text content. The ranges cannot overlap.""" word_pattern: Optional[str] = None """An optional word pattern (regular expression) that describes valid contents for the given ranges. If no pattern is provided, the client configuration's word pattern will be used.""" @dataclass class LinkedEditingRangeOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None @dataclass class LinkedEditingRangeRegistrationOptions(CamelSnakeMixin): document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class CreateFilesParams(CamelSnakeMixin): """The parameters sent in notifications/requests for user-initiated creation of files. @since 3.16.0""" # Since: 3.16.0 files: List[FileCreate] """An array of all files/folders created in this operation.""" @dataclass class WorkspaceEdit(CamelSnakeMixin): """A workspace edit represents changes to many resources managed in the workspace. The edit should either provide `changes` or `documentChanges`. If documentChanges are present they are preferred over `changes` if the client can handle versioned document edits. Since version 3.13.0 a workspace edit can contain resource operations as well. If resource operations are present clients need to execute the operations in the order in which they are provided. So a workspace edit for example can consist of the following two changes: (1) a create file a.txt and (2) a text document edit which insert text into file a.txt. An invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will cause failure of the operation. How the client recovers from the failure is described by the client capability: `workspace.workspaceEdit.failureHandling`""" changes: Optional[Dict[DocumentUri, List[TextEdit]]] = None """Holds changes to existing resources.""" document_changes: Optional[List[Union[TextDocumentEdit, CreateFile, RenameFile, DeleteFile]]] = None """Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes are either an array of `TextDocumentEdit`s to express changes to n different text documents where each text document edit addresses a specific version of a text document. Or it can contain above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations. Whether a client supports versioned document edits is expressed via `workspace.workspaceEdit.documentChanges` client capability. If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then only plain `TextEdit`s using the `changes` property are supported.""" change_annotations: Optional[Dict[ChangeAnnotationIdentifier, ChangeAnnotation]] = None """A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and delete file / folder operations. Whether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`. @since 3.16.0""" # Since: 3.16.0 @dataclass class FileOperationRegistrationOptions(CamelSnakeMixin): """The options to register for file operations. @since 3.16.0""" # Since: 3.16.0 filters: List[FileOperationFilter] """The actual filters.""" @dataclass class RenameFilesParams(CamelSnakeMixin): """The parameters sent in notifications/requests for user-initiated renames of files. @since 3.16.0""" # Since: 3.16.0 files: List[FileRename] """An array of all files/folders renamed in this operation. When a folder is renamed, only the folder will be included, and not its children.""" @dataclass class DeleteFilesParams(CamelSnakeMixin): """The parameters sent in notifications/requests for user-initiated deletes of files. @since 3.16.0""" # Since: 3.16.0 files: List[FileDelete] """An array of all files/folders deleted in this operation.""" @dataclass class MonikerParams(CamelSnakeMixin): text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class Moniker(CamelSnakeMixin): """Moniker definition to match LSIF 0.5 moniker definition. @since 3.16.0""" # Since: 3.16.0 scheme: str """The scheme of the moniker. For example tsc or .Net""" identifier: str """The identifier of the moniker. The value is opaque in LSIF however schema owners are allowed to define the structure if they want.""" unique: UniquenessLevel """The scope in which the moniker is unique""" kind: Optional[MonikerKind] = None """The moniker kind if known.""" @dataclass class MonikerOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None @dataclass class MonikerRegistrationOptions(CamelSnakeMixin): document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None @dataclass class TypeHierarchyPrepareParams(CamelSnakeMixin): """The parameter of a `textDocument/prepareTypeHierarchy` request. @since 3.17.0""" # Since: 3.17.0 text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class TypeHierarchyItem(CamelSnakeMixin): """@since 3.17.0""" # Since: 3.17.0 name: str """The name of this item.""" kind: SymbolKind """The kind of this item.""" uri: DocumentUri """The resource identifier of this item.""" range: Range """The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code.""" selection_range: Range """The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. Must be contained by the {@link TypeHierarchyItem.range `range`}.""" tags: Optional[List[SymbolTag]] = None """Tags for this item.""" detail: Optional[str] = None """More detail for this item, e.g. the signature of a function.""" data: Optional[LSPAny] = None """A data entry field that is preserved between a type hierarchy prepare and supertypes or subtypes requests. It could also be used to identify the type hierarchy in the server, helping improve the performance on resolving supertypes and subtypes.""" @dataclass class TypeHierarchyOptions(CamelSnakeMixin): """Type hierarchy options used during static registration. @since 3.17.0""" # Since: 3.17.0 work_done_progress: Optional[bool] = None @dataclass class TypeHierarchyRegistrationOptions(CamelSnakeMixin): """Type hierarchy options used during static or dynamic registration. @since 3.17.0""" # Since: 3.17.0 document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class TypeHierarchySupertypesParams(CamelSnakeMixin): """The parameter of a `typeHierarchy/supertypes` request. @since 3.17.0""" # Since: 3.17.0 item: TypeHierarchyItem work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class TypeHierarchySubtypesParams(CamelSnakeMixin): """The parameter of a `typeHierarchy/subtypes` request. @since 3.17.0""" # Since: 3.17.0 item: TypeHierarchyItem work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class InlineValueParams(CamelSnakeMixin): """A parameter literal used in inline value requests. @since 3.17.0""" # Since: 3.17.0 text_document: TextDocumentIdentifier """The text document.""" range: Range """The document range for which inline values should be computed.""" context: InlineValueContext """Additional information about the context in which inline values were requested.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class InlineValueOptions(CamelSnakeMixin): """Inline value options used during static registration. @since 3.17.0""" # Since: 3.17.0 work_done_progress: Optional[bool] = None @dataclass class InlineValueRegistrationOptions(CamelSnakeMixin): """Inline value options used during static or dynamic registration. @since 3.17.0""" # Since: 3.17.0 work_done_progress: Optional[bool] = None document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class InlayHintParams(CamelSnakeMixin): """A parameter literal used in inlay hint requests. @since 3.17.0""" # Since: 3.17.0 text_document: TextDocumentIdentifier """The text document.""" range: Range """The document range for which inlay hints should be computed.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class InlayHint(CamelSnakeMixin): """Inlay hint information. @since 3.17.0""" # Since: 3.17.0 position: Position """The position of this hint.""" label: Union[str, List[InlayHintLabelPart]] """The label of this hint. A human readable string or an array of InlayHintLabelPart label parts. *Note* that neither the string nor the label part can be empty.""" kind: Optional[InlayHintKind] = None """The kind of this hint. Can be omitted in which case the client should fall back to a reasonable default.""" text_edits: Optional[List[TextEdit]] = None """Optional text edits that are performed when accepting this inlay hint. *Note* that edits are expected to change the document so that the inlay hint (or its nearest variant) is now part of the document and the inlay hint itself is now obsolete.""" tooltip: Optional[Union[str, MarkupContent]] = None """The tooltip text when you hover over this item.""" padding_left: Optional[bool] = None """Render padding before the hint. Note: Padding should use the editor's background color, not the background color of the hint itself. That means padding can be used to visually align/separate an inlay hint.""" padding_right: Optional[bool] = None """Render padding after the hint. Note: Padding should use the editor's background color, not the background color of the hint itself. That means padding can be used to visually align/separate an inlay hint.""" data: Optional[LSPAny] = None """A data entry field that is preserved on an inlay hint between a `textDocument/inlayHint` and a `inlayHint/resolve` request.""" @dataclass class InlayHintOptions(CamelSnakeMixin): """Inlay hint options used during static registration. @since 3.17.0""" # Since: 3.17.0 resolve_provider: Optional[bool] = None """The server provides support to resolve additional information for an inlay hint item.""" work_done_progress: Optional[bool] = None @dataclass class InlayHintRegistrationOptions(CamelSnakeMixin): """Inlay hint options used during static or dynamic registration. @since 3.17.0""" # Since: 3.17.0 resolve_provider: Optional[bool] = None """The server provides support to resolve additional information for an inlay hint item.""" work_done_progress: Optional[bool] = None document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class DocumentDiagnosticParams(CamelSnakeMixin): """Parameters of the document diagnostic request. @since 3.17.0""" # Since: 3.17.0 text_document: TextDocumentIdentifier """The text document.""" identifier: Optional[str] = None """The additional identifier provided during registration.""" previous_result_id: Optional[str] = None """The result id of a previous response if provided.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class DocumentDiagnosticReportPartialResult(CamelSnakeMixin): """A partial result for a document diagnostic report. @since 3.17.0""" # Since: 3.17.0 related_documents: Dict[ DocumentUri, Union[FullDocumentDiagnosticReport, UnchangedDocumentDiagnosticReport], ] @dataclass class DiagnosticServerCancellationData(CamelSnakeMixin): """Cancellation data returned from a diagnostic request. @since 3.17.0""" # Since: 3.17.0 retrigger_request: bool @dataclass class DiagnosticOptions(CamelSnakeMixin): """Diagnostic options. @since 3.17.0""" # Since: 3.17.0 inter_file_dependencies: bool """Whether the language has inter file dependencies meaning that editing code in one file can result in a different diagnostic set in another file. Inter file dependencies are common for most programming languages and typically uncommon for linters.""" workspace_diagnostics: bool """The server provides support for workspace diagnostics as well.""" identifier: Optional[str] = None """An optional identifier under which the diagnostics are managed by the client.""" work_done_progress: Optional[bool] = None @dataclass class DiagnosticRegistrationOptions(CamelSnakeMixin): """Diagnostic registration options. @since 3.17.0""" # Since: 3.17.0 inter_file_dependencies: bool """Whether the language has inter file dependencies meaning that editing code in one file can result in a different diagnostic set in another file. Inter file dependencies are common for most programming languages and typically uncommon for linters.""" workspace_diagnostics: bool """The server provides support for workspace diagnostics as well.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" identifier: Optional[str] = None """An optional identifier under which the diagnostics are managed by the client.""" work_done_progress: Optional[bool] = None id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class WorkspaceDiagnosticParams(CamelSnakeMixin): """Parameters of the workspace diagnostic request. @since 3.17.0""" # Since: 3.17.0 previous_result_ids: List[PreviousResultId] """The currently known diagnostic reports with their previous result ids.""" identifier: Optional[str] = None """The additional identifier provided during registration.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class WorkspaceDiagnosticReport(CamelSnakeMixin): """A workspace diagnostic report. @since 3.17.0""" # Since: 3.17.0 items: List[WorkspaceDocumentDiagnosticReport] @dataclass class WorkspaceDiagnosticReportPartialResult(CamelSnakeMixin): """A partial result for a workspace diagnostic report. @since 3.17.0""" # Since: 3.17.0 items: List[WorkspaceDocumentDiagnosticReport] @dataclass class DidOpenNotebookDocumentParams(CamelSnakeMixin): """The params sent in an open notebook document notification. @since 3.17.0""" # Since: 3.17.0 notebook_document: NotebookDocument """The notebook document that got opened.""" cell_text_documents: List[TextDocumentItem] """The text documents that represent the content of a notebook cell.""" @dataclass class DidChangeNotebookDocumentParams(CamelSnakeMixin): """The params sent in a change notebook document notification. @since 3.17.0""" # Since: 3.17.0 notebook_document: VersionedNotebookDocumentIdentifier """The notebook document that did change. The version number points to the version after all provided changes have been applied. If only the text document content of a cell changes the notebook version doesn't necessarily have to change.""" change: NotebookDocumentChangeEvent """The actual changes to the notebook document. The changes describe single state changes to the notebook document. So if there are two changes c1 (at array index 0) and c2 (at array index 1) for a notebook in state S then c1 moves the notebook from S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed on the state S'. To mirror the content of a notebook using change events use the following approach: - start with the same initial content - apply the 'notebookDocument/didChange' notifications in the order you receive them. - apply the `NotebookChangeEvent`s in a single notification in the order you receive them.""" @dataclass class DidSaveNotebookDocumentParams(CamelSnakeMixin): """The params sent in a save notebook document notification. @since 3.17.0""" # Since: 3.17.0 notebook_document: NotebookDocumentIdentifier """The notebook document that got saved.""" @dataclass class DidCloseNotebookDocumentParams(CamelSnakeMixin): """The params sent in a close notebook document notification. @since 3.17.0""" # Since: 3.17.0 notebook_document: NotebookDocumentIdentifier """The notebook document that got closed.""" cell_text_documents: List[TextDocumentIdentifier] """The text documents that represent the content of a notebook cell that got closed.""" @dataclass class RegistrationParams(CamelSnakeMixin): registrations: List[Registration] @dataclass class UnregistrationParams(CamelSnakeMixin): unregisterations: List[Unregistration] @dataclass class InitializeParamsClientInfoType(CamelSnakeMixin): name: str """The name of the client as defined by the client.""" version: Optional[str] = None """The client's version as defined by the client.""" @dataclass class WorkspaceFoldersInitializeParams(CamelSnakeMixin): workspace_folders: Optional[List[WorkspaceFolder]] = None """The workspace folders configured in the client when the server starts. This property is only available if the client supports workspace folders. It can be `null` if the client supports workspace folders but none are configured. @since 3.6.0""" # Since: 3.6.0 @dataclass class InitializeParams(CamelSnakeMixin): capabilities: ClientCapabilities """The capabilities provided by the client (editor or tool)""" process_id: Optional[int] = None """The process Id of the parent process that started the server. Is `null` if the process has not been started by another process. If the parent process is not alive then the server should exit.""" client_info: Optional[InitializeParamsClientInfoType] = None """Information about the client @since 3.15.0""" # Since: 3.15.0 locale: Optional[str] = None """The locale the client is currently showing the user interface in. This must not necessarily be the locale of the operating system. Uses IETF language tags as the value's syntax (See https://en.wikipedia.org/wiki/IETF_language_tag) @since 3.16.0""" # Since: 3.16.0 root_path: Optional[str] = None """The rootPath of the workspace. Is null if no folder is open. @deprecated in favour of rootUri.""" root_uri: Optional[DocumentUri] = None """The rootUri of the workspace. Is null if no folder is open. If both `rootPath` and `rootUri` are set `rootUri` wins. @deprecated in favour of workspaceFolders.""" initialization_options: Optional[LSPAny] = None """User provided initialization options.""" trace: Optional[TraceValues] = None """The initial trace setting. If omitted trace is disabled ('off').""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" workspace_folders: Optional[List[WorkspaceFolder]] = None """The workspace folders configured in the client when the server starts. This property is only available if the client supports workspace folders. It can be `null` if the client supports workspace folders but none are configured. @since 3.6.0""" # Since: 3.6.0 @dataclass class InitializeResultServerInfoType(CamelSnakeMixin): name: str """The name of the server as defined by the server.""" version: Optional[str] = None """The server's version as defined by the server.""" @dataclass class InitializeResult(CamelSnakeMixin): """The result returned from an initialize request.""" capabilities: ServerCapabilities """The capabilities the language server provides.""" server_info: Optional[InitializeResultServerInfoType] = None """Information about the server. @since 3.15.0""" # Since: 3.15.0 @dataclass class InitializeError(CamelSnakeMixin): """The data type of the ResponseError if the initialize request fails.""" retry: bool """Indicates whether the client execute the following retry logic: (1) show the message provided by the ResponseError to the user (2) user selects retry or cancel (3) if user selected retry the initialize method is sent again.""" @dataclass class InitializedParams(CamelSnakeMixin): pass @dataclass class DidChangeConfigurationParams(CamelSnakeMixin): """The parameters of a change configuration notification.""" settings: LSPAny """The actual changed settings""" @dataclass class DidChangeConfigurationRegistrationOptions(CamelSnakeMixin): section: Optional[Union[str, List[str]]] = None @dataclass class ShowMessageParams(CamelSnakeMixin): """The parameters of a notification message.""" type: MessageType """The message type. See {@link MessageType}""" message: str """The actual message.""" @dataclass class ShowMessageRequestParams(CamelSnakeMixin): type: MessageType """The message type. See {@link MessageType}""" message: str """The actual message.""" actions: Optional[List[MessageActionItem]] = None """The message action items to present.""" @dataclass class MessageActionItem(CamelSnakeMixin): title: str """A short title like 'Retry', 'Open Log' etc.""" @dataclass class LogMessageParams(CamelSnakeMixin): """The log message parameters.""" type: MessageType """The message type. See {@link MessageType}""" message: str """The actual message.""" @dataclass class DidOpenTextDocumentParams(CamelSnakeMixin): """The parameters sent in an open text document notification""" text_document: TextDocumentItem """The document that was opened.""" @dataclass class DidChangeTextDocumentParams(CamelSnakeMixin): """The change text document notification's parameters.""" text_document: VersionedTextDocumentIdentifier """The document that did change. The version number points to the version after all provided content changes have been applied.""" content_changes: List[TextDocumentContentChangeEvent] """The actual content changes. The content changes describe single state changes to the document. So if there are two content changes c1 (at array index 0) and c2 (at array index 1) for a document in state S then c1 moves the document from S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed on the state S'. To mirror the content of a document using change events use the following approach: - start with the same initial content - apply the 'textDocument/didChange' notifications in the order you receive them. - apply the `TextDocumentContentChangeEvent`s in a single notification in the order you receive them.""" @dataclass class TextDocumentChangeRegistrationOptions(CamelSnakeMixin): """Describe options to be used when registered for text document change events.""" sync_kind: TextDocumentSyncKind """How documents are synced to the server.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" @dataclass class DidCloseTextDocumentParams(CamelSnakeMixin): """The parameters sent in a close text document notification""" text_document: TextDocumentIdentifier """The document that was closed.""" @dataclass class DidSaveTextDocumentParams(CamelSnakeMixin): """The parameters sent in a save text document notification""" text_document: TextDocumentIdentifier """The document that was saved.""" text: Optional[str] = None """Optional the content when saved. Depends on the includeText value when the save notification was requested.""" @dataclass class SaveOptions(CamelSnakeMixin): """Save options.""" include_text: Optional[bool] = None """The client is supposed to include the content on save.""" @dataclass class TextDocumentSaveRegistrationOptions(CamelSnakeMixin): """Save registration options.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" include_text: Optional[bool] = None """The client is supposed to include the content on save.""" @dataclass class WillSaveTextDocumentParams(CamelSnakeMixin): """The parameters sent in a will save text document notification.""" text_document: TextDocumentIdentifier """The document that will be saved.""" reason: TextDocumentSaveReason """The 'TextDocumentSaveReason'.""" @dataclass class TextEdit(CamelSnakeMixin): """A text edit applicable to a text document.""" range: Range """The range of the text document to be manipulated. To insert text into a document create a range where start === end.""" new_text: str """The string to be inserted. For delete operations use an empty string.""" @dataclass class DidChangeWatchedFilesParams(CamelSnakeMixin): """The watched files change notification's parameters.""" changes: List[FileEvent] """The actual file events.""" @dataclass class DidChangeWatchedFilesRegistrationOptions(CamelSnakeMixin): """Describe options to be used when registered for text document change events.""" watchers: List[FileSystemWatcher] """The watchers to register.""" @dataclass class PublishDiagnosticsParams(CamelSnakeMixin): """The publish diagnostic notification's parameters.""" uri: DocumentUri """The URI for which diagnostic information is reported.""" diagnostics: List[Diagnostic] """An array of diagnostic information items.""" version: Optional[int] = None """Optional the version number of the document the diagnostics are published for. @since 3.15.0""" # Since: 3.15.0 @dataclass class CompletionParams(CamelSnakeMixin): """Completion parameters""" text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" context: Optional[CompletionContext] = None """The completion context. This is only available it the client specifies to send this using the client capability `textDocument.completion.contextSupport === true`""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class CompletionItem(CamelSnakeMixin): """A completion item represents a text snippet that is proposed to complete text that is being typed.""" label: str """The label of this completion item. The label property is also by default the text that is inserted when selecting this completion. If label details are provided the label itself should be an unqualified name of the completion item.""" label_details: Optional[CompletionItemLabelDetails] = None """Additional details for the label @since 3.17.0""" # Since: 3.17.0 kind: Optional[CompletionItemKind] = None """The kind of this completion item. Based of the kind an icon is chosen by the editor.""" tags: Optional[List[CompletionItemTag]] = None """Tags for this completion item. @since 3.15.0""" # Since: 3.15.0 detail: Optional[str] = None """A human-readable string with additional information about this item, like type or symbol information.""" documentation: Optional[Union[str, MarkupContent]] = None """A human-readable string that represents a doc-comment.""" deprecated: Optional[bool] = None """Indicates if this item is deprecated. @deprecated Use `tags` instead.""" preselect: Optional[bool] = None """Select this item when showing. *Note* that only one completion item can be selected and that the tool / client decides which item that is. The rule is that the *first* item of those that match best is selected.""" sort_text: Optional[str] = None """A string that should be used when comparing this item with other items. When `falsy` the {@link CompletionItem.label label} is used.""" filter_text: Optional[str] = None """A string that should be used when filtering a set of completion items. When `falsy` the {@link CompletionItem.label label} is used.""" insert_text: Optional[str] = None """A string that should be inserted into a document when selecting this completion. When `falsy` the {@link CompletionItem.label label} is used. The `insertText` is subject to interpretation by the client side. Some tools might not take the string literally. For example VS Code when code complete is requested in this example `con<cursor position>` and a completion item with an `insertText` of `console` is provided it will only insert `sole`. Therefore it is recommended to use `textEdit` instead since it avoids additional client side interpretation.""" insert_text_format: Optional[InsertTextFormat] = None """The format of the insert text. The format applies to both the `insertText` property and the `newText` property of a provided `textEdit`. If omitted defaults to `InsertTextFormat.PlainText`. Please note that the insertTextFormat doesn't apply to `additionalTextEdits`.""" insert_text_mode: Optional[InsertTextMode] = None """How whitespace and indentation is handled during completion item insertion. If not provided the clients default value depends on the `textDocument.completion.insertTextMode` client capability. @since 3.16.0""" # Since: 3.16.0 text_edit: Optional[Union[TextEdit, InsertReplaceEdit]] = None """An {@link TextEdit edit} which is applied to a document when selecting this completion. When an edit is provided the value of {@link CompletionItem.insertText insertText} is ignored. Most editors support two different operations when accepting a completion item. One is to insert a completion text and the other is to replace an existing text with a completion text. Since this can usually not be predetermined by a server it can report both ranges. Clients need to signal support for `InsertReplaceEdits` via the `textDocument.completion.insertReplaceSupport` client capability property. *Note 1:* The text edit's range as well as both ranges from an insert replace edit must be a [single line] and they must contain the position at which completion has been requested. *Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range must be a prefix of the edit's replace range, that means it must be contained and starting at the same position. @since 3.16.0 additional type `InsertReplaceEdit`""" # Since: 3.16.0 additional type `InsertReplaceEdit` text_edit_text: Optional[str] = None """The edit text used if the completion item is part of a CompletionList and CompletionList defines an item default for the text edit range. Clients will only honor this property if they opt into completion list item defaults using the capability `completionList.itemDefaults`. If not provided and a list's default range is provided the label property is used as a text. @since 3.17.0""" # Since: 3.17.0 additional_text_edits: Optional[List[TextEdit]] = None """An optional array of additional {@link TextEdit text edits} that are applied when selecting this completion. Edits must not overlap (including the same insert position) with the main {@link CompletionItem.textEdit edit} nor with themselves. Additional text edits should be used to change text unrelated to the current cursor position (for example adding an import statement at the top of the file if the completion item will insert an unqualified type).""" commit_characters: Optional[List[str]] = None """An optional set of characters that when pressed while this completion is active will accept it first and then type that character. *Note* that all commit characters should have `length=1` and that superfluous characters will be ignored.""" command: Optional[Command] = None """An optional {@link Command command} that is executed *after* inserting this completion. *Note* that additional modifications to the current document should be described with the {@link CompletionItem.additionalTextEdits additionalTextEdits}-property.""" data: Optional[LSPAny] = None """A data entry field that is preserved on a completion item between a {@link CompletionRequest} and a {@link CompletionResolveRequest}.""" @dataclass class CompletionListItemDefaultsTypeEditRangeType1(CamelSnakeMixin): insert: Range replace: Range @dataclass class CompletionListItemDefaultsType(CamelSnakeMixin): commit_characters: Optional[List[str]] = None """A default commit character set. @since 3.17.0""" # Since: 3.17.0 edit_range: Optional[Union[Range, CompletionListItemDefaultsTypeEditRangeType1]] = None """A default edit range. @since 3.17.0""" # Since: 3.17.0 insert_text_format: Optional[InsertTextFormat] = None """A default insert text format. @since 3.17.0""" # Since: 3.17.0 insert_text_mode: Optional[InsertTextMode] = None """A default insert text mode. @since 3.17.0""" # Since: 3.17.0 data: Optional[LSPAny] = None """A default data value. @since 3.17.0""" # Since: 3.17.0 @dataclass class CompletionList(CamelSnakeMixin): """Represents a collection of {@link CompletionItem completion items} to be presented in the editor.""" is_incomplete: bool """This list it not complete. Further typing results in recomputing this list. Recomputed lists have all their items replaced (not appended) in the incomplete completion sessions.""" items: List[CompletionItem] """The completion items.""" item_defaults: Optional[CompletionListItemDefaultsType] = None """In many cases the items of an actual completion result share the same value for properties like `commitCharacters` or the range of a text edit. A completion list can therefore define item defaults which will be used if a completion item itself doesn't specify the value. If a completion list specifies a default value and a completion item also specifies a corresponding value the one from the item is used. Servers are only allowed to return default values if the client signals support for this via the `completionList.itemDefaults` capability. @since 3.17.0""" # Since: 3.17.0 @dataclass class CompletionOptionsCompletionItemType(CamelSnakeMixin): label_details_support: Optional[bool] = None """The server has support for completion item label details (see also `CompletionItemLabelDetails`) when receiving a completion item in a resolve call. @since 3.17.0""" # Since: 3.17.0 @dataclass class CompletionOptions(CamelSnakeMixin): """Completion options.""" trigger_characters: Optional[List[str]] = None """Most tools trigger completion request automatically without explicitly requesting it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user starts to type an identifier. For example if the user types `c` in a JavaScript file code complete will automatically pop up present `console` besides others as a completion item. Characters that make up identifiers don't need to be listed here. If code complete should automatically be trigger on characters not being valid inside an identifier (for example `.` in JavaScript) list them in `triggerCharacters`.""" all_commit_characters: Optional[List[str]] = None """The list of all possible characters that commit a completion. This field can be used if clients don't support individual commit characters per completion item. See `ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport` If a server provides both `allCommitCharacters` and commit characters on an individual completion item the ones on the completion item win. @since 3.2.0""" # Since: 3.2.0 resolve_provider: Optional[bool] = None """The server provides support to resolve additional information for a completion item.""" completion_item: Optional[CompletionOptionsCompletionItemType] = None """The server supports the following `CompletionItem` specific capabilities. @since 3.17.0""" # Since: 3.17.0 work_done_progress: Optional[bool] = None @dataclass class CompletionRegistrationOptionsCompletionItemType(CamelSnakeMixin): label_details_support: Optional[bool] = None """The server has support for completion item label details (see also `CompletionItemLabelDetails`) when receiving a completion item in a resolve call. @since 3.17.0""" # Since: 3.17.0 @dataclass class CompletionRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link CompletionRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" trigger_characters: Optional[List[str]] = None """Most tools trigger completion request automatically without explicitly requesting it using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user starts to type an identifier. For example if the user types `c` in a JavaScript file code complete will automatically pop up present `console` besides others as a completion item. Characters that make up identifiers don't need to be listed here. If code complete should automatically be trigger on characters not being valid inside an identifier (for example `.` in JavaScript) list them in `triggerCharacters`.""" all_commit_characters: Optional[List[str]] = None """The list of all possible characters that commit a completion. This field can be used if clients don't support individual commit characters per completion item. See `ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport` If a server provides both `allCommitCharacters` and commit characters on an individual completion item the ones on the completion item win. @since 3.2.0""" # Since: 3.2.0 resolve_provider: Optional[bool] = None """The server provides support to resolve additional information for a completion item.""" completion_item: Optional[CompletionRegistrationOptionsCompletionItemType] = None """The server supports the following `CompletionItem` specific capabilities. @since 3.17.0""" # Since: 3.17.0 work_done_progress: Optional[bool] = None @dataclass class HoverParams(CamelSnakeMixin): """Parameters for a {@link HoverRequest}.""" text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class Hover(CamelSnakeMixin): """The result of a hover request.""" contents: Union[MarkupContent, MarkedString, List[MarkedString]] """The hover's content""" range: Optional[Range] = None """An optional range inside the text document that is used to visualize the hover, e.g. by changing the background color.""" @dataclass class HoverOptions(CamelSnakeMixin): """Hover options.""" work_done_progress: Optional[bool] = None @dataclass class HoverRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link HoverRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None @dataclass class SignatureHelpParams(CamelSnakeMixin): """Parameters for a {@link SignatureHelpRequest}.""" text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" context: Optional[SignatureHelpContext] = None """The signature help context. This is only available if the client specifies to send this using the client capability `textDocument.signatureHelp.contextSupport === true` @since 3.15.0""" # Since: 3.15.0 work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class SignatureHelp(CamelSnakeMixin): """Signature help represents the signature of something callable. There can be multiple signature but only one active and only one active parameter.""" signatures: List[SignatureInformation] """One or more signatures.""" active_signature: Optional[int] = None """The active signature. If omitted or the value lies outside the range of `signatures` the value defaults to zero or is ignored if the `SignatureHelp` has no signatures. Whenever possible implementors should make an active decision about the active signature and shouldn't rely on a default value. In future version of the protocol this property might become mandatory to better express this.""" active_parameter: Optional[int] = None """The active parameter of the active signature. If omitted or the value lies outside the range of `signatures[activeSignature].parameters` defaults to 0 if the active signature has parameters. If the active signature has no parameters it is ignored. In future version of the protocol this property might become mandatory to better express the active parameter if the active signature does have any.""" @dataclass class SignatureHelpOptions(CamelSnakeMixin): """Server Capabilities for a {@link SignatureHelpRequest}.""" trigger_characters: Optional[List[str]] = None """List of characters that trigger signature help automatically.""" retrigger_characters: Optional[List[str]] = None """List of characters that re-trigger signature help. These trigger characters are only active when signature help is already showing. All trigger characters are also counted as re-trigger characters. @since 3.15.0""" # Since: 3.15.0 work_done_progress: Optional[bool] = None @dataclass class SignatureHelpRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link SignatureHelpRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" trigger_characters: Optional[List[str]] = None """List of characters that trigger signature help automatically.""" retrigger_characters: Optional[List[str]] = None """List of characters that re-trigger signature help. These trigger characters are only active when signature help is already showing. All trigger characters are also counted as re-trigger characters. @since 3.15.0""" # Since: 3.15.0 work_done_progress: Optional[bool] = None @dataclass class DefinitionParams(CamelSnakeMixin): """Parameters for a {@link DefinitionRequest}.""" text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class DefinitionOptions(CamelSnakeMixin): """Server Capabilities for a {@link DefinitionRequest}.""" work_done_progress: Optional[bool] = None @dataclass class DefinitionRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link DefinitionRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None @dataclass class ReferenceParams(CamelSnakeMixin): """Parameters for a {@link ReferencesRequest}.""" context: ReferenceContext text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class ReferenceOptions(CamelSnakeMixin): """Reference options.""" work_done_progress: Optional[bool] = None @dataclass class ReferenceRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link ReferencesRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None @dataclass class DocumentHighlightParams(CamelSnakeMixin): """Parameters for a {@link DocumentHighlightRequest}.""" text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class DocumentHighlight(CamelSnakeMixin): """A document highlight is a range inside a text document which deserves special attention. Usually a document highlight is visualized by changing the background color of its range.""" range: Range """The range this highlight applies to.""" kind: Optional[DocumentHighlightKind] = None """The highlight kind, default is {@link DocumentHighlightKind.Text text}.""" @dataclass class DocumentHighlightOptions(CamelSnakeMixin): """Provider options for a {@link DocumentHighlightRequest}.""" work_done_progress: Optional[bool] = None @dataclass class DocumentHighlightRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link DocumentHighlightRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None @dataclass class DocumentSymbolParams(CamelSnakeMixin): """Parameters for a {@link DocumentSymbolRequest}.""" text_document: TextDocumentIdentifier """The text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class BaseSymbolInformation(CamelSnakeMixin): """A base for all symbol information.""" name: str """The name of this symbol.""" kind: SymbolKind """The kind of this symbol.""" tags: Optional[List[SymbolTag]] = None """Tags for this symbol. @since 3.16.0""" # Since: 3.16.0 container_name: Optional[str] = None """The name of the symbol containing this symbol. This information is for user interface purposes (e.g. to render a qualifier in the user interface if necessary). It can't be used to re-infer a hierarchy for the document symbols.""" @dataclass class SymbolInformation(CamelSnakeMixin): """Represents information about programming constructs like variables, classes, interfaces etc.""" location: Location """The location of this symbol. The location's range is used by a tool to reveal the location in the editor. If the symbol is selected in the tool the range's start information is used to position the cursor. So the range usually spans more than the actual symbol's name and does normally include things like visibility modifiers. The range doesn't have to denote a node range in the sense of an abstract syntax tree. It can therefore not be used to re-construct a hierarchy of the symbols.""" name: str """The name of this symbol.""" kind: SymbolKind """The kind of this symbol.""" deprecated: Optional[bool] = None """Indicates if this symbol is deprecated. @deprecated Use tags instead""" tags: Optional[List[SymbolTag]] = None """Tags for this symbol. @since 3.16.0""" # Since: 3.16.0 container_name: Optional[str] = None """The name of the symbol containing this symbol. This information is for user interface purposes (e.g. to render a qualifier in the user interface if necessary). It can't be used to re-infer a hierarchy for the document symbols.""" @dataclass class DocumentSymbol(CamelSnakeMixin): """Represents programming constructs like variables, classes, interfaces etc. that appear in a document. Document symbols can be hierarchical and they have two ranges: one that encloses its definition and one that points to its most interesting range, e.g. the range of an identifier.""" name: str """The name of this symbol. Will be displayed in the user interface and therefore must not be an empty string or a string only consisting of white spaces.""" kind: SymbolKind """The kind of this symbol.""" range: Range """The range enclosing this symbol not including leading/trailing whitespace but everything else like comments. This information is typically used to determine if the clients cursor is inside the symbol to reveal in the symbol in the UI.""" selection_range: Range """The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. Must be contained by the `range`.""" detail: Optional[str] = None """More detail for this symbol, e.g the signature of a function.""" tags: Optional[List[SymbolTag]] = None """Tags for this document symbol. @since 3.16.0""" # Since: 3.16.0 deprecated: Optional[bool] = None """Indicates if this symbol is deprecated. @deprecated Use tags instead""" children: Optional[List[DocumentSymbol]] = None """Children of this symbol, e.g. properties of a class.""" @dataclass class DocumentSymbolOptions(CamelSnakeMixin): """Provider options for a {@link DocumentSymbolRequest}.""" label: Optional[str] = None """A human-readable string that is shown when multiple outlines trees are shown for the same document. @since 3.16.0""" # Since: 3.16.0 work_done_progress: Optional[bool] = None @dataclass class DocumentSymbolRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link DocumentSymbolRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" label: Optional[str] = None """A human-readable string that is shown when multiple outlines trees are shown for the same document. @since 3.16.0""" # Since: 3.16.0 work_done_progress: Optional[bool] = None @dataclass class CodeActionParams(CamelSnakeMixin): """The parameters of a {@link CodeActionRequest}.""" text_document: TextDocumentIdentifier """The document in which the command was invoked.""" range: Range """The range for which the command was invoked.""" context: CodeActionContext """Context carrying additional information.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class Command(CamelSnakeMixin): """Represents a reference to a command. Provides a title which will be used to represent a command in the UI and, optionally, an array of arguments which will be passed to the command handler function when invoked.""" title: str """Title of the command, like `save`.""" command: str """The identifier of the actual command handler.""" arguments: Optional[List[LSPAny]] = None """Arguments that the command handler should be invoked with.""" @dataclass class CodeActionDisabledType(CamelSnakeMixin): reason: str """Human readable description of why the code action is currently disabled. This is displayed in the code actions UI.""" @dataclass class CodeAction(CamelSnakeMixin): """A code action represents a change that can be performed in code, e.g. to fix a problem or to refactor code. A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed. """ title: str """A short, human-readable, title for this code action.""" kind: Optional[Union[CodeActionKind, str]] = None """The kind of the code action. Used to filter code actions.""" diagnostics: Optional[List[Diagnostic]] = None """The diagnostics that this code action resolves.""" is_preferred: Optional[bool] = None """Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted by keybindings. A quick fix should be marked preferred if it properly addresses the underlying error. A refactoring should be marked preferred if it is the most reasonable choice of actions to take. @since 3.15.0""" # Since: 3.15.0 disabled: Optional[CodeActionDisabledType] = None """Marks that the code action cannot currently be applied. Clients should follow the following guidelines regarding disabled code actions: - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) code action menus. - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type of code action, such as refactorings. - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions) that auto applies a code action and only disabled code actions are returned, the client should show the user an error message with `reason` in the editor. @since 3.16.0""" # Since: 3.16.0 edit: Optional[WorkspaceEdit] = None """The workspace edit this code action performs.""" command: Optional[Command] = None """A command this code action executes. If a code action provides an edit and a command, first the edit is executed and then the command.""" data: Optional[LSPAny] = None """A data entry field that is preserved on a code action between a `textDocument/codeAction` and a `codeAction/resolve` request. @since 3.16.0""" # Since: 3.16.0 @dataclass class CodeActionOptions(CamelSnakeMixin): """Provider options for a {@link CodeActionRequest}.""" code_action_kinds: Optional[List[Union[CodeActionKind, str]]] = None """CodeActionKinds that this server may return. The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server may list out every specific kind they provide.""" resolve_provider: Optional[bool] = None """The server provides support to resolve additional information for a code action. @since 3.16.0""" # Since: 3.16.0 work_done_progress: Optional[bool] = None @dataclass class CodeActionRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link CodeActionRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" code_action_kinds: Optional[List[Union[CodeActionKind, str]]] = None """CodeActionKinds that this server may return. The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server may list out every specific kind they provide.""" resolve_provider: Optional[bool] = None """The server provides support to resolve additional information for a code action. @since 3.16.0""" # Since: 3.16.0 work_done_progress: Optional[bool] = None @dataclass class WorkspaceSymbolParams(CamelSnakeMixin): """The parameters of a {@link WorkspaceSymbolRequest}.""" query: str """A query string to filter symbols by. Clients may send an empty string here to request all symbols.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class WorkspaceSymbolLocationType1(CamelSnakeMixin): uri: DocumentUri @dataclass class WorkspaceSymbol(CamelSnakeMixin): """A special workspace symbol that supports locations without a range. See also SymbolInformation. @since 3.17.0""" # Since: 3.17.0 location: Union[Location, WorkspaceSymbolLocationType1] """The location of the symbol. Whether a server is allowed to return a location without a range depends on the client capability `workspace.symbol.resolveSupport`. See SymbolInformation#location for more details.""" name: str """The name of this symbol.""" kind: SymbolKind """The kind of this symbol.""" data: Optional[LSPAny] = None """A data entry field that is preserved on a workspace symbol between a workspace symbol request and a workspace symbol resolve request.""" tags: Optional[List[SymbolTag]] = None """Tags for this symbol. @since 3.16.0""" # Since: 3.16.0 container_name: Optional[str] = None """The name of the symbol containing this symbol. This information is for user interface purposes (e.g. to render a qualifier in the user interface if necessary). It can't be used to re-infer a hierarchy for the document symbols.""" @dataclass class WorkspaceSymbolOptions(CamelSnakeMixin): """Server capabilities for a {@link WorkspaceSymbolRequest}.""" resolve_provider: Optional[bool] = None """The server provides support to resolve additional information for a workspace symbol. @since 3.17.0""" # Since: 3.17.0 work_done_progress: Optional[bool] = None @dataclass class WorkspaceSymbolRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link WorkspaceSymbolRequest}.""" resolve_provider: Optional[bool] = None """The server provides support to resolve additional information for a workspace symbol. @since 3.17.0""" # Since: 3.17.0 work_done_progress: Optional[bool] = None @dataclass class CodeLensParams(CamelSnakeMixin): """The parameters of a {@link CodeLensRequest}.""" text_document: TextDocumentIdentifier """The document to request code lens for.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class CodeLens(CamelSnakeMixin): """A code lens represents a {@link Command command} that should be shown along with source text, like the number of references, a way to run tests, etc. A code lens is _unresolved_ when no command is associated to it. For performance reasons the creation of a code lens and resolving should be done in two stages.""" range: Range """The range in which this code lens is valid. Should only span a single line.""" command: Optional[Command] = None """The command this code lens represents.""" data: Optional[LSPAny] = None """A data entry field that is preserved on a code lens item between a {@link CodeLensRequest} and a [CodeLensResolveRequest] (#CodeLensResolveRequest)""" @dataclass class CodeLensOptions(CamelSnakeMixin): """Code Lens provider options of a {@link CodeLensRequest}.""" resolve_provider: Optional[bool] = None """Code lens has a resolve provider as well.""" work_done_progress: Optional[bool] = None @dataclass class CodeLensRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link CodeLensRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" resolve_provider: Optional[bool] = None """Code lens has a resolve provider as well.""" work_done_progress: Optional[bool] = None @dataclass class DocumentLinkParams(CamelSnakeMixin): """The parameters of a {@link DocumentLinkRequest}.""" text_document: TextDocumentIdentifier """The document to provide document links for.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" partial_result_token: Optional[ProgressToken] = None """An optional token that a server can use to report partial results (e.g. streaming) to the client.""" @dataclass class DocumentLink(CamelSnakeMixin): """A document link is a range in a text document that links to an internal or external resource, like another text document or a web site.""" range: Range """The range this link applies to.""" target: Optional[str] = None """The uri this link points to. If missing a resolve request is sent later.""" tooltip: Optional[str] = None """The tooltip text when you hover over this link. If a tooltip is provided, is will be displayed in a string that includes instructions on how to trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS, user settings, and localization. @since 3.15.0""" # Since: 3.15.0 data: Optional[LSPAny] = None """A data entry field that is preserved on a document link between a DocumentLinkRequest and a DocumentLinkResolveRequest.""" @dataclass class DocumentLinkOptions(CamelSnakeMixin): """Provider options for a {@link DocumentLinkRequest}.""" resolve_provider: Optional[bool] = None """Document links have a resolve provider as well.""" work_done_progress: Optional[bool] = None @dataclass class DocumentLinkRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link DocumentLinkRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" resolve_provider: Optional[bool] = None """Document links have a resolve provider as well.""" work_done_progress: Optional[bool] = None @dataclass class DocumentFormattingParams(CamelSnakeMixin): """The parameters of a {@link DocumentFormattingRequest}.""" text_document: TextDocumentIdentifier """The document to format.""" options: FormattingOptions """The format options.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class DocumentFormattingOptions(CamelSnakeMixin): """Provider options for a {@link DocumentFormattingRequest}.""" work_done_progress: Optional[bool] = None @dataclass class DocumentFormattingRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link DocumentFormattingRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None @dataclass class DocumentRangeFormattingParams(CamelSnakeMixin): """The parameters of a {@link DocumentRangeFormattingRequest}.""" text_document: TextDocumentIdentifier """The document to format.""" range: Range """The range to format""" options: FormattingOptions """The format options""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class DocumentRangeFormattingOptions(CamelSnakeMixin): """Provider options for a {@link DocumentRangeFormattingRequest}.""" work_done_progress: Optional[bool] = None @dataclass class DocumentRangeFormattingRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link DocumentRangeFormattingRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" work_done_progress: Optional[bool] = None @dataclass class DocumentOnTypeFormattingParams(CamelSnakeMixin): """The parameters of a {@link DocumentOnTypeFormattingRequest}.""" text_document: TextDocumentIdentifier """The document to format.""" position: Position """The position around which the on type formatting should happen. This is not necessarily the exact position where the character denoted by the property `ch` got typed.""" ch: str """The character that has been typed that triggered the formatting on type request. That is not necessarily the last character that got inserted into the document since the client could auto insert characters as well (e.g. like automatic brace completion).""" options: FormattingOptions """The formatting options.""" @dataclass class DocumentOnTypeFormattingOptions(CamelSnakeMixin): """Provider options for a {@link DocumentOnTypeFormattingRequest}.""" first_trigger_character: str """A character on which formatting should be triggered, like `{`.""" more_trigger_character: Optional[List[str]] = None """More trigger characters.""" @dataclass class DocumentOnTypeFormattingRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link DocumentOnTypeFormattingRequest}.""" first_trigger_character: str """A character on which formatting should be triggered, like `{`.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" more_trigger_character: Optional[List[str]] = None """More trigger characters.""" @dataclass class RenameParams(CamelSnakeMixin): """The parameters of a {@link RenameRequest}.""" text_document: TextDocumentIdentifier """The document to rename.""" position: Position """The position at which this request was sent.""" new_name: str """The new name of the symbol. If the given name is not valid the request must return a {@link ResponseError} with an appropriate message set.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class RenameOptions(CamelSnakeMixin): """Provider options for a {@link RenameRequest}.""" prepare_provider: Optional[bool] = None """Renames should be checked and tested before being executed. @since version 3.12.0""" # Since: version 3.12.0 work_done_progress: Optional[bool] = None @dataclass class RenameRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link RenameRequest}.""" document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" prepare_provider: Optional[bool] = None """Renames should be checked and tested before being executed. @since version 3.12.0""" # Since: version 3.12.0 work_done_progress: Optional[bool] = None @dataclass class PrepareRenameParams(CamelSnakeMixin): text_document: TextDocumentIdentifier """The text document.""" position: Position """The position inside the text document.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class ExecuteCommandParams(CamelSnakeMixin): """The parameters of a {@link ExecuteCommandRequest}.""" command: str """The identifier of the actual command handler.""" arguments: Optional[List[LSPAny]] = None """Arguments that the command should be invoked with.""" work_done_token: Optional[ProgressToken] = None """An optional token that a server can use to report work done progress.""" @dataclass class ExecuteCommandOptions(CamelSnakeMixin): """The server capabilities of a {@link ExecuteCommandRequest}.""" commands: List[str] """The commands to be executed on the server""" work_done_progress: Optional[bool] = None @dataclass class ExecuteCommandRegistrationOptions(CamelSnakeMixin): """Registration options for a {@link ExecuteCommandRequest}.""" commands: List[str] """The commands to be executed on the server""" work_done_progress: Optional[bool] = None @dataclass class ApplyWorkspaceEditParams(CamelSnakeMixin): """The parameters passed via a apply workspace edit request.""" edit: WorkspaceEdit """The edits to apply.""" label: Optional[str] = None """An optional label of the workspace edit. This label is presented in the user interface for example on an undo stack to undo the workspace edit.""" @dataclass class ApplyWorkspaceEditResult(CamelSnakeMixin): """The result returned from the apply workspace edit request. @since 3.17 renamed from ApplyWorkspaceEditResponse""" # Since: 3.17 renamed from ApplyWorkspaceEditResponse applied: bool """Indicates whether the edit was applied or not.""" failure_reason: Optional[str] = None """An optional textual description for why the edit was not applied. This may be used by the server for diagnostic logging or to provide a suitable error for a request that triggered the edit.""" failed_change: Optional[int] = None """Depending on the client's failure handling strategy `failedChange` might contain the index of the change that failed. This property is only available if the client signals a `failureHandlingStrategy` in its client capabilities.""" @dataclass class WorkDoneProgressBegin(CamelSnakeMixin): title: str """Mandatory title of the progress operation. Used to briefly inform about the kind of operation being performed. Examples: "Indexing" or "Linking dependencies".""" kind: Literal["begin"] = "begin" cancellable: Optional[bool] = None """Controls if a cancel button should show to allow the user to cancel the long running operation. Clients that don't support cancellation are allowed to ignore the setting.""" message: Optional[str] = None """Optional, more detailed associated progress message. Contains complementary information to the `title`. Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". If unset, the previous progress message (if any) is still valid.""" percentage: Optional[int] = None """Optional progress percentage to display (value 100 is considered 100%). If not provided infinite progress is assumed and clients are allowed to ignore the `percentage` value in subsequent in report notifications. The value should be steadily rising. Clients are free to ignore values that are not following this rule. The value range is [0, 100].""" @dataclass class WorkDoneProgressReport(CamelSnakeMixin): kind: Literal["report"] = "report" cancellable: Optional[bool] = None """Controls enablement state of a cancel button. Clients that don't support cancellation or don't support controlling the button's enablement state are allowed to ignore the property.""" message: Optional[str] = None """Optional, more detailed associated progress message. Contains complementary information to the `title`. Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". If unset, the previous progress message (if any) is still valid.""" percentage: Optional[int] = None """Optional progress percentage to display (value 100 is considered 100%). If not provided infinite progress is assumed and clients are allowed to ignore the `percentage` value in subsequent in report notifications. The value should be steadily rising. Clients are free to ignore values that are not following this rule. The value range is [0, 100]""" @dataclass class WorkDoneProgressEnd(CamelSnakeMixin): kind: Literal["end"] = "end" message: Optional[str] = None """Optional, a final message indicating to for example indicate the outcome of the operation.""" @dataclass class SetTraceParams(CamelSnakeMixin): value: TraceValues @dataclass class LogTraceParams(CamelSnakeMixin): message: str verbose: Optional[str] = None @dataclass class CancelParams(CamelSnakeMixin): id: Union[int, str] """The request id to cancel.""" @dataclass class ProgressParams(CamelSnakeMixin): token: ProgressToken """The progress token provided by the client or server.""" value: LSPAny """The progress data.""" @dataclass class LocationLink(CamelSnakeMixin): """Represents the connection of two locations. Provides additional metadata over normal {@link Location locations}, including an origin range.""" target_uri: DocumentUri """The target resource identifier of this link.""" target_range: Range """The full target range of this link. If the target for example is a symbol then target range is the range enclosing this symbol not including leading/trailing whitespace but everything else like comments. This information is typically used to highlight the range in the editor.""" target_selection_range: Range """The range that should be selected and revealed when this link is being followed, e.g the name of a function. Must be contained by the `targetRange`. See also `DocumentSymbol#range`""" origin_selection_range: Optional[Range] = None """Span of the origin of this link. Used as the underlined span for mouse interaction. Defaults to the word range at the definition position.""" @dataclass class Range(CamelSnakeMixin): """A range in a text document expressed as (zero-based) start and end positions. If you want to specify a range that contains a line including the line ending character(s) then use an end position denoting the start of the next line. For example: ```ts { start: { line: 5, character: 23 } end : { line 6, character : 0 } } ```""" start: Position """The range's start position.""" end: Position """The range's end position.""" def __iter__(self) -> Iterator[Position]: return iter((self.start, self.end)) @staticmethod def zero() -> Range: return Range( start=Position( line=0, character=0, ), end=Position( line=0, character=0, ), ) @staticmethod def invalid() -> Range: return Range( start=Position( line=-1, character=-1, ), end=Position( line=-1, character=-1, ), ) def extend( self, start_line: int = 0, start_character: int = 0, end_line: int = 0, end_character: int = 0, ) -> Range: return Range( start=Position( line=self.start.line + start_line, character=self.start.character + start_character, ), end=Position( line=self.end.line + end_line, character=self.end.character + end_character, ), ) def __bool__(self) -> bool: return self.start != self.end def __contains__(self, x: object) -> bool: if isinstance(x, (Position, Range)): return x.is_in_range(self) return False def is_in_range(self, range: Range) -> bool: return self.start.is_in_range(range) and self.end.is_in_range(range) def __hash__(self) -> int: return hash((self.start, self.end)) @dataclass class WorkspaceFoldersChangeEvent(CamelSnakeMixin): """The workspace folder change event.""" added: List[WorkspaceFolder] """The array of added workspace folders""" removed: List[WorkspaceFolder] """The array of the removed workspace folders""" @dataclass class ConfigurationItem(CamelSnakeMixin): scope_uri: Optional[str] = None """The scope to get the configuration section for.""" section: Optional[str] = None """The configuration section asked for.""" @dataclass class TextDocumentIdentifier(CamelSnakeMixin): """A literal to identify a text document in the client.""" uri: DocumentUri """The text document's uri.""" @dataclass class Color(CamelSnakeMixin): """Represents a color in RGBA space.""" red: float """The red component of this color in the range [0-1].""" green: float """The green component of this color in the range [0-1].""" blue: float """The blue component of this color in the range [0-1].""" alpha: float """The alpha component of this color in the range [0-1].""" @dataclass @functools.total_ordering class Position(CamelSnakeMixin): """Position in a text document expressed as zero-based line and character offset. Prior to 3.17 the offsets were always based on a UTF-16 string representation. So a string of the form `a𐐀b` the character offset of the character `a` is 0, the character offset of `𐐀` is 1 and the character offset of b is 3 since `𐐀` is represented using two code units in UTF-16. Since 3.17 clients and servers can agree on a different string encoding representation (e.g. UTF-8). The client announces it's supported encoding via the client capability [`general.positionEncodings`](#clientCapabilities). The value is an array of position encodings the client supports, with decreasing preference (e.g. the encoding at index `0` is the most preferred one). To stay backwards compatible the only mandatory encoding is UTF-16 represented via the string `utf-16`. The server can pick one of the encodings offered by the client and signals that encoding back to the client via the initialize result's property [`capabilities.positionEncoding`](#serverCapabilities). If the string value `utf-16` is missing from the client's capability `general.positionEncodings` servers can safely assume that the client supports UTF-16. If the server omits the position encoding in its initialize result the encoding defaults to the string value `utf-16`. Implementation considerations: since the conversion from one encoding into another requires the content of the file / line the conversion is best done where the file is read which is usually on the server side. Positions are line end character agnostic. So you can not specify a position that denotes `\r|\n` or `\n|` where `|` represents the character offset. @since 3.17.0 - support for negotiated position encoding.""" # Since: 3.17.0 - support for negotiated position encoding. line: int """Line position in a document (zero-based). If a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document. If a line number is negative, it defaults to 0.""" character: int """Character offset on a line in a document (zero-based). The meaning of this offset is determined by the negotiated `PositionEncodingKind`. If the character value is greater than the line length it defaults back to the line length.""" def __eq__(self, o: object) -> bool: if not isinstance(o, Position): return NotImplemented return (self.line, self.character) == (o.line, o.character) def __gt__(self, o: object) -> bool: if not isinstance(o, Position): return NotImplemented return (self.line, self.character) > (o.line, o.character) def __iter__(self) -> Iterator[int]: return iter((self.line, self.character)) def is_in_range(self, range: Range, include_end: bool = True) -> bool: if include_end: return range.start <= self <= range.end return range.start <= self < range.end def __hash__(self) -> int: return hash((self.line, self.character)) @dataclass class SemanticTokensEdit(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 start: int """The start offset of the edit.""" delete_count: int """The count of elements to remove.""" data: Optional[List[int]] = None """The elements to insert.""" @dataclass class FileCreate(CamelSnakeMixin): """Represents information on a file/folder create. @since 3.16.0""" # Since: 3.16.0 uri: str """A file:// URI for the location of the file/folder being created.""" @dataclass class TextDocumentEdit(CamelSnakeMixin): """Describes textual changes on a text document. A TextDocumentEdit describes all changes on a document version Si and after they are applied move the document to version Si+1. So the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any kind of ordering. However the edits must be non overlapping.""" text_document: OptionalVersionedTextDocumentIdentifier """The text document to change.""" edits: List[Union[TextEdit, AnnotatedTextEdit]] """The edits to be applied. @since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a client capability.""" # Since: 3.16.0 - support for AnnotatedTextEdit. This is guarded using aclient capability. @dataclass class ResourceOperation(CamelSnakeMixin): """A generic resource operation.""" kind: str """The resource operation kind.""" annotation_id: Optional[ChangeAnnotationIdentifier] = None """An optional annotation identifier describing the operation. @since 3.16.0""" # Since: 3.16.0 @dataclass class CreateFile(CamelSnakeMixin): """Create file operation.""" uri: DocumentUri """The resource to create.""" kind: Literal["create"] = "create" """A create""" options: Optional[CreateFileOptions] = None """Additional options""" annotation_id: Optional[ChangeAnnotationIdentifier] = None """An optional annotation identifier describing the operation. @since 3.16.0""" # Since: 3.16.0 @dataclass class RenameFile(CamelSnakeMixin): """Rename file operation""" old_uri: DocumentUri """The old (existing) location.""" new_uri: DocumentUri """The new location.""" kind: Literal["rename"] = "rename" """A rename""" options: Optional[RenameFileOptions] = None """Rename options.""" annotation_id: Optional[ChangeAnnotationIdentifier] = None """An optional annotation identifier describing the operation. @since 3.16.0""" # Since: 3.16.0 @dataclass class DeleteFile(CamelSnakeMixin): """Delete file operation""" uri: DocumentUri """The file to delete.""" kind: Literal["delete"] = "delete" """A delete""" options: Optional[DeleteFileOptions] = None """Delete options.""" annotation_id: Optional[ChangeAnnotationIdentifier] = None """An optional annotation identifier describing the operation. @since 3.16.0""" # Since: 3.16.0 @dataclass class ChangeAnnotation(CamelSnakeMixin): """Additional information that describes document changes. @since 3.16.0""" # Since: 3.16.0 label: str """A human-readable string describing the actual change. The string is rendered prominent in the user interface.""" needs_confirmation: Optional[bool] = None """A flag which indicates that user confirmation is needed before applying the change.""" description: Optional[str] = None """A human-readable string which is rendered less prominent in the user interface.""" @dataclass class FileOperationFilter(CamelSnakeMixin): """A filter to describe in which file operation requests or notifications the server is interested in receiving. @since 3.16.0""" # Since: 3.16.0 pattern: FileOperationPattern """The actual file operation pattern.""" scheme: Optional[str] = None """A Uri scheme like `file` or `untitled`.""" @dataclass class FileRename(CamelSnakeMixin): """Represents information on a file/folder rename. @since 3.16.0""" # Since: 3.16.0 old_uri: str """A file:// URI for the original location of the file/folder being renamed.""" new_uri: str """A file:// URI for the new location of the file/folder being renamed.""" @dataclass class FileDelete(CamelSnakeMixin): """Represents information on a file/folder delete. @since 3.16.0""" # Since: 3.16.0 uri: str """A file:// URI for the location of the file/folder being deleted.""" @dataclass class InlineValueContext(CamelSnakeMixin): """@since 3.17.0""" # Since: 3.17.0 frame_id: int """The stack frame (as a DAP Id) where the execution has stopped.""" stopped_location: Range """The document range where execution has stopped. Typically the end position of the range denotes the line where the inline values are shown.""" @dataclass class InlineValueText(CamelSnakeMixin): """Provide inline value as text. @since 3.17.0""" # Since: 3.17.0 range: Range """The document range for which the inline value applies.""" text: str """The text of the inline value.""" @dataclass class InlineValueVariableLookup(CamelSnakeMixin): """Provide inline value through a variable lookup. If only a range is specified, the variable name will be extracted from the underlying document. An optional variable name can be used to override the extracted name. @since 3.17.0""" # Since: 3.17.0 range: Range """The document range for which the inline value applies. The range is used to extract the variable name from the underlying document.""" case_sensitive_lookup: bool """How to perform the lookup.""" variable_name: Optional[str] = None """If specified the name of the variable to look up.""" @dataclass class InlineValueEvaluatableExpression(CamelSnakeMixin): """Provide an inline value through an expression evaluation. If only a range is specified, the expression will be extracted from the underlying document. An optional expression can be used to override the extracted expression. @since 3.17.0""" # Since: 3.17.0 range: Range """The document range for which the inline value applies. The range is used to extract the evaluatable expression from the underlying document.""" expression: Optional[str] = None """If specified the expression overrides the extracted expression.""" @dataclass class InlayHintLabelPart(CamelSnakeMixin): """An inlay hint label part allows for interactive and composite labels of inlay hints. @since 3.17.0""" # Since: 3.17.0 value: str """The value of this label part.""" tooltip: Optional[Union[str, MarkupContent]] = None """The tooltip text when you hover over this label part. Depending on the client capability `inlayHint.resolveSupport` clients might resolve this property late using the resolve request.""" location: Optional[Location] = None """An optional source code location that represents this label part. The editor will use this location for the hover and for code navigation features: This part will become a clickable link that resolves to the definition of the symbol at the given location (not necessarily the location itself), it shows the hover that shows at the given location, and it shows a context menu with further code navigation commands. Depending on the client capability `inlayHint.resolveSupport` clients might resolve this property late using the resolve request.""" command: Optional[Command] = None """An optional command for this label part. Depending on the client capability `inlayHint.resolveSupport` clients might resolve this property late using the resolve request.""" @dataclass class MarkupContent(CamelSnakeMixin): """A `MarkupContent` literal represents a string value which content is interpreted base on its kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting Here is an example how such a string can be constructed using JavaScript / TypeScript: ```ts let markdown: MarkdownContent = { kind: MarkupKind.Markdown, value: [ '# Header', 'Some text', '```typescript', 'someCode();', '```' ].join('\n') }; ``` *Please Note* that clients might sanitize the return markdown. A client could decide to remove HTML from the markdown to avoid script execution.""" kind: MarkupKind """The type of the Markup""" value: str """The content itself""" @dataclass class FullDocumentDiagnosticReport(CamelSnakeMixin): """A diagnostic report with a full set of problems. @since 3.17.0""" # Since: 3.17.0 items: List[Diagnostic] """The actual items.""" kind: Literal["full"] = "full" """A full document diagnostic report.""" result_id: Optional[str] = None """An optional result id. If provided it will be sent on the next diagnostic request for the same document.""" @dataclass class RelatedFullDocumentDiagnosticReport(CamelSnakeMixin): """A full diagnostic report with a set of related documents. @since 3.17.0""" # Since: 3.17.0 items: List[Diagnostic] """The actual items.""" related_documents: Optional[ Dict[ DocumentUri, Union[FullDocumentDiagnosticReport, UnchangedDocumentDiagnosticReport], ] ] = None """Diagnostics of related documents. This information is useful in programming languages where code in a file A can generate diagnostics in a file B which A depends on. An example of such a language is C/C++ where marco definitions in a file a.cpp and result in errors in a header file b.hpp. @since 3.17.0""" # Since: 3.17.0 kind: Literal["full"] = "full" """A full document diagnostic report.""" result_id: Optional[str] = None """An optional result id. If provided it will be sent on the next diagnostic request for the same document.""" @dataclass class UnchangedDocumentDiagnosticReport(CamelSnakeMixin): """A diagnostic report indicating that the last returned report is still accurate. @since 3.17.0""" # Since: 3.17.0 result_id: str """A result id which will be sent on the next diagnostic request for the same document.""" kind: Literal["unchanged"] = "unchanged" """A document diagnostic report indicating no changes to the last result. A server can only return `unchanged` if result ids are provided.""" @dataclass class RelatedUnchangedDocumentDiagnosticReport(CamelSnakeMixin): """An unchanged diagnostic report with a set of related documents. @since 3.17.0""" # Since: 3.17.0 result_id: str """A result id which will be sent on the next diagnostic request for the same document.""" related_documents: Optional[ Dict[ DocumentUri, Union[FullDocumentDiagnosticReport, UnchangedDocumentDiagnosticReport], ] ] = None """Diagnostics of related documents. This information is useful in programming languages where code in a file A can generate diagnostics in a file B which A depends on. An example of such a language is C/C++ where marco definitions in a file a.cpp and result in errors in a header file b.hpp. @since 3.17.0""" # Since: 3.17.0 kind: Literal["unchanged"] = "unchanged" """A document diagnostic report indicating no changes to the last result. A server can only return `unchanged` if result ids are provided.""" @dataclass class PreviousResultId(CamelSnakeMixin): """A previous result id in a workspace pull request. @since 3.17.0""" # Since: 3.17.0 uri: DocumentUri """The URI for which the client knowns a result id.""" value: str """The value of the previous result id.""" @dataclass class NotebookDocument(CamelSnakeMixin): """A notebook document. @since 3.17.0""" # Since: 3.17.0 uri: URI """The notebook document's uri.""" notebook_type: str """The type of the notebook.""" version: int """The version number of this document (it will increase after each change, including undo/redo).""" cells: List[NotebookCell] """The cells of a notebook.""" metadata: Optional[LSPObject] = None """Additional metadata stored with the notebook document. Note: should always be an object literal (e.g. LSPObject)""" @dataclass class TextDocumentItem(CamelSnakeMixin): """An item to transfer a text document from the client to the server.""" uri: DocumentUri """The text document's uri.""" language_id: str """The text document's language identifier.""" version: int """The version number of this document (it will increase after each change, including undo/redo).""" text: str """The content of the opened text document.""" @dataclass class VersionedNotebookDocumentIdentifier(CamelSnakeMixin): """A versioned notebook document identifier. @since 3.17.0""" # Since: 3.17.0 version: int """The version number of this notebook document.""" uri: URI """The notebook document's uri.""" @dataclass class NotebookDocumentChangeEventCellsTypeStructureType(CamelSnakeMixin): array: NotebookCellArrayChange """The change to the cell array.""" did_open: Optional[List[TextDocumentItem]] = None """Additional opened cell text documents.""" did_close: Optional[List[TextDocumentIdentifier]] = None """Additional closed cell text documents.""" @dataclass class NotebookDocumentChangeEventCellsTypeTextContentType(CamelSnakeMixin): document: VersionedTextDocumentIdentifier changes: List[TextDocumentContentChangeEvent] @dataclass class NotebookDocumentChangeEventCellsType(CamelSnakeMixin): structure: Optional[NotebookDocumentChangeEventCellsTypeStructureType] = None """Changes to the cell structure to add or remove cells.""" data: Optional[List[NotebookCell]] = None """Changes to notebook cells properties like its kind, execution summary or metadata.""" text_content: Optional[List[NotebookDocumentChangeEventCellsTypeTextContentType]] = None """Changes to the text content of notebook cells.""" @dataclass class NotebookDocumentChangeEvent(CamelSnakeMixin): """A change event for a notebook document. @since 3.17.0""" # Since: 3.17.0 metadata: Optional[LSPObject] = None """The changed meta data if any. Note: should always be an object literal (e.g. LSPObject)""" cells: Optional[NotebookDocumentChangeEventCellsType] = None """Changes to cells""" @dataclass class NotebookDocumentIdentifier(CamelSnakeMixin): """A literal to identify a notebook document in the client. @since 3.17.0""" # Since: 3.17.0 uri: URI """The notebook document's uri.""" @dataclass class Registration(CamelSnakeMixin): """General parameters to to register for an notification or to register a provider.""" id: str """The id used to register the request. The id can be used to deregister the request again.""" method: str """The method / capability to register for.""" register_options: Optional[LSPAny] = None """Options necessary for the registration.""" @dataclass class Unregistration(CamelSnakeMixin): """General parameters to unregister a request or notification.""" id: str """The id used to unregister the request or notification. Usually an id provided during the register request.""" method: str """The method to unregister for.""" @dataclass class ServerCapabilitiesWorkspaceType(CamelSnakeMixin): workspace_folders: Optional[WorkspaceFoldersServerCapabilities] = None """The server supports workspace folder. @since 3.6.0""" # Since: 3.6.0 file_operations: Optional[FileOperationOptions] = None """The server is interested in notifications/requests for operations on files. @since 3.16.0""" # Since: 3.16.0 @dataclass class ServerCapabilities(CamelSnakeMixin): """Defines the capabilities provided by a language server.""" position_encoding: Optional[Union[PositionEncodingKind, str]] = None """The position encoding the server picked from the encodings offered by the client via the client capability `general.positionEncodings`. If the client didn't provide any position encodings the only valid value that a server can return is 'utf-16'. If omitted it defaults to 'utf-16'. @since 3.17.0""" # Since: 3.17.0 text_document_sync: Optional[Union[TextDocumentSyncOptions, TextDocumentSyncKind]] = None """Defines how text documents are synced. Is either a detailed structure defining each notification or for backwards compatibility the TextDocumentSyncKind number.""" notebook_document_sync: Optional[Union[NotebookDocumentSyncOptions, NotebookDocumentSyncRegistrationOptions]] = None """Defines how notebook documents are synced. @since 3.17.0""" # Since: 3.17.0 completion_provider: Optional[CompletionOptions] = None """The server provides completion support.""" hover_provider: Optional[Union[bool, HoverOptions]] = None """The server provides hover support.""" signature_help_provider: Optional[SignatureHelpOptions] = None """The server provides signature help support.""" declaration_provider: Optional[Union[bool, DeclarationOptions, DeclarationRegistrationOptions]] = None """The server provides Goto Declaration support.""" definition_provider: Optional[Union[bool, DefinitionOptions]] = None """The server provides goto definition support.""" type_definition_provider: Optional[Union[bool, TypeDefinitionOptions, TypeDefinitionRegistrationOptions]] = None """The server provides Goto Type Definition support.""" implementation_provider: Optional[Union[bool, ImplementationOptions, ImplementationRegistrationOptions]] = None """The server provides Goto Implementation support.""" references_provider: Optional[Union[bool, ReferenceOptions]] = None """The server provides find references support.""" document_highlight_provider: Optional[Union[bool, DocumentHighlightOptions]] = None """The server provides document highlight support.""" document_symbol_provider: Optional[Union[bool, DocumentSymbolOptions]] = None """The server provides document symbol support.""" code_action_provider: Optional[Union[bool, CodeActionOptions]] = None """The server provides code actions. CodeActionOptions may only be specified if the client states that it supports `codeActionLiteralSupport` in its initial `initialize` request.""" code_lens_provider: Optional[CodeLensOptions] = None """The server provides code lens.""" document_link_provider: Optional[DocumentLinkOptions] = None """The server provides document link support.""" color_provider: Optional[Union[bool, DocumentColorOptions, DocumentColorRegistrationOptions]] = None """The server provides color provider support.""" workspace_symbol_provider: Optional[Union[bool, WorkspaceSymbolOptions]] = None """The server provides workspace symbol support.""" document_formatting_provider: Optional[Union[bool, DocumentFormattingOptions]] = None """The server provides document formatting.""" document_range_formatting_provider: Optional[Union[bool, DocumentRangeFormattingOptions]] = None """The server provides document range formatting.""" document_on_type_formatting_provider: Optional[DocumentOnTypeFormattingOptions] = None """The server provides document formatting on typing.""" rename_provider: Optional[Union[bool, RenameOptions]] = None """The server provides rename support. RenameOptions may only be specified if the client states that it supports `prepareSupport` in its initial `initialize` request.""" folding_range_provider: Optional[Union[bool, FoldingRangeOptions, FoldingRangeRegistrationOptions]] = None """The server provides folding provider support.""" selection_range_provider: Optional[Union[bool, SelectionRangeOptions, SelectionRangeRegistrationOptions]] = None """The server provides selection range support.""" execute_command_provider: Optional[ExecuteCommandOptions] = None """The server provides execute command support.""" call_hierarchy_provider: Optional[Union[bool, CallHierarchyOptions, CallHierarchyRegistrationOptions]] = None """The server provides call hierarchy support. @since 3.16.0""" # Since: 3.16.0 linked_editing_range_provider: Optional[ Union[bool, LinkedEditingRangeOptions, LinkedEditingRangeRegistrationOptions] ] = None """The server provides linked editing range support. @since 3.16.0""" # Since: 3.16.0 semantic_tokens_provider: Optional[Union[SemanticTokensOptions, SemanticTokensRegistrationOptions]] = None """The server provides semantic tokens support. @since 3.16.0""" # Since: 3.16.0 moniker_provider: Optional[Union[bool, MonikerOptions, MonikerRegistrationOptions]] = None """The server provides moniker support. @since 3.16.0""" # Since: 3.16.0 type_hierarchy_provider: Optional[Union[bool, TypeHierarchyOptions, TypeHierarchyRegistrationOptions]] = None """The server provides type hierarchy support. @since 3.17.0""" # Since: 3.17.0 inline_value_provider: Optional[Union[bool, InlineValueOptions, InlineValueRegistrationOptions]] = None """The server provides inline values. @since 3.17.0""" # Since: 3.17.0 inlay_hint_provider: Optional[Union[bool, InlayHintOptions, InlayHintRegistrationOptions]] = None """The server provides inlay hints. @since 3.17.0""" # Since: 3.17.0 diagnostic_provider: Optional[Union[DiagnosticOptions, DiagnosticRegistrationOptions]] = None """The server has support for pull model diagnostics. @since 3.17.0""" # Since: 3.17.0 workspace: Optional[ServerCapabilitiesWorkspaceType] = None """Workspace specific server capabilities.""" experimental: Optional[LSPAny] = None """Experimental server capabilities.""" @dataclass class VersionedTextDocumentIdentifier(CamelSnakeMixin): """A text document identifier to denote a specific version of a text document.""" version: int """The version number of this document.""" uri: DocumentUri """The text document's uri.""" @dataclass class FileEvent(CamelSnakeMixin): """An event describing a file change.""" uri: DocumentUri """The file's uri.""" type: FileChangeType """The change type.""" @dataclass class FileSystemWatcher(CamelSnakeMixin): glob_pattern: GlobPattern """The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail. @since 3.17.0 support for relative patterns.""" # Since: 3.17.0 support for relative patterns. kind: Optional[Union[WatchKind, int]] = None """The kind of events of interest. If omitted it defaults to WatchKind.Create | WatchKind.Change | WatchKind.Delete which is 7.""" @dataclass class Diagnostic(CamelSnakeMixin): """Represents a diagnostic, such as a compiler error or warning. Diagnostic objects are only valid in the scope of a resource.""" range: Range """The range at which the message applies""" message: str """The diagnostic's message. It usually appears in the user interface""" severity: Optional[DiagnosticSeverity] = None """The diagnostic's severity. Can be omitted. If omitted it is up to the client to interpret diagnostics as error, warning, info or hint.""" code: Optional[Union[int, str]] = None """The diagnostic's code, which usually appear in the user interface.""" code_description: Optional[CodeDescription] = None """An optional property to describe the error code. Requires the code field (above) to be present/not null. @since 3.16.0""" # Since: 3.16.0 source: Optional[str] = None """A human-readable string describing the source of this diagnostic, e.g. 'typescript' or 'super lint'. It usually appears in the user interface.""" tags: Optional[List[DiagnosticTag]] = None """Additional metadata about the diagnostic. @since 3.15.0""" # Since: 3.15.0 related_information: Optional[List[DiagnosticRelatedInformation]] = None """An array of related diagnostic information, e.g. when symbol-names within a scope collide all definitions can be marked via this property.""" data: Optional[LSPAny] = None """A data entry field that is preserved between a `textDocument/publishDiagnostics` notification and `textDocument/codeAction` request. @since 3.16.0""" # Since: 3.16.0 @dataclass class CompletionContext(CamelSnakeMixin): """Contains additional information about the context in which a completion request is triggered.""" trigger_kind: CompletionTriggerKind """How the completion was triggered.""" trigger_character: Optional[str] = None """The trigger character (a single character) that has trigger code complete. Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`""" @dataclass class CompletionItemLabelDetails(CamelSnakeMixin): """Additional details for a completion item label. @since 3.17.0""" # Since: 3.17.0 detail: Optional[str] = None """An optional string which is rendered less prominently directly after {@link CompletionItem.label label}, without any spacing. Should be used for function signatures and type annotations.""" description: Optional[str] = None """An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used for fully qualified names and file paths.""" @dataclass class InsertReplaceEdit(CamelSnakeMixin): """A special text edit to provide an insert and a replace operation. @since 3.16.0""" # Since: 3.16.0 new_text: str """The string to be inserted.""" insert: Range """The range if the insert is requested""" replace: Range """The range if the replace is requested.""" @dataclass class SignatureHelpContext(CamelSnakeMixin): """Additional information about the context in which a signature help request was triggered. @since 3.15.0""" # Since: 3.15.0 trigger_kind: SignatureHelpTriggerKind """Action that caused signature help to be triggered.""" is_retrigger: bool """`true` if signature help was already showing when it was triggered. Retriggers occurs when the signature help is already active and can be caused by actions such as typing a trigger character, a cursor move, or document content changes.""" trigger_character: Optional[str] = None """Character that caused signature help to be triggered. This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter`""" active_signature_help: Optional[SignatureHelp] = None """The currently active `SignatureHelp`. The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on the user navigating through available signatures.""" @dataclass class SignatureInformation(CamelSnakeMixin): """Represents the signature of something callable. A signature can have a label, like a function-name, a doc-comment, and a set of parameters.""" label: str """The label of this signature. Will be shown in the UI.""" documentation: Optional[Union[str, MarkupContent]] = None """The human-readable doc-comment of this signature. Will be shown in the UI but can be omitted.""" parameters: Optional[List[ParameterInformation]] = None """The parameters of this signature.""" active_parameter: Optional[int] = None """The index of the active parameter. If provided, this is used in place of `SignatureHelp.activeParameter`. @since 3.16.0""" # Since: 3.16.0 @dataclass class ReferenceContext(CamelSnakeMixin): """Value-object that contains additional information when requesting references.""" include_declaration: bool """Include the declaration of the current symbol.""" @dataclass class CodeActionContext(CamelSnakeMixin): """Contains additional diagnostic information about the context in which a {@link CodeActionProvider.provideCodeActions code action} is run.""" diagnostics: List[Diagnostic] """An array of diagnostics known on the client side overlapping the range provided to the `textDocument/codeAction` request. They are provided so that the server knows which errors are currently presented to the user for the given range. There is no guarantee that these accurately reflect the error state of the resource. The primary parameter to compute code actions is the provided range.""" only: Optional[List[Union[CodeActionKind, str]]] = None """Requested kind of actions to return. Actions not of this kind are filtered out by the client before being shown. So servers can omit computing them.""" trigger_kind: Optional[CodeActionTriggerKind] = None """The reason why code actions were requested. @since 3.17.0""" # Since: 3.17.0 @dataclass class FormattingOptions(CamelSnakeMixin): """Value-object describing what options formatting should use.""" tab_size: int """Size of a tab in spaces.""" insert_spaces: bool """Prefer spaces over tabs.""" trim_trailing_whitespace: Optional[bool] = None """Trim trailing whitespace on a line. @since 3.15.0""" # Since: 3.15.0 insert_final_newline: Optional[bool] = None """Insert a newline character at the end of the file if one does not exist. @since 3.15.0""" # Since: 3.15.0 trim_final_newlines: Optional[bool] = None """Trim all newlines after the final newline at the end of the file. @since 3.15.0""" # Since: 3.15.0 @dataclass class SemanticTokensLegend(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 token_types: List[str] """The token types a server uses.""" token_modifiers: List[str] """The token modifiers a server uses.""" @dataclass class OptionalVersionedTextDocumentIdentifier(CamelSnakeMixin): """A text document identifier to optionally denote a specific version of a text document.""" uri: DocumentUri """The text document's uri.""" version: Optional[int] """The version number of this document. If a versioned text document identifier is sent from the server to the client and the file is not open in the editor (the server has not received an open notification before) the server can send `null` to indicate that the version is unknown and the content on disk is the truth (as specified with document content ownership).""" @dataclass class AnnotatedTextEdit(CamelSnakeMixin): """A special text edit with an additional change annotation. @since 3.16.0.""" # Since: 3.16.0. annotation_id: ChangeAnnotationIdentifier """The actual identifier of the change annotation""" range: Range """The range of the text document to be manipulated. To insert text into a document create a range where start === end.""" new_text: str """The string to be inserted. For delete operations use an empty string.""" @dataclass class CreateFileOptions(CamelSnakeMixin): """Options to create a file.""" overwrite: Optional[bool] = None """Overwrite existing file. Overwrite wins over `ignoreIfExists`""" ignore_if_exists: Optional[bool] = None """Ignore if exists.""" @dataclass class RenameFileOptions(CamelSnakeMixin): """Rename file options""" overwrite: Optional[bool] = None """Overwrite target if existing. Overwrite wins over `ignoreIfExists`""" ignore_if_exists: Optional[bool] = None """Ignores if target exists.""" @dataclass class DeleteFileOptions(CamelSnakeMixin): """Delete file options""" recursive: Optional[bool] = None """Delete the content recursively if a folder is denoted.""" ignore_if_not_exists: Optional[bool] = None """Ignore the operation if the file doesn't exist.""" @dataclass class FileOperationPattern(CamelSnakeMixin): """A pattern to describe in which file operation requests or notifications the server is interested in receiving. @since 3.16.0""" # Since: 3.16.0 glob: str """The glob pattern to match. Glob patterns can have the following syntax: - `*` to match one or more characters in a path segment - `?` to match on one character in a path segment - `**` to match any number of path segments, including none - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files) - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)""" matches: Optional[FileOperationPatternKind] = None """Whether to match files or folders with this pattern. Matches both if undefined.""" options: Optional[FileOperationPatternOptions] = None """Additional options used during matching.""" @dataclass class WorkspaceFullDocumentDiagnosticReport(CamelSnakeMixin): """A full document diagnostic report for a workspace diagnostic result. @since 3.17.0""" # Since: 3.17.0 uri: DocumentUri """The URI for which diagnostic information is reported.""" items: List[Diagnostic] """The actual items.""" version: Optional[int] = None """The version number for which the diagnostics are reported. If the document is not marked as open `null` can be provided.""" kind: Literal["full"] = "full" """A full document diagnostic report.""" result_id: Optional[str] = None """An optional result id. If provided it will be sent on the next diagnostic request for the same document.""" @dataclass class WorkspaceUnchangedDocumentDiagnosticReport(CamelSnakeMixin): """An unchanged document diagnostic report for a workspace diagnostic result. @since 3.17.0""" # Since: 3.17.0 uri: DocumentUri """The URI for which diagnostic information is reported.""" result_id: str """A result id which will be sent on the next diagnostic request for the same document.""" version: Optional[int] = None """The version number for which the diagnostics are reported. If the document is not marked as open `null` can be provided.""" kind: Literal["unchanged"] = "unchanged" """A document diagnostic report indicating no changes to the last result. A server can only return `unchanged` if result ids are provided.""" @dataclass class NotebookCell(CamelSnakeMixin): """A notebook cell. A cell's document URI must be unique across ALL notebook cells and can therefore be used to uniquely identify a notebook cell or the cell's text document. @since 3.17.0""" # Since: 3.17.0 kind: NotebookCellKind """The cell's kind""" document: DocumentUri """The URI of the cell's text document content.""" metadata: Optional[LSPObject] = None """Additional metadata stored with the cell. Note: should always be an object literal (e.g. LSPObject)""" execution_summary: Optional[ExecutionSummary] = None """Additional execution summary information if supported by the client.""" @dataclass class NotebookCellArrayChange(CamelSnakeMixin): """A change describing how to move a `NotebookCell` array from state S to S'. @since 3.17.0""" # Since: 3.17.0 start: int """The start oftest of the cell that changed.""" delete_count: int """The deleted cells""" cells: Optional[List[NotebookCell]] = None """The new cells, if any""" @dataclass class ClientCapabilities(CamelSnakeMixin): """Defines the capabilities provided by the client.""" workspace: Optional[WorkspaceClientCapabilities] = None """Workspace specific client capabilities.""" text_document: Optional[TextDocumentClientCapabilities] = None """Text document specific client capabilities.""" notebook_document: Optional[NotebookDocumentClientCapabilities] = None """Capabilities specific to the notebook document support. @since 3.17.0""" # Since: 3.17.0 window: Optional[WindowClientCapabilities] = None """Window specific client capabilities.""" general: Optional[GeneralClientCapabilities] = None """General client capabilities. @since 3.16.0""" # Since: 3.16.0 experimental: Optional[LSPAny] = None """Experimental client capabilities.""" @dataclass class TextDocumentSyncOptions(CamelSnakeMixin): open_close: Optional[bool] = None """Open and close notifications are sent to the server. If omitted open close notification should not be sent.""" change: Optional[TextDocumentSyncKind] = None """Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None.""" will_save: Optional[bool] = None """If present will save notifications are sent to the server. If omitted the notification should not be sent.""" will_save_wait_until: Optional[bool] = None """If present will save wait until requests are sent to the server. If omitted the request should not be sent.""" save: Optional[Union[bool, SaveOptions]] = None """If present save notifications are sent to the server. If omitted the notification should not be sent.""" @dataclass class NotebookDocumentSyncOptionsNotebookSelectorType1CellsType(CamelSnakeMixin): language: str @dataclass class NotebookDocumentSyncOptionsNotebookSelectorType1(CamelSnakeMixin): notebook: Union[str, NotebookDocumentFilter] """The notebook to be synced If a string value is provided it matches against the notebook type. '*' matches every notebook.""" cells: Optional[List[NotebookDocumentSyncOptionsNotebookSelectorType1CellsType]] = None """The cells of the matching notebook to be synced.""" @dataclass class NotebookDocumentSyncOptionsNotebookSelectorType2CellsType(CamelSnakeMixin): language: str @dataclass class NotebookDocumentSyncOptionsNotebookSelectorType2(CamelSnakeMixin): cells: List[NotebookDocumentSyncOptionsNotebookSelectorType2CellsType] """The cells of the matching notebook to be synced.""" notebook: Optional[Union[str, NotebookDocumentFilter]] = None """The notebook to be synced If a string value is provided it matches against the notebook type. '*' matches every notebook.""" @dataclass class NotebookDocumentSyncOptions(CamelSnakeMixin): """Options specific to a notebook plus its cells to be synced to the server. If a selector provides a notebook document filter but no cell selector all cells of a matching notebook document will be synced. If a selector provides no notebook document filter but only a cell selector all notebook document that contain at least one matching cell will be synced. @since 3.17.0""" # Since: 3.17.0 notebook_selector: List[ Union[ NotebookDocumentSyncOptionsNotebookSelectorType1, NotebookDocumentSyncOptionsNotebookSelectorType2, ] ] """The notebooks to be synced""" save: Optional[bool] = None """Whether save notification should be forwarded to the server. Will only be honored if mode === `notebook`.""" @dataclass class NotebookDocumentSyncRegistrationOptionsNotebookSelectorType1CellsType(CamelSnakeMixin): language: str @dataclass class NotebookDocumentSyncRegistrationOptionsNotebookSelectorType1(CamelSnakeMixin): notebook: Union[str, NotebookDocumentFilter] """The notebook to be synced If a string value is provided it matches against the notebook type. '*' matches every notebook.""" cells: Optional[List[NotebookDocumentSyncRegistrationOptionsNotebookSelectorType1CellsType]] = None """The cells of the matching notebook to be synced.""" @dataclass class NotebookDocumentSyncRegistrationOptionsNotebookSelectorType2CellsType(CamelSnakeMixin): language: str @dataclass class NotebookDocumentSyncRegistrationOptionsNotebookSelectorType2(CamelSnakeMixin): cells: List[NotebookDocumentSyncRegistrationOptionsNotebookSelectorType2CellsType] """The cells of the matching notebook to be synced.""" notebook: Optional[Union[str, NotebookDocumentFilter]] = None """The notebook to be synced If a string value is provided it matches against the notebook type. '*' matches every notebook.""" @dataclass class NotebookDocumentSyncRegistrationOptions(CamelSnakeMixin): """Registration options specific to a notebook. @since 3.17.0""" # Since: 3.17.0 notebook_selector: List[ Union[ NotebookDocumentSyncRegistrationOptionsNotebookSelectorType1, NotebookDocumentSyncRegistrationOptionsNotebookSelectorType2, ] ] """The notebooks to be synced""" save: Optional[bool] = None """Whether save notification should be forwarded to the server. Will only be honored if mode === `notebook`.""" id: Optional[str] = None """The id used to register the request. The id can be used to deregister the request again. See also Registration#id.""" @dataclass class WorkspaceFoldersServerCapabilities(CamelSnakeMixin): supported: Optional[bool] = None """The server has support for workspace folders""" change_notifications: Optional[Union[str, bool]] = None """Whether the server wants to receive workspace folder change notifications. If a string is provided the string is treated as an ID under which the notification is registered on the client side. The ID can be used to unregister for these events using the `client/unregisterCapability` request.""" @dataclass class FileOperationOptions(CamelSnakeMixin): """Options for notifications/requests for user operations on files. @since 3.16.0""" # Since: 3.16.0 did_create: Optional[FileOperationRegistrationOptions] = None """The server is interested in receiving didCreateFiles notifications.""" will_create: Optional[FileOperationRegistrationOptions] = None """The server is interested in receiving willCreateFiles requests.""" did_rename: Optional[FileOperationRegistrationOptions] = None """The server is interested in receiving didRenameFiles notifications.""" will_rename: Optional[FileOperationRegistrationOptions] = None """The server is interested in receiving willRenameFiles requests.""" did_delete: Optional[FileOperationRegistrationOptions] = None """The server is interested in receiving didDeleteFiles file notifications.""" will_delete: Optional[FileOperationRegistrationOptions] = None """The server is interested in receiving willDeleteFiles file requests.""" @dataclass class CodeDescription(CamelSnakeMixin): """Structure to capture a description for an error code. @since 3.16.0""" # Since: 3.16.0 href: URI """An URI to open with more information about the diagnostic error.""" @dataclass class DiagnosticRelatedInformation(CamelSnakeMixin): """Represents a related message and source code location for a diagnostic. This should be used to point to code locations that cause or related to a diagnostics, e.g when duplicating a symbol in a scope.""" location: Location """The location of this related diagnostic information.""" message: str """The message of this related diagnostic information.""" @dataclass class ParameterInformation(CamelSnakeMixin): """Represents a parameter of a callable-signature. A parameter can have a label and a doc-comment.""" label: Union[str, Tuple[int, int]] """The label of this parameter information. Either a string or an inclusive start and exclusive end offsets within its containing signature label. (see SignatureInformation.label). The offsets are based on a UTF-16 string representation as `Position` and `Range` does. *Note*: a label of type string should be a substring of its containing signature label. Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`.""" documentation: Optional[Union[str, MarkupContent]] = None """The human-readable doc-comment of this parameter. Will be shown in the UI but can be omitted.""" @dataclass class NotebookCellTextDocumentFilter(CamelSnakeMixin): """A notebook cell text document filter denotes a cell text document by different properties. @since 3.17.0""" # Since: 3.17.0 notebook: Union[str, NotebookDocumentFilter] """A filter that matches against the notebook containing the notebook cell. If a string value is provided it matches against the notebook type. '*' matches every notebook.""" language: Optional[str] = None """A language id like `python`. Will be matched against the language id of the notebook cell document. '*' matches every language.""" @dataclass class FileOperationPatternOptions(CamelSnakeMixin): """Matching options for the file operation pattern. @since 3.16.0""" # Since: 3.16.0 ignore_case: Optional[bool] = None """The pattern should be matched ignoring casing.""" @dataclass class ExecutionSummary(CamelSnakeMixin): execution_order: int """A strict monotonically increasing value indicating the execution order of a cell inside a notebook.""" success: Optional[bool] = None """Whether the execution was successful or not if known by the client.""" @dataclass class WorkspaceClientCapabilities(CamelSnakeMixin): """Workspace specific client capabilities.""" apply_edit: Optional[bool] = None """The client supports applying batch edits to the workspace by supporting the request 'workspace/applyEdit'""" workspace_edit: Optional[WorkspaceEditClientCapabilities] = None """Capabilities specific to `WorkspaceEdit`s.""" did_change_configuration: Optional[DidChangeConfigurationClientCapabilities] = None """Capabilities specific to the `workspace/didChangeConfiguration` notification.""" did_change_watched_files: Optional[DidChangeWatchedFilesClientCapabilities] = None """Capabilities specific to the `workspace/didChangeWatchedFiles` notification.""" symbol: Optional[WorkspaceSymbolClientCapabilities] = None """Capabilities specific to the `workspace/symbol` request.""" execute_command: Optional[ExecuteCommandClientCapabilities] = None """Capabilities specific to the `workspace/executeCommand` request.""" workspace_folders: Optional[bool] = None """The client has support for workspace folders. @since 3.6.0""" # Since: 3.6.0 configuration: Optional[bool] = None """The client supports `workspace/configuration` requests. @since 3.6.0""" # Since: 3.6.0 semantic_tokens: Optional[SemanticTokensWorkspaceClientCapabilities] = None """Capabilities specific to the semantic token requests scoped to the workspace. @since 3.16.0.""" # Since: 3.16.0. code_lens: Optional[CodeLensWorkspaceClientCapabilities] = None """Capabilities specific to the code lens requests scoped to the workspace. @since 3.16.0.""" # Since: 3.16.0. file_operations: Optional[FileOperationClientCapabilities] = None """The client has support for file notifications/requests for user operations on files. Since 3.16.0""" inline_value: Optional[InlineValueWorkspaceClientCapabilities] = None """Capabilities specific to the inline values requests scoped to the workspace. @since 3.17.0.""" # Since: 3.17.0. inlay_hint: Optional[InlayHintWorkspaceClientCapabilities] = None """Capabilities specific to the inlay hint requests scoped to the workspace. @since 3.17.0.""" # Since: 3.17.0. diagnostics: Optional[DiagnosticWorkspaceClientCapabilities] = None """Capabilities specific to the diagnostic requests scoped to the workspace. @since 3.17.0.""" # Since: 3.17.0. @dataclass class TextDocumentClientCapabilities(CamelSnakeMixin): """Text document specific client capabilities.""" synchronization: Optional[TextDocumentSyncClientCapabilities] = None """Defines which synchronization capabilities the client supports.""" completion: Optional[CompletionClientCapabilities] = None """Capabilities specific to the `textDocument/completion` request.""" hover: Optional[HoverClientCapabilities] = None """Capabilities specific to the `textDocument/hover` request.""" signature_help: Optional[SignatureHelpClientCapabilities] = None """Capabilities specific to the `textDocument/signatureHelp` request.""" declaration: Optional[DeclarationClientCapabilities] = None """Capabilities specific to the `textDocument/declaration` request. @since 3.14.0""" # Since: 3.14.0 definition: Optional[DefinitionClientCapabilities] = None """Capabilities specific to the `textDocument/definition` request.""" type_definition: Optional[TypeDefinitionClientCapabilities] = None """Capabilities specific to the `textDocument/typeDefinition` request. @since 3.6.0""" # Since: 3.6.0 implementation: Optional[ImplementationClientCapabilities] = None """Capabilities specific to the `textDocument/implementation` request. @since 3.6.0""" # Since: 3.6.0 references: Optional[ReferenceClientCapabilities] = None """Capabilities specific to the `textDocument/references` request.""" document_highlight: Optional[DocumentHighlightClientCapabilities] = None """Capabilities specific to the `textDocument/documentHighlight` request.""" document_symbol: Optional[DocumentSymbolClientCapabilities] = None """Capabilities specific to the `textDocument/documentSymbol` request.""" code_action: Optional[CodeActionClientCapabilities] = None """Capabilities specific to the `textDocument/codeAction` request.""" code_lens: Optional[CodeLensClientCapabilities] = None """Capabilities specific to the `textDocument/codeLens` request.""" document_link: Optional[DocumentLinkClientCapabilities] = None """Capabilities specific to the `textDocument/documentLink` request.""" color_provider: Optional[DocumentColorClientCapabilities] = None """Capabilities specific to the `textDocument/documentColor` and the `textDocument/colorPresentation` request. @since 3.6.0""" # Since: 3.6.0 formatting: Optional[DocumentFormattingClientCapabilities] = None """Capabilities specific to the `textDocument/formatting` request.""" range_formatting: Optional[DocumentRangeFormattingClientCapabilities] = None """Capabilities specific to the `textDocument/rangeFormatting` request.""" on_type_formatting: Optional[DocumentOnTypeFormattingClientCapabilities] = None """Capabilities specific to the `textDocument/onTypeFormatting` request.""" rename: Optional[RenameClientCapabilities] = None """Capabilities specific to the `textDocument/rename` request.""" folding_range: Optional[FoldingRangeClientCapabilities] = None """Capabilities specific to the `textDocument/foldingRange` request. @since 3.10.0""" # Since: 3.10.0 selection_range: Optional[SelectionRangeClientCapabilities] = None """Capabilities specific to the `textDocument/selectionRange` request. @since 3.15.0""" # Since: 3.15.0 publish_diagnostics: Optional[PublishDiagnosticsClientCapabilities] = None """Capabilities specific to the `textDocument/publishDiagnostics` notification.""" call_hierarchy: Optional[CallHierarchyClientCapabilities] = None """Capabilities specific to the various call hierarchy requests. @since 3.16.0""" # Since: 3.16.0 semantic_tokens: Optional[SemanticTokensClientCapabilities] = None """Capabilities specific to the various semantic token request. @since 3.16.0""" # Since: 3.16.0 linked_editing_range: Optional[LinkedEditingRangeClientCapabilities] = None """Capabilities specific to the `textDocument/linkedEditingRange` request. @since 3.16.0""" # Since: 3.16.0 moniker: Optional[MonikerClientCapabilities] = None """Client capabilities specific to the `textDocument/moniker` request. @since 3.16.0""" # Since: 3.16.0 type_hierarchy: Optional[TypeHierarchyClientCapabilities] = None """Capabilities specific to the various type hierarchy requests. @since 3.17.0""" # Since: 3.17.0 inline_value: Optional[InlineValueClientCapabilities] = None """Capabilities specific to the `textDocument/inlineValue` request. @since 3.17.0""" # Since: 3.17.0 inlay_hint: Optional[InlayHintClientCapabilities] = None """Capabilities specific to the `textDocument/inlayHint` request. @since 3.17.0""" # Since: 3.17.0 diagnostic: Optional[DiagnosticClientCapabilities] = None """Capabilities specific to the diagnostic pull model. @since 3.17.0""" # Since: 3.17.0 @dataclass class NotebookDocumentClientCapabilities(CamelSnakeMixin): """Capabilities specific to the notebook document support. @since 3.17.0""" # Since: 3.17.0 synchronization: NotebookDocumentSyncClientCapabilities """Capabilities specific to notebook document synchronization @since 3.17.0""" # Since: 3.17.0 @dataclass class WindowClientCapabilities(CamelSnakeMixin): work_done_progress: Optional[bool] = None """It indicates whether the client supports server initiated progress using the `window/workDoneProgress/create` request. The capability also controls Whether client supports handling of progress notifications. If set servers are allowed to report a `workDoneProgress` property in the request specific server capabilities. @since 3.15.0""" # Since: 3.15.0 show_message: Optional[ShowMessageRequestClientCapabilities] = None """Capabilities specific to the showMessage request. @since 3.16.0""" # Since: 3.16.0 show_document: Optional[ShowDocumentClientCapabilities] = None """Capabilities specific to the showDocument request. @since 3.16.0""" # Since: 3.16.0 @dataclass class GeneralClientCapabilitiesStaleRequestSupportType(CamelSnakeMixin): cancel: bool """The client will actively cancel the request.""" retry_on_content_modified: List[str] """The list of requests for which the client will retry the request if it receives a response with error code `ContentModified`""" @dataclass class GeneralClientCapabilities(CamelSnakeMixin): """General client capabilities. @since 3.16.0""" # Since: 3.16.0 stale_request_support: Optional[GeneralClientCapabilitiesStaleRequestSupportType] = None """Client capability that signals how the client handles stale requests (e.g. a request for which the client will not process the response anymore since the information is outdated). @since 3.17.0""" # Since: 3.17.0 regular_expressions: Optional[RegularExpressionsClientCapabilities] = None """Client capabilities specific to regular expressions. @since 3.16.0""" # Since: 3.16.0 markdown: Optional[MarkdownClientCapabilities] = None """Client capabilities specific to the client's markdown parser. @since 3.16.0""" # Since: 3.16.0 position_encodings: Optional[List[Union[PositionEncodingKind, str]]] = None """The position encodings supported by the client. Client and server have to agree on the same position encoding to ensure that offsets (e.g. character position in a line) are interpreted the same on both sides. To keep the protocol backwards compatible the following applies: if the value 'utf-16' is missing from the array of position encodings servers can assume that the client supports UTF-16. UTF-16 is therefore a mandatory encoding. If omitted it defaults to ['utf-16']. Implementation considerations: since the conversion from one encoding into another requires the content of the file / line the conversion is best done where the file is read which is usually on the server side. @since 3.17.0""" # Since: 3.17.0 @dataclass class RelativePattern(CamelSnakeMixin): """A relative pattern is a helper to construct glob patterns that are matched relatively to a base URI. The common value for a `baseUri` is a workspace folder root, but it can be another absolute URI as well. @since 3.17.0""" # Since: 3.17.0 base_uri: Union[WorkspaceFolder, URI] """A workspace folder or a base URI to which this pattern will be matched against relatively.""" pattern: Pattern """The actual glob pattern;""" @dataclass class WorkspaceEditClientCapabilitiesChangeAnnotationSupportType(CamelSnakeMixin): groups_on_label: Optional[bool] = None """Whether the client groups edits with equal labels into tree nodes, for instance all edits labelled with "Changes in Strings" would be a tree node.""" @dataclass class WorkspaceEditClientCapabilities(CamelSnakeMixin): document_changes: Optional[bool] = None """The client supports versioned document changes in `WorkspaceEdit`s""" resource_operations: Optional[List[ResourceOperationKind]] = None """The resource operations the client supports. Clients should at least support 'create', 'rename' and 'delete' files and folders. @since 3.13.0""" # Since: 3.13.0 failure_handling: Optional[FailureHandlingKind] = None """The failure handling strategy of a client if applying the workspace edit fails. @since 3.13.0""" # Since: 3.13.0 normalizes_line_endings: Optional[bool] = None """Whether the client normalizes line endings to the client specific setting. If set to `true` the client will normalize line ending characters in a workspace edit to the client-specified new line character. @since 3.16.0""" # Since: 3.16.0 change_annotation_support: Optional[WorkspaceEditClientCapabilitiesChangeAnnotationSupportType] = None """Whether the client in general supports change annotations on text edits, create file, rename file and delete file changes. @since 3.16.0""" # Since: 3.16.0 @dataclass class DidChangeConfigurationClientCapabilities(CamelSnakeMixin): dynamic_registration: Optional[bool] = None """Did change configuration notification supports dynamic registration.""" @dataclass class DidChangeWatchedFilesClientCapabilities(CamelSnakeMixin): dynamic_registration: Optional[bool] = None """Did change watched files notification supports dynamic registration. Please note that the current protocol doesn't support static configuration for file changes from the server side.""" relative_pattern_support: Optional[bool] = None """Whether the client has support for {@link RelativePattern relative pattern} or not. @since 3.17.0""" # Since: 3.17.0 @dataclass class WorkspaceSymbolClientCapabilitiesSymbolKindType(CamelSnakeMixin): value_set: Optional[List[SymbolKind]] = None """The symbol kind values the client supports. When this property exists the client also guarantees that it will handle values outside its set gracefully and falls back to a default value when unknown. If this property is not present the client only supports the symbol kinds from `File` to `Array` as defined in the initial version of the protocol.""" @dataclass class WorkspaceSymbolClientCapabilitiesTagSupportType(CamelSnakeMixin): value_set: List[SymbolTag] """The tags supported by the client.""" @dataclass class WorkspaceSymbolClientCapabilitiesResolveSupportType(CamelSnakeMixin): properties: List[str] """The properties that a client can resolve lazily. Usually `location.range`""" @dataclass class WorkspaceSymbolClientCapabilities(CamelSnakeMixin): """Client capabilities for a {@link WorkspaceSymbolRequest}.""" dynamic_registration: Optional[bool] = None """Symbol request supports dynamic registration.""" symbol_kind: Optional[WorkspaceSymbolClientCapabilitiesSymbolKindType] = None """Specific capabilities for the `SymbolKind` in the `workspace/symbol` request.""" tag_support: Optional[WorkspaceSymbolClientCapabilitiesTagSupportType] = None """The client supports tags on `SymbolInformation`. Clients supporting tags have to handle unknown tags gracefully. @since 3.16.0""" # Since: 3.16.0 resolve_support: Optional[WorkspaceSymbolClientCapabilitiesResolveSupportType] = None """The client support partial workspace symbols. The client will send the request `workspaceSymbol/resolve` to the server to resolve additional properties. @since 3.17.0""" # Since: 3.17.0 @dataclass class ExecuteCommandClientCapabilities(CamelSnakeMixin): """The client capabilities of a {@link ExecuteCommandRequest}.""" dynamic_registration: Optional[bool] = None """Execute command supports dynamic registration.""" @dataclass class SemanticTokensWorkspaceClientCapabilities(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 refresh_support: Optional[bool] = None """Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all semantic tokens currently shown. It should be used with absolute care and is useful for situation where a server for example detects a project wide change that requires such a calculation.""" @dataclass class CodeLensWorkspaceClientCapabilities(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 refresh_support: Optional[bool] = None """Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all code lenses currently shown. It should be used with absolute care and is useful for situation where a server for example detect a project wide change that requires such a calculation.""" @dataclass class FileOperationClientCapabilities(CamelSnakeMixin): """Capabilities relating to events from file operations by the user in the client. These events do not come from the file system, they come from user operations like renaming a file in the UI. @since 3.16.0""" # Since: 3.16.0 dynamic_registration: Optional[bool] = None """Whether the client supports dynamic registration for file requests/notifications.""" did_create: Optional[bool] = None """The client has support for sending didCreateFiles notifications.""" will_create: Optional[bool] = None """The client has support for sending willCreateFiles requests.""" did_rename: Optional[bool] = None """The client has support for sending didRenameFiles notifications.""" will_rename: Optional[bool] = None """The client has support for sending willRenameFiles requests.""" did_delete: Optional[bool] = None """The client has support for sending didDeleteFiles notifications.""" will_delete: Optional[bool] = None """The client has support for sending willDeleteFiles requests.""" @dataclass class InlineValueWorkspaceClientCapabilities(CamelSnakeMixin): """Client workspace capabilities specific to inline values. @since 3.17.0""" # Since: 3.17.0 refresh_support: Optional[bool] = None """Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all inline values currently shown. It should be used with absolute care and is useful for situation where a server for example detects a project wide change that requires such a calculation.""" @dataclass class InlayHintWorkspaceClientCapabilities(CamelSnakeMixin): """Client workspace capabilities specific to inlay hints. @since 3.17.0""" # Since: 3.17.0 refresh_support: Optional[bool] = None """Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all inlay hints currently shown. It should be used with absolute care and is useful for situation where a server for example detects a project wide change that requires such a calculation.""" @dataclass class DiagnosticWorkspaceClientCapabilities(CamelSnakeMixin): """Workspace client capabilities specific to diagnostic pull requests. @since 3.17.0""" # Since: 3.17.0 refresh_support: Optional[bool] = None """Whether the client implementation supports a refresh request sent from the server to the client. Note that this event is global and will force the client to refresh all pulled diagnostics currently shown. It should be used with absolute care and is useful for situation where a server for example detects a project wide change that requires such a calculation.""" @dataclass class TextDocumentSyncClientCapabilities(CamelSnakeMixin): dynamic_registration: Optional[bool] = None """Whether text document synchronization supports dynamic registration.""" will_save: Optional[bool] = None """The client supports sending will save notifications.""" will_save_wait_until: Optional[bool] = None """The client supports sending a will save request and waits for a response providing text edits which will be applied to the document before it is saved.""" did_save: Optional[bool] = None """The client supports did save notifications.""" @dataclass class CompletionClientCapabilitiesCompletionItemTypeTagSupportType(CamelSnakeMixin): value_set: List[CompletionItemTag] """The tags supported by the client.""" @dataclass class CompletionClientCapabilitiesCompletionItemTypeResolveSupportType(CamelSnakeMixin): properties: List[str] """The properties that a client can resolve lazily.""" @dataclass class CompletionClientCapabilitiesCompletionItemTypeInsertTextModeSupportType(CamelSnakeMixin): value_set: List[InsertTextMode] @dataclass class CompletionClientCapabilitiesCompletionItemType(CamelSnakeMixin): snippet_support: Optional[bool] = None """Client supports snippets as insert text. A snippet can define tab stops and placeholders with `$1`, `$2` and `${3:foo}`. `$0` defines the final tab stop, it defaults to the end of the snippet. Placeholders with equal identifiers are linked, that is typing in one will update others too.""" commit_characters_support: Optional[bool] = None """Client supports commit characters on a completion item.""" documentation_format: Optional[List[MarkupKind]] = None """Client supports the following content formats for the documentation property. The order describes the preferred format of the client.""" deprecated_support: Optional[bool] = None """Client supports the deprecated property on a completion item.""" preselect_support: Optional[bool] = None """Client supports the preselect property on a completion item.""" tag_support: Optional[CompletionClientCapabilitiesCompletionItemTypeTagSupportType] = None """Client supports the tag property on a completion item. Clients supporting tags have to handle unknown tags gracefully. Clients especially need to preserve unknown tags when sending a completion item back to the server in a resolve call. @since 3.15.0""" # Since: 3.15.0 insert_replace_support: Optional[bool] = None """Client support insert replace edit to control different behavior if a completion item is inserted in the text or should replace text. @since 3.16.0""" # Since: 3.16.0 resolve_support: Optional[CompletionClientCapabilitiesCompletionItemTypeResolveSupportType] = None """Indicates which properties a client can resolve lazily on a completion item. Before version 3.16.0 only the predefined properties `documentation` and `details` could be resolved lazily. @since 3.16.0""" # Since: 3.16.0 insert_text_mode_support: Optional[CompletionClientCapabilitiesCompletionItemTypeInsertTextModeSupportType] = None """The client supports the `insertTextMode` property on a completion item to override the whitespace handling mode as defined by the client (see `insertTextMode`). @since 3.16.0""" # Since: 3.16.0 label_details_support: Optional[bool] = None """The client has support for completion item label details (see also `CompletionItemLabelDetails`). @since 3.17.0""" # Since: 3.17.0 @dataclass class CompletionClientCapabilitiesCompletionItemKindType(CamelSnakeMixin): value_set: Optional[List[CompletionItemKind]] = None """The completion item kind values the client supports. When this property exists the client also guarantees that it will handle values outside its set gracefully and falls back to a default value when unknown. If this property is not present the client only supports the completion items kinds from `Text` to `Reference` as defined in the initial version of the protocol.""" @dataclass class CompletionClientCapabilitiesCompletionListType(CamelSnakeMixin): item_defaults: Optional[List[str]] = None """The client supports the following itemDefaults on a completion list. The value lists the supported property names of the `CompletionList.itemDefaults` object. If omitted no properties are supported. @since 3.17.0""" # Since: 3.17.0 @dataclass class CompletionClientCapabilities(CamelSnakeMixin): """Completion client capabilities""" dynamic_registration: Optional[bool] = None """Whether completion supports dynamic registration.""" completion_item: Optional[CompletionClientCapabilitiesCompletionItemType] = None """The client supports the following `CompletionItem` specific capabilities.""" completion_item_kind: Optional[CompletionClientCapabilitiesCompletionItemKindType] = None insert_text_mode: Optional[InsertTextMode] = None """Defines how the client handles whitespace and indentation when accepting a completion item that uses multi line text in either `insertText` or `textEdit`. @since 3.17.0""" # Since: 3.17.0 context_support: Optional[bool] = None """The client supports to send additional context information for a `textDocument/completion` request.""" completion_list: Optional[CompletionClientCapabilitiesCompletionListType] = None """The client supports the following `CompletionList` specific capabilities. @since 3.17.0""" # Since: 3.17.0 @dataclass class HoverClientCapabilities(CamelSnakeMixin): dynamic_registration: Optional[bool] = None """Whether hover supports dynamic registration.""" content_format: Optional[List[MarkupKind]] = None """Client supports the following content formats for the content property. The order describes the preferred format of the client.""" @dataclass class SignatureHelpClientCapabilitiesSignatureInformationTypeParameterInformationType(CamelSnakeMixin): label_offset_support: Optional[bool] = None """The client supports processing label offsets instead of a simple label string. @since 3.14.0""" # Since: 3.14.0 @dataclass class SignatureHelpClientCapabilitiesSignatureInformationType(CamelSnakeMixin): documentation_format: Optional[List[MarkupKind]] = None """Client supports the following content formats for the documentation property. The order describes the preferred format of the client.""" parameter_information: Optional[ SignatureHelpClientCapabilitiesSignatureInformationTypeParameterInformationType ] = None """Client capabilities specific to parameter information.""" active_parameter_support: Optional[bool] = None """The client supports the `activeParameter` property on `SignatureInformation` literal. @since 3.16.0""" # Since: 3.16.0 @dataclass class SignatureHelpClientCapabilities(CamelSnakeMixin): """Client Capabilities for a {@link SignatureHelpRequest}.""" dynamic_registration: Optional[bool] = None """Whether signature help supports dynamic registration.""" signature_information: Optional[SignatureHelpClientCapabilitiesSignatureInformationType] = None """The client supports the following `SignatureInformation` specific properties.""" context_support: Optional[bool] = None """The client supports to send additional context information for a `textDocument/signatureHelp` request. A client that opts into contextSupport will also support the `retriggerCharacters` on `SignatureHelpOptions`. @since 3.15.0""" # Since: 3.15.0 @dataclass class DeclarationClientCapabilities(CamelSnakeMixin): """@since 3.14.0""" # Since: 3.14.0 dynamic_registration: Optional[bool] = None """Whether declaration supports dynamic registration. If this is set to `true` the client supports the new `DeclarationRegistrationOptions` return value for the corresponding server capability as well.""" link_support: Optional[bool] = None """The client supports additional metadata in the form of declaration links.""" @dataclass class DefinitionClientCapabilities(CamelSnakeMixin): """Client Capabilities for a {@link DefinitionRequest}.""" dynamic_registration: Optional[bool] = None """Whether definition supports dynamic registration.""" link_support: Optional[bool] = None """The client supports additional metadata in the form of definition links. @since 3.14.0""" # Since: 3.14.0 @dataclass class TypeDefinitionClientCapabilities(CamelSnakeMixin): """Since 3.6.0""" dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `TypeDefinitionRegistrationOptions` return value for the corresponding server capability as well.""" link_support: Optional[bool] = None """The client supports additional metadata in the form of definition links. Since 3.14.0""" @dataclass class ImplementationClientCapabilities(CamelSnakeMixin): """@since 3.6.0""" # Since: 3.6.0 dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `ImplementationRegistrationOptions` return value for the corresponding server capability as well.""" link_support: Optional[bool] = None """The client supports additional metadata in the form of definition links. @since 3.14.0""" # Since: 3.14.0 @dataclass class ReferenceClientCapabilities(CamelSnakeMixin): """Client Capabilities for a {@link ReferencesRequest}.""" dynamic_registration: Optional[bool] = None """Whether references supports dynamic registration.""" @dataclass class DocumentHighlightClientCapabilities(CamelSnakeMixin): """Client Capabilities for a {@link DocumentHighlightRequest}.""" dynamic_registration: Optional[bool] = None """Whether document highlight supports dynamic registration.""" @dataclass class DocumentSymbolClientCapabilitiesSymbolKindType(CamelSnakeMixin): value_set: Optional[List[SymbolKind]] = None """The symbol kind values the client supports. When this property exists the client also guarantees that it will handle values outside its set gracefully and falls back to a default value when unknown. If this property is not present the client only supports the symbol kinds from `File` to `Array` as defined in the initial version of the protocol.""" @dataclass class DocumentSymbolClientCapabilitiesTagSupportType(CamelSnakeMixin): value_set: List[SymbolTag] """The tags supported by the client.""" @dataclass class DocumentSymbolClientCapabilities(CamelSnakeMixin): """Client Capabilities for a {@link DocumentSymbolRequest}.""" dynamic_registration: Optional[bool] = None """Whether document symbol supports dynamic registration.""" symbol_kind: Optional[DocumentSymbolClientCapabilitiesSymbolKindType] = None """Specific capabilities for the `SymbolKind` in the `textDocument/documentSymbol` request.""" hierarchical_document_symbol_support: Optional[bool] = None """The client supports hierarchical document symbols.""" tag_support: Optional[DocumentSymbolClientCapabilitiesTagSupportType] = None """The client supports tags on `SymbolInformation`. Tags are supported on `DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true. Clients supporting tags have to handle unknown tags gracefully. @since 3.16.0""" # Since: 3.16.0 label_support: Optional[bool] = None """The client supports an additional label presented in the UI when registering a document symbol provider. @since 3.16.0""" # Since: 3.16.0 @dataclass class CodeActionClientCapabilitiesCodeActionLiteralSupportTypeCodeActionKindType(CamelSnakeMixin): value_set: List[Union[CodeActionKind, str]] """The code action kind values the client supports. When this property exists the client also guarantees that it will handle values outside its set gracefully and falls back to a default value when unknown.""" @dataclass class CodeActionClientCapabilitiesCodeActionLiteralSupportType(CamelSnakeMixin): code_action_kind: CodeActionClientCapabilitiesCodeActionLiteralSupportTypeCodeActionKindType """The code action kind is support with the following value set.""" @dataclass class CodeActionClientCapabilitiesResolveSupportType(CamelSnakeMixin): properties: List[str] """The properties that a client can resolve lazily.""" @dataclass class CodeActionClientCapabilities(CamelSnakeMixin): """The Client Capabilities of a {@link CodeActionRequest}.""" dynamic_registration: Optional[bool] = None """Whether code action supports dynamic registration.""" code_action_literal_support: Optional[CodeActionClientCapabilitiesCodeActionLiteralSupportType] = None """The client support code action literals of type `CodeAction` as a valid response of the `textDocument/codeAction` request. If the property is not set the request can only return `Command` literals. @since 3.8.0""" # Since: 3.8.0 is_preferred_support: Optional[bool] = None """Whether code action supports the `isPreferred` property. @since 3.15.0""" # Since: 3.15.0 disabled_support: Optional[bool] = None """Whether code action supports the `disabled` property. @since 3.16.0""" # Since: 3.16.0 data_support: Optional[bool] = None """Whether code action supports the `data` property which is preserved between a `textDocument/codeAction` and a `codeAction/resolve` request. @since 3.16.0""" # Since: 3.16.0 resolve_support: Optional[CodeActionClientCapabilitiesResolveSupportType] = None """Whether the client supports resolving additional code action properties via a separate `codeAction/resolve` request. @since 3.16.0""" # Since: 3.16.0 honors_change_annotations: Optional[bool] = None """Whether the client honors the change annotations in text edits and resource operations returned via the `CodeAction#edit` property by for example presenting the workspace edit in the user interface and asking for confirmation. @since 3.16.0""" # Since: 3.16.0 @dataclass class CodeLensClientCapabilities(CamelSnakeMixin): """The client capabilities of a {@link CodeLensRequest}.""" dynamic_registration: Optional[bool] = None """Whether code lens supports dynamic registration.""" @dataclass class DocumentLinkClientCapabilities(CamelSnakeMixin): """The client capabilities of a {@link DocumentLinkRequest}.""" dynamic_registration: Optional[bool] = None """Whether document link supports dynamic registration.""" tooltip_support: Optional[bool] = None """Whether the client supports the `tooltip` property on `DocumentLink`. @since 3.15.0""" # Since: 3.15.0 @dataclass class DocumentColorClientCapabilities(CamelSnakeMixin): dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `DocumentColorRegistrationOptions` return value for the corresponding server capability as well.""" @dataclass class DocumentFormattingClientCapabilities(CamelSnakeMixin): """Client capabilities of a {@link DocumentFormattingRequest}.""" dynamic_registration: Optional[bool] = None """Whether formatting supports dynamic registration.""" @dataclass class DocumentRangeFormattingClientCapabilities(CamelSnakeMixin): """Client capabilities of a {@link DocumentRangeFormattingRequest}.""" dynamic_registration: Optional[bool] = None """Whether range formatting supports dynamic registration.""" @dataclass class DocumentOnTypeFormattingClientCapabilities(CamelSnakeMixin): """Client capabilities of a {@link DocumentOnTypeFormattingRequest}.""" dynamic_registration: Optional[bool] = None """Whether on type formatting supports dynamic registration.""" @dataclass class RenameClientCapabilities(CamelSnakeMixin): dynamic_registration: Optional[bool] = None """Whether rename supports dynamic registration.""" prepare_support: Optional[bool] = None """Client supports testing for validity of rename operations before execution. @since 3.12.0""" # Since: 3.12.0 prepare_support_default_behavior: Optional[PrepareSupportDefaultBehavior] = None """Client supports the default behavior result. The value indicates the default behavior used by the client. @since 3.16.0""" # Since: 3.16.0 honors_change_annotations: Optional[bool] = None """Whether the client honors the change annotations in text edits and resource operations returned via the rename request's workspace edit by for example presenting the workspace edit in the user interface and asking for confirmation. @since 3.16.0""" # Since: 3.16.0 @dataclass class FoldingRangeClientCapabilitiesFoldingRangeKindType(CamelSnakeMixin): value_set: Optional[List[Union[FoldingRangeKind, str]]] = None """The folding range kind values the client supports. When this property exists the client also guarantees that it will handle values outside its set gracefully and falls back to a default value when unknown.""" @dataclass class FoldingRangeClientCapabilitiesFoldingRangeType(CamelSnakeMixin): collapsed_text: Optional[bool] = None """If set, the client signals that it supports setting collapsedText on folding ranges to display custom labels instead of the default text. @since 3.17.0""" # Since: 3.17.0 @dataclass class FoldingRangeClientCapabilities(CamelSnakeMixin): dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration for folding range providers. If this is set to `true` the client supports the new `FoldingRangeRegistrationOptions` return value for the corresponding server capability as well.""" range_limit: Optional[int] = None """The maximum number of folding ranges that the client prefers to receive per document. The value serves as a hint, servers are free to follow the limit.""" line_folding_only: Optional[bool] = None """If set, the client signals that it only supports folding complete lines. If set, client will ignore specified `startCharacter` and `endCharacter` properties in a FoldingRange.""" folding_range_kind: Optional[FoldingRangeClientCapabilitiesFoldingRangeKindType] = None """Specific options for the folding range kind. @since 3.17.0""" # Since: 3.17.0 folding_range: Optional[FoldingRangeClientCapabilitiesFoldingRangeType] = None """Specific options for the folding range. @since 3.17.0""" # Since: 3.17.0 @dataclass class SelectionRangeClientCapabilities(CamelSnakeMixin): dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration for selection range providers. If this is set to `true` the client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server capability as well.""" @dataclass class PublishDiagnosticsClientCapabilitiesTagSupportType(CamelSnakeMixin): value_set: List[DiagnosticTag] """The tags supported by the client.""" @dataclass class PublishDiagnosticsClientCapabilities(CamelSnakeMixin): """The publish diagnostic client capabilities.""" related_information: Optional[bool] = None """Whether the clients accepts diagnostics with related information.""" tag_support: Optional[PublishDiagnosticsClientCapabilitiesTagSupportType] = None """Client supports the tag property to provide meta data about a diagnostic. Clients supporting tags have to handle unknown tags gracefully. @since 3.15.0""" # Since: 3.15.0 version_support: Optional[bool] = None """Whether the client interprets the version property of the `textDocument/publishDiagnostics` notification's parameter. @since 3.15.0""" # Since: 3.15.0 code_description_support: Optional[bool] = None """Client supports a codeDescription property @since 3.16.0""" # Since: 3.16.0 data_support: Optional[bool] = None """Whether code action supports the `data` property which is preserved between a `textDocument/publishDiagnostics` and `textDocument/codeAction` request. @since 3.16.0""" # Since: 3.16.0 @dataclass class CallHierarchyClientCapabilities(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well.""" @dataclass class SemanticTokensClientCapabilitiesRequestsTypeFullType1(CamelSnakeMixin): delta: Optional[bool] = None """The client will send the `textDocument/semanticTokens/full/delta` request if the server provides a corresponding handler.""" @dataclass class SemanticTokensClientCapabilitiesRequestsType(CamelSnakeMixin): range: Optional[Union[bool, Any]] = None """The client will send the `textDocument/semanticTokens/range` request if the server provides a corresponding handler.""" full: Optional[Union[bool, SemanticTokensClientCapabilitiesRequestsTypeFullType1]] = None """The client will send the `textDocument/semanticTokens/full` request if the server provides a corresponding handler.""" @dataclass class SemanticTokensClientCapabilities(CamelSnakeMixin): """@since 3.16.0""" # Since: 3.16.0 requests: SemanticTokensClientCapabilitiesRequestsType """Which requests the client supports and might send to the server depending on the server's capability. Please note that clients might not show semantic tokens or degrade some of the user experience if a range or full request is advertised by the client but not provided by the server. If for example the client capability `requests.full` and `request.range` are both set to true but the server only provides a range provider the client might not render a minimap correctly or might even decide to not show any semantic tokens at all.""" token_types: List[str] """The token types that the client supports.""" token_modifiers: List[str] """The token modifiers that the client supports.""" formats: List[TokenFormat] """The token formats the clients supports.""" dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well.""" overlapping_token_support: Optional[bool] = None """Whether the client supports tokens that can overlap each other.""" multiline_token_support: Optional[bool] = None """Whether the client supports tokens that can span multiple lines.""" server_cancel_support: Optional[bool] = None """Whether the client allows the server to actively cancel a semantic token request, e.g. supports returning LSPErrorCodes.ServerCancelled. If a server does the client needs to retrigger the request. @since 3.17.0""" # Since: 3.17.0 augments_syntax_tokens: Optional[bool] = None """Whether the client uses semantic tokens to augment existing syntax tokens. If set to `true` client side created syntax tokens and semantic tokens are both used for colorization. If set to `false` the client only uses the returned semantic tokens for colorization. If the value is `undefined` then the client behavior is not specified. @since 3.17.0""" # Since: 3.17.0 @dataclass class LinkedEditingRangeClientCapabilities(CamelSnakeMixin): """Client capabilities for the linked editing range request. @since 3.16.0""" # Since: 3.16.0 dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well.""" @dataclass class MonikerClientCapabilities(CamelSnakeMixin): """Client capabilities specific to the moniker request. @since 3.16.0""" # Since: 3.16.0 dynamic_registration: Optional[bool] = None """Whether moniker supports dynamic registration. If this is set to `true` the client supports the new `MonikerRegistrationOptions` return value for the corresponding server capability as well.""" @dataclass class TypeHierarchyClientCapabilities(CamelSnakeMixin): """@since 3.17.0""" # Since: 3.17.0 dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well.""" @dataclass class InlineValueClientCapabilities(CamelSnakeMixin): """Client capabilities specific to inline values. @since 3.17.0""" # Since: 3.17.0 dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration for inline value providers.""" @dataclass class InlayHintClientCapabilitiesResolveSupportType(CamelSnakeMixin): properties: List[str] """The properties that a client can resolve lazily.""" @dataclass class InlayHintClientCapabilities(CamelSnakeMixin): """Inlay hint client capabilities. @since 3.17.0""" # Since: 3.17.0 dynamic_registration: Optional[bool] = None """Whether inlay hints support dynamic registration.""" resolve_support: Optional[InlayHintClientCapabilitiesResolveSupportType] = None """Indicates which properties a client can resolve lazily on an inlay hint.""" @dataclass class DiagnosticClientCapabilities(CamelSnakeMixin): """Client capabilities specific to diagnostic pull requests. @since 3.17.0""" # Since: 3.17.0 dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well.""" related_document_support: Optional[bool] = None """Whether the clients supports related documents for document diagnostic pulls.""" @dataclass class NotebookDocumentSyncClientCapabilities(CamelSnakeMixin): """Notebook specific client capabilities. @since 3.17.0""" # Since: 3.17.0 dynamic_registration: Optional[bool] = None """Whether implementation supports dynamic registration. If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` return value for the corresponding server capability as well.""" execution_summary_support: Optional[bool] = None """The client supports sending execution summary data per cell.""" @dataclass class ShowMessageRequestClientCapabilitiesMessageActionItemType(CamelSnakeMixin): additional_properties_support: Optional[bool] = None """Whether the client supports additional attributes which are preserved and send back to the server in the request's response.""" @dataclass class ShowMessageRequestClientCapabilities(CamelSnakeMixin): """Show message request client capabilities""" message_action_item: Optional[ShowMessageRequestClientCapabilitiesMessageActionItemType] = None """Capabilities specific to the `MessageActionItem` type.""" @dataclass class ShowDocumentClientCapabilities(CamelSnakeMixin): """Client capabilities for the showDocument request. @since 3.16.0""" # Since: 3.16.0 support: bool """The client has support for the showDocument request.""" @dataclass class RegularExpressionsClientCapabilities(CamelSnakeMixin): """Client capabilities specific to regular expressions. @since 3.16.0""" # Since: 3.16.0 engine: str """The engine's name.""" version: Optional[str] = None """The engine's version.""" @dataclass class MarkdownClientCapabilities(CamelSnakeMixin): """Client capabilities specific to the used markdown parser. @since 3.16.0""" # Since: 3.16.0 parser: str """The name of the parser.""" version: Optional[str] = None """The version of the parser.""" allowed_tags: Optional[List[str]] = None """A list of HTML tags that the client allows / supports in Markdown. @since 3.17.0""" # Since: 3.17.0 @dataclass class TextDocumentColorPresentationOptions(CamelSnakeMixin): work_done_progress: Optional[bool] = None document_selector: Optional[DocumentSelector] = None """A document selector to identify the scope of the registration. If set to null the document selector provided on the client side will be used.""" Definition = Union[Location, List[Location]] """The definition of a symbol represented as one or many {@link Location locations}. For most programming languages there is only one location at which a symbol is defined. Servers should prefer returning `DefinitionLink` over `Definition` if supported by the client.""" DefinitionLink = LocationLink """Information about where a symbol is defined. Provides additional metadata over normal {@link Location location} definitions, including the range of the defining symbol""" LSPArray = List[Any] """LSP arrays. @since 3.17.0""" # Since: 3.17.0 LSPAny = Union[Any, None] """The LSP any type. Please note that strictly speaking a property with the value `undefined` can't be converted into JSON preserving the property name. However for convenience it is allowed and assumed that all these properties are optional as well. @since 3.17.0""" # Since: 3.17.0 Declaration = Union[Location, List[Location]] """The declaration of a symbol representation as one or many {@link Location locations}.""" DeclarationLink = LocationLink """Information about where a symbol is declared. Provides additional metadata over normal {@link Location location} declarations, including the range of the declaring symbol. Servers should prefer returning `DeclarationLink` over `Declaration` if supported by the client.""" InlineValue = Union[InlineValueText, InlineValueVariableLookup, InlineValueEvaluatableExpression] """Inline value information can be provided by different means: - directly as a text value (class InlineValueText). - as a name to use for a variable lookup (class InlineValueVariableLookup) - as an evaluatable expression (class InlineValueEvaluatableExpression) The InlineValue types combines all inline value types into one type. @since 3.17.0""" # Since: 3.17.0 DocumentDiagnosticReport = Union[RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport] """The result of a document diagnostic pull request. A report can either be a full report containing all diagnostics for the requested document or an unchanged report indicating that nothing has changed in terms of diagnostics in comparison to the last pull request. @since 3.17.0""" # Since: 3.17.0 @dataclass class PrepareRenameResultType1(CamelSnakeMixin): range: Range placeholder: str @dataclass class PrepareRenameResultType2(CamelSnakeMixin): default_behavior: bool PrepareRenameResult = Union[Range, PrepareRenameResultType1, PrepareRenameResultType2] ProgressToken = Union[int, str] ChangeAnnotationIdentifier = str """An identifier to refer to a change annotation stored with a workspace edit.""" WorkspaceDocumentDiagnosticReport = Union[ WorkspaceFullDocumentDiagnosticReport, WorkspaceUnchangedDocumentDiagnosticReport ] """A workspace diagnostic document report. @since 3.17.0""" # Since: 3.17.0 @dataclass class TextDocumentContentChangeEventType1(CamelSnakeMixin): range: Range """The range of the document that changed.""" text: str """The new text for the provided range.""" range_length: Optional[int] = None """The optional length of the range that got replaced. @deprecated use range instead.""" @dataclass class TextDocumentContentChangeEventType2(CamelSnakeMixin): text: str """The new text of the whole document.""" TextDocumentContentChangeEvent = Union[TextDocumentContentChangeEventType1, TextDocumentContentChangeEventType2] """An event describing a change to a text document. If only a text is provided it is considered to be the full content of the document.""" @dataclass class MarkedStringType1(CamelSnakeMixin): language: str value: str MarkedString = Union[str, MarkedStringType1] """MarkedString can be used to render human readable text. It is either a markdown string or a code-block that provides a language and a code snippet. The language identifier is semantically equal to the optional language identifier in fenced code blocks in GitHub issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting The pair of a language and a value is an equivalent to markdown: ```${language} ${value} ``` Note that markdown strings will be sanitized - that means html will be escaped. @deprecated use MarkupContent instead.""" @dataclass class TextDocumentFilterType1(CamelSnakeMixin): language: str """A language id, like `typescript`.""" scheme: Optional[str] = None """A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.""" pattern: Optional[str] = None """A glob pattern, like `*.{ts,js}`.""" @dataclass class TextDocumentFilterType2(CamelSnakeMixin): scheme: str """A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.""" language: Optional[str] = None """A language id, like `typescript`.""" pattern: Optional[str] = None """A glob pattern, like `*.{ts,js}`.""" @dataclass class TextDocumentFilterType3(CamelSnakeMixin): pattern: str """A glob pattern, like `*.{ts,js}`.""" language: Optional[str] = None """A language id, like `typescript`.""" scheme: Optional[str] = None """A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.""" TextDocumentFilter = Union[TextDocumentFilterType1, TextDocumentFilterType2, TextDocumentFilterType3] """A document filter denotes a document by different properties like the {@link TextDocument.languageId language}, the {@link Uri.scheme scheme} of its resource, or a glob-pattern that is applied to the {@link TextDocument.fileName path}. Glob patterns can have the following syntax: - `*` to match one or more characters in a path segment - `?` to match on one character in a path segment - `**` to match any number of path segments, including none - `{}` to group sub patterns into an OR expression. (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files) - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }` @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }` @since 3.17.0""" # Since: 3.17.0 @dataclass class NotebookDocumentFilterType1(CamelSnakeMixin): notebook_type: str """The type of the enclosing notebook.""" scheme: Optional[str] = None """A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.""" pattern: Optional[str] = None """A glob pattern.""" @dataclass class NotebookDocumentFilterType2(CamelSnakeMixin): scheme: str """A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.""" notebook_type: Optional[str] = None """The type of the enclosing notebook.""" pattern: Optional[str] = None """A glob pattern.""" @dataclass class NotebookDocumentFilterType3(CamelSnakeMixin): pattern: str """A glob pattern.""" notebook_type: Optional[str] = None """The type of the enclosing notebook.""" scheme: Optional[str] = None """A Uri {@link Uri.scheme scheme}, like `file` or `untitled`.""" NotebookDocumentFilter = Union[ NotebookDocumentFilterType1, NotebookDocumentFilterType2, NotebookDocumentFilterType3, ] """A notebook document filter denotes a notebook document by different properties. The properties will be match against the notebook's URI (same as with documents) @since 3.17.0""" # Since: 3.17.0 Pattern = str """The glob pattern to watch relative to the base path. Glob patterns can have the following syntax: - `*` to match one or more characters in a path segment - `?` to match on one character in a path segment - `**` to match any number of path segments, including none - `{}` to group conditions (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files) - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) @since 3.17.0""" # Since: 3.17.0 DocumentFilter = Union[TextDocumentFilter, NotebookCellTextDocumentFilter] """A document filter describes a top level text document or a notebook cell document. @since 3.17.0 - proposed support for NotebookCellTextDocumentFilter.""" # Since: 3.17.0 - proposed support for NotebookCellTextDocumentFilter. GlobPattern = Union[Pattern, RelativePattern] """The glob pattern. Either a string pattern or a relative pattern. @since 3.17.0""" # Since: 3.17.0 DocumentSelector = List[DocumentFilter] """A document selector is the combination of one or many document filters. @sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**/tsconfig.json' }]`; The use of a string as a document filter is deprecated @since 3.16.0.""" # Since: 3.16.0.
/robotcode_core-0.54.3-py3-none-any.whl/robotcode/core/lsp/types.py
0.957318
0.201617
types.py
pypi
from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Any, Dict, Iterator, List, Literal, Optional, Union from robotcode.core.dataclasses import to_camel_case, to_snake_case @dataclass class Model: @classmethod def _encode_case(cls, s: str) -> str: return to_camel_case(s) @classmethod def _decode_case(cls, s: str) -> str: return to_snake_case(s) def __next_id_iter() -> Iterator[int]: i = 0 while True: yield i i += 1 _next_id_iterator = __next_id_iter() def _next_id() -> int: return next(_next_id_iterator) @dataclass class ProtocolMessage(Model): type: Union[Literal["request", "response", "event"], str] seq: int = field(default_factory=lambda: _next_id()) @dataclass class _Request: command: str arguments: Optional[Any] = None @dataclass class Request(ProtocolMessage, _Request): type: str = "request" @dataclass class _Event: event: str body: Optional[Any] = None @dataclass class Event(ProtocolMessage, _Event): type: str = "event" @dataclass class _Response: request_seq: int = field(metadata={"alias": "request_seq"}) success: bool command: str message: Optional[Union[Literal["cancelled"], str]] = None @dataclass class Response(ProtocolMessage, _Response): type: str = "response" body: Optional[Any] = None @dataclass class Message(Model): format: str id: int = -1 variables: Optional[Dict[str, str]] = None send_telemetry: Optional[bool] = None show_user: Optional[bool] = None url: Optional[str] = None url_label: Optional[str] = None def __str__(self) -> str: result = self.format for k, v in (self.variables or {}).items(): result = result.replace(f"{{{k}}}", v) result += f" ({super().__str__()})" return result @dataclass class ErrorBody(Model): error: Optional[Message] = None @dataclass class _ErrorResponse: body: Optional[ErrorBody] @dataclass class ErrorResponse(Response, _ErrorResponse): body: Optional[ErrorBody] = field() @dataclass class CancelArguments(Model): request_id: Optional[int] = None progress_id: Optional[int] = None @dataclass class CancelRequest(Request): arguments: Optional[CancelArguments] = None command: str = "cancel" @dataclass class CancelResponse(Response): pass @dataclass class InitializedEvent(Event): event: str = "initialized" class StoppedReason(Enum): STEP = "step" BREAKPOINT = "breakpoint" EXCEPTION = "exception" PAUSE = "pause" ENTRY = "entry" GOTO = "goto" FUNCTION_BREAKPOINT = "function breakpoint" DATA_BREAKPOINT = "data breakpoint" INSTRUCTION_BREAKPOINT = "instruction breakpoint" def __repr__(self) -> str: # pragma: no cover return super().__str__() @dataclass class StoppedEventBody(Model): reason: Union[ StoppedReason, str, ] description: Optional[str] = None thread_id: Optional[int] = None preserve_focus_hint: Optional[bool] = None text: Optional[str] = None all_threads_stopped: Optional[bool] = None hit_breakpoint_ids: Optional[List[int]] = None @dataclass class _StoppedEvent: body: StoppedEventBody @dataclass class StoppedEvent(Event, _StoppedEvent): body: StoppedEventBody = field() event: str = "stopped" @dataclass class ContinuedEventBody(Model): thread_id: int all_threads_continued: Optional[bool] @dataclass class _ContinuedEvent: body: ContinuedEventBody @dataclass class ContinuedEvent(Event, _ContinuedEvent): body: ContinuedEventBody = field() event: str = "continued" @dataclass class ExitedEventBody(Model): exit_code: int @dataclass class _ExitedEvent: body: ExitedEventBody @dataclass class ExitedEvent(Event, _ExitedEvent): body: ExitedEventBody = field() event: str = "exited" @dataclass class TerminatedEventBody(Model): restart: Optional[Any] = None @dataclass class _TerminatedEvent: body: Optional[TerminatedEventBody] = None @dataclass class TerminatedEvent(Event, _TerminatedEvent): body: Optional[TerminatedEventBody] = None event: str = "terminated" class ChecksumAlgorithm(Enum): MD5 = "MD5" SHA1 = "SHA1" SHA256 = "SHA256" TIMESTAMP = "timestamp" def __repr__(self) -> str: # pragma: no cover return super().__str__() @dataclass class Checksum(Model): algorithm: ChecksumAlgorithm checksum: str @dataclass class Source(Model): name: Optional[str] = None path: Optional[str] = None source_reference: Optional[int] = None presentation_hint: Optional[Literal["normal", "emphasize", "deemphasize"]] = None origin: Optional[str] = None sources: Optional[List[Source]] = None adapter_data: Optional[Any] = None checksums: Optional[List[Checksum]] = None class OutputCategory(Enum): CONSOLE = "console" IMPORTANT = "important" STDOUT = "stdout" STDERR = "stderr" TELEMETRY = "telemetry" def __repr__(self) -> str: # pragma: no cover return super().__str__() class OutputGroup(Enum): START = "start" STARTCOLLAPSED = "startCollapsed" END = "end" def __repr__(self) -> str: # pragma: no cover return super().__str__() @dataclass class OutputEventBody(Model): output: str category: Union[OutputCategory, str, None] = None group: Optional[OutputGroup] = None variables_reference: Optional[int] = None source: Optional[Source] = None line: Optional[int] = None column: Optional[int] = None data: Optional[Any] = None @dataclass class _OutputEvent: body: Optional[OutputEventBody] = None @dataclass class OutputEvent(Event, _OutputEvent): body: Optional[OutputEventBody] = None event: str = "output" @dataclass class InitializeRequestArguments(Model): adapter_id: str = field(metadata={"alias": "adapterID"}) client_id: Optional[str] = field(metadata={"alias": "clientID"}) client_name: Optional[str] = None locale: Optional[str] = None lines_start_at1: Optional[bool] = None columns_start_at1: Optional[bool] = None path_format: Optional[Union[Literal["path", "uri"], str]] = None supports_variable_type: Optional[bool] = None supports_variable_paging: Optional[bool] = None supports_run_in_terminal_request: Optional[bool] = None supports_memory_references: Optional[bool] = None supports_progress_reporting: Optional[bool] = None supports_invalidated_event: Optional[bool] = None @dataclass class _InitializeRequest: arguments: InitializeRequestArguments @dataclass class InitializeRequest(Request, _InitializeRequest): arguments: InitializeRequestArguments = field() command: str = "initialize" @dataclass class AttachRequestArguments(Model): restart: Optional[Any] = field(default=None, metadata={"alias": "__restart"}) @dataclass class _AttachRequest: arguments: AttachRequestArguments @dataclass class AttachRequest(Request, _AttachRequest): arguments: AttachRequestArguments = field() command: str = "attach" @dataclass class AttachResponse(Response): pass @dataclass class ExceptionBreakpointsFilter(Model): filter: str label: str description: Optional[str] = None default: Optional[bool] = None supports_condition: Optional[bool] = None condition_description: Optional[str] = None @dataclass class ColumnDescriptor(Model): attribute_name: str label: str format: Optional[str] = None type: Optional[Literal["string", "number", "boolean", "unixTimestampUTC"]] = None width: Optional[int] = None @dataclass class Capabilities(Model): supports_configuration_done_request: Optional[bool] = None supports_function_breakpoints: Optional[bool] = None supports_conditional_breakpoints: Optional[bool] = None supports_hit_conditional_breakpoints: Optional[bool] = None supports_evaluate_for_hovers: Optional[bool] = None exception_breakpoint_filters: Optional[List[ExceptionBreakpointsFilter]] = None supports_step_back: Optional[bool] = None supports_set_variable: Optional[bool] = None supports_restart_frame: Optional[bool] = None supports_goto_targets_request: Optional[bool] = None supports_step_in_targets_request: Optional[bool] = None supports_completions_request: Optional[bool] = None completion_trigger_characters: Optional[List[str]] = None supports_modules_request: Optional[bool] = None additional_module_columns: Optional[List[ColumnDescriptor]] = None supported_checksum_algorithms: Optional[List[ChecksumAlgorithm]] = None supports_restart_request: Optional[bool] = None supports_exception_options: Optional[bool] = None supports_value_formatting_options: Optional[bool] = None supports_exception_info_request: Optional[bool] = None support_terminate_debuggee: Optional[bool] = None support_suspend_debuggee: Optional[bool] = None supports_delayed_stack_trace_loading: Optional[bool] = None supports_loaded_sources_request: Optional[bool] = None supports_log_points: Optional[bool] = None supports_terminate_threads_request: Optional[bool] = None supports_set_expression: Optional[bool] = None supports_terminate_request: Optional[bool] = None supports_data_breakpoints: Optional[bool] = None supports_read_memory_request: Optional[bool] = None supports_disassemble_request: Optional[bool] = None supports_cancel_request: Optional[bool] = None supports_breakpoint_locations_request: Optional[bool] = None supports_clipboard_context: Optional[bool] = None supports_stepping_granularity: Optional[bool] = None supports_instruction_breakpoints: Optional[bool] = None supports_exception_filter_options: Optional[bool] = None @dataclass class InitializeResponse(Response): body: Optional[Capabilities] = None @dataclass class LaunchRequestArguments(Model): no_debug: Optional[bool] = None restart: Optional[Any] = field(default=None, metadata={"alias": "__restart"}) @dataclass class _LaunchRequest: arguments: LaunchRequestArguments @dataclass class LaunchRequest(Request, _LaunchRequest): arguments: LaunchRequestArguments = field() command: str = "launch" @dataclass class LaunchResponse(Response): pass class RunInTerminalKind(Enum): INTEGRATED = "integrated" EXTERNAL = "external" def __repr__(self) -> str: # pragma: no cover return super().__str__() @dataclass class RunInTerminalRequestArguments(Model): cwd: str args: List[str] env: Optional[Dict[str, Optional[str]]] = None kind: Optional[RunInTerminalKind] = None title: Optional[str] = None args_can_be_interpreted_by_shell: Optional[bool] = None @dataclass class _RunInTerminalRequest: arguments: RunInTerminalRequestArguments @dataclass class RunInTerminalRequest(Request, _RunInTerminalRequest): arguments: RunInTerminalRequestArguments = field() command: str = field(default="runInTerminal", init=False, metadata={"force_json": True}) @dataclass class RunInTerminalResponseBody(Model): process_id: Optional[int] = None shell_process_id: Optional[int] = None @dataclass class _RunInTerminalResponse: body: RunInTerminalResponseBody @dataclass class RunInTerminalResponse(Response, _RunInTerminalResponse): body: RunInTerminalResponseBody = field() @dataclass class ConfigurationDoneArguments(Model): pass @dataclass class _ConfigurationDoneRequest: arguments: Optional[ConfigurationDoneArguments] = None @dataclass class ConfigurationDoneRequest(Request, _ConfigurationDoneRequest): arguments: Optional[ConfigurationDoneArguments] = None command: str = "configurationDone" @dataclass class ConfigurationDoneResponse(Response): pass @dataclass class DisconnectArguments(Model): restart: Optional[bool] = None terminate_debuggee: Optional[bool] = None suspend_debuggee: Optional[bool] = None @dataclass class _DisconnectRequest: arguments: Optional[DisconnectArguments] = None @dataclass class DisconnectRequest(Request, _DisconnectRequest): arguments: Optional[DisconnectArguments] = None command: str = "disconnect" @dataclass class DisconnectResponse(Response): pass @dataclass class SourceBreakpoint(Model): line: int column: Optional[int] = None condition: Optional[str] = None hit_condition: Optional[str] = None log_message: Optional[str] = None @dataclass class SetBreakpointsArguments(Model): source: Source breakpoints: Optional[List[SourceBreakpoint]] = None lines: Optional[List[int]] = None source_modified: Optional[bool] = None @dataclass class _SetBreakpointsRequest: arguments: SetBreakpointsArguments @dataclass class SetBreakpointsRequest(Request, _SetBreakpointsRequest): arguments: SetBreakpointsArguments = field() command: str = "setBreakpoints" @dataclass class Breakpoint(Model): verified: bool id: Optional[int] = None message: Optional[str] = None source: Optional[Source] = None line: Optional[int] = None column: Optional[int] = None end_line: Optional[int] = None end_column: Optional[int] = None instruction_reference: Optional[str] = None offset: Optional[int] = None @dataclass class SetBreakpointsResponseBody(Model): breakpoints: List[Breakpoint] @dataclass class _SetBreakpointsResponse: body: SetBreakpointsResponseBody @dataclass class SetBreakpointsResponse(Response, _SetBreakpointsResponse): body: SetBreakpointsResponseBody = field() @dataclass class ThreadsRequest(Request): command: str = "threads" @dataclass class Thread(Model): id: int name: str @dataclass class ThreadsResponseBody(Model): threads: List[Thread] @dataclass class _ThreadsResponse: body: ThreadsResponseBody @dataclass class ThreadsResponse(Response, _ThreadsResponse): body: ThreadsResponseBody = field() @dataclass class TerminateArguments(Model): restart: Optional[bool] = None @dataclass class _TerminateRequest: arguments: Optional[TerminateArguments] = None @dataclass class TerminateRequest(Request, _TerminateRequest): arguments: Optional[TerminateArguments] = None command: str = "terminate" @dataclass class TerminateResponse(Response): pass @dataclass class StackFrameFormat(Model): parameters: Optional[bool] = None parameter_types: Optional[bool] = None parameter_names: Optional[bool] = None parameter_values: Optional[bool] = None line: Optional[bool] = None module: Optional[bool] = None include_all: Optional[bool] = None @dataclass class StackTraceArguments(Model): thread_id: int start_frame: Optional[int] = None levels: Optional[int] = None format: Optional[StackFrameFormat] = None @dataclass class _StackTraceRequest: arguments: StackTraceArguments @dataclass class StackTraceRequest(Request, _StackTraceRequest): arguments: StackTraceArguments = field() command: str = "stackTrace" @dataclass class StackFrame(Model): id: int name: str line: int column: int source: Optional[Source] = None end_line: Optional[int] = None end_column: Optional[int] = None can_restart: Optional[bool] = None instruction_pointer_reference: Optional[str] = None module_id: Union[int, str, None] = None presentation_hint: Optional[Literal["normal", "label", "subtle"]] = None @dataclass class StackTraceResponseBody(Model): stack_frames: List[StackFrame] total_frames: Optional[int] @dataclass class _StackTraceResponse: body: StackTraceResponseBody @dataclass class StackTraceResponse(Response, _StackTraceResponse): body: StackTraceResponseBody = field() @dataclass class ScopesArguments(Model): frame_id: int @dataclass class Scope(Model): name: str variables_reference: int expensive: bool presentation_hint: Union[Literal["arguments", "locals", "registers"], str, None] = None named_variables: Optional[int] = None indexed_variables: Optional[int] = None source: Optional[Source] = None line: Optional[int] = None column: Optional[int] = None end_line: Optional[int] = None end_column: Optional[int] = None @dataclass class _ScopesRequest: arguments: ScopesArguments @dataclass class ScopesRequest(Request, _ScopesRequest): arguments: ScopesArguments = field() command: str = "scopes" @dataclass class ScopesResponseBody(Model): scopes: List[Scope] @dataclass class _ScopesResponse: body: ScopesResponseBody @dataclass class ScopesResponse(Response, _ScopesResponse): body: ScopesResponseBody = field() @dataclass class ContinueArguments(Model): thread_id: int @dataclass class _ContinueRequest: arguments: ContinueArguments @dataclass class ContinueRequest(Request, _ContinueRequest): arguments: ContinueArguments = field() command: str = "continue" @dataclass class ContinueResponseBody(Model): all_threads_continued: Optional[bool] = None @dataclass class _ContinueResponse: body: ContinueResponseBody @dataclass class ContinueResponse(Response, _ContinueResponse): body: ContinueResponseBody = field() @dataclass class PauseArguments(Model): thread_id: int @dataclass class _PauseRequest: arguments: PauseArguments @dataclass class PauseRequest(Request, _PauseRequest): arguments: PauseArguments = field() command: str = "pause" @dataclass class PauseResponse(Response): pass @dataclass class SteppingGranularity(Enum): STATEMENT = "statement" LINE = "line" INSTRUCTION = "instruction" def __repr__(self) -> str: # pragma: no cover return super().__str__() @dataclass class NextArguments(Model): thread_id: int granularity: Optional[SteppingGranularity] = None @dataclass class _NextRequest: arguments: NextArguments @dataclass class NextRequest(Request, _NextRequest): arguments: NextArguments = field() command: str = "next" @dataclass class NextResponse(Response): pass @dataclass class StepInArguments(Model): thread_id: int target_id: Optional[int] = None granularity: Optional[SteppingGranularity] = None @dataclass class _StepInRequest: arguments: StepInArguments @dataclass class StepInRequest(Request, _StepInRequest): arguments: StepInArguments = field() command: str = "stepIn" @dataclass class StepInResponse(Response): pass @dataclass class StepOutArguments(Model): thread_id: int granularity: Optional[SteppingGranularity] = None @dataclass class _StepOutRequest: arguments: StepOutArguments @dataclass class StepOutRequest(Request, _StepOutRequest): arguments: StepOutArguments = field() command: str = "stepOut" @dataclass class StepOutResponse(Response): pass @dataclass class ValueFormat(Model): hex: Optional[bool] = None @dataclass class VariablesArguments(Model): variables_reference: int filter: Optional[Literal["indexed", "named"]] = None start: Optional[int] = None count: Optional[int] = None format: Optional[ValueFormat] = None @dataclass class _VariablesRequest: arguments: VariablesArguments @dataclass class VariablesRequest(Request, _VariablesRequest): arguments: VariablesArguments = field() command: str = "variables" @dataclass class VariablePresentationHint(Model): kind: Union[ Literal[ "property", "method", "class", "data", "event", "baseClass", "innerClass", "interface", "mostDerivedClass", "virtual", "dataBreakpoint", ], str, None, ] = None attributes: Optional[ List[ Union[ Literal[ "static", "constant", "readOnly", "rawString", "hasObjectId", "canHaveObjectId", "hasSideEffects", "hasDataBreakpoint", ], str, ] ] ] = None visibility: Union[Literal["public", "private", "protected", "internal", "final"], str, None] = None @dataclass class Variable(Model): name: str value: str type: Optional[str] = None presentation_hint: Optional[VariablePresentationHint] = None evaluate_name: Optional[str] = None variables_reference: int = 0 named_variables: Optional[int] = None indexed_variables: Optional[int] = None memory_reference: Optional[str] = None @dataclass class VariablesResponseBody(Model): variables: List[Variable] @dataclass class _VariablesResponse: body: VariablesResponseBody @dataclass class VariablesResponse(Response, _VariablesResponse): body: VariablesResponseBody = field() class EvaluateArgumentContext(Enum): WATCH = "watch" REPL = "repl" HOVER = "hover" CLIPBOARD = "clipboard" def __repr__(self) -> str: # pragma: no cover return super().__str__() @dataclass class EvaluateArguments(Model): expression: str frame_id: Optional[int] = None context: Union[EvaluateArgumentContext, str, None] = None format: Optional[ValueFormat] = None @dataclass class _EvaluateRequest: arguments: EvaluateArguments @dataclass class EvaluateRequest(Request, _EvaluateRequest): arguments: EvaluateArguments = field() command: str = "evaluate" @dataclass class EvaluateResponseBody(Model): result: str type: Optional[str] = None presentation_hint: Optional[VariablePresentationHint] = None variables_reference: int = 0 named_variables: Optional[int] = None indexed_variables: Optional[int] = None memory_reference: Optional[str] = None @dataclass class _EvaluateResponse: body: VariablesResponseBody @dataclass class EvaluateResponse(Response, _EvaluateResponse): body: VariablesResponseBody = field() @dataclass class SetVariableArguments(Model): variables_reference: int name: str value: str format: Optional[ValueFormat] = None @dataclass class _SetVariableRequest: arguments: SetVariableArguments @dataclass class SetVariableRequest(Request, _SetVariableRequest): arguments: SetVariableArguments = field() command: str = "setVariable" @dataclass class SetVariableResponseBody(Model): value: str type: Optional[str] variables_reference: Optional[int] = None named_variables: Optional[int] = None indexed_variables: Optional[int] = None @dataclass class _SetVariableResponse: body: SetVariableResponseBody @dataclass class SetVariableResponse(Response, _SetVariableResponse): body: SetVariableResponseBody = field() @dataclass(unsafe_hash=True) class ExceptionFilterOptions(Model): filter_id: str condition: Optional[str] = None class ExceptionBreakMode(Enum): NEVER = "never" ALWAYS = "always" UNHANDLED = "unhandled" USER_UNHANDLED = "userUnhandled" def __repr__(self) -> str: # pragma: no cover return super().__str__() @dataclass class ExceptionPathSegment(Model): names: List[str] negate: Optional[bool] = None @dataclass class ExceptionOptions(Model): break_mode: ExceptionBreakMode path: Optional[List[ExceptionPathSegment]] = None @dataclass class SetExceptionBreakpointsArguments(Model): filters: List[str] filter_options: Optional[List[ExceptionFilterOptions]] = None exception_options: Optional[List[ExceptionOptions]] = None @dataclass class _SetExceptionBreakpointsRequest: arguments: SetExceptionBreakpointsArguments @dataclass class SetExceptionBreakpointsRequest(Request, _SetExceptionBreakpointsRequest): arguments: SetExceptionBreakpointsArguments = field() command: str = "setExceptionBreakpoints" @dataclass class SetExceptionBreakpointsResponseBody(Model): breakpoints: Optional[List[Breakpoint]] = None @dataclass class SetExceptionBreakpointsResponse(Response): body: Optional[SetExceptionBreakpointsResponseBody] = None @dataclass class _CompletionsRequest: arguments: CompletionsArguments @dataclass class CompletionsRequest(Request, _CompletionsRequest): arguments: CompletionsArguments = field() command: str = "completions" @dataclass class CompletionsArguments(Model): text: str column: int line: Optional[int] = None frame_id: Optional[int] = None class CompletionItemType(Enum): METHOD = "method" FUNCTION = "function" CONSTRUCTOR = "constructor" FIELD = "field" VARIABLE = "variable" CLASS = "class" INTERFACE = "interface" MODULE = "module" PROPERTY = "property" UNIT = "unit" VALUE = "value" ENUM = "enum" KEYWORD = "keyword" SNIPPET = "snippet" TEXT = "text" COLOR = "color" FILE = "file" REFERENCE = "reference" CUSTOMCOLOR = "customcolor" @dataclass class CompletionItem(Model): label: str text: Optional[str] = None sort_text: Optional[str] = None detail: Optional[str] = None type: Optional[CompletionItemType] = None start: Optional[int] = None length: Optional[int] = None selection_start: Optional[int] = None selection_length: Optional[int] = None @dataclass class CompletionsResponseBody(Model): targets: List[CompletionItem] @dataclass class CompletionsResponse(Response): body: Optional[CompletionsResponseBody] = None
/robotcode_debugger-0.54.3-py3-none-any.whl/robotcode/debugger/dap_types.py
0.861771
0.193547
dap_types.py
pypi
from dataclasses import dataclass, field from enum import Enum from typing import Any, Dict, List, Optional, Tuple from robotcode.language_server.common.parts.diagnostics import AnalysisProgressMode, DiagnosticsMode from robotcode.language_server.common.parts.workspace import ConfigBase, config_section @config_section("robotcode.languageServer") @dataclass class LanguageServerConfig(ConfigBase): mode: str = "stdio" tcp_port: int = 0 args: Tuple[str, ...] = field(default_factory=tuple) class RpaMode(Enum): DEFAULT = "default" RPA = "rpa" NORPA = "norpa" class CacheSaveLocation(Enum): WORKSPACE_FOLDER = "workspaceFolder" WORKSPACE_STORAGE = "workspaceStorage" @config_section("robotcode.robot") @dataclass class RobotConfig(ConfigBase): args: List[str] = field(default_factory=list) python_path: List[str] = field(default_factory=list) env: Dict[str, str] = field(default_factory=dict) variables: Dict[str, Any] = field(default_factory=dict) variable_files: List[str] = field(default_factory=list) paths: List[str] = field(default_factory=list) output_dir: Optional[str] = None output_file: Optional[str] = None log_file: Optional[str] = None debug_file: Optional[str] = None log_level: Optional[str] = None mode: Optional[RpaMode] = None languages: Optional[List[str]] = None parsers: Optional[List[str]] = None def get_rpa_mode(self) -> Optional[bool]: if self.mode == RpaMode.RPA: return True if self.mode == RpaMode.NORPA: return False return None @config_section("robotcode.completion") @dataclass class CompletionConfig(ConfigBase): filter_default_language: bool = False header_style: Optional[str] = None @config_section("robotcode.robocop") @dataclass class RoboCopConfig(ConfigBase): enabled: bool = True include: List[str] = field(default_factory=list) exclude: List[str] = field(default_factory=list) configurations: List[str] = field(default_factory=list) @config_section("robotcode.robotidy") @dataclass class RoboTidyConfig(ConfigBase): enabled: bool = True ignore_git_dir: bool = False config: Optional[str] = None @config_section("robotcode.workspace") @dataclass class WorkspaceConfig(ConfigBase): exclude_patterns: List[str] = field(default_factory=list) @config_section("robotcode.analysis.cache") @dataclass class Cache(ConfigBase): save_location: CacheSaveLocation = CacheSaveLocation.WORKSPACE_STORAGE ignored_libraries: List[str] = field(default_factory=list) ignored_variables: List[str] = field(default_factory=list) @config_section("robotcode.analysis") @dataclass class AnalysisConfig(ConfigBase): diagnostic_mode: DiagnosticsMode = DiagnosticsMode.OPENFILESONLY progress_mode: AnalysisProgressMode = AnalysisProgressMode.OFF max_project_file_count: int = 5000 references_code_lens: bool = False find_unused_references: bool = False cache: Cache = field(default_factory=Cache) @config_section("robotcode.documentationServer") @dataclass class DocumentationServerConfig(ConfigBase): start_port: int = 3100 end_port: int = 3199 @config_section("robotcode.inlayHints") @dataclass class InlayHintsConfig(ConfigBase): parameter_names: bool = True namespaces: bool = True @config_section("robotcode") @dataclass class RobotCodeConfig(ConfigBase): language_server: LanguageServerConfig = field(default_factory=LanguageServerConfig) robot: RobotConfig = field(default_factory=RobotConfig) syntax: CompletionConfig = field(default_factory=CompletionConfig) workspace: WorkspaceConfig = field(default_factory=WorkspaceConfig) analysis: AnalysisConfig = field(default_factory=AnalysisConfig) documentation_server: DocumentationServerConfig = field(default_factory=DocumentationServerConfig) inlay_hints: InlayHintsConfig = field(default_factory=InlayHintsConfig)
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/configuration.py
0.775562
0.192103
configuration.py
pypi
from __future__ import annotations import ast import itertools from typing import TYPE_CHECKING, Any, List, Optional, Union, cast from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import DocumentSymbol, SymbolInformation, SymbolKind from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.utils.ast_utils import ( Token, range_from_node, range_from_token, tokenize_variables, ) from robotcode.language_server.robotframework.utils.async_ast import AsyncVisitor if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import RobotLanguageServerProtocol from .protocol_part import RobotLanguageServerProtocolPart class _Visitor(AsyncVisitor): def __init__(self, parent: RobotDocumentSymbolsProtocolPart) -> None: super().__init__() self.parent = parent self.result: List[DocumentSymbol] = [] self.current_symbol: Optional[DocumentSymbol] = None async def generic_visit_current_symbol(self, node: ast.AST, symbol: DocumentSymbol) -> None: old = self.current_symbol self.current_symbol = symbol try: await self.generic_visit(node) finally: self.current_symbol = old @classmethod async def find_from( cls, model: ast.AST, parent: RobotDocumentSymbolsProtocolPart ) -> Optional[List[DocumentSymbol]]: finder = cls(parent) await finder.visit(model) return finder.result if finder.result else None async def visit_Section(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.model.blocks import Section from robot.parsing.model.statements import SectionHeader section = cast(Section, node) if section.header is None: return header = cast(SectionHeader, section.header) if not header.name: return r = range_from_node(section) symbol = DocumentSymbol( name=header.name.replace("*", "").strip(), kind=SymbolKind.NAMESPACE, range=r, selection_range=r, children=[], ) self.result.append(symbol) await self.generic_visit_current_symbol(node, symbol) async def visit_TestCase(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.model.blocks import TestCase testcase = cast(TestCase, node) if testcase.name is None: return if self.current_symbol is not None and self.current_symbol.children is not None: r = range_from_node(testcase) symbol = DocumentSymbol(name=testcase.name, kind=SymbolKind.METHOD, range=r, selection_range=r, children=[]) self.current_symbol.children.append(symbol) await self.generic_visit_current_symbol(node, symbol) async def visit_Keyword(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.model.blocks import Keyword keyword = cast(Keyword, node) if keyword.name is None: return if self.current_symbol is not None and self.current_symbol.children is not None: r = range_from_node(keyword) symbol = DocumentSymbol( name=keyword.name, kind=SymbolKind.FUNCTION, range=r, selection_range=r, children=[] ) self.current_symbol.children.append(symbol) await self.generic_visit_current_symbol(node, symbol) async def visit_Arguments(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Arguments n = cast(Arguments, node) arguments = n.get_tokens(RobotToken.ARGUMENT) if self.current_symbol is not None and self.current_symbol.children is not None: for argument_token in (cast(RobotToken, e) for e in arguments): if argument_token.value == "@{}": continue argument = self.get_variable_token(argument_token) if argument is not None: r = range_from_token(argument) symbol = DocumentSymbol(name=argument.value, kind=SymbolKind.VARIABLE, range=r, selection_range=r) if symbol.name not in map(lambda v: v.name, self.current_symbol.children): self.current_symbol.children.append(symbol) def get_variable_token(self, token: Token) -> Optional[Token]: from robot.parsing.lexer.tokens import Token as RobotToken return next( ( v for v in itertools.dropwhile( lambda t: t.type in RobotToken.NON_DATA_TOKENS, tokenize_variables(token, ignore_errors=True), ) if v.type == RobotToken.VARIABLE ), None, ) async def visit_KeywordCall(self, node: ast.AST) -> None: # noqa: N802 from robot.errors import VariableError from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import KeywordCall # TODO analyse "Set Local/Global/Suite Variable" keyword_call = cast(KeywordCall, node) for assign_token in keyword_call.get_tokens(RobotToken.ASSIGN): if assign_token is None: continue if self.current_symbol is not None and self.current_symbol.children is not None: try: variable_token = self.get_variable_token(assign_token) if variable_token is not None: r = range_from_token(variable_token) symbol = DocumentSymbol( name=variable_token.value, kind=SymbolKind.VARIABLE, range=r, selection_range=r ) if symbol.name not in map(lambda v: v.name, self.current_symbol.children): self.current_symbol.children.append(symbol) except VariableError: pass async def visit_ForHeader(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import ForHeader n = cast(ForHeader, node) variables = n.get_tokens(RobotToken.VARIABLE) if self.current_symbol is not None and self.current_symbol.children is not None: for variable in variables: variable_token = self.get_variable_token(variable) if variable_token is not None: r = range_from_token(variable_token) symbol = DocumentSymbol( name=variable_token.value, kind=SymbolKind.VARIABLE, range=r, selection_range=r ) if symbol.name not in map(lambda v: v.name, self.current_symbol.children): self.current_symbol.children.append(symbol) async def visit_KeywordName(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import KeywordName n = cast(KeywordName, node) nt = n.get_token(RobotToken.KEYWORD_NAME) if nt is None: return name_token = cast(Token, nt) if self.current_symbol is not None and self.current_symbol.children is not None: for variable in filter( lambda e: e.type == RobotToken.VARIABLE, tokenize_variables(name_token, identifiers="$", ignore_errors=True), ): variable_token = self.get_variable_token(variable) if variable_token is not None: r = range_from_token(variable_token) symbol = DocumentSymbol( name=variable_token.value, kind=SymbolKind.VARIABLE, range=r, selection_range=r ) if symbol.name not in map(lambda v: v.name, self.current_symbol.children): self.current_symbol.children.append(symbol) async def visit_Variable(self, node: ast.AST) -> None: # noqa: N802 from robot.api.parsing import Token as RobotToken from robot.parsing.model.statements import Variable from robot.variables import search_variable variable = cast(Variable, node) name_token = variable.get_token(RobotToken.VARIABLE) name = name_token.value if name is not None: match = search_variable(name, ignore_errors=True) if not match.is_assign(allow_assign_mark=True): return if name.endswith("="): name = name[:-1].rstrip() if self.current_symbol is not None and self.current_symbol.children is not None: r = range_from_node(variable) symbol = DocumentSymbol(name=name, kind=SymbolKind.VARIABLE, range=r, selection_range=r) self.current_symbol.children.append(symbol) class RobotDocumentSymbolsProtocolPart(RobotLanguageServerProtocolPart): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.document_symbols.collect.add(self.collect) @language_id("robotframework") @_logger.call async def collect( self, sender: Any, document: TextDocument ) -> Optional[Union[List[DocumentSymbol], List[SymbolInformation], None]]: return await _Visitor.find_from(await self.parent.documents_cache.get_model(document), self)
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/document_symbols.py
0.688887
0.183447
document_symbols.py
pypi
from __future__ import annotations import ast import asyncio from typing import TYPE_CHECKING, Any, List, Optional from robotcode.core.async_tools import check_canceled, create_sub_task, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import Diagnostic, DiagnosticSeverity, DiagnosticTag, Position, Range from robotcode.core.uri import Uri from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.parts.diagnostics import DiagnosticsResult from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.configuration import AnalysisConfig from robotcode.language_server.robotframework.diagnostics.entities import ArgumentDefinition from robotcode.language_server.robotframework.diagnostics.namespace import Namespace from robotcode.language_server.robotframework.utils.ast_utils import ( HeaderAndBodyBlock, Token, range_from_node, range_from_token, ) if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import RobotLanguageServerProtocol from .protocol_part import RobotLanguageServerProtocolPart class RobotDiagnosticsProtocolPart(RobotLanguageServerProtocolPart): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) self.source_name = "robotcode.diagnostics" parent.diagnostics.collect.add(self.collect_token_errors) parent.diagnostics.collect.add(self.collect_model_errors) parent.diagnostics.collect.add(self.collect_namespace_diagnostics) parent.diagnostics.collect.add(self.collect_unused_keyword_references) parent.diagnostics.collect.add(self.collect_unused_variable_references) parent.documents_cache.namespace_invalidated.add(self.namespace_invalidated) async def namespace_invalidated_task(self, namespace: Namespace) -> None: if namespace.document is not None: refresh = namespace.document.opened_in_editor await self.parent.diagnostics.force_refresh_document(namespace.document, False) if await namespace.is_initialized(): resources = (await namespace.get_resources()).values() for r in resources: if r.library_doc.source: doc = await self.parent.documents.get(Uri.from_path(r.library_doc.source).normalized()) if doc is not None: refresh |= doc.opened_in_editor await self.parent.diagnostics.force_refresh_document(doc, False) if refresh: await self.parent.diagnostics.refresh() @language_id("robotframework") @_logger.call async def namespace_invalidated(self, sender: Any, namespace: Namespace) -> None: create_sub_task(self.namespace_invalidated_task(namespace), loop=self.parent.diagnostics.diagnostics_loop) @language_id("robotframework") @threaded() @_logger.call async def collect_namespace_diagnostics(self, sender: Any, document: TextDocument) -> DiagnosticsResult: return await document.get_cache(self._collect_namespace_diagnostics) async def _collect_namespace_diagnostics(self, document: TextDocument) -> DiagnosticsResult: try: namespace = await self.parent.documents_cache.get_namespace(document) return DiagnosticsResult(self.collect_namespace_diagnostics, await namespace.get_diagnostisc()) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException as e: self._logger.exception(e) return DiagnosticsResult( self.collect_namespace_diagnostics, [ Diagnostic( range=Range( start=Position( line=0, character=0, ), end=Position( line=len(document.get_lines()), character=len((document.get_lines())[-1] or ""), ), ), message=f"Fatal: can't get namespace diagnostics '{e}' ({type(e).__qualname__})", severity=DiagnosticSeverity.ERROR, source=self.source_name, code=type(e).__qualname__, ) ], ) def _create_error_from_node( self, node: ast.AST, msg: str, source: Optional[str] = None, only_start: bool = True ) -> Diagnostic: from robot.parsing.model.statements import Statement if isinstance(node, HeaderAndBodyBlock): if node.header is not None: node = node.header elif node.body: stmt = next((n for n in node.body if isinstance(n, Statement)), None) if stmt is not None: node = stmt return Diagnostic( range=range_from_node(node, True, only_start), message=msg, severity=DiagnosticSeverity.ERROR, source=source if source is not None else self.source_name, code="ModelError", ) def _create_error_from_token(self, token: Token, source: Optional[str] = None) -> Diagnostic: return Diagnostic( range=range_from_token(token), message=token.error if token.error is not None else "(No Message).", severity=DiagnosticSeverity.ERROR, source=source if source is not None else self.source_name, code="TokenError", ) @language_id("robotframework") @threaded() @_logger.call async def collect_token_errors(self, sender: Any, document: TextDocument) -> DiagnosticsResult: return await document.get_cache(self._collect_token_errors) async def _collect_token_errors(self, document: TextDocument) -> DiagnosticsResult: from robot.errors import VariableError from robot.parsing.lexer.tokens import Token result: List[Diagnostic] = [] try: for token in await self.parent.documents_cache.get_tokens(document): await check_canceled() if token.type in [Token.ERROR, Token.FATAL_ERROR] and not Namespace.should_ignore( document, range_from_token(token) ): result.append(self._create_error_from_token(token)) try: for variable_token in token.tokenize_variables(): await check_canceled() if variable_token == token: break if variable_token.type in [ Token.ERROR, Token.FATAL_ERROR, ] and not Namespace.should_ignore(document, range_from_token(variable_token)): result.append(self._create_error_from_token(variable_token)) except VariableError as e: if not Namespace.should_ignore(document, range_from_token(token)): result.append( Diagnostic( range=range_from_token(token), message=str(e), severity=DiagnosticSeverity.ERROR, source=self.source_name, code=type(e).__qualname__, ) ) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException as e: return DiagnosticsResult( self.collect_token_errors, [ Diagnostic( range=Range( start=Position( line=0, character=0, ), end=Position( line=len(document.get_lines()), character=len((document.get_lines())[-1] or ""), ), ), message=f"Fatal: can't get token diagnostics '{e}' ({type(e).__qualname__})", severity=DiagnosticSeverity.ERROR, source=self.source_name, code=type(e).__qualname__, ) ], ) return DiagnosticsResult(self.collect_token_errors, result) @language_id("robotframework") @threaded() @_logger.call async def collect_model_errors(self, sender: Any, document: TextDocument) -> DiagnosticsResult: return await document.get_cache(self._collect_model_errors) async def _collect_model_errors(self, document: TextDocument) -> DiagnosticsResult: from robotcode.language_server.robotframework.utils.ast_utils import HasError, HasErrors from robotcode.language_server.robotframework.utils.async_ast import iter_nodes try: model = await self.parent.documents_cache.get_model(document, True) result: List[Diagnostic] = [] async for node in iter_nodes(model): error = node.error if isinstance(node, HasError) else None if error is not None and not Namespace.should_ignore(document, range_from_node(node)): result.append(self._create_error_from_node(node, error)) errors = node.errors if isinstance(node, HasErrors) else None if errors is not None: for e in errors: if not Namespace.should_ignore(document, range_from_node(node)): result.append(self._create_error_from_node(node, e)) return DiagnosticsResult(self.collect_model_errors, result) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException as e: return DiagnosticsResult( self.collect_model_errors, [ Diagnostic( range=Range( start=Position( line=0, character=0, ), end=Position( line=len(document.get_lines()), character=len((document.get_lines())[-1] or ""), ), ), message=f"Fatal: can't get model diagnostics '{e}' ({type(e).__qualname__})", severity=DiagnosticSeverity.ERROR, source=self.source_name, code=type(e).__qualname__, ) ], ) @language_id("robotframework") @threaded() @_logger.call async def collect_unused_keyword_references(self, sender: Any, document: TextDocument) -> DiagnosticsResult: if not self.parent.diagnostics.workspace_loaded_event.is_set(): return DiagnosticsResult(self.collect_unused_keyword_references, None) config = await self.parent.workspace.get_configuration(AnalysisConfig, document.uri) if not config.find_unused_references: return DiagnosticsResult(self.collect_unused_keyword_references, []) return await self._collect_unused_keyword_references(document) async def _collect_unused_keyword_references(self, document: TextDocument) -> DiagnosticsResult: try: namespace = await self.parent.documents_cache.get_namespace(document) result: List[Diagnostic] = [] for kw in (await namespace.get_library_doc()).keywords.values(): references = await self.parent.robot_references.find_keyword_references(document, kw, False, True) if not references and not Namespace.should_ignore(document, kw.name_range): result.append( Diagnostic( range=kw.name_range, message=f"Keyword '{kw.name}' is not used.", severity=DiagnosticSeverity.WARNING, source=self.source_name, code="KeywordNotUsed", tags=[DiagnosticTag.UNNECESSARY], ) ) return DiagnosticsResult(self.collect_unused_keyword_references, result) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException as e: return DiagnosticsResult( self.collect_unused_keyword_references, [ Diagnostic( range=Range( start=Position( line=0, character=0, ), end=Position( line=len(document.get_lines()), character=len((document.get_lines())[-1] or ""), ), ), message=f"Fatal: can't collect unused keyword references '{e}' ({type(e).__qualname__})", severity=DiagnosticSeverity.ERROR, source=self.source_name, code=type(e).__qualname__, ) ], ) @language_id("robotframework") @threaded() @_logger.call async def collect_unused_variable_references(self, sender: Any, document: TextDocument) -> DiagnosticsResult: if not self.parent.diagnostics.workspace_loaded_event.is_set(): return DiagnosticsResult(self.collect_unused_variable_references, None) config = await self.parent.workspace.get_configuration(AnalysisConfig, document.uri) if not config.find_unused_references: return DiagnosticsResult(self.collect_unused_variable_references, []) return await self._collect_unused_variable_references(document) async def _collect_unused_variable_references(self, document: TextDocument) -> DiagnosticsResult: try: namespace = await self.parent.documents_cache.get_namespace(document) result: List[Diagnostic] = [] for var in (await namespace.get_variable_references()).keys(): references = await self.parent.robot_references.find_variable_references(document, var, False, True) if not references and not Namespace.should_ignore(document, var.name_range): result.append( Diagnostic( range=var.name_range, message=f"{'Argument' if isinstance(var, ArgumentDefinition) else 'Variable'}" f" '{var.name}' is not used.", severity=DiagnosticSeverity.WARNING, source=self.source_name, code="VariableNotUsed", tags=[DiagnosticTag.UNNECESSARY], ) ) return DiagnosticsResult(self.collect_unused_variable_references, result) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException as e: return DiagnosticsResult( self.collect_unused_variable_references, [ Diagnostic( range=Range( start=Position( line=0, character=0, ), end=Position( line=len(document.get_lines()), character=len((document.get_lines())[-1] or ""), ), ), message=f"Fatal: can't collect unused variable references '{e}' ({type(e).__qualname__})", severity=DiagnosticSeverity.ERROR, source=self.source_name, code=type(e).__qualname__, ) ], )
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/diagnostics.py
0.762203
0.186558
diagnostics.py
pypi
from __future__ import annotations import ast from typing import TYPE_CHECKING, Any, List, Optional, Set, Tuple, cast from robotcode.core.async_tools import create_sub_task from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import CodeLens, Command from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.configuration import AnalysisConfig from robotcode.language_server.robotframework.diagnostics.library_doc import KeywordDoc from robotcode.language_server.robotframework.utils.ast_utils import range_from_token from robotcode.language_server.robotframework.utils.async_ast import AsyncVisitor from .model_helper import ModelHelperMixin from .protocol_part import RobotLanguageServerProtocolPart if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import ( RobotLanguageServerProtocol, ) class _Visitor(AsyncVisitor): def __init__(self, parent: RobotCodeLensProtocolPart, document: TextDocument) -> None: super().__init__() self.parent = parent self.document = document self.result: List[CodeLens] = [] async def visit(self, node: ast.AST) -> None: await super().visit(node) @classmethod async def find_from( cls, model: ast.AST, parent: RobotCodeLensProtocolPart, document: TextDocument ) -> Optional[List[CodeLens]]: finder = cls(parent, document) await finder.visit(model) return finder.result if finder.result else None async def visit_Section(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.model.blocks import KeywordSection if isinstance(node, KeywordSection): await self.generic_visit(node) async def visit_KeywordName(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import KeywordName kw_node = cast(KeywordName, node) name_token = cast(RobotToken, kw_node.get_token(RobotToken.KEYWORD_NAME)) if not name_token: return self.result.append( CodeLens( range_from_token(name_token), command=None, data={ "uri": str(self.document.uri), "name": name_token.value, "line": name_token.lineno, }, ) ) class RobotCodeLensProtocolPart(RobotLanguageServerProtocolPart, ModelHelperMixin): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.code_lens.collect.add(self.collect) parent.code_lens.resolve.add(self.resolve) self._running_task: Set[Tuple[TextDocument, KeywordDoc]] = set() parent.diagnostics.on_workspace_loaded.add(self.codelens_refresh) parent.robot_references.cache_cleared.add(self.codelens_refresh) @language_id("robotframework") async def codelens_refresh(self, sender: Any) -> None: # NOSONAR await self.parent.code_lens.refresh() @language_id("robotframework") async def collect(self, sender: Any, document: TextDocument) -> Optional[List[CodeLens]]: if not (await self.parent.workspace.get_configuration(AnalysisConfig, document.uri)).references_code_lens: return None return await _Visitor.find_from(await self.parent.documents_cache.get_model(document), self, document) @language_id("robotframework") async def resolve(self, sender: Any, code_lens: CodeLens) -> Optional[CodeLens]: if code_lens.data is None: return code_lens document = await self.parent.documents.get(code_lens.data.get("uri", None)) if document is None: return None if not (await self.parent.workspace.get_configuration(AnalysisConfig, document.uri)).references_code_lens: return None namespace = await self.parent.documents_cache.get_namespace(document) name = code_lens.data["name"] line = code_lens.data["line"] if self.parent.diagnostics.workspace_loaded_event.is_set(): kw_doc = self.get_keyword_definition_at_line(await namespace.get_library_doc(), name, line) if kw_doc is not None and not kw_doc.is_error_handler: if not await self.parent.robot_references.has_cached_keyword_references( document, kw_doc, include_declaration=False ): code_lens.command = Command( "...", "editor.action.showReferences", [str(document.uri), code_lens.range.start, []], ) async def find_refs() -> None: if document is None or kw_doc is None: return # type: ignore[unreachable] await self.parent.robot_references.find_keyword_references( document, kw_doc, include_declaration=False ) await self.parent.code_lens.refresh() key = (document, kw_doc) if key not in self._running_task: task = create_sub_task(find_refs(), loop=self.parent.diagnostics.diagnostics_loop) def done(task: Any) -> None: self._running_task.remove(key) task.add_done_callback(done) self._running_task.add(key) else: references = await self.parent.robot_references.find_keyword_references( document, kw_doc, include_declaration=False ) code_lens.command = Command( f"{len(references)} references", "editor.action.showReferences", [str(document.uri), code_lens.range.start, references], ) else: code_lens.command = Command( "0 references", "editor.action.showReferences", [str(document.uri), code_lens.range.start, []], ) else: code_lens.command = Command( "...", "editor.action.showReferences", [str(document.uri), code_lens.range.start, []], ) return code_lens
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/codelens.py
0.866641
0.150903
codelens.py
pypi
from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Optional from robotcode.core.async_itertools import async_next from robotcode.core.async_tools import threaded from robotcode.core.dataclasses import CamelSnakeMixin from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import Position, Range, TextDocumentIdentifier from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.robotframework.utils.ast_utils import ( HasTokens, get_nodes_at_position, get_tokens_at_position, range_from_token, ) from .model_helper import ModelHelperMixin from .protocol_part import RobotLanguageServerProtocolPart if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import RobotLanguageServerProtocol @dataclass(repr=False) class EvaluatableExpressionParams(CamelSnakeMixin): text_document: TextDocumentIdentifier position: Position @dataclass(repr=False) class EvaluatableExpression(CamelSnakeMixin): range: Range expression: Optional[str] class RobotDebuggingUtilsProtocolPart(RobotLanguageServerProtocolPart, ModelHelperMixin): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) @rpc_method(name="robot/debugging/getEvaluatableExpression", param_type=EvaluatableExpressionParams) @threaded() @_logger.call async def _get_evaluatable_expression( self, text_document: TextDocumentIdentifier, position: Position, *args: Any, **kwargs: Any, ) -> Optional[EvaluatableExpression]: from robot.parsing.lexer.tokens import Token as RobotToken document = await self.parent.documents.get(text_document.uri) if document is None: return None namespace = await self.parent.documents_cache.get_namespace(document) model = await self.parent.documents_cache.get_model(document, False) nodes = await get_nodes_at_position(model, position) node = nodes[-1] if not isinstance(node, HasTokens): return None token = get_tokens_at_position(node, position)[-1] token_and_var = await async_next( ( (t, v) async for t, v in self.iter_variables_from_token(token, namespace, nodes, position) if position in range_from_token(t) ), None, ) if ( token_and_var is None and isinstance(node, self.get_expression_statement_types()) and (token := node.get_token(RobotToken.ARGUMENT)) is not None and position in range_from_token(token) ): token_and_var = await async_next( ( (var_token, var) async for var_token, var in self.iter_expression_variables_from_token( token, namespace, nodes, position ) if position in range_from_token(var_token) ), None, ) if token_and_var is None: return None var_token, var = token_and_var if var.name == "${CURDIR}": return None return EvaluatableExpression(range_from_token(var_token), var.name)
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/debugging_utils.py
0.886168
0.182244
debugging_utils.py
pypi
from __future__ import annotations import ast import re import token as python_token from io import StringIO from tokenize import TokenError, generate_tokens from typing import ( Any, AsyncIterator, Dict, Iterator, List, Optional, Set, Tuple, Type, Union, ) from robotcode.core.lsp.types import Position from robotcode.language_server.robotframework.diagnostics.entities import ( LibraryEntry, ResourceEntry, VariableDefinition, VariableNotFoundDefinition, ) from robotcode.language_server.robotframework.diagnostics.library_doc import ( ArgumentInfo, KeywordArgumentKind, KeywordDoc, KeywordMatcher, LibraryDoc, ) from robotcode.language_server.robotframework.diagnostics.namespace import ( DEFAULT_BDD_PREFIXES, Namespace, ) from robotcode.language_server.robotframework.utils.ast_utils import ( Token, iter_over_keyword_names_and_owners, range_from_token, strip_variable_token, tokenize_variables, whitespace_at_begin_of_token, whitespace_from_begin_of_token, ) from robotcode.language_server.robotframework.utils.version import get_robot_version class ModelHelperMixin: @classmethod async def get_run_keyword_keyworddoc_and_token_from_position( cls, keyword_doc: Optional[KeywordDoc], argument_tokens: List[Token], namespace: Namespace, position: Position, ) -> Tuple[Optional[Tuple[Optional[KeywordDoc], Token]], List[Token]]: from robot.utils.escaping import unescape if keyword_doc is None or not keyword_doc.is_any_run_keyword(): return None, argument_tokens if keyword_doc.is_run_keyword() and len(argument_tokens) > 0: result = await cls.get_keyworddoc_and_token_from_position( unescape(argument_tokens[0].value), argument_tokens[0], argument_tokens[1:], namespace, position, ) return result, argument_tokens[1:] if keyword_doc.is_run_keyword_with_condition() and len(argument_tokens) > ( cond_count := keyword_doc.run_keyword_condition_count() ): result = await cls.get_keyworddoc_and_token_from_position( unescape(argument_tokens[cond_count].value), argument_tokens[cond_count], argument_tokens[cond_count + 1 :], namespace, position, ) return result, argument_tokens[cond_count + 1 :] if keyword_doc.is_run_keywords(): has_and = False while argument_tokens: t = argument_tokens[0] argument_tokens = argument_tokens[1:] if t.value == "AND": continue and_token = next((e for e in argument_tokens if e.value == "AND"), None) if and_token is not None: args = argument_tokens[: argument_tokens.index(and_token)] has_and = True else: if has_and: args = argument_tokens else: args = [] result = await cls.get_keyworddoc_and_token_from_position( unescape(t.value), t, args, namespace, position ) if result is not None and result[0] is not None: return result, [] if and_token is not None: argument_tokens = argument_tokens[argument_tokens.index(and_token) + 1 :] elif has_and: argument_tokens = [] return None, [] if keyword_doc.is_run_keyword_if() and len(argument_tokens) > 1: def skip_args() -> None: nonlocal argument_tokens while argument_tokens: if argument_tokens[0].value in ["ELSE", "ELSE IF"]: break argument_tokens = argument_tokens[1:] inner_keyword_doc = await namespace.find_keyword(argument_tokens[1].value, raise_keyword_error=False) if position.is_in_range(range_from_token(argument_tokens[1])): return (inner_keyword_doc, argument_tokens[1]), argument_tokens[2:] argument_tokens = argument_tokens[2:] inner_keyword_doc_and_args = await cls.get_run_keyword_keyworddoc_and_token_from_position( inner_keyword_doc, argument_tokens, namespace, position ) if inner_keyword_doc_and_args[0] is not None: return inner_keyword_doc_and_args argument_tokens = inner_keyword_doc_and_args[1] skip_args() while argument_tokens: if argument_tokens[0].value == "ELSE" and len(argument_tokens) > 1: inner_keyword_doc = await namespace.find_keyword(unescape(argument_tokens[1].value)) if position.is_in_range(range_from_token(argument_tokens[1])): return (inner_keyword_doc, argument_tokens[1]), argument_tokens[2:] argument_tokens = argument_tokens[2:] inner_keyword_doc_and_args = await cls.get_run_keyword_keyworddoc_and_token_from_position( inner_keyword_doc, argument_tokens, namespace, position ) if inner_keyword_doc_and_args[0] is not None: return inner_keyword_doc_and_args argument_tokens = inner_keyword_doc_and_args[1] skip_args() break if argument_tokens[0].value == "ELSE IF" and len(argument_tokens) > 2: inner_keyword_doc = await namespace.find_keyword(unescape(argument_tokens[2].value)) if position.is_in_range(range_from_token(argument_tokens[2])): return (inner_keyword_doc, argument_tokens[2]), argument_tokens[3:] argument_tokens = argument_tokens[3:] inner_keyword_doc_and_args = await cls.get_run_keyword_keyworddoc_and_token_from_position( inner_keyword_doc, argument_tokens, namespace, position ) if inner_keyword_doc_and_args[0] is not None: return inner_keyword_doc_and_args argument_tokens = inner_keyword_doc_and_args[1] skip_args() else: break return None, argument_tokens @classmethod async def get_keyworddoc_and_token_from_position( cls, keyword_name: Optional[str], keyword_token: Token, argument_tokens: List[Token], namespace: Namespace, position: Position, analyse_run_keywords: bool = True, ) -> Optional[Tuple[Optional[KeywordDoc], Token]]: keyword_doc = await namespace.find_keyword(keyword_name, raise_keyword_error=False) if keyword_doc is None: return None if position.is_in_range(range_from_token(keyword_token)): return keyword_doc, keyword_token if analyse_run_keywords: return ( await cls.get_run_keyword_keyworddoc_and_token_from_position( keyword_doc, argument_tokens, namespace, position ) )[0] return None async def get_namespace_info_from_keyword( self, namespace: Namespace, keyword_token: Token, libraries_matchers: Optional[Dict[KeywordMatcher, LibraryEntry]] = None, resources_matchers: Optional[Dict[KeywordMatcher, ResourceEntry]] = None, ) -> Tuple[Optional[LibraryEntry], Optional[str]]: lib_entry: Optional[LibraryEntry] = None kw_namespace: Optional[str] = None if libraries_matchers is None: libraries_matchers = await namespace.get_libraries_matchers() if resources_matchers is None: resources_matchers = await namespace.get_resources_matchers() for lib, _ in iter_over_keyword_names_and_owners(keyword_token.value): if lib is not None: lib_entry = next((v for k, v in libraries_matchers.items() if k == lib), None) if lib_entry is not None: kw_namespace = lib break lib_entry = next((v for k, v in resources_matchers.items() if k == lib), None) if lib_entry is not None: kw_namespace = lib break return lib_entry, kw_namespace __match_extended = re.compile( r""" (.+?) # base name (group 1) ([^\s\w].+) # extended part (group 2) """, re.UNICODE | re.VERBOSE, ) @staticmethod async def iter_expression_variables_from_token( expression: Token, namespace: Namespace, nodes: Optional[List[ast.AST]], position: Optional[Position] = None, skip_commandline_variables: bool = False, return_not_found: bool = False, ) -> AsyncIterator[Tuple[Token, VariableDefinition]]: from robot.api.parsing import Token as RobotToken variable_started = False try: for toknum, tokval, (_, tokcol), _, _ in generate_tokens(StringIO(expression.value).readline): if variable_started: if toknum == python_token.NAME: var = await namespace.find_variable( f"${{{tokval}}}", nodes, position, skip_commandline_variables=skip_commandline_variables, ignore_error=True, ) sub_token = RobotToken( expression.type, tokval, expression.lineno, expression.col_offset + tokcol, expression.error, ) if var is not None: yield sub_token, var elif return_not_found: yield sub_token, VariableNotFoundDefinition( sub_token.lineno, sub_token.col_offset, sub_token.lineno, sub_token.end_col_offset, namespace.source, tokval, sub_token, ) variable_started = False if tokval == "$": variable_started = True except TokenError: pass @staticmethod def remove_index_from_variable_token(token: Token) -> Tuple[Token, Optional[Token]]: from robot.parsing.lexer import Token as RobotToken def escaped(i: int) -> bool: return token.value[-i - 3 : -i - 2] == "\\" if token.type != RobotToken.VARIABLE or not token.value.endswith("]"): return (token, None) braces = 1 curly_braces = 0 index = 0 for i, c in enumerate(reversed(token.value[:-1])): if c == "}" and not escaped(i): curly_braces += 1 elif c == "{" and not escaped(i): curly_braces -= 1 elif c == "]" and curly_braces == 0 and not escaped(i): braces += 1 if braces == 0: index = i elif c == "[" and curly_braces == 0 and not escaped(i): braces -= 1 if braces == 0: index = i if braces != 0 or curly_braces != 0: return (token, None) value = token.value[: -index - 2] var = RobotToken(token.type, value, token.lineno, token.col_offset, token.error) if len(value) > 0 else None rest = RobotToken( RobotToken.ARGUMENT, token.value[-index - 2 :], token.lineno, token.col_offset + len(value), token.error, ) return (var, rest) @classmethod def _tokenize_variables( cls, token: Token, identifiers: str = "$@&%", ignore_errors: bool = False, *, extra_types: Optional[Set[str]] = None, ) -> Iterator[Token]: from robot.api.parsing import Token as RobotToken for t in tokenize_variables(token, identifiers, ignore_errors, extra_types=extra_types): if t.type == RobotToken.VARIABLE: var, rest = cls.remove_index_from_variable_token(t) if var is not None: yield var if rest is not None: yield from cls._tokenize_variables(rest, identifiers, ignore_errors, extra_types=extra_types) else: yield t @classmethod async def iter_variables_from_token( cls, token: Token, namespace: Namespace, nodes: Optional[List[ast.AST]], position: Optional[Position] = None, skip_commandline_variables: bool = False, return_not_found: bool = False, ) -> AsyncIterator[Tuple[Token, VariableDefinition]]: from robot.api.parsing import Token as RobotToken from robot.variables.search import contains_variable, search_variable def is_number(name: str) -> bool: from robot.variables.finders import NOT_FOUND, NumberFinder if name.startswith("$"): finder = NumberFinder() return bool(finder.find(name) != NOT_FOUND) return False async def iter_token( to: Token, ignore_errors: bool = False ) -> AsyncIterator[Union[Token, Tuple[Token, VariableDefinition]]]: for sub_token in cls._tokenize_variables(to, ignore_errors=ignore_errors): if sub_token.type == RobotToken.VARIABLE: base = sub_token.value[2:-1] if base and not (base[0] == "{" and base[-1] == "}"): yield sub_token elif base: async for v in cls.iter_expression_variables_from_token( RobotToken( sub_token.type, base[1:-1], sub_token.lineno, sub_token.col_offset + 3, sub_token.error, ), namespace, nodes, position, skip_commandline_variables=skip_commandline_variables, return_not_found=return_not_found, ): yield v elif base == "" and return_not_found: yield sub_token, VariableNotFoundDefinition( sub_token.lineno, sub_token.col_offset, sub_token.lineno, sub_token.end_col_offset, namespace.source, sub_token.value, sub_token, ) return if contains_variable(base, "$@&%"): async for sub_token_or_var in iter_token( RobotToken( to.type, base, sub_token.lineno, sub_token.col_offset + 2, ), ignore_errors=ignore_errors, ): if isinstance(sub_token_or_var, Token): if sub_token_or_var.type == RobotToken.VARIABLE: yield sub_token_or_var else: yield sub_token_or_var if token.type == RobotToken.VARIABLE and token.value.endswith("="): match = search_variable(token.value, ignore_errors=True) if not match.is_assign(allow_assign_mark=True): return token = RobotToken( token.type, token.value[:-1].strip(), token.lineno, token.col_offset, token.error, ) async for token_or_var in iter_token(token, ignore_errors=True): if isinstance(token_or_var, Token): sub_token = token_or_var name = sub_token.value var = await namespace.find_variable( name, nodes, position, skip_commandline_variables=skip_commandline_variables, ignore_error=True, ) if var is not None: yield strip_variable_token(sub_token), var continue if is_number(sub_token.value): continue if ( sub_token.type == RobotToken.VARIABLE and sub_token.value[:1] in "$@&%" and sub_token.value[1:2] == "{" and sub_token.value[-1:] == "}" ): match = cls.__match_extended.match(name[2:-1]) if match is not None: base_name, _ = match.groups() name = f"{name[0]}{{{base_name.strip()}}}" var = await namespace.find_variable( name, nodes, position, skip_commandline_variables=skip_commandline_variables, ignore_error=True, ) sub_sub_token = RobotToken(sub_token.type, name, sub_token.lineno, sub_token.col_offset) if var is not None: yield strip_variable_token(sub_sub_token), var continue if is_number(name): continue elif return_not_found: if contains_variable(sub_token.value[2:-1]): continue else: yield strip_variable_token(sub_sub_token), VariableNotFoundDefinition( sub_sub_token.lineno, sub_sub_token.col_offset, sub_sub_token.lineno, sub_sub_token.end_col_offset, namespace.source, name, sub_sub_token, ) if return_not_found: yield strip_variable_token(sub_token), VariableNotFoundDefinition( sub_token.lineno, sub_token.col_offset, sub_token.lineno, sub_token.end_col_offset, namespace.source, sub_token.value, sub_token, ) else: yield token_or_var __expression_statement_types: Optional[Tuple[Type[Any]]] = None @classmethod def get_expression_statement_types(cls) -> Tuple[Type[Any]]: import robot.parsing.model.statements if cls.__expression_statement_types is None: cls.__expression_statement_types = (robot.parsing.model.statements.IfHeader,) if get_robot_version() >= (5, 0): cls.__expression_statement_types = ( # type: ignore[assignment] robot.parsing.model.statements.IfElseHeader, robot.parsing.model.statements.WhileHeader, ) return cls.__expression_statement_types BDD_TOKEN_REGEX = re.compile(r"^(Given|When|Then|And|But)\s", flags=re.IGNORECASE) BDD_TOKEN = re.compile(r"^(Given|When|Then|And|But)$", flags=re.IGNORECASE) @classmethod def split_bdd_prefix(cls, namespace: Namespace, token: Token) -> Tuple[Optional[Token], Optional[Token]]: from robot.parsing.lexer import Token as RobotToken bdd_token = None parts = token.value.split() if len(parts) < 2: return None, token for index in range(1, len(parts)): prefix = " ".join(parts[:index]).title() if prefix in ( namespace.languages.bdd_prefixes if namespace.languages is not None else DEFAULT_BDD_PREFIXES ): bdd_len = len(prefix) bdd_token = RobotToken( token.type, token.value[:bdd_len], token.lineno, token.col_offset, token.error, ) token = RobotToken( token.type, token.value[bdd_len + 1 :], token.lineno, token.col_offset + bdd_len + 1, token.error, ) break return bdd_token, token @classmethod def strip_bdd_prefix(cls, namespace: Namespace, token: Token) -> Token: from robot.parsing.lexer import Token as RobotToken if get_robot_version() < (6, 0): bdd_match = cls.BDD_TOKEN_REGEX.match(token.value) if bdd_match: bdd_len = len(bdd_match.group(1)) token = RobotToken( token.type, token.value[bdd_len + 1 :], token.lineno, token.col_offset + bdd_len + 1, token.error, ) return token parts = token.value.split() if len(parts) < 2: return token for index in range(1, len(parts)): prefix = " ".join(parts[:index]).title() if prefix in ( namespace.languages.bdd_prefixes if namespace.languages is not None else DEFAULT_BDD_PREFIXES ): bdd_len = len(prefix) token = RobotToken( token.type, token.value[bdd_len + 1 :], token.lineno, token.col_offset + bdd_len + 1, token.error, ) break return token @classmethod def is_bdd_token(cls, namespace: Namespace, token: Token) -> bool: if get_robot_version() < (6, 0): bdd_match = cls.BDD_TOKEN.match(token.value) return bool(bdd_match) parts = token.value.split() for index in range(len(parts)): prefix = " ".join(parts[: index + 1]).title() if prefix.title() in ( namespace.languages.bdd_prefixes if namespace.languages is not None else DEFAULT_BDD_PREFIXES ): return True return False @classmethod def get_keyword_definition_at_token(cls, library_doc: LibraryDoc, token: Token) -> Optional[KeywordDoc]: return cls.get_keyword_definition_at_line(library_doc, token.value, token.lineno) @classmethod def get_keyword_definition_at_line(cls, library_doc: LibraryDoc, value: str, line: int) -> Optional[KeywordDoc]: return next( (k for k in library_doc.keywords.get_all(value) if k.line_no == line), None, ) def get_argument_info_at_position( self, keyword_doc: KeywordDoc, tokens: Tuple[Token, ...], token_at_position: Token, position: Position, ) -> Tuple[int, Optional[List[ArgumentInfo]], Optional[Token]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.utils.escaping import split_from_equals argument_index = -1 named_arg = False kw_arguments = [ a for a in keyword_doc.arguments if a.kind not in [ KeywordArgumentKind.POSITIONAL_ONLY_MARKER, KeywordArgumentKind.NAMED_ONLY_MARKER, ] ] token_at_position_index = tokens.index(token_at_position) if ( token_at_position.type in [RobotToken.EOL, RobotToken.SEPARATOR] and token_at_position_index > 2 and tokens[token_at_position_index - 1].type == RobotToken.CONTINUATION and position.character < range_from_token(tokens[token_at_position_index - 1]).end.character + 2 ): return -1, None, None token_at_position_index = tokens.index(token_at_position) argument_token_index = token_at_position_index while argument_token_index >= 0 and tokens[argument_token_index].type != RobotToken.ARGUMENT: argument_token_index -= 1 if ( token_at_position.type == RobotToken.EOL and len(tokens) > 1 and tokens[argument_token_index - 1].type == RobotToken.CONTINUATION ): argument_token_index -= 2 while argument_token_index >= 0 and tokens[argument_token_index].type != RobotToken.ARGUMENT: argument_token_index -= 1 arguments = [a for a in tokens if a.type == RobotToken.ARGUMENT] argument_token: Optional[Token] = None if argument_token_index >= 0: argument_token = tokens[argument_token_index] if argument_token is not None and argument_token.type == RobotToken.ARGUMENT: argument_index = arguments.index(argument_token) else: argument_index = 0 else: argument_index = -1 if whitespace_at_begin_of_token(token_at_position) > 1: r = range_from_token(token_at_position) ws_b = whitespace_from_begin_of_token(token_at_position) r.start.character += 2 if ws_b and ws_b[0] != "\t" else 1 if position.is_in_range(r, True): argument_index += 1 argument_token = None if argument_token is None: r.end.character = r.start.character + whitespace_at_begin_of_token(token_at_position) - 3 if not position.is_in_range(r, False): argument_token_index += 2 if argument_token_index < len(tokens) and tokens[argument_token_index].type == RobotToken.ARGUMENT: argument_token = tokens[argument_token_index] if argument_index < 0: return -1, kw_arguments, argument_token if argument_token is not None and argument_token.type == RobotToken.ARGUMENT: arg_name_or_value, arg_value = split_from_equals(argument_token.value) if arg_value is not None: old_argument_index = argument_index argument_index = next( ( i for i, v in enumerate(kw_arguments) if v.name == arg_name_or_value or v.kind == KeywordArgumentKind.VAR_NAMED ), -1, ) if argument_index == -1: argument_index = old_argument_index else: named_arg = True if not named_arg and argument_index >= 0: need_named = False for i, a in enumerate(arguments): if i == argument_index: break arg_name_or_value, arg_value = split_from_equals(a.value) if arg_value is not None and any( (i for i, v in enumerate(kw_arguments) if v.name == arg_name_or_value) ): need_named = True break a_index = next( ( i for i, v in enumerate(kw_arguments) if v.kind in [KeywordArgumentKind.POSITIONAL_ONLY, KeywordArgumentKind.POSITIONAL_OR_NAMED] and i == argument_index ), -1, ) if a_index >= 0 and not need_named: argument_index = a_index else: if need_named: argument_index = next( (i for i, v in enumerate(kw_arguments) if v.kind == KeywordArgumentKind.VAR_NAMED), -1 ) else: argument_index = next( (i for i, v in enumerate(kw_arguments) if v.kind == KeywordArgumentKind.VAR_POSITIONAL), -1 ) if argument_index >= len(kw_arguments): argument_index = -1 return argument_index, kw_arguments, argument_token
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/model_helper.py
0.780579
0.242576
model_helper.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING, Any, List, Optional from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import Position, SelectionRange from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.utils.ast_utils import ( HasTokens, get_nodes_at_position, get_tokens_at_position, range_from_node, range_from_token, ) if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import RobotLanguageServerProtocol from .model_helper import ModelHelperMixin from .protocol_part import RobotLanguageServerProtocolPart class RobotSelectionRangeProtocolPart(RobotLanguageServerProtocolPart, ModelHelperMixin): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.selection_range.collect.add(self.collect) @language_id("robotframework") @_logger.call async def collect( self, sender: Any, document: TextDocument, positions: List[Position] ) -> Optional[List[SelectionRange]]: namespace = await self.parent.documents_cache.get_namespace(document) results: List[SelectionRange] = [] for position in positions: nodes = await get_nodes_at_position(await self.parent.documents_cache.get_model(document, True), position) if not nodes: break current_range: Optional[SelectionRange] = None for n in nodes: current_range = SelectionRange(range_from_node(n), current_range) if current_range is not None: node = nodes[-1] if node is not None and isinstance(node, HasTokens): tokens = get_tokens_at_position(node, position, True) if tokens: token = tokens[-1] if token is not None: current_range = SelectionRange(range_from_token(token), current_range) async for var_token, _ in self.iter_variables_from_token( token, namespace, nodes, position, return_not_found=True ): var_token_range = range_from_token(var_token) if position in var_token_range: current_range = SelectionRange(var_token_range, current_range) break results.append(current_range) return results
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/selection_range.py
0.900251
0.213336
selection_range.py
pypi
from __future__ import annotations import asyncio import io import os import re from typing import TYPE_CHECKING, Any, List, Optional, cast from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( FormattingOptions, MessageType, Position, Range, TextEdit, ) from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.utils.version import get_robot_version if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import ( RobotLanguageServerProtocol, ) from robotcode.core.utils.version import create_version_from_str from robotcode.language_server.robotframework.configuration import RoboTidyConfig from .model_helper import ModelHelperMixin from .protocol_part import RobotLanguageServerProtocolPart def robotidy_installed() -> bool: try: __import__("robotidy") except ImportError: return False return True class RobotFormattingProtocolPart(RobotLanguageServerProtocolPart, ModelHelperMixin): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.formatting.format.add(self.format) if robotidy_installed(): parent.formatting.format_range.add(self.format_range) self.space_count = 4 self.use_pipes = False self.line_separator = os.linesep self.short_test_name_length = 18 self.setting_and_variable_name_length = 14 async def get_config(self, document: TextDocument) -> RoboTidyConfig: folder = self.parent.workspace.get_workspace_folder(document.uri) if folder is None: return RoboTidyConfig() return await self.parent.workspace.get_configuration(RoboTidyConfig, folder.uri) @language_id("robotframework") @_logger.call async def format( self, sender: Any, document: TextDocument, options: FormattingOptions, **further_options: Any, ) -> Optional[List[TextEdit]]: config = await self.get_config(document) if (config.enabled or get_robot_version() >= (5, 0)) and robotidy_installed(): return await self.format_robot_tidy(document, options, config=config, **further_options) if get_robot_version() < (5, 0): return await self.format_internal(document, options, **further_options) self.parent.window.show_message( "RobotFramework formatter is not available, please install 'robotframework-tidy'.", MessageType.ERROR, ) return None RE_LINEBREAKS = re.compile(r"\r\n|\r|\n") async def format_robot_tidy( self, document: TextDocument, options: FormattingOptions, range: Optional[Range] = None, config: Optional[RoboTidyConfig] = None, **further_options: Any, ) -> Optional[List[TextEdit]]: from robotidy.version import __version__ try: if config is None: config = await self.get_config(document) robotidy_version = create_version_from_str(__version__) model = await self.parent.documents_cache.get_model(document, False) if robotidy_version >= (3, 0): from robotidy.api import get_robotidy from robotidy.disablers import RegisterDisablers if robotidy_version >= (4, 2): robot_tidy = get_robotidy( document.uri.to_path(), None, ignore_git_dir=config.ignore_git_dir, config=config.config, ) elif robotidy_version >= (4, 1): robot_tidy = get_robotidy( document.uri.to_path(), None, ignore_git_dir=config.ignore_git_dir, ) else: robot_tidy = get_robotidy(document.uri.to_path(), None) if range is not None: robot_tidy.config.formatting.start_line = range.start.line + 1 robot_tidy.config.formatting.end_line = range.end.line + 1 disabler_finder = RegisterDisablers( robot_tidy.config.formatting.start_line, robot_tidy.config.formatting.end_line, ) disabler_finder.visit(model) if disabler_finder.file_disabled: return None if robotidy_version >= (4, 0): _, _, new, _ = robot_tidy.transform_until_stable(model, disabler_finder) else: _, _, new = robot_tidy.transform(model, disabler_finder.disablers) else: from robotidy.api import RobotidyAPI robot_tidy = RobotidyAPI(document.uri.to_path(), None) if range is not None: robot_tidy.formatting_config.start_line = range.start.line + 1 robot_tidy.formatting_config.end_line = range.end.line + 1 if robotidy_version >= (2, 2): from robotidy.disablers import RegisterDisablers disabler_finder = RegisterDisablers( robot_tidy.formatting_config.start_line, robot_tidy.formatting_config.end_line, ) disabler_finder.visit(model) if disabler_finder.file_disabled: return None _, _, new = robot_tidy.transform(model, disabler_finder.disablers) else: _, _, new = robot_tidy.transform(model) if new.text == document.text(): return None return [ TextEdit( range=Range( start=Position(line=0, character=0), end=Position( line=len(document.get_lines()), character=0, ), ), new_text=new.text, ) ] except (SystemExit, KeyboardInterrupt, asyncio.CancelledError): raise except BaseException as e: self._logger.exception(e) self.parent.window.show_message(f"Executing `robotidy` failed: {e}", MessageType.ERROR) return None async def format_internal( self, document: TextDocument, options: FormattingOptions, **further_options: Any ) -> Optional[List[TextEdit]]: from robot.parsing.model.blocks import File from robot.tidypkg import ( # pyright: ignore [reportMissingImports] Aligner, Cleaner, NewlineNormalizer, SeparatorNormalizer, ) model = cast(File, await self.parent.documents_cache.get_model(document, False)) Cleaner().visit(model) NewlineNormalizer(self.line_separator, self.short_test_name_length).visit(model) SeparatorNormalizer(self.use_pipes, self.space_count).visit(model) Aligner( self.short_test_name_length, self.setting_and_variable_name_length, self.use_pipes, ).visit(model) with io.StringIO() as s: model.save(s) return [ TextEdit( range=Range( start=Position(line=0, character=0), end=Position( line=len(document.get_lines()), character=0, ), ), new_text=s.getvalue(), ) ] @language_id("robotframework") async def format_range( self, sender: Any, document: TextDocument, range: Range, options: FormattingOptions, **further_options: Any, ) -> Optional[List[TextEdit]]: config = await self.get_config(document) if config.enabled and robotidy_installed(): return await self.format_robot_tidy(document, options, range=range, config=config, **further_options) return None
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/formatting.py
0.800107
0.150965
formatting.py
pypi
from __future__ import annotations import ast import asyncio import reprlib from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, List, Optional, Tuple, Type, cast, ) from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import Hover, MarkupContent, MarkupKind, Position, Range from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.utils.ast_utils import ( get_nodes_at_position, range_from_node, range_from_token, ) from robotcode.language_server.robotframework.utils.markdownformatter import MarkDownFormatter if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import RobotLanguageServerProtocol from .model_helper import ModelHelperMixin from .protocol_part import RobotLanguageServerProtocolPart _HoverMethod = Callable[[ast.AST, List[ast.AST], TextDocument, Position], Awaitable[Optional[Hover]]] class RobotHoverProtocolPart(RobotLanguageServerProtocolPart, ModelHelperMixin): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.hover.collect.add(self.collect) def _find_method(self, cls: Type[Any]) -> Optional[_HoverMethod]: if cls is ast.AST: return None method_name = "hover_" + cls.__name__ if hasattr(self, method_name): method = getattr(self, method_name) if callable(method): return cast(_HoverMethod, method) for base in cls.__bases__: method = self._find_method(base) if method: return cast(_HoverMethod, method) return None @language_id("robotframework") @_logger.call async def collect(self, sender: Any, document: TextDocument, position: Position) -> Optional[Hover]: model = await self.parent.documents_cache.get_model(document) result_nodes = await get_nodes_at_position(model, position) if not result_nodes: return None result = await self._hover_default(result_nodes, document, position) if result: return result for result_node in reversed(result_nodes): method = self._find_method(type(result_node)) if method is not None: result = await method(result_node, result_nodes, document, position) if result is not None: return result return None async def _hover_default(self, nodes: List[ast.AST], document: TextDocument, position: Position) -> Optional[Hover]: namespace = await self.parent.documents_cache.get_namespace(document) all_variable_refs = await namespace.get_variable_references() if all_variable_refs: text = None highlight_range = None for variable, var_refs in all_variable_refs.items(): found_range = ( variable.name_range if variable.source == namespace.source and position.is_in_range(variable.name_range, False) else cast(Optional[Range], next((r.range for r in var_refs if position.is_in_range(r.range)), None)) ) if found_range is not None: highlight_range = found_range if variable.has_value or variable.resolvable: try: value = reprlib.repr( await namespace.imports_manager.resolve_variable( variable.name, str(document.uri.to_path().parent), await namespace.get_resolvable_variables(nodes, position), ) ) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException: self._logger.exception("Error resolving variable: {e}") value = "" else: value = "" if text is None: text = "" if text: text += "\n" text += f"| ({variable.type.value}) | {variable.name} | {f' `{value}`' if value else ''} |" if text: text = "| | | |\n|:--|:--|:--|\n" + text return Hover( contents=MarkupContent( kind=MarkupKind.MARKDOWN, value=text, ), range=highlight_range, ) all_kw_refs = await namespace.get_keyword_references() if all_kw_refs: result: List[Tuple[Range, str]] = [] for kw, kw_refs in all_kw_refs.items(): found_range = ( kw.name_range if kw.source == namespace.source and position.is_in_range(kw.name_range, False) else cast( Optional[Range], next((r.range for r in kw_refs if position.is_in_range(r.range, False)), None) ) ) if found_range is not None: result.append((found_range, kw.to_markdown())) if result: r = result[0][0] if all(r == i[0] for i in result): doc = "\n\n---\n\n".join(i[1] for i in result) return Hover( contents=MarkupContent(kind=MarkupKind.MARKDOWN, value=doc), range=found_range, ) all_namespace_refs = await namespace.get_namespace_references() if all_namespace_refs: for ns, ns_refs in all_namespace_refs.items(): found_range = ( ns.import_range if ns.import_source == namespace.source and position.is_in_range(ns.import_range, False) else ns.alias_range if ns.import_source == namespace.source and position.is_in_range(ns.alias_range, False) else cast( Optional[Range], next((r.range for r in ns_refs if position.is_in_range(r.range, False)), None) ) ) if found_range is not None: return Hover( contents=MarkupContent(kind=MarkupKind.MARKDOWN, value=ns.library_doc.to_markdown()), range=found_range, ) return None async def hover_TestCase( # noqa: N802 self, node: ast.AST, nodes: List[ast.AST], document: TextDocument, position: Position ) -> Optional[Hover]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.blocks import TestCase, TestCaseSection from robot.parsing.model.statements import Documentation, Tags test_case = cast(TestCase, node) if not position.is_in_range(range_from_node(test_case.header)): return None name_token = cast(RobotToken, test_case.header.get_token(RobotToken.TESTCASE_NAME)) if name_token is None: return None doc = next((e for e in test_case.body if isinstance(e, Documentation)), None) tags = next((e for e in test_case.body if isinstance(e, Tags)), None) section = next((e for e in nodes if isinstance(e, TestCaseSection)), None) if section is not None and section.tasks: txt = f"= Task *{test_case.name}* =\n" else: txt = f"= Test Case *{test_case.name}* =\n" if doc is not None: txt += "\n== Documentation ==\n" txt += f"\n{doc.value}\n" if tags is not None: txt += "\n*Tags*: " txt += f"{', '.join(tags.values)}\n" return Hover( contents=MarkupContent( kind=MarkupKind.MARKDOWN, value=MarkDownFormatter().format(txt), ), range=range_from_token(name_token), )
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/hover.py
0.763748
0.176938
hover.py
pypi
from __future__ import annotations import ast import io import weakref from typing import ( TYPE_CHECKING, Any, Callable, Iterable, Iterator, List, Optional, Tuple, Union, cast, ) from robotcode.core.async_tools import Lock, async_tasking_event, check_canceled_sync from robotcode.core.lsp.types import MessageType from robotcode.core.uri import Uri from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.parts.workspace import WorkspaceFolder from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.configuration import RobotCodeConfig, RobotConfig from robotcode.language_server.robotframework.diagnostics.imports_manager import ImportsManager from robotcode.language_server.robotframework.diagnostics.namespace import DocumentType, Namespace from robotcode.language_server.robotframework.utils.ast_utils import Token from robotcode.language_server.robotframework.utils.version import get_robot_version if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import RobotLanguageServerProtocol from robotcode.language_server.robotframework.languages import Languages from .protocol_part import RobotLanguageServerProtocolPart class UnknownFileTypeError(Exception): pass class DocumentsCache(RobotLanguageServerProtocolPart): def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) self._imports_managers_lock = Lock() self._imports_managers: weakref.WeakKeyDictionary[WorkspaceFolder, ImportsManager] = weakref.WeakKeyDictionary() self._default_imports_manager: Optional[ImportsManager] = None self._workspace_languages: weakref.WeakKeyDictionary[WorkspaceFolder, Languages] = weakref.WeakKeyDictionary() async def get_workspace_languages(self, document_or_uri: Union[TextDocument, Uri, str]) -> Optional[Languages]: if get_robot_version() < (6, 0): return None from robot.conf.languages import Languages as RobotLanguages # pyright: ignore[reportMissingImports] uri: Union[Uri, str] if isinstance(document_or_uri, TextDocument): uri = document_or_uri.uri else: uri = document_or_uri folder = self.parent.workspace.get_workspace_folder(uri) if folder is None: return None result = self._workspace_languages.get(folder, None) if result is None: config = await self.parent.workspace.get_configuration(RobotConfig, folder.uri) languages = [str(v) for v in self.parent.profile.languages or []] languages += config.languages or [] if not languages: return None result = RobotLanguages() for lang in languages: try: result.add_language(lang) except ValueError as e: self.parent.window.show_message( f"Language configuration is not valid: {e}" "\nPlease check your 'robotcode.robot.language' configuration.", MessageType.ERROR, ) self._workspace_languages[folder] = result return cast(Languages, RobotLanguages(result.languages)) async def build_languages_from_model( self, document: TextDocument, model: ast.AST ) -> Tuple[Optional[Languages], Optional[Languages]]: if get_robot_version() < (6, 0): return (None, None) from robot.conf.languages import Languages as RobotLanguages # pyright: ignore[reportMissingImports] from robot.parsing.model.blocks import File workspace_langs = await self.get_workspace_languages(document) return ( cast( Languages, RobotLanguages( [ *(workspace_langs.languages if workspace_langs else []), *(model.languages if isinstance(model, File) else []), ] ), ), workspace_langs, ) async def get_document_type(self, document: TextDocument) -> DocumentType: return await document.get_cache(self.__get_document_type) async def __get_document_type(self, document: TextDocument) -> DocumentType: path = document.uri.to_path() suffix = path.suffix.lower() if path.name == "__init__.robot": return DocumentType.INIT if suffix == ".robot": return DocumentType.GENERAL if suffix == ".resource": return DocumentType.RESOURCE return DocumentType.UNKNOWN async def get_tokens(self, document: TextDocument, data_only: bool = False) -> List[Token]: if data_only: return await document.get_cache(self.__get_tokens_data_only) return await document.get_cache(self.__get_tokens) async def __get_tokens_data_only(self, document: TextDocument) -> List[Token]: document_type = await self.get_document_type(document) if document_type == DocumentType.INIT: return await self.get_init_tokens(document, True) if document_type == DocumentType.GENERAL: return await self.get_general_tokens(document, True) if document_type == DocumentType.RESOURCE: return await self.get_resource_tokens(document, True) raise UnknownFileTypeError(str(document.uri)) async def __get_tokens(self, document: TextDocument) -> List[Token]: document_type = await self.get_document_type(document) if document_type == DocumentType.INIT: return await self.get_init_tokens(document) if document_type == DocumentType.GENERAL: return await self.get_general_tokens(document) if document_type == DocumentType.RESOURCE: return await self.get_resource_tokens(document) raise UnknownFileTypeError(str(document.uri)) async def get_general_tokens(self, document: TextDocument, data_only: bool = False) -> List[Token]: if data_only: return await document.get_cache(self.__get_general_tokens_data_only) return await document.get_cache(self.__get_general_tokens) def __internal_get_tokens( self, source: Any, data_only: bool = False, tokenize_variables: bool = False, lang: Any = None ) -> Any: import robot.api if get_robot_version() >= (6, 0): return robot.api.get_tokens(source, data_only=data_only, tokenize_variables=tokenize_variables, lang=lang) return robot.api.get_tokens(source, data_only=data_only, tokenize_variables=tokenize_variables) def __internal_get_resource_tokens( self, source: Any, data_only: bool = False, tokenize_variables: bool = False, lang: Any = None, ) -> Any: import robot.api if get_robot_version() >= (6, 0): return robot.api.get_resource_tokens( source, data_only=data_only, tokenize_variables=tokenize_variables, lang=lang ) return robot.api.get_resource_tokens(source, data_only=data_only, tokenize_variables=tokenize_variables) def __internal_get_init_tokens( self, source: Any, data_only: bool = False, tokenize_variables: bool = False, lang: Any = None ) -> Any: import robot.api if get_robot_version() >= (6, 0): return robot.api.get_init_tokens( source, data_only=data_only, tokenize_variables=tokenize_variables, lang=lang ) return robot.api.get_init_tokens(source, data_only=data_only, tokenize_variables=tokenize_variables) async def __get_general_tokens_data_only(self, document: TextDocument) -> List[Token]: lang = await self.get_workspace_languages(document) def get(text: str) -> List[Token]: with io.StringIO(text) as content: return [e for e in self.__internal_get_tokens(content, True, lang=lang) if check_canceled_sync()] return await self.__get_tokens_internal(document, get) async def __get_general_tokens(self, document: TextDocument) -> List[Token]: lang = await self.get_workspace_languages(document) def get(text: str) -> List[Token]: with io.StringIO(text) as content: return [e for e in self.__internal_get_tokens(content, lang=lang) if check_canceled_sync()] return await self.__get_tokens_internal(document, get) async def __get_tokens_internal( self, document: TextDocument, get: Callable[[str], List[Token]], ) -> List[Token]: return get(document.text()) async def get_resource_tokens(self, document: TextDocument, data_only: bool = False) -> List[Token]: if data_only: return await document.get_cache(self.__get_resource_tokens_data_only) return await document.get_cache(self.__get_resource_tokens) async def __get_resource_tokens_data_only(self, document: TextDocument) -> List[Token]: lang = await self.get_workspace_languages(document) def get(text: str) -> List[Token]: with io.StringIO(text) as content: return [ e for e in self.__internal_get_resource_tokens(content, True, lang=lang) if check_canceled_sync() ] return await self.__get_tokens_internal(document, get) async def __get_resource_tokens(self, document: TextDocument) -> List[Token]: lang = await self.get_workspace_languages(document) def get(text: str) -> List[Token]: with io.StringIO(text) as content: return [e for e in self.__internal_get_resource_tokens(content, lang=lang) if check_canceled_sync()] return await self.__get_tokens_internal(document, get) async def get_init_tokens(self, document: TextDocument, data_only: bool = False) -> List[Token]: if data_only: return await document.get_cache(self.__get_init_tokens_data_only) return await document.get_cache(self.__get_init_tokens) async def __get_init_tokens_data_only(self, document: TextDocument) -> List[Token]: lang = await self.get_workspace_languages(document) def get(text: str) -> List[Token]: with io.StringIO(text) as content: return [e for e in self.__internal_get_init_tokens(content, True, lang=lang) if check_canceled_sync()] return await self.__get_tokens_internal(document, get) async def __get_init_tokens(self, document: TextDocument) -> List[Token]: lang = await self.get_workspace_languages(document) def get(text: str) -> List[Token]: with io.StringIO(text) as content: return [e for e in self.__internal_get_init_tokens(content, lang=lang) if check_canceled_sync()] return await self.__get_tokens_internal(document, get) async def get_model(self, document: TextDocument, data_only: bool = True) -> ast.AST: document_type = await self.get_document_type(document) if document_type == DocumentType.INIT: return await self.get_init_model(document, data_only) if document_type == DocumentType.GENERAL: return await self.get_general_model(document, data_only) if document_type == DocumentType.RESOURCE: return await self.get_resource_model(document, data_only) raise UnknownFileTypeError(f"Unknown file type '{document.uri}'.") def __get_model(self, document: TextDocument, tokens: Iterable[Any], document_type: DocumentType) -> ast.AST: from robot.parsing.parser.parser import _get_model def get_tokens(source: str, data_only: bool = False, lang: Any = None) -> Iterator[Token]: for t in tokens: check_canceled_sync() yield t if get_robot_version() >= (6, 0): model = _get_model(get_tokens, document.uri.to_path(), False, None, None) else: model = _get_model(get_tokens, document.uri.to_path(), False, None) setattr(model, "source", str(document.uri.to_path())) setattr(model, "model_type", document_type) return cast(ast.AST, model) async def get_general_model(self, document: TextDocument, data_only: bool = True) -> ast.AST: if data_only: return await document.get_cache( self.__get_general_model_data_only, await self.get_general_tokens(document, True) ) return await document.get_cache(self.__get_general_model, await self.get_general_tokens(document)) async def __get_general_model_data_only(self, document: TextDocument, tokens: Iterable[Any]) -> ast.AST: return self.__get_model(document, tokens, DocumentType.GENERAL) async def __get_general_model(self, document: TextDocument, tokens: Iterable[Any]) -> ast.AST: return self.__get_model(document, tokens, DocumentType.GENERAL) async def get_resource_model(self, document: TextDocument, data_only: bool = True) -> ast.AST: if data_only: return await document.get_cache( self.__get_resource_model_data_only, await self.get_resource_tokens(document, True) ) return await document.get_cache(self.__get_resource_model, await self.get_resource_tokens(document)) async def __get_resource_model_data_only(self, document: TextDocument, tokens: Iterable[Any]) -> ast.AST: return self.__get_model(document, tokens, DocumentType.RESOURCE) async def __get_resource_model(self, document: TextDocument, tokens: Iterable[Any]) -> ast.AST: return self.__get_model(document, tokens, DocumentType.RESOURCE) async def get_init_model(self, document: TextDocument, data_only: bool = True) -> ast.AST: if data_only: return await document.get_cache(self.__get_init_model_data_only, await self.get_init_tokens(document, True)) return await document.get_cache(self.__get_init_model, await self.get_init_tokens(document)) async def __get_init_model_data_only(self, document: TextDocument, tokens: Iterable[Any]) -> ast.AST: return self.__get_model(document, tokens, DocumentType.INIT) async def __get_init_model(self, document: TextDocument, tokens: Iterable[Any]) -> ast.AST: return self.__get_model(document, tokens, DocumentType.INIT) async def get_namespace(self, document: TextDocument) -> Namespace: return await document.get_cache(self.__get_namespace) async def __get_namespace(self, document: TextDocument) -> Namespace: return await self.__get_namespace_for_document_type(document, None) async def get_resource_namespace(self, document: TextDocument) -> Namespace: return await document.get_cache(self.__get_resource_namespace) async def __get_resource_namespace(self, document: TextDocument) -> Namespace: return await self.__get_namespace_for_document_type(document, DocumentType.RESOURCE) async def get_init_namespace(self, document: TextDocument) -> Namespace: return await document.get_cache(self.__get_init_namespace) async def __get_init_namespace(self, document: TextDocument) -> Namespace: return await self.__get_namespace_for_document_type(document, DocumentType.INIT) async def get_general_namespace(self, document: TextDocument) -> Namespace: return await document.get_cache(self.__get_general_namespace) async def __get_general_namespace(self, document: TextDocument) -> Namespace: return await self.__get_namespace_for_document_type(document, DocumentType.GENERAL) @async_tasking_event async def namespace_invalidated(sender, namespace: Namespace) -> None: # NOSONAR ... async def __invalidate_namespace(self, sender: Namespace) -> None: document = sender.document if document is not None: document.invalidate_cache() await self.namespace_invalidated( self, sender, callback_filter=language_id_filter(document), ) async def __document_cache_invalidate(self, sender: TextDocument) -> None: namespace: Optional[Namespace] = sender.get_cache_value(self.__get_namespace) if namespace is not None: await self.namespace_invalidated( self, namespace, callback_filter=language_id_filter(sender), ) async def __get_namespace_for_document_type( self, document: TextDocument, document_type: Optional[DocumentType], ) -> Namespace: if document_type is not None and document_type == DocumentType.INIT: model = await self.get_init_model(document) elif document_type is not None and document_type == DocumentType.RESOURCE: model = await self.get_resource_model(document) elif document_type is not None and document_type == DocumentType.GENERAL: model = await self.get_general_model(document) else: model = await self.get_model(document) imports_manager = await self.get_imports_manager(document) languages, workspace_languages = await self.build_languages_from_model(document, model) result = Namespace( imports_manager, model, str(document.uri.to_path()), document, document_type, languages, workspace_languages ) result.has_invalidated.add(self.__invalidate_namespace) result.has_imports_changed.add(self.__invalidate_namespace) document.cache_invalidate.add(self.__document_cache_invalidate) return result async def default_imports_manager(self) -> ImportsManager: async with self._imports_managers_lock: if self._default_imports_manager is None: self._default_imports_manager = ImportsManager( self.parent, Uri(self.parent.workspace.root_uri or "."), RobotCodeConfig(), ) return self._default_imports_manager async def get_imports_manager(self, document: TextDocument) -> ImportsManager: return await self.get_imports_manager_for_uri(document.uri) async def get_imports_manager_for_uri(self, uri: Uri) -> ImportsManager: return await self.get_imports_manager_for_workspace_folder(self.parent.workspace.get_workspace_folder(uri)) async def get_imports_manager_for_workspace_folder(self, folder: Optional[WorkspaceFolder]) -> ImportsManager: if folder is None: if len(self.parent.workspace.workspace_folders) == 1: folder = self.parent.workspace.workspace_folders[0] else: return await self.default_imports_manager() async with self._imports_managers_lock: if folder not in self._imports_managers: config = await self.parent.workspace.get_configuration(RobotCodeConfig, folder.uri) self._imports_managers[folder] = ImportsManager(self.parent, folder.uri, config) return self._imports_managers[folder]
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/documents_cache.py
0.760562
0.192539
documents_cache.py
pypi
from __future__ import annotations import ast from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, List, Optional, Tuple, Type, TypeVar, Union, cast, ) from robotcode.core.async_itertools import async_next from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( AnnotatedTextEdit, ChangeAnnotation, CreateFile, DeleteFile, OptionalVersionedTextDocumentIdentifier, Position, PrepareRenameResult, PrepareRenameResultType1, RenameFile, TextDocumentEdit, WorkspaceEdit, ) from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.parts.rename import CantRenameError from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.diagnostics.entities import ( VariableDefinition, VariableDefinitionType, ) from robotcode.language_server.robotframework.diagnostics.library_doc import KeywordDoc from robotcode.language_server.robotframework.utils.ast_utils import ( HasTokens, Token, get_nodes_at_position, get_tokens_at_position, range_from_token, ) from .model_helper import ModelHelperMixin from .protocol_part import RobotLanguageServerProtocolPart if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import ( RobotLanguageServerProtocol, ) _RenameMethod = Callable[[ast.AST, TextDocument, Position, str], Awaitable[Optional[WorkspaceEdit]]] _PrepareRenameMethod = Callable[[ast.AST, TextDocument, Position], Awaitable[Optional[PrepareRenameResult]]] _T = TypeVar("_T", bound=Callable[..., Any]) class RobotRenameProtocolPart(RobotLanguageServerProtocolPart, ModelHelperMixin): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.rename.collect.add(self.collect) parent.rename.collect_prepare.add(self.collect_prepare) def _find_method(self, cls: Type[Any], prefix: str) -> Optional[_T]: if cls is ast.AST: return None method_name = prefix + "_" + cls.__name__ if hasattr(self, method_name): method = getattr(self, method_name) if callable(method): return cast(_T, method) for base in cls.__bases__: method = self._find_method(base, prefix) if method: return cast(_T, method) return None @language_id("robotframework") @_logger.call async def collect( self, sender: Any, document: TextDocument, position: Position, new_name: str, ) -> Optional[WorkspaceEdit]: result_nodes = await get_nodes_at_position(await self.parent.documents_cache.get_model(document), position) if not result_nodes: return None result_node = result_nodes[-1] result = await self._rename_default(result_nodes, document, position, new_name) if result: return result method: Optional[_RenameMethod] = self._find_method(type(result_node), "rename") if method is not None: result = await method(result_node, document, position, new_name) if result is not None: return result return None @language_id("robotframework") @_logger.call async def collect_prepare( self, sender: Any, document: TextDocument, position: Position, ) -> Optional[PrepareRenameResult]: result_nodes = await get_nodes_at_position(await self.parent.documents_cache.get_model(document), position) if not result_nodes: return None result_node = result_nodes[-1] result = await self._prepare_rename_default(result_nodes, document, position) if result: return result method: Optional[_PrepareRenameMethod] = self._find_method(type(result_node), "prepare_rename") if method is not None: result = await method(result_node, document, position) if result is not None: return result return None async def _prepare_rename_default( self, nodes: List[ast.AST], document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: result = await self._find_default(nodes, document, position) if result is not None: var, token = result if var.type == VariableDefinitionType.BUILTIN_VARIABLE: self.parent.window.show_message("You cannot rename a builtin variable, only references are renamed.") elif var.type == VariableDefinitionType.IMPORTED_VARIABLE: self.parent.window.show_message( "You are about to rename an imported variable. " "Only references are renamed and you have to rename the variable definition yourself." ) elif var.type == VariableDefinitionType.COMMAND_LINE_VARIABLE: self.parent.window.show_message( "You are about to rename a variable defined at commandline. " "Only references are renamed and you have to rename the variable definition yourself." ) elif var.type == VariableDefinitionType.ENVIRONMENT_VARIABLE: token.value, _, _ = token.value.partition("=") self.parent.window.show_message( "You are about to rename an environment variable. " "Only references are renamed and you have to rename the variable definition yourself." ) return PrepareRenameResultType1(range_from_token(token), token.value) return None async def _rename_default( self, nodes: List[ast.AST], document: TextDocument, position: Position, new_name: str, ) -> Optional[WorkspaceEdit]: result = await self._find_default(nodes, document, position) if result is not None: var, _ = result references = await self.parent.robot_references.find_variable_references( document, var, include_declaration=var.type in [ VariableDefinitionType.VARIABLE, VariableDefinitionType.ARGUMENT, VariableDefinitionType.LOCAL_VARIABLE, ], ) changes: List[Union[TextDocumentEdit, CreateFile, RenameFile, DeleteFile]] = [] for reference in references: changes.append( TextDocumentEdit( OptionalVersionedTextDocumentIdentifier(reference.uri, None), [AnnotatedTextEdit("rename_variable", reference.range, new_name)], ) ) return WorkspaceEdit( document_changes=changes, change_annotations={"rename_variable": ChangeAnnotation("Rename Variable", False)}, ) return None async def _find_default( self, nodes: List[ast.AST], document: TextDocument, position: Position ) -> Optional[Tuple[VariableDefinition, Token]]: from robot.parsing.lexer.tokens import Token as RobotToken namespace = await self.parent.documents_cache.get_namespace(document) if not nodes: return None node = nodes[-1] if not isinstance(node, HasTokens): return None tokens = get_tokens_at_position(node, position) token_and_var: Optional[Tuple[VariableDefinition, Token]] = None for token in tokens: token_and_var = await async_next( ( (var, var_token) async for var_token, var in self.iter_variables_from_token(token, namespace, nodes, position) if position in range_from_token(var_token) ), None, ) if ( token_and_var is None and isinstance(node, self.get_expression_statement_types()) and (token := node.get_token(RobotToken.ARGUMENT)) is not None and position in range_from_token(token) ): token_and_var = await async_next( ( (var, var_token) async for var_token, var in self.iter_expression_variables_from_token( token, namespace, nodes, position ) if position in range_from_token(var_token) ), None, ) return token_and_var def _prepare_rename_keyword(self, result: Optional[Tuple[KeywordDoc, Token]]) -> Optional[PrepareRenameResult]: if result is not None: kw_doc, token = result if kw_doc.is_embedded: raise CantRenameError("Renaming of keywords with embedded parameters is not supported.") if kw_doc.is_library_keyword: self.parent.window.show_message( "You are about to rename a library keyword. " "Only references are renamed and you have to rename the keyword definition yourself." ) return PrepareRenameResultType1(range_from_token(token), token.value) return None async def _rename_keyword( self, document: TextDocument, new_name: str, result: Optional[Tuple[KeywordDoc, Token]], ) -> Optional[WorkspaceEdit]: if result is not None: kw_doc, _ = result references = await self.parent.robot_references.find_keyword_references( document, kw_doc, include_declaration=kw_doc.is_resource_keyword ) changes: List[Union[TextDocumentEdit, CreateFile, RenameFile, DeleteFile]] = [] for reference in references: changes.append( TextDocumentEdit( OptionalVersionedTextDocumentIdentifier(reference.uri, None), [AnnotatedTextEdit("rename_keyword", reference.range, new_name)], ) ) return WorkspaceEdit( document_changes=changes, change_annotations={"rename_keyword": ChangeAnnotation("Rename Keyword", False)}, ) return None async def prepare_rename_KeywordCall( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: return self._prepare_rename_keyword(await self._find_KeywordCall(node, document, position)) async def rename_KeywordCall( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position, new_name: str ) -> Optional[WorkspaceEdit]: return await self._rename_keyword(document, new_name, await self._find_KeywordCall(node, document, position)) async def _find_KeywordCall( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[Tuple[KeywordDoc, Token]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import KeywordCall namespace = await self.parent.documents_cache.get_namespace(document) kw_node = cast(KeywordCall, node) result = await self.get_keyworddoc_and_token_from_position( kw_node.keyword, cast(Token, kw_node.get_token(RobotToken.KEYWORD)), [cast(Token, t) for t in kw_node.get_tokens(RobotToken.ARGUMENT)], namespace, position, ) if result is not None: keyword_doc, keyword_token = result if ( await namespace.find_keyword( keyword_token.value, raise_keyword_error=False, handle_bdd_style=False, ) is None ): keyword_token = self.strip_bdd_prefix(namespace, keyword_token) lib_entry, kw_namespace = await self.get_namespace_info_from_keyword(namespace, keyword_token) kw_range = range_from_token(keyword_token) if lib_entry and kw_namespace: r = range_from_token(keyword_token) r.end.character = r.start.character + len(kw_namespace) kw_range.start.character = r.end.character + 1 if position in r: # TODO namespaces return None if ( position in kw_range and keyword_doc is not None and not keyword_doc.is_error_handler and keyword_doc.source ): return ( keyword_doc, RobotToken( keyword_token.type, keyword_token.value[len(kw_namespace) + 1 :], keyword_token.lineno, keyword_token.col_offset + len(kw_namespace) + 1, keyword_token.error, ) if lib_entry and kw_namespace else keyword_token, ) return None async def prepare_rename_KeywordName( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: return self._prepare_rename_keyword(await self._find_KeywordName(node, document, position)) async def rename_KeywordName( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position, new_name: str ) -> Optional[WorkspaceEdit]: return await self._rename_keyword(document, new_name, await self._find_KeywordName(node, document, position)) async def _find_KeywordName( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[Tuple[KeywordDoc, Token]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import KeywordName namespace = await self.parent.documents_cache.get_namespace(document) kw_node = cast(KeywordName, node) name_token = cast(RobotToken, kw_node.get_token(RobotToken.KEYWORD_NAME)) if not name_token: return None doc = await namespace.get_library_doc() if doc is not None: keyword = next( (v for v in doc.keywords.keywords if v.name == name_token.value and v.line_no == kw_node.lineno), None, ) if keyword is not None and keyword.source and not keyword.is_error_handler: return keyword, name_token return None async def prepare_rename_Fixture( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: return self._prepare_rename_keyword(await self._find_Fixture(node, document, position)) async def rename_Fixture( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position, new_name: str ) -> Optional[WorkspaceEdit]: return await self._rename_keyword(document, new_name, await self._find_Fixture(node, document, position)) async def _find_Fixture( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[Tuple[KeywordDoc, Token]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Fixture namespace = await self.parent.documents_cache.get_namespace(document) fixture_node = cast(Fixture, node) name_token = cast(Token, fixture_node.get_token(RobotToken.NAME)) if name_token is None or name_token.value is None or name_token.value.upper() in ("", "NONE"): return None result = await self.get_keyworddoc_and_token_from_position( fixture_node.name, name_token, [cast(Token, t) for t in fixture_node.get_tokens(RobotToken.ARGUMENT)], namespace, position, ) if result is not None: keyword_doc, keyword_token = result if ( await namespace.find_keyword( keyword_token.value, raise_keyword_error=False, handle_bdd_style=False, ) is None ): keyword_token = self.strip_bdd_prefix(namespace, keyword_token) lib_entry, kw_namespace = await self.get_namespace_info_from_keyword(namespace, keyword_token) kw_range = range_from_token(keyword_token) if lib_entry and kw_namespace: r = range_from_token(keyword_token) r.end.character = r.start.character + len(kw_namespace) kw_range.start.character = r.end.character + 1 if position in r: # TODO namespaces return None if position in kw_range and keyword_doc is not None and not keyword_doc.is_error_handler: return ( keyword_doc, RobotToken( keyword_token.type, keyword_token.value[len(kw_namespace) + 1 :], keyword_token.lineno, keyword_token.col_offset + len(kw_namespace) + 1, keyword_token.error, ) if lib_entry and kw_namespace else keyword_token, ) return None async def _find_Template_or_TestTemplate( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[Tuple[KeywordDoc, Token]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Template, TestTemplate template_node = cast(Union[Template, TestTemplate], node) if template_node.value: keyword_token = cast(RobotToken, template_node.get_token(RobotToken.NAME)) if keyword_token is None or keyword_token.value is None or keyword_token.value.upper() in ("", "NONE"): return None namespace = await self.parent.documents_cache.get_namespace(document) if ( await namespace.find_keyword( keyword_token.value, raise_keyword_error=False, handle_bdd_style=False, ) is None ): keyword_token = self.strip_bdd_prefix(namespace, keyword_token) if position.is_in_range(range_from_token(keyword_token), False): keyword_doc = await namespace.find_keyword(template_node.value) if keyword_doc is not None: ( lib_entry, kw_namespace, ) = await self.get_namespace_info_from_keyword(namespace, keyword_token) kw_range = range_from_token(keyword_token) if lib_entry and kw_namespace: r = range_from_token(keyword_token) r.end.character = r.start.character + len(kw_namespace) kw_range.start.character = r.end.character + 1 if position in r: # TODO namespaces return None if not keyword_doc.is_error_handler: return ( keyword_doc, RobotToken( keyword_token.type, keyword_token.value[len(kw_namespace) + 1 :], keyword_token.lineno, keyword_token.col_offset + len(kw_namespace) + 1, keyword_token.error, ) if lib_entry and kw_namespace else keyword_token, ) return None async def prepare_rename_TestTemplate( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: return self._prepare_rename_keyword(await self._find_Template_or_TestTemplate(node, document, position)) async def rename_TestTemplate( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position, new_name: str ) -> Optional[WorkspaceEdit]: return await self._rename_keyword( document, new_name, await self._find_Template_or_TestTemplate(node, document, position), ) async def prepare_rename_Template( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: return self._prepare_rename_keyword(await self._find_Template_or_TestTemplate(node, document, position)) async def rename_Template( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position, new_name: str ) -> Optional[WorkspaceEdit]: return await self._rename_keyword( document, new_name, await self._find_Template_or_TestTemplate(node, document, position), ) async def _prepare_rename_tags( self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: from robot.parsing.lexer.tokens import Token as RobotToken tokens = get_tokens_at_position(cast(HasTokens, node), position) if not tokens: return None token = tokens[-1] if token.type in [RobotToken.ARGUMENT] and token.value: return PrepareRenameResultType1(range_from_token(token), token.value) return None async def prepare_rename_ForceTags( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: return await self._prepare_rename_tags(node, document, position) async def prepare_rename_DefaultTags( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: return await self._prepare_rename_tags(node, document, position) async def prepare_rename_Tags( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position ) -> Optional[PrepareRenameResult]: return await self._prepare_rename_tags(node, document, position) async def _rename_tags( self, node: ast.AST, document: TextDocument, position: Position, new_name: str ) -> Optional[WorkspaceEdit]: from robot.parsing.lexer.tokens import Token as RobotToken tokens = get_tokens_at_position(cast(HasTokens, node), position) if not tokens: return None token = tokens[-1] if token.type in [RobotToken.ARGUMENT] and token.value: references = await self.parent.robot_references.find_tag_references(document, token.value) changes: List[Union[TextDocumentEdit, CreateFile, RenameFile, DeleteFile]] = [] for reference in references: changes.append( TextDocumentEdit( OptionalVersionedTextDocumentIdentifier(reference.uri, None), [AnnotatedTextEdit("rename_tag", reference.range, new_name)], ) ) return WorkspaceEdit( document_changes=changes, change_annotations={"rename_keyword": ChangeAnnotation("Rename Tag", False)}, ) return None async def rename_ForceTags( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position, new_name: str ) -> Optional[WorkspaceEdit]: return await self._rename_tags(node, document, position, new_name) async def rename_DefaultTags( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position, new_name: str ) -> Optional[WorkspaceEdit]: return await self._rename_tags(node, document, position, new_name) async def rename_Tags( # noqa: N802 self, node: ast.AST, document: TextDocument, position: Position, new_name: str ) -> Optional[WorkspaceEdit]: return await self._rename_tags(node, document, position, new_name)
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/rename.py
0.864782
0.170404
rename.py
pypi
from __future__ import annotations import ast from typing import TYPE_CHECKING, Any, List, Optional, cast from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import FoldingRange from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.utils.async_ast import AsyncVisitor from .protocol_part import RobotLanguageServerProtocolPart if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import ( RobotLanguageServerProtocol, ) class _Visitor(AsyncVisitor): def __init__(self, parent: RobotFoldingRangeProtocolPart) -> None: super().__init__() self.parent = parent self.line_folding_only = True if ( self.parent.parent.client_capabilities and self.parent.parent.client_capabilities.text_document and self.parent.parent.client_capabilities.text_document.folding_range and self.parent.parent.client_capabilities.text_document.folding_range.line_folding_only is not None ): self.line_folding_only = ( self.parent.parent.client_capabilities.text_document.folding_range.line_folding_only ) self.result: List[FoldingRange] = [] async def visit(self, node: ast.AST) -> None: await super().visit(node) @classmethod async def find_from(cls, model: ast.AST, parent: RobotFoldingRangeProtocolPart) -> Optional[List[FoldingRange]]: finder = cls(parent) await finder.visit(model) return finder.result if finder.result else None def __append(self, node: ast.AST, kind: str) -> None: if not self.line_folding_only: self.result.append( FoldingRange( start_line=node.lineno - 1, end_line=node.end_lineno - 1 if node.end_lineno is not None else node.lineno - 1, start_character=node.col_offset if not self.line_folding_only else None, end_character=node.end_col_offset if not self.line_folding_only else None, kind=kind, ) ) else: self.result.append( FoldingRange( start_line=node.lineno - 1, end_line=node.end_lineno - 1 if node.end_lineno is not None else node.lineno - 1, kind=kind, ) ) async def visit_Section(self, node: ast.AST) -> None: # noqa: N802 self.__append(node, kind="section") await self.generic_visit(node) async def visit_CommentSection(self, node: ast.AST) -> None: # noqa: N802 self.__append(node, kind="comment") await self.generic_visit(node) async def visit_TestCase(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.model.blocks import TestCase if cast(TestCase, node).name: self.__append(node, kind="testcase") await self.generic_visit(node) async def visit_Keyword(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.model.blocks import Keyword if cast(Keyword, node).name: self.__append(node, kind="keyword") await self.generic_visit(node) async def visit_ForLoop(self, node: ast.AST) -> None: # noqa: N802, pragma: no cover self.__append(node, kind="for_loop") await self.generic_visit(node) async def visit_For(self, node: ast.AST) -> None: # noqa: N802 self.__append(node, kind="for") await self.generic_visit(node) async def visit_If(self, node: ast.AST) -> None: # noqa: N802 self.__append(node, kind="if") await self.generic_visit(node) class RobotFoldingRangeProtocolPart(RobotLanguageServerProtocolPart): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.folding_ranges.collect.add(self.collect) @language_id("robotframework") @_logger.call async def collect(self, sender: Any, document: TextDocument) -> Optional[List[FoldingRange]]: return await _Visitor.find_from(await self.parent.documents_cache.get_model(document, False), self)
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/folding_range.py
0.822617
0.188417
folding_range.py
pypi
from __future__ import annotations from typing import ( TYPE_CHECKING, Any, List, Optional, Union, cast, ) from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import Location, LocationLink, Position, Range from robotcode.core.uri import Uri from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.utils.ast_utils import ( range_from_token, ) if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import RobotLanguageServerProtocol from .protocol_part import RobotLanguageServerProtocolPart class RobotGotoProtocolPart(RobotLanguageServerProtocolPart): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.definition.collect.add(self.collect_definition) parent.implementation.collect.add(self.collect_implementation) @language_id("robotframework") @_logger.call async def collect_definition( self, sender: Any, document: TextDocument, position: Position ) -> Union[Location, List[Location], List[LocationLink], None]: return await self.collect(document, position) @language_id("robotframework") @_logger.call async def collect_implementation( self, sender: Any, document: TextDocument, position: Position ) -> Union[Location, List[Location], List[LocationLink], None]: return await self.collect(document, position) async def collect( self, document: TextDocument, position: Position ) -> Union[Location, List[Location], List[LocationLink], None]: namespace = await self.parent.documents_cache.get_namespace(document) all_variable_refs = await namespace.get_variable_references() if all_variable_refs: result = [] for variable, var_refs in all_variable_refs.items(): found_range = ( variable.name_range if variable.source == namespace.source and position.is_in_range(variable.name_range, False) else cast(Optional[Range], next((r.range for r in var_refs if position.is_in_range(r.range)), None)) ) if found_range is not None and variable.source: result.append( LocationLink( origin_selection_range=found_range, target_uri=str(Uri.from_path(variable.source)), target_range=variable.range, target_selection_range=range_from_token(variable.name_token) if variable.name_token else variable.range, ) ) if result: return result all_kw_refs = await namespace.get_keyword_references() if all_kw_refs: result = [] for kw, kw_refs in all_kw_refs.items(): found_range = ( kw.name_range if kw.source == namespace.source and position.is_in_range(kw.name_range, False) else cast( Optional[Range], next((r.range for r in kw_refs if position.is_in_range(r.range, False)), None) ) ) if found_range is not None and kw.source: result.append( LocationLink( origin_selection_range=found_range, target_uri=str(Uri.from_path(kw.source)), target_range=kw.range, target_selection_range=range_from_token(kw.name_token) if kw.name_token else kw.range, ) ) if result: return result all_namespace_refs = await namespace.get_namespace_references() if all_namespace_refs: result = [] for ns, ns_refs in all_namespace_refs.items(): for found_range in [ next((r.range for r in ns_refs if position.is_in_range(r.range, False)), None), ns.alias_range if position.is_in_range(ns.alias_range, False) else None, ns.import_range if position.is_in_range(ns.import_range, False) else None, ]: if found_range is not None: libdoc = ns.library_doc if found_range == ns.import_range: if libdoc.source: result.append( LocationLink( origin_selection_range=found_range, target_uri=str(Uri.from_path(libdoc.source)), target_range=ns.library_doc.range, target_selection_range=ns.library_doc.range, ) ) else: if ns.import_source: result.append( LocationLink( origin_selection_range=found_range, target_uri=str(Uri.from_path(ns.import_source)), target_range=ns.alias_range if ns.alias_range else ns.import_range, target_selection_range=ns.alias_range if ns.alias_range else ns.import_range, ) ) elif libdoc is not None and libdoc.source: result.append( LocationLink( origin_selection_range=found_range, target_uri=str(Uri.from_path(libdoc.source)), target_range=ns.library_doc.range, target_selection_range=ns.library_doc.range, ) ) if result: return result return None
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/goto.py
0.783202
0.189915
goto.py
pypi
from __future__ import annotations import ast from typing import TYPE_CHECKING, Any, Iterator, List, Optional, Tuple from robotcode.core.async_itertools import async_dropwhile, async_takewhile from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( InlineValue, InlineValueContext, InlineValueEvaluatableExpression, Range, ) from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.utils.ast_utils import ( HasTokens, Token, get_nodes_at_position, iter_nodes, range_from_node, range_from_token, ) from .model_helper import ModelHelperMixin from .protocol_part import RobotLanguageServerProtocolPart if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import ( RobotLanguageServerProtocol, ) class RobotInlineValueProtocolPart(RobotLanguageServerProtocolPart, ModelHelperMixin): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.inline_value.collect.add(self.collect) @language_id("robotframework") @_logger.call async def collect( self, sender: Any, document: TextDocument, range: Range, context: InlineValueContext, ) -> Optional[List[InlineValue]]: from robot.parsing.lexer import Token as RobotToken # TODO make this configurable namespace = await self.parent.documents_cache.get_namespace(document) model = await self.parent.documents_cache.get_model(document, False) real_range = Range(range.start, min(range.end, context.stopped_location.end)) nodes = await get_nodes_at_position(model, context.stopped_location.start) def get_tokens() -> Iterator[Tuple[Token, ast.AST]]: for n in iter_nodes(model): r = range_from_node(n) if (r.start in real_range or r.end in real_range) and isinstance(n, HasTokens): for t in n.tokens: yield t, n if r.start > real_range.end: break result: List[InlineValue] = [] async for token, node in async_takewhile( lambda t: range_from_token(t[0]).end.line <= real_range.end.line, async_dropwhile( lambda t: range_from_token(t[0]).start < real_range.start, get_tokens(), ), ): if token.type == RobotToken.ARGUMENT and isinstance(node, self.get_expression_statement_types()): async for t, var in self.iter_expression_variables_from_token( token, namespace, nodes, context.stopped_location.start, ): if var.name != "${CURDIR}": result.append(InlineValueEvaluatableExpression(range_from_token(t), var.name)) async for t, var in self.iter_variables_from_token( token, namespace, nodes, context.stopped_location.start, ): if var.name != "${CURDIR}": result.append(InlineValueEvaluatableExpression(range_from_token(t), var.name)) return result
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/inline_value.py
0.615435
0.208743
inline_value.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING, Any, List, Optional, cast from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import DocumentHighlight, DocumentHighlightKind, Position, Range from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import RobotLanguageServerProtocol from .protocol_part import RobotLanguageServerProtocolPart class RobotDocumentHighlightProtocolPart(RobotLanguageServerProtocolPart): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.document_highlight.collect.add(self.collect) @language_id("robotframework") @_logger.call async def collect( self, sender: Any, document: TextDocument, position: Position, ) -> Optional[List[DocumentHighlight]]: namespace = await self.parent.documents_cache.get_namespace(document) all_variable_refs = await namespace.get_variable_references() if all_variable_refs: for var, var_refs in all_variable_refs.items(): for r in var_refs: if (var.source == namespace.source and position in var.name_range) or position in r.range: return [ *( [DocumentHighlight(var.name_range, DocumentHighlightKind.TEXT)] if var.source == namespace.source else [] ), *(DocumentHighlight(e.range, DocumentHighlightKind.TEXT) for e in var_refs), ] all_kw_refs = await namespace.get_keyword_references() if all_kw_refs: for kw, kw_refs in all_kw_refs.items(): for r in kw_refs: if (kw.source == namespace.source and position in kw.range) or position in r.range: return [ *( [DocumentHighlight(kw.range, DocumentHighlightKind.TEXT)] if kw.source == namespace.source else [] ), *(DocumentHighlight(e.range, DocumentHighlightKind.TEXT) for e in kw_refs), ] all_namespace_refs = await namespace.get_namespace_references() if all_namespace_refs: for ns, ns_refs in all_namespace_refs.items(): found_range = ( ns.import_range if ns.import_source == namespace.source and (position.is_in_range(ns.alias_range, False) or position.is_in_range(ns.import_range, False)) else cast( Optional[Range], next((r.range for r in ns_refs if position.is_in_range(r.range, False)), None) ) ) if found_range is not None: return [ *( [ DocumentHighlight( ns.import_range, DocumentHighlightKind.TEXT, ) ] if ns.import_source == namespace.source and ns.import_range else [] ), *( [ DocumentHighlight( ns.alias_range, DocumentHighlightKind.TEXT, ) ] if ns.import_source == namespace.source and ns.alias_range else [] ), *(DocumentHighlight(e.range, DocumentHighlightKind.TEXT) for e in ns_refs), ] return None
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/document_highlight.py
0.798265
0.159185
document_highlight.py
pypi
from __future__ import annotations import io from typing import TYPE_CHECKING, Any, List, Optional from robotcode.core.async_tools import check_canceled, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( CodeDescription, Diagnostic, DiagnosticSeverity, Position, Range, ) from robotcode.core.utils.version import Version, create_version_from_str from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.parts.diagnostics import DiagnosticsResult from robotcode.language_server.common.parts.workspace import WorkspaceFolder from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.configuration import RoboCopConfig from .protocol_part import RobotLanguageServerProtocolPart if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import ( RobotLanguageServerProtocol, ) def robocop_installed() -> bool: try: __import__("robocop") except ImportError: return False return True class RobotRoboCopDiagnosticsProtocolPart(RobotLanguageServerProtocolPart): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) self.source_name = "robocop" if robocop_installed(): parent.diagnostics.collect.add(self.collect_diagnostics) async def get_config(self, document: TextDocument) -> Optional[RoboCopConfig]: folder = self.parent.workspace.get_workspace_folder(document.uri) if folder is None: return None return await self.parent.workspace.get_configuration(RoboCopConfig, folder.uri) @language_id("robotframework") @threaded() @_logger.call async def collect_diagnostics(self, sender: Any, document: TextDocument) -> DiagnosticsResult: workspace_folder = self.parent.workspace.get_workspace_folder(document.uri) if workspace_folder is not None: extension_config = await self.get_config(document) if extension_config is not None and extension_config.enabled: return DiagnosticsResult( self.collect_diagnostics, await self.collect(document, workspace_folder, extension_config), ) return DiagnosticsResult(self.collect_diagnostics, []) @_logger.call async def collect( self, document: TextDocument, workspace_folder: WorkspaceFolder, extension_config: RoboCopConfig, ) -> List[Diagnostic]: from robocop import __version__ from robocop.config import Config from robocop.rules import RuleSeverity from robocop.run import Robocop from robocop.utils.misc import is_suite_templated robocop_version = create_version_from_str(__version__) result: List[Diagnostic] = [] await check_canceled() with io.StringIO() as output: config = Config(str(workspace_folder.uri.to_path())) config.exec_dir = str(workspace_folder.uri.to_path()) config.output = output if extension_config.include: config.include = set(extension_config.include) if extension_config.exclude: config.exclude = set(extension_config.exclude) if extension_config.configurations: config.configure = set(extension_config.configurations) class MyRobocop(Robocop): async def run_check(self, ast_model, filename, source=None): # type: ignore await check_canceled() if robocop_version >= (4, 0): from robocop.utils.disablers import DisablersFinder disablers = DisablersFinder(ast_model) elif robocop_version >= (2, 4): from robocop.utils import DisablersFinder disablers = DisablersFinder(filename=filename, source=source) else: self.register_disablers(filename, source) disablers = self.disabler if disablers.file_disabled: return [] found_issues = [] # type: ignore templated = is_suite_templated(ast_model) for checker in self.checkers: await check_canceled() if len(found_issues) >= 1000: break if checker.disabled: continue found_issues += [ issue for issue in checker.scan_file(ast_model, filename, source, templated) if not disablers.is_rule_disabled(issue) ] return found_issues analyser = MyRobocop(from_cli=False, config=config) analyser.reload_config() # TODO find a way to cancel the run_check issues = await analyser.run_check( await self.parent.documents_cache.get_model(document, False), str(document.uri.to_path()), document.text(), ) for issue in issues: await check_canceled() d = Diagnostic( range=Range( start=Position(line=max(0, issue.line - 1), character=max(0, issue.col - 1)), end=Position( line=max(0, issue.end_line - 1), character=max(0, issue.end_col - 1), ), ), message=issue.desc, severity=DiagnosticSeverity.INFORMATION if issue.severity == RuleSeverity.INFO else DiagnosticSeverity.WARNING if issue.severity == RuleSeverity.WARNING else DiagnosticSeverity.ERROR if issue.severity == RuleSeverity.ERROR else DiagnosticSeverity.HINT, source=self.source_name, code=f"{issue.name}-{issue.severity.value}{issue.rule_id}", code_description=self.get_code_description(robocop_version, issue), ) result.append(d) return result def get_code_description(self, version: Version, issue: Any) -> Optional[CodeDescription]: if version < (3, 0): return None base = f"https://robocop.readthedocs.io/en/{version.major}.{version.minor}.{version.patch}" if version < (4, 0): return CodeDescription(href=f"{base}/rules.html#{issue.name}".lower()) if version < (4, 1): return CodeDescription(href=f"{base}/rules.html#{issue.name}-{issue.severity.value}{issue.rule_id}".lower()) return CodeDescription( href=f"{base}/rules_list.html#{issue.name}-{issue.severity.value}{issue.rule_id}".lower() )
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/robocop_diagnostics.py
0.688049
0.161949
robocop_diagnostics.py
pypi
from __future__ import annotations import ast import asyncio from typing import TYPE_CHECKING, Any, Awaitable, Callable, List, Optional, Type, cast from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import InlayHint, InlayHintKind, Range from robotcode.language_server.common.decorators import language_id from robotcode.language_server.common.text_document import TextDocument from robotcode.language_server.robotframework.configuration import InlayHintsConfig from robotcode.language_server.robotframework.diagnostics.library_doc import KeywordArgumentKind, KeywordDoc, LibraryDoc from robotcode.language_server.robotframework.diagnostics.namespace import Namespace from robotcode.language_server.robotframework.utils.ast_utils import Token, range_from_node, range_from_token from robotcode.language_server.robotframework.utils.async_ast import iter_nodes if TYPE_CHECKING: from robotcode.language_server.robotframework.protocol import RobotLanguageServerProtocol from .model_helper import ModelHelperMixin from .protocol_part import RobotLanguageServerProtocolPart _HandlerMethod = Callable[ [TextDocument, Range, ast.AST, ast.AST, Namespace, InlayHintsConfig], Awaitable[Optional[List[InlayHint]]] ] class RobotInlayHintProtocolPart(RobotLanguageServerProtocolPart, ModelHelperMixin): _logger = LoggingDescriptor() def __init__(self, parent: RobotLanguageServerProtocol) -> None: super().__init__(parent) parent.inlay_hint.collect.add(self.collect) async def get_config(self, document: TextDocument) -> Optional[InlayHintsConfig]: folder = self.parent.workspace.get_workspace_folder(document.uri) if folder is None: return None return await self.parent.workspace.get_configuration(InlayHintsConfig, folder.uri) def _find_method(self, cls: Type[Any]) -> Optional[_HandlerMethod]: if cls is ast.AST: return None method_name = "handle_" + cls.__name__ if hasattr(self, method_name): method = getattr(self, method_name) if callable(method): return cast(_HandlerMethod, method) for base in cls.__bases__: method = self._find_method(base) if method: return cast(_HandlerMethod, method) return None @language_id("robotframework") @_logger.call async def collect(self, sender: Any, document: TextDocument, range: Range) -> Optional[List[InlayHint]]: config = await self.get_config(document) if config is None or not config.parameter_names and not config.namespaces: return None model = await self.parent.documents_cache.get_model(document, False) namespace = await self.parent.documents_cache.get_namespace(document) result: List[InlayHint] = [] async for node in iter_nodes(model): node_range = range_from_node(node) if node_range.end < range.start: continue if node_range.start > range.end: break method = self._find_method(type(node)) if method is not None: r = await method(document, range, node, model, namespace, config) if r is not None: result.extend(r) return result async def _handle_keywordcall_fixture_template( self, keyword_token: Token, arguments: List[Token], namespace: Namespace, config: InlayHintsConfig, ) -> Optional[List[InlayHint]]: kw_result = await self.get_keyworddoc_and_token_from_position( keyword_token.value, keyword_token, arguments, namespace, range_from_token(keyword_token).start, ) if kw_result is None: return None kw_doc, _ = kw_result if kw_doc is None: return None return await self._get_inlay_hint(keyword_token, kw_doc, arguments, namespace, config) async def _get_inlay_hint( self, keyword_token: Optional[Token], kw_doc: KeywordDoc, arguments: List[Token], namespace: Namespace, config: InlayHintsConfig, ) -> Optional[List[InlayHint]]: from robot.errors import DataError result: List[InlayHint] = [] if config.parameter_names: positional = None if kw_doc.arguments_spec is not None: try: positional, _ = kw_doc.arguments_spec.resolve( [a.value for a in arguments], None, resolve_variables_until=kw_doc.args_to_process, resolve_named=not kw_doc.is_any_run_keyword(), validate=False, ) except DataError: pass if positional is not None: kw_arguments = [ a for a in kw_doc.arguments if a.kind not in [ KeywordArgumentKind.NAMED_ONLY_MARKER, KeywordArgumentKind.POSITIONAL_ONLY_MARKER, KeywordArgumentKind.VAR_NAMED, KeywordArgumentKind.NAMED_ONLY, ] ] for i, _ in enumerate(positional): if i >= len(arguments): break index = i if i < len(kw_arguments) else len(kw_arguments) - 1 if index < 0: continue arg = kw_arguments[index] if i >= len(kw_arguments) and arg.kind not in [ KeywordArgumentKind.VAR_POSITIONAL, ]: break prefix = "" if arg.kind == KeywordArgumentKind.VAR_POSITIONAL: prefix = "*" elif arg.kind == KeywordArgumentKind.VAR_NAMED: prefix = "**" result.append( InlayHint(range_from_token(arguments[i]).start, f"{prefix}{arg.name}=", InlayHintKind.PARAMETER) ) if keyword_token is not None and config.namespaces: lib_entry, kw_namespace = await self.get_namespace_info_from_keyword(namespace, keyword_token) if lib_entry is None and kw_namespace is None: if kw_doc.libtype == "LIBRARY": lib = next( ( lib for lib in (await namespace.get_libraries()).values() if lib.name == kw_doc.libname and kw_doc in lib.library_doc.keywords.keywords ), None, ) else: lib = next( ( lib for lib in (await namespace.get_resources()).values() if lib.name == kw_doc.libname and kw_doc in lib.library_doc.keywords.keywords ), None, ) if lib is not None: result.append(InlayHint(range_from_token(keyword_token).start, f"{lib.alias or lib.name}.")) return result async def handle_KeywordCall( # noqa: N802 self, document: TextDocument, range: Range, node: ast.AST, model: ast.AST, namespace: Namespace, config: InlayHintsConfig, ) -> Optional[List[InlayHint]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import KeywordCall keyword_call = cast(KeywordCall, node) keyword_token = keyword_call.get_token(RobotToken.KEYWORD) if keyword_token is None or not keyword_token.value: return None arguments = keyword_call.get_tokens(RobotToken.ARGUMENT) return await self._handle_keywordcall_fixture_template(keyword_token, arguments, namespace, config) async def handle_Fixture( # noqa: N802 self, document: TextDocument, range: Range, node: ast.AST, model: ast.AST, namespace: Namespace, config: InlayHintsConfig, ) -> Optional[List[InlayHint]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Fixture fixture = cast(Fixture, node) keyword_token = fixture.get_token(RobotToken.NAME) if keyword_token is None or not keyword_token.value: return None arguments = fixture.get_tokens(RobotToken.ARGUMENT) return await self._handle_keywordcall_fixture_template(keyword_token, arguments, namespace, config) async def handle_TestTemplate( # noqa: N802 self, document: TextDocument, range: Range, node: ast.AST, model: ast.AST, namespace: Namespace, config: InlayHintsConfig, ) -> Optional[List[InlayHint]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import TestTemplate template = cast(TestTemplate, node) keyword_token = template.get_token(RobotToken.NAME, RobotToken.ARGUMENT) if keyword_token is None or not keyword_token.value: return None return await self._handle_keywordcall_fixture_template(keyword_token, [], namespace, config) async def handle_Template( # noqa: N802 self, document: TextDocument, range: Range, node: ast.AST, model: ast.AST, namespace: Namespace, config: InlayHintsConfig, ) -> Optional[List[InlayHint]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Template template = cast(Template, node) keyword_token = template.get_token(RobotToken.NAME, RobotToken.ARGUMENT) if keyword_token is None or not keyword_token.value: return None return await self._handle_keywordcall_fixture_template(keyword_token, [], namespace, config) async def handle_LibraryImport( # noqa: N802 self, document: TextDocument, range: Range, node: ast.AST, model: ast.AST, namespace: Namespace, config: InlayHintsConfig, ) -> Optional[List[InlayHint]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import LibraryImport library_node = cast(LibraryImport, node) if not library_node.name: return None lib_doc: Optional[LibraryDoc] = None try: namespace = await self.parent.documents_cache.get_namespace(document) lib_doc = await namespace.get_imported_library_libdoc( library_node.name, library_node.args, library_node.alias ) if lib_doc is None or lib_doc.errors: lib_doc = await namespace.imports_manager.get_libdoc_for_library_import( str(library_node.name), (), str(document.uri.to_path().parent), variables=await namespace.get_resolvable_variables(), ) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException: return None arguments = library_node.get_tokens(RobotToken.ARGUMENT) for kw_doc in lib_doc.inits: return await self._get_inlay_hint(None, kw_doc, arguments, namespace, config) return None async def handle_VariablesImport( # noqa: N802 self, document: TextDocument, range: Range, node: ast.AST, model: ast.AST, namespace: Namespace, config: InlayHintsConfig, ) -> Optional[List[InlayHint]]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import VariablesImport library_node = cast(VariablesImport, node) if not library_node.name: return None lib_doc: Optional[LibraryDoc] = None try: namespace = await self.parent.documents_cache.get_namespace(document) lib_doc = await namespace.get_imported_variables_libdoc( library_node.name, library_node.args, ) if lib_doc is None or lib_doc.errors: lib_doc = await namespace.imports_manager.get_libdoc_for_variables_import( str(library_node.name), (), str(document.uri.to_path().parent), variables=await namespace.get_resolvable_variables(), ) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException: return None arguments = library_node.get_tokens(RobotToken.ARGUMENT) for kw_doc in lib_doc.inits: return await self._get_inlay_hint(None, kw_doc, arguments, namespace, config) return None
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/parts/inlay_hint.py
0.81615
0.192046
inlay_hint.py
pypi
from __future__ import annotations import ast import asyncio import itertools import os from collections import defaultdict from dataclasses import dataclass from typing import Any, Dict, Iterator, List, Optional, Set, Tuple, Union, cast from robotcode.core.lsp.types import ( CodeDescription, Diagnostic, DiagnosticRelatedInformation, DiagnosticSeverity, DiagnosticTag, Location, Position, Range, ) from robotcode.core.uri import Uri from robotcode.language_server.robotframework.parts.model_helper import ModelHelperMixin from robotcode.language_server.robotframework.utils.ast_utils import ( HasTokens, Statement, Token, is_not_variable_token, iter_over_keyword_names_and_owners, range_from_node, range_from_node_or_token, range_from_token, strip_variable_token, tokenize_variables, ) from robotcode.language_server.robotframework.utils.async_ast import AsyncVisitor from robotcode.language_server.robotframework.utils.version import get_robot_version from .entities import ( CommandLineVariableDefinition, EnvironmentVariableDefinition, LibraryEntry, ResourceEntry, VariableDefinition, VariableDefinitionType, VariableNotFoundDefinition, ) from .library_doc import KeywordDoc, KeywordMatcher, is_embedded_keyword from .namespace import ( DIAGNOSTICS_SOURCE_NAME, KeywordFinder, Namespace, ) @dataclass class AnalyzerResult: diagnostics: List[Diagnostic] keyword_references: Dict[KeywordDoc, Set[Location]] variable_references: Dict[VariableDefinition, Set[Location]] namespace_references: Dict[LibraryEntry, Set[Location]] class Analyzer(AsyncVisitor, ModelHelperMixin): def __init__( self, model: ast.AST, namespace: Namespace, finder: KeywordFinder, ignored_lines: List[int], libraries_matchers: Dict[KeywordMatcher, LibraryEntry], resources_matchers: Dict[KeywordMatcher, ResourceEntry], ) -> None: from robot.parsing.model.statements import Template, TestTemplate self.model = model self.namespace = namespace self.finder = finder self._ignored_lines = ignored_lines self.libraries_matchers = libraries_matchers self.resources_matchers = resources_matchers self.current_testcase_or_keyword_name: Optional[str] = None self.test_template: Optional[TestTemplate] = None self.template: Optional[Template] = None self.node_stack: List[ast.AST] = [] self._diagnostics: List[Diagnostic] = [] self._keyword_references: Dict[KeywordDoc, Set[Location]] = defaultdict(set) self._variable_references: Dict[VariableDefinition, Set[Location]] = defaultdict(set) self._namespace_references: Dict[LibraryEntry, Set[Location]] = defaultdict(set) async def run(self) -> AnalyzerResult: self._diagnostics = [] self._keyword_references = defaultdict(set) await self.visit(self.model) return AnalyzerResult( self._diagnostics, self._keyword_references, self._variable_references, self._namespace_references ) def yield_argument_name_and_rest(self, node: ast.AST, token: Token) -> Iterator[Token]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Arguments if isinstance(node, Arguments) and token.type == RobotToken.ARGUMENT: argument = next( ( v for v in itertools.dropwhile( lambda t: t.type in RobotToken.NON_DATA_TOKENS, tokenize_variables(token, ignore_errors=True), ) if v.type == RobotToken.VARIABLE ), None, ) if argument is None or argument.value == token.value: yield token else: yield argument i = len(argument.value) for t in self.yield_argument_name_and_rest( node, RobotToken(token.type, token.value[i:], token.lineno, token.col_offset + i, token.error) ): yield t else: yield token async def visit_Variable(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Variable from robot.variables import search_variable variable = cast(Variable, node) name_token = variable.get_token(RobotToken.VARIABLE) if name_token is None: return name = name_token.value if name is not None: match = search_variable(name, ignore_errors=True) if not match.is_assign(allow_assign_mark=True): return if name.endswith("="): name = name[:-1].rstrip() r = range_from_token( strip_variable_token( RobotToken(name_token.type, name, name_token.lineno, name_token.col_offset, name_token.error) ) ) var_def = next( ( v for v in await self.namespace.get_own_variables() if v.name_token is not None and range_from_token(v.name_token) == r ), None, ) if var_def is None: return cmd_line_var = await self.namespace.find_variable( name, skip_commandline_variables=False, position=r.start, ignore_error=True ) if isinstance(cmd_line_var, CommandLineVariableDefinition): if self.namespace.document is not None: self._variable_references[cmd_line_var].add(Location(self.namespace.document.document_uri, r)) if var_def not in self._variable_references: self._variable_references[var_def] = set() async def visit(self, node: ast.AST) -> None: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import ( Arguments, DocumentationOrMetadata, KeywordCall, Template, TestTemplate, Variable, ) from robot.variables.search import contains_variable self.node_stack.append(node) try: severity = ( DiagnosticSeverity.HINT if isinstance(node, DocumentationOrMetadata) else DiagnosticSeverity.ERROR ) if isinstance(node, KeywordCall) and node.keyword: kw_doc = self.finder.find_keyword(node.keyword, raise_keyword_error=False) if kw_doc is not None and kw_doc.longname in ["BuiltIn.Comment"]: severity = DiagnosticSeverity.HINT if isinstance(node, HasTokens) and not isinstance(node, (TestTemplate, Template)): for token1 in ( t for t in node.tokens if not (isinstance(node, Variable) and t.type == RobotToken.VARIABLE) and t.error is None and contains_variable(t.value, "$@&%") ): for token in self.yield_argument_name_and_rest(node, token1): if isinstance(node, Arguments) and token.value == "@{}": continue async for var_token, var in self.iter_variables_from_token( token, self.namespace, self.node_stack, range_from_token(token).start, skip_commandline_variables=False, return_not_found=True, ): if isinstance(var, VariableNotFoundDefinition): self.append_diagnostics( range=range_from_token(var_token), message=f"Variable '{var.name}' not found.", severity=severity, source=DIAGNOSTICS_SOURCE_NAME, code="VariableNotFound", ) else: if isinstance(var, EnvironmentVariableDefinition) and var.default_value is None: env_name = var.name[2:-1] if os.environ.get(env_name, None) is None: self.append_diagnostics( range=range_from_token(var_token), message=f"Environment variable '{var.name}' not found.", severity=severity, source=DIAGNOSTICS_SOURCE_NAME, code="EnvirommentVariableNotFound", ) if self.namespace.document is not None: if isinstance(var, EnvironmentVariableDefinition): var_token.value, _, _ = var_token.value.partition("=") var_range = range_from_token(var_token) else: var_range = range_from_token(var_token) suite_var = None if isinstance(var, CommandLineVariableDefinition): suite_var = await self.namespace.find_variable( var.name, skip_commandline_variables=True, ignore_error=True, ) if suite_var is not None and suite_var.type not in [ VariableDefinitionType.VARIABLE ]: suite_var = None if var.name_range != var_range: self._variable_references[var].add( Location(self.namespace.document.document_uri, var_range) ) if suite_var is not None: self._variable_references[suite_var].add( Location(self.namespace.document.document_uri, var_range) ) elif var not in self._variable_references and token1.type in [ RobotToken.ASSIGN, RobotToken.ARGUMENT, RobotToken.VARIABLE, ]: self._variable_references[var] = set() if suite_var is not None: self._variable_references[suite_var] = set() if ( isinstance(node, Statement) and isinstance(node, self.get_expression_statement_types()) and (token := node.get_token(RobotToken.ARGUMENT)) is not None ): async for var_token, var in self.iter_expression_variables_from_token( token, self.namespace, self.node_stack, range_from_token(token).start, skip_commandline_variables=False, return_not_found=True, ): if isinstance(var, VariableNotFoundDefinition): self.append_diagnostics( range=range_from_token(var_token), message=f"Variable '{var.name}' not found.", severity=DiagnosticSeverity.ERROR, source=DIAGNOSTICS_SOURCE_NAME, code="VariableNotFound", ) else: if self.namespace.document is not None: var_range = range_from_token(var_token) if var.name_range != var_range: self._variable_references[var].add( Location(self.namespace.document.document_uri, range_from_token(var_token)) ) if isinstance(var, CommandLineVariableDefinition): suite_var = await self.namespace.find_variable( var.name, skip_commandline_variables=True, ignore_error=True, ) if suite_var is not None and suite_var.type in [VariableDefinitionType.VARIABLE]: self._variable_references[suite_var].add( Location(self.namespace.document.document_uri, range_from_token(var_token)) ) await super().visit(node) finally: self.node_stack = self.node_stack[:-1] def _should_ignore(self, range: Range) -> bool: import builtins for line_no in builtins.range(range.start.line, range.end.line + 1): if line_no in self._ignored_lines: return True return False def append_diagnostics( self, range: Range, message: str, severity: Optional[DiagnosticSeverity] = None, code: Union[int, str, None] = None, code_description: Optional[CodeDescription] = None, source: Optional[str] = None, tags: Optional[List[DiagnosticTag]] = None, related_information: Optional[List[DiagnosticRelatedInformation]] = None, data: Optional[Any] = None, ) -> None: if self._should_ignore(range): return self._diagnostics.append( Diagnostic( range, message, severity, code, code_description, source or DIAGNOSTICS_SOURCE_NAME, tags, related_information, data, ) ) async def _analyze_keyword_call( self, keyword: Optional[str], node: ast.AST, keyword_token: Token, argument_tokens: List[Token], analyse_run_keywords: bool = True, allow_variables: bool = False, ignore_errors_if_contains_variables: bool = False, ) -> Optional[KeywordDoc]: from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Template, TestTemplate from robot.utils.escaping import split_from_equals result: Optional[KeywordDoc] = None try: if not allow_variables and not is_not_variable_token(keyword_token): return None if self.finder.find_keyword(keyword_token.value, raise_keyword_error=False, handle_bdd_style=False) is None: keyword_token = self.strip_bdd_prefix(self.namespace, keyword_token) kw_range = range_from_token(keyword_token) lib_entry = None lib_range = None kw_namespace = None if keyword is not None: for lib, name in iter_over_keyword_names_and_owners(keyword): if ( lib is not None and not any(k for k in self.libraries_matchers.keys() if k == lib) and not any(k for k in self.resources_matchers.keys() if k == lib) ): continue lib_entry, kw_namespace = await self.get_namespace_info_from_keyword( self.namespace, keyword_token, self.libraries_matchers, self.resources_matchers ) if lib_entry and kw_namespace: r = range_from_token(keyword_token) lib_range = r r.end.character = r.start.character + len(kw_namespace) kw_range.start.character = r.end.character + 1 lib_range.end.character = kw_range.start.character - 1 result = self.finder.find_keyword(keyword, raise_keyword_error=False) if ( result is not None and lib_entry is not None and kw_namespace and result.parent_digest is not None and result.parent_digest != lib_entry.library_doc.digest ): entry = next( ( v for v in (await self.namespace.get_libraries()).values() if v.library_doc.digest == result.parent_digest ), None, ) if entry is None: entry = next( ( v for v in (await self.namespace.get_resources()).values() if v.library_doc.digest == result.parent_digest ), None, ) if entry is not None: lib_entry = entry if kw_namespace and lib_entry is not None and lib_range is not None: if self.namespace.document is not None: self._namespace_references[lib_entry].add(Location(self.namespace.document.document_uri, lib_range)) if not ignore_errors_if_contains_variables or is_not_variable_token(keyword_token): for e in self.finder.diagnostics: self.append_diagnostics( range=kw_range, message=e.message, severity=e.severity, code=e.code, ) if result is None: if self.namespace.document is not None and self.finder.multiple_keywords_result is not None: for d in self.finder.multiple_keywords_result: self._keyword_references[d].add(Location(self.namespace.document.document_uri, kw_range)) else: if self.namespace.document is not None: self._keyword_references[result].add(Location(self.namespace.document.document_uri, kw_range)) if result.errors: self.append_diagnostics( range=kw_range, message="Keyword definition contains errors.", severity=DiagnosticSeverity.ERROR, related_information=[ DiagnosticRelatedInformation( location=Location( uri=str( Uri.from_path( err.source if err.source is not None else result.source if result.source is not None else "/<unknown>" ) ), range=Range( start=Position( line=err.line_no - 1 if err.line_no is not None else result.line_no if result.line_no >= 0 else 0, character=0, ), end=Position( line=err.line_no - 1 if err.line_no is not None else result.line_no if result.line_no >= 0 else 0, character=0, ), ), ), message=err.message, ) for err in result.errors ], ) if result.is_deprecated: self.append_diagnostics( range=kw_range, message=f"Keyword '{result.name}' is deprecated" f"{f': {result.deprecated_message}' if result.deprecated_message else ''}.", severity=DiagnosticSeverity.HINT, tags=[DiagnosticTag.DEPRECATED], code="DeprecatedKeyword", ) if result.is_error_handler: self.append_diagnostics( range=kw_range, message=f"Keyword definition contains errors: {result.error_handler_message}", severity=DiagnosticSeverity.ERROR, code="KeywordContainsErrors", ) if result.is_reserved(): self.append_diagnostics( range=kw_range, message=f"'{result.name}' is a reserved keyword.", severity=DiagnosticSeverity.ERROR, code="ReservedKeyword", ) if get_robot_version() >= (6, 0) and result.is_resource_keyword and result.is_private(): if self.namespace.source != result.source: self.append_diagnostics( range=kw_range, message=f"Keyword '{result.longname}' is private and should only be called by" f" keywords in the same file.", severity=DiagnosticSeverity.WARNING, code="PrivateKeyword", ) if not isinstance(node, (Template, TestTemplate)): try: if result.arguments_spec is not None: result.arguments_spec.resolve( [v.value for v in argument_tokens], None, resolve_variables_until=result.args_to_process, resolve_named=not result.is_any_run_keyword(), ) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException as e: self.append_diagnostics( range=Range( start=kw_range.start, end=range_from_token(argument_tokens[-1]).end if argument_tokens else kw_range.end, ), message=str(e), severity=DiagnosticSeverity.ERROR, code=type(e).__qualname__, ) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException as e: self.append_diagnostics( range=range_from_node_or_token(node, keyword_token), message=str(e), severity=DiagnosticSeverity.ERROR, code=type(e).__qualname__, ) if self.namespace.document is not None and result is not None: if result.longname in [ "BuiltIn.Evaluate", "BuiltIn.Should Be True", "BuiltIn.Should Not Be True", "BuiltIn.Skip If", "BuiltIn.Continue For Loop If", "BuiltIn.Exit For Loop If", "BuiltIn.Return From Keyword If", "BuiltIn.Run Keyword And Return If", "BuiltIn.Pass Execution If", "BuiltIn.Run Keyword If", "BuiltIn.Run Keyword Unless", ]: tokens = argument_tokens if tokens and (token := tokens[0]): async for var_token, var in self.iter_expression_variables_from_token( token, self.namespace, self.node_stack, range_from_token(token).start, skip_commandline_variables=False, return_not_found=True, ): if isinstance(var, VariableNotFoundDefinition): self.append_diagnostics( range=range_from_token(var_token), message=f"Variable '{var.name}' not found.", severity=DiagnosticSeverity.ERROR, code="VariableNotFound", ) else: if self.namespace.document is not None: self._variable_references[var].add( Location(self.namespace.document.document_uri, range_from_token(var_token)) ) if isinstance(var, CommandLineVariableDefinition): suite_var = await self.namespace.find_variable( var.name, skip_commandline_variables=True, ignore_error=True, ) if suite_var is not None and suite_var.type in [VariableDefinitionType.VARIABLE]: self._variable_references[suite_var].add( Location(self.namespace.document.document_uri, range_from_token(var_token)) ) if result.argument_definitions: for arg in argument_tokens: name, value = split_from_equals(arg.value) if value is not None and name: arg_def = next( (e for e in result.argument_definitions if e.name[2:-1] == name), None, ) if arg_def is not None: name_token = RobotToken(RobotToken.ARGUMENT, name, arg.lineno, arg.col_offset) self._variable_references[arg_def].add( Location(self.namespace.document.document_uri, range_from_token(name_token)) ) if result is not None and analyse_run_keywords: await self._analyse_run_keyword(result, node, argument_tokens) return result async def _analyse_run_keyword( self, keyword_doc: Optional[KeywordDoc], node: ast.AST, argument_tokens: List[Token] ) -> List[Token]: from robot.utils.escaping import unescape if keyword_doc is None or not keyword_doc.is_any_run_keyword(): return argument_tokens if keyword_doc.is_run_keyword() and len(argument_tokens) > 0: await self._analyze_keyword_call( unescape(argument_tokens[0].value), node, argument_tokens[0], argument_tokens[1:], allow_variables=True, ignore_errors_if_contains_variables=True, ) return argument_tokens[1:] if keyword_doc.is_run_keyword_with_condition() and len(argument_tokens) > ( cond_count := keyword_doc.run_keyword_condition_count() ): await self._analyze_keyword_call( unescape(argument_tokens[cond_count].value), node, argument_tokens[cond_count], argument_tokens[cond_count + 1 :], allow_variables=True, ignore_errors_if_contains_variables=True, ) return argument_tokens[cond_count + 1 :] if keyword_doc.is_run_keywords(): has_and = False while argument_tokens: t = argument_tokens[0] argument_tokens = argument_tokens[1:] if t.value == "AND": self.append_diagnostics( range=range_from_token(t), message=f"Incorrect use of {t.value}.", severity=DiagnosticSeverity.ERROR, code="IncorrectUse", ) continue and_token = next((e for e in argument_tokens if e.value == "AND"), None) args = [] if and_token is not None: args = argument_tokens[: argument_tokens.index(and_token)] argument_tokens = argument_tokens[argument_tokens.index(and_token) + 1 :] has_and = True elif has_and: args = argument_tokens argument_tokens = [] await self._analyze_keyword_call( unescape(t.value), node, t, args, allow_variables=True, ignore_errors_if_contains_variables=True, ) return [] if keyword_doc.is_run_keyword_if() and len(argument_tokens) > 1: def skip_args() -> List[Token]: nonlocal argument_tokens result = [] while argument_tokens: if argument_tokens[0].value in ["ELSE", "ELSE IF"]: break if argument_tokens: result.append(argument_tokens[0]) argument_tokens = argument_tokens[1:] return result result = self.finder.find_keyword(argument_tokens[1].value) if result is not None and result.is_any_run_keyword(): argument_tokens = argument_tokens[2:] argument_tokens = await self._analyse_run_keyword(result, node, argument_tokens) else: kwt = argument_tokens[1] argument_tokens = argument_tokens[2:] args = skip_args() await self._analyze_keyword_call( unescape(kwt.value), node, kwt, args, analyse_run_keywords=False, allow_variables=True, ignore_errors_if_contains_variables=True, ) while argument_tokens: if argument_tokens[0].value == "ELSE" and len(argument_tokens) > 1: kwt = argument_tokens[1] argument_tokens = argument_tokens[2:] args = skip_args() result = await self._analyze_keyword_call( unescape(kwt.value), node, kwt, args, analyse_run_keywords=False, ) if result is not None and result.is_any_run_keyword(): argument_tokens = await self._analyse_run_keyword(result, node, argument_tokens) break if argument_tokens[0].value == "ELSE IF" and len(argument_tokens) > 2: kwt = argument_tokens[2] argument_tokens = argument_tokens[3:] args = skip_args() result = await self._analyze_keyword_call( unescape(kwt.value), node, kwt, args, analyse_run_keywords=False, ) if result is not None and result.is_any_run_keyword(): argument_tokens = await self._analyse_run_keyword(result, node, argument_tokens) else: break return argument_tokens async def visit_Fixture(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Fixture value = cast(Fixture, node) keyword_token = cast(Token, value.get_token(RobotToken.NAME)) # TODO: calculate possible variables in NAME if ( keyword_token is not None and keyword_token.value is not None and keyword_token.value.upper() not in ("", "NONE") ): await self._analyze_keyword_call( value.name, value, keyword_token, [cast(Token, e) for e in value.get_tokens(RobotToken.ARGUMENT)], allow_variables=True, ignore_errors_if_contains_variables=True, ) await self.generic_visit(node) async def visit_TestTemplate(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import TestTemplate value = cast(TestTemplate, node) keyword_token = cast(Token, value.get_token(RobotToken.NAME)) if keyword_token is not None and keyword_token.value.upper() not in ("", "NONE"): await self._analyze_keyword_call( value.value, value, keyword_token, [], analyse_run_keywords=False, allow_variables=True ) self.test_template = value await self.generic_visit(node) async def visit_Template(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Template value = cast(Template, node) keyword_token = cast(Token, value.get_token(RobotToken.NAME)) if keyword_token is not None and keyword_token.value.upper() not in ("", "NONE"): await self._analyze_keyword_call( value.value, value, keyword_token, [], analyse_run_keywords=False, allow_variables=True ) self.template = value await self.generic_visit(node) async def visit_KeywordCall(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import KeywordCall value = cast(KeywordCall, node) keyword_token = cast(RobotToken, value.get_token(RobotToken.KEYWORD)) if value.assign and not value.keyword: self.append_diagnostics( range=range_from_node_or_token(value, value.get_token(RobotToken.ASSIGN)), message="Keyword name cannot be empty.", severity=DiagnosticSeverity.ERROR, code="KeywordNameEmpty", ) else: await self._analyze_keyword_call( value.keyword, value, keyword_token, [cast(Token, e) for e in value.get_tokens(RobotToken.ARGUMENT)] ) if not self.current_testcase_or_keyword_name: self.append_diagnostics( range=range_from_node_or_token(value, value.get_token(RobotToken.ASSIGN)), message="Code is unreachable.", severity=DiagnosticSeverity.HINT, tags=[DiagnosticTag.UNNECESSARY], code="CodeUnreachable", ) await self.generic_visit(node) async def visit_TestCase(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.blocks import TestCase from robot.parsing.model.statements import TestCaseName testcase = cast(TestCase, node) if not testcase.name: name_token = cast(TestCaseName, testcase.header).get_token(RobotToken.TESTCASE_NAME) self.append_diagnostics( range=range_from_node_or_token(testcase, name_token), message="Test case name cannot be empty.", severity=DiagnosticSeverity.ERROR, code="TestCaseNameEmpty", ) self.current_testcase_or_keyword_name = testcase.name try: await self.generic_visit(node) finally: self.current_testcase_or_keyword_name = None self.template = None async def visit_Keyword(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.blocks import Keyword from robot.parsing.model.statements import Arguments, KeywordName keyword = cast(Keyword, node) if keyword.name: name_token = cast(KeywordName, keyword.header).get_token(RobotToken.KEYWORD_NAME) kw_doc = self.get_keyword_definition_at_token(await self.namespace.get_library_doc(), name_token) if kw_doc is not None and kw_doc not in self._keyword_references: self._keyword_references[kw_doc] = set() if ( get_robot_version() < (6, 1) and is_embedded_keyword(keyword.name) and any(isinstance(v, Arguments) and len(v.values) > 0 for v in keyword.body) ): self.append_diagnostics( range=range_from_node_or_token(keyword, name_token), message="Keyword cannot have both normal and embedded arguments.", severity=DiagnosticSeverity.ERROR, code="KeywordNormalAndEmbbededError", ) else: name_token = cast(KeywordName, keyword.header).get_token(RobotToken.KEYWORD_NAME) self.append_diagnostics( range=range_from_node_or_token(keyword, name_token), message="Keyword name cannot be empty.", severity=DiagnosticSeverity.ERROR, code="KeywordNameEmpty", ) self.current_testcase_or_keyword_name = keyword.name try: await self.generic_visit(node) finally: self.current_testcase_or_keyword_name = None def _format_template(self, template: str, arguments: Tuple[str, ...]) -> Tuple[str, Tuple[str, ...]]: from robot.variables import VariableIterator variables = VariableIterator(template, identifiers="$") count = len(variables) if count == 0 or count != len(arguments): return template, arguments temp = [] for (before, _, after), arg in zip(variables, arguments): temp.extend([before, arg]) temp.append(after) return "".join(temp), () async def visit_TemplateArguments(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import TemplateArguments arguments = cast(TemplateArguments, node) template = self.template or self.test_template if template is not None and template.value is not None and template.value.upper() not in ("", "NONE"): argument_tokens = arguments.get_tokens(RobotToken.ARGUMENT) args = tuple(t.value for t in argument_tokens) keyword = template.value keyword, args = self._format_template(keyword, args) result = self.finder.find_keyword(keyword) if result is not None: try: if result.arguments_spec is not None: result.arguments_spec.resolve( args, None, resolve_variables_until=result.args_to_process, resolve_named=not result.is_any_run_keyword(), ) except (asyncio.CancelledError, SystemExit, KeyboardInterrupt): raise except BaseException as e: self.append_diagnostics( range=range_from_node(arguments, skip_non_data=True), message=str(e), severity=DiagnosticSeverity.ERROR, code=type(e).__qualname__, ) for d in self.finder.diagnostics: self.append_diagnostics( range=range_from_node(arguments, skip_non_data=True), message=d.message, severity=d.severity, code=d.code, ) await self.generic_visit(node) async def visit_ForceTags(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import ForceTags if get_robot_version() >= (6, 0): tag = cast(ForceTags, node).get_token(RobotToken.FORCE_TAGS) if tag.value.upper() == "FORCE TAGS": self.append_diagnostics( range=range_from_node_or_token(node, tag), message="`Force Tags` is deprecated in favour of new `Test Tags` setting.", severity=DiagnosticSeverity.INFORMATION, tags=[DiagnosticTag.DEPRECATED], code="DeprecatedHyphenTag", ) async def visit_DefaultTags(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import ForceTags if get_robot_version() >= (6, 0): tag = cast(ForceTags, node).get_token(RobotToken.DEFAULT_TAGS) self.append_diagnostics( range=range_from_node_or_token(node, tag), message="`Force Tags` is deprecated in favour of new `Test Tags` setting.", severity=DiagnosticSeverity.INFORMATION, tags=[DiagnosticTag.DEPRECATED], code="DeprecatedHyphenTag", ) async def visit_Tags(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import Tags if get_robot_version() >= (6, 0): tags = cast(Tags, node) for tag in tags.get_tokens(RobotToken.ARGUMENT): if tag.value and tag.value.startswith("-"): self.append_diagnostics( range=range_from_node_or_token(node, tag), message=f"Settings tags starting with a hyphen using the '[Tags]' setting " f"is deprecated. In Robot Framework 7.0 this syntax will be used " f"for removing tags. Escape '{tag.value}' like '\\{tag.value}' to use the " f"literal value and to avoid this warning.", severity=DiagnosticSeverity.WARNING, tags=[DiagnosticTag.DEPRECATED], code="DeprecatedHyphenTag", ) def _check_import_name(self, value: Optional[str], node: ast.AST, type: str) -> None: if not value: self.append_diagnostics( range=range_from_node(node), message=f"{type} setting requires value.", severity=DiagnosticSeverity.ERROR, code="ImportRequiresValue", ) async def visit_VariablesImport(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import VariablesImport if get_robot_version() >= (6, 1): import_node = cast(VariablesImport, node) self._check_import_name(import_node.name, node, "Variables") n = cast(VariablesImport, node) name_token = cast(RobotToken, n.get_token(RobotToken.NAME)) if name_token is None: return entries = await self.namespace.get_import_entries() if entries and self.namespace.document: for v in entries.values(): if v.import_source == self.namespace.source and v.import_range == range_from_token(name_token): if v not in self._namespace_references: self._namespace_references[v] = set() async def visit_ResourceImport(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import ResourceImport if get_robot_version() >= (6, 1): import_node = cast(ResourceImport, node) self._check_import_name(import_node.name, node, "Resource") n = cast(ResourceImport, node) name_token = cast(RobotToken, n.get_token(RobotToken.NAME)) if name_token is None: return entries = await self.namespace.get_import_entries() if entries and self.namespace.document: for v in entries.values(): if v.import_source == self.namespace.source and v.import_range == range_from_token(name_token): if v not in self._namespace_references: self._namespace_references[v] = set() async def visit_LibraryImport(self, node: ast.AST) -> None: # noqa: N802 from robot.parsing.lexer.tokens import Token as RobotToken from robot.parsing.model.statements import LibraryImport if get_robot_version() >= (6, 1): import_node = cast(LibraryImport, node) self._check_import_name(import_node.name, node, "Library") n = cast(LibraryImport, node) name_token = cast(RobotToken, n.get_token(RobotToken.NAME)) if name_token is None: return entries = await self.namespace.get_import_entries() if entries and self.namespace.document: for v in entries.values(): if v.import_source == self.namespace.source and v.import_range == range_from_token(name_token): if v not in self._namespace_references: self._namespace_references[v] = set()
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/diagnostics/analyzer.py
0.745028
0.18352
analyzer.py
pypi
from __future__ import annotations import ast import itertools from typing import ( Any, AsyncIterator, Iterator, List, Optional, Protocol, Set, Tuple, cast, runtime_checkable, ) from robotcode.core.lsp.types import Position, Range from . import async_ast def iter_nodes(node: ast.AST) -> Iterator[ast.AST]: for _field, value in ast.iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, ast.AST): yield item yield from iter_nodes(item) elif isinstance(value, ast.AST): yield value yield from iter_nodes(value) @runtime_checkable class Token(Protocol): type: Optional[str] value: str lineno: int col_offset: int error: Optional[str] @property def end_col_offset(self) -> int: ... def tokenize_variables(self) -> Iterator[Token]: ... @runtime_checkable class HasTokens(Protocol): tokens: Tuple[Token, ...] @runtime_checkable class HasError(Protocol): error: Optional[str] @runtime_checkable class HasErrors(Protocol): errors: Optional[List[str]] @runtime_checkable class Statement(HasTokens, Protocol): def get_token(self, type: str) -> Optional[Token]: ... def get_tokens(self, *types: str) -> Tuple[Token, ...]: ... def get_value(self, type: str, default: Any = None) -> Any: ... def get_values(self, *types: str) -> Tuple[Any, ...]: ... @property def lineno(self) -> int: ... @property def col_offset(self) -> int: ... @property def end_lineno(self) -> int: ... @property def end_col_offset(self) -> int: ... @runtime_checkable class HeaderAndBodyBlock(Protocol): header: Any body: List[Any] def range_from_token(token: Token) -> Range: return Range( start=Position(line=token.lineno - 1, character=token.col_offset), end=Position( line=token.lineno - 1, character=token.end_col_offset, ), ) def range_from_node(node: ast.AST, skip_non_data: bool = False, only_start: bool = False) -> Range: from robot.parsing.lexer import Token as RobotToken if skip_non_data and isinstance(node, HasTokens) and node.tokens: start_token = next((v for v in node.tokens if v.type not in RobotToken.NON_DATA_TOKENS), None) if only_start and start_token is not None: end_tokens = tuple(t for t in node.tokens if start_token.lineno == t.lineno) else: end_tokens = node.tokens end_token = next((v for v in reversed(end_tokens) if v.type not in RobotToken.NON_DATA_TOKENS), None) if start_token is not None and end_token is not None: return Range(start=range_from_token(start_token).start, end=range_from_token(end_token).end) return Range( start=Position(line=node.lineno - 1, character=node.col_offset), end=Position( line=node.end_lineno - 1 if node.end_lineno is not None else -1, character=node.end_col_offset if node.end_col_offset is not None else -1, ), ) def token_in_range(token: Token, range: Range, include_end: bool = False) -> bool: token_range = range_from_token(token) return token_range.start.is_in_range(range, include_end) or token_range.end.is_in_range(range, include_end) def node_in_range(node: ast.AST, range: Range, include_end: bool = False) -> bool: node_range = range_from_node(node) return node_range.start.is_in_range(range, include_end) or node_range.end.is_in_range(range, include_end) def range_from_node_or_token(node: Optional[ast.AST], token: Optional[Token]) -> Range: if token is not None: return range_from_token(token) if node is not None: return range_from_node(node, True) return Range.zero() def is_not_variable_token(token: Token) -> bool: from robot.errors import VariableError try: r = list(token.tokenize_variables()) if len(r) == 1 and r[0] == token: return True except VariableError: pass return False def whitespace_at_begin_of_token(token: Token) -> int: s = str(token.value) result = 0 for c in s: if c == " ": result += 1 elif c == "\t": result += 2 else: break return result def whitespace_from_begin_of_token(token: Token) -> str: s = str(token.value) result = "" for c in s: if c in [" ", "\t"]: result += c else: break return result def get_tokens_at_position(node: HasTokens, position: Position, include_end: bool = False) -> List[Token]: return [ t for t in node.tokens if position.is_in_range(range := range_from_token(t), include_end) or range.end == position ] def iter_nodes_at_position(node: ast.AST, position: Position, include_end: bool = False) -> AsyncIterator[ast.AST]: return ( n async for n in async_ast.iter_nodes(node) if position.is_in_range(range := range_from_node(n), include_end) or range.end == position ) async def get_nodes_at_position(node: ast.AST, position: Position, include_end: bool = False) -> List[ast.AST]: return [n async for n in iter_nodes_at_position(node, position, include_end)] async def get_node_at_position(node: ast.AST, position: Position, include_end: bool = False) -> Optional[ast.AST]: result_nodes = await get_nodes_at_position(node, position, include_end) if not result_nodes: return None return result_nodes[-1] def _tokenize_no_variables(token: Token) -> Iterator[Token]: yield token def tokenize_variables( token: Token, identifiers: str = "$@&%", ignore_errors: bool = False, *, extra_types: Optional[Set[str]] = None ) -> Iterator[Token]: from robot.api.parsing import Token as RobotToken from robot.variables import VariableIterator if token.type not in { *RobotToken.ALLOW_VARIABLES, RobotToken.KEYWORD, RobotToken.ASSIGN, *(extra_types if extra_types is not None else set()), }: return _tokenize_no_variables(token) value = token.value variables = VariableIterator(value, identifiers=identifiers, ignore_errors=ignore_errors) if not variables: return _tokenize_no_variables(token) return _tokenize_variables(token, variables) def _tokenize_variables(token: Token, variables: Any) -> Iterator[Token]: from robot.api.parsing import Token as RobotToken lineno = token.lineno col_offset = token.col_offset remaining = "" for before, variable, remaining in variables: if before: yield RobotToken(token.type, before, lineno, col_offset) col_offset += len(before) yield RobotToken(RobotToken.VARIABLE, variable, lineno, col_offset) col_offset += len(variable) if remaining: yield RobotToken(token.type, remaining, lineno, col_offset) def iter_over_keyword_names_and_owners(full_name: str) -> Iterator[Tuple[Optional[str], ...]]: yield None, full_name tokens = full_name.split(".") if len(tokens) > 1: for i in range(1, len(tokens)): yield ".".join(tokens[:i]), ".".join(tokens[i:]) def strip_variable_token(token: Token) -> Token: from robot.api.parsing import Token as RobotToken if ( token.type == RobotToken.VARIABLE and token.value[:1] in "$@&%" and token.value[1:2] == "{" and token.value[-1:] == "}" ): value = token.value[2:-1] stripped_value = value.lstrip() stripped_offset = len(value) - len(stripped_value) return cast( Token, RobotToken(token.type, stripped_value.rstrip(), token.lineno, token.col_offset + 2 + stripped_offset) ) return token def get_variable_token(token: Token) -> Optional[Token]: from robot.parsing.lexer.tokens import Token as RobotToken return next( ( v for v in itertools.dropwhile( lambda t: t.type in RobotToken.NON_DATA_TOKENS, tokenize_variables(token, ignore_errors=True), ) if v.type == RobotToken.VARIABLE ), None, )
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/utils/ast_utils.py
0.856197
0.352285
ast_utils.py
pypi
import ast from typing import Any, AsyncIterator, Callable, Iterator, Optional, Type, cast __all__ = ["iter_fields", "iter_child_nodes", "AsyncVisitor"] def iter_fields(node: ast.AST) -> Iterator[Any]: """ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass def iter_child_nodes(node: ast.AST) -> Iterator[ast.AST]: """ Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ for _name, field in iter_fields(node): if isinstance(field, ast.AST): yield field elif isinstance(field, list): for item in field: if isinstance(item, ast.AST): yield item async def iter_nodes(node: ast.AST) -> AsyncIterator[ast.AST]: for _name, value in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, ast.AST): yield item async for n in iter_nodes(item): yield n elif isinstance(value, ast.AST): yield value async for n in iter_nodes(value): yield n class VisitorFinder: def _find_visitor(self, cls: Type[Any]) -> Optional[Callable[..., Any]]: if cls is ast.AST: return None method_name = "visit_" + cls.__name__ if hasattr(self, method_name): method = getattr(self, method_name) if callable(method): return cast("Callable[..., Any]", method) for base in cls.__bases__: method = self._find_visitor(base) if method: return cast("Callable[..., Any]", method) return None class AsyncVisitor(VisitorFinder): async def visit(self, node: ast.AST) -> None: visitor = self._find_visitor(type(node)) or self.generic_visit await visitor(node) async def generic_visit(self, node: ast.AST) -> None: """Called if no explicit visitor function exists for a node.""" for _, value in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, ast.AST): await self.visit(item) elif isinstance(value, ast.AST): await self.visit(value) class Visitor(VisitorFinder): def visit(self, node: ast.AST) -> None: visitor = self._find_visitor(type(node)) or self.generic_visit visitor(node) def generic_visit(self, node: ast.AST) -> None: """Called if no explicit visitor function exists for a node.""" for field, value in iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, ast.AST): self.visit(item) elif isinstance(value, ast.AST): self.visit(value)
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/robotframework/utils/async_ast.py
0.823931
0.305186
async_ast.py
pypi
from typing import Any, Callable, List, Protocol, TypeVar, Union, runtime_checkable from .text_document import TextDocument _F = TypeVar("_F", bound=Callable[..., Any]) LANGUAGE_ID_ATTR = "__language_id__" def language_id(id: str, *ids: str) -> Callable[[_F], _F]: def decorator(func: _F) -> _F: setattr(func, LANGUAGE_ID_ATTR, {id, *ids}) return func return decorator TRIGGER_CHARACTERS_ATTR = "__trigger_characters__" def trigger_characters(characters: List[str]) -> Callable[[_F], _F]: def decorator(func: _F) -> _F: setattr(func, TRIGGER_CHARACTERS_ATTR, characters) return func return decorator @runtime_checkable class HasTriggerCharacters(Protocol): __trigger_characters__: List[str] RETRIGGER_CHARACTERS_ATTR = "__retrigger_characters__" @runtime_checkable class HasRetriggerCharacters(Protocol): __retrigger_characters__: str def retrigger_characters(characters: List[str]) -> Callable[[_F], _F]: def decorator(func: _F) -> _F: setattr(func, RETRIGGER_CHARACTERS_ATTR, characters) return func return decorator ALL_COMMIT_CHARACTERS_ATTR = "__all_commit_characters__" def all_commit_characters(characters: List[str]) -> Callable[[_F], _F]: def decorator(func: _F) -> _F: setattr(func, ALL_COMMIT_CHARACTERS_ATTR, characters) return func return decorator @runtime_checkable class HasAllCommitCharacters(Protocol): __all_commit_characters__: List[str] CODE_ACTION_KINDS_ATTR = "__code_action_kinds__" def code_action_kinds(characters: List[str]) -> Callable[[_F], _F]: def decorator(func: _F) -> _F: setattr(func, CODE_ACTION_KINDS_ATTR, characters) return func return decorator @runtime_checkable class HasCodeActionKinds(Protocol): __code_action_kinds__: List[str] def language_id_filter(language_id_or_document: Union[str, TextDocument]) -> Callable[[Any], bool]: def filter(c: Any) -> bool: return not hasattr(c, LANGUAGE_ID_ATTR) or ( ( language_id_or_document.language_id if isinstance(language_id_or_document, TextDocument) else language_id_or_document ) in getattr(c, LANGUAGE_ID_ATTR) ) return filter COMMAND_NAME_ATTR = "__command_name__" def command(name: str) -> Callable[[_F], _F]: def decorator(func: _F) -> _F: setattr(func, COMMAND_NAME_ATTR, name) return func return decorator def is_command(func: Callable[..., Any]) -> bool: return hasattr(func, COMMAND_NAME_ATTR) def get_command_name(func: Callable[..., Any]) -> str: if hasattr(func, COMMAND_NAME_ATTR): return str(getattr(func, COMMAND_NAME_ATTR)) raise TypeError(f"{func} is not a command.")
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/decorators.py
0.797714
0.176583
decorators.py
pypi
from __future__ import annotations import collections import inspect import io import threading import weakref from typing import Any, Awaitable, Callable, Dict, Final, List, Optional, TypeVar, Union, cast from robotcode.core.async_tools import async_event, create_sub_task from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import DocumentUri, Position, Range from robotcode.core.uri import Uri def is_multibyte_char(char: str) -> bool: return ord(char) > 0xFFFF def position_from_utf16(lines: List[str], position: Position) -> Position: if position.line >= len(lines): return position utf32_offset = 0 utf16_counter = 0 for c in lines[position.line]: utf16_counter += 2 if is_multibyte_char(c) else 1 if utf16_counter > position.character: break utf32_offset += 1 return Position(line=position.line, character=utf32_offset) def position_to_utf16(lines: List[str], position: Position) -> Position: if position.line >= len(lines): return position utf16_counter = 0 for i, c in enumerate(lines[position.line]): if i >= position.character: break utf16_counter += 2 if is_multibyte_char(c) else 1 return Position(line=position.line, character=utf16_counter) def range_from_utf16(lines: List[str], range: Range) -> Range: return Range(start=position_from_utf16(lines, range.start), end=position_from_utf16(lines, range.end)) def range_to_utf16(lines: List[str], range: Range) -> Range: return Range(start=position_to_utf16(lines, range.start), end=position_to_utf16(lines, range.end)) class InvalidRangeError(Exception): pass _T = TypeVar("_T") class CacheEntry: def __init__(self) -> None: self.data: Any = None self.has_data: bool = False self.lock = threading.RLock() class TextDocument: _logger: Final = LoggingDescriptor() def __init__( self, document_uri: DocumentUri, text: str, language_id: Optional[str] = None, version: Optional[int] = None, ) -> None: super().__init__() self._lock = threading.RLock() self.document_uri = document_uri self.uri = Uri(self.document_uri).normalized() self.language_id = language_id self._version = version self._text = text self._orig_text = text self._orig_version = version self._lines: Optional[List[str]] = None self._cache: Dict[weakref.ref[Any], CacheEntry] = collections.defaultdict(CacheEntry) self._data: weakref.WeakKeyDictionary[Any, Any] = weakref.WeakKeyDictionary() self.opened_in_editor = False @property def version(self) -> Optional[int]: return self._version @version.setter def version(self, value: Optional[int]) -> None: self._version = value def __str__(self) -> str: # pragma: no cover return self.__repr__() def __repr__(self) -> str: # pragma: no cover return f"TextDocument(uri={self.uri!r}, language_id={self.language_id!r}, version={self._version!r})" def text(self) -> str: with self._lock: return self._text def save(self, version: Optional[int], text: Optional[str]) -> None: self.apply_full_change(version, text, save=True) def revert(self, version: Optional[int]) -> bool: if self._orig_text != self._text or self._orig_version != self._version: self.apply_full_change(version or self._orig_version, self._orig_text) return True return False @_logger.call def apply_none_change(self) -> None: with self._lock: self._lines = None self._invalidate_cache() @_logger.call def apply_full_change(self, version: Optional[int], text: Optional[str], *, save: bool = False) -> None: with self._lock: if version is not None: self._version = version if text is not None: self._text = text self._lines = None if save: self._orig_text = self._text self._invalidate_cache() @_logger.call def apply_incremental_change(self, version: Optional[int], range: Range, text: str) -> None: with self._lock: try: if version is not None: self._version = version if range.start > range.end: raise InvalidRangeError(f"Start position is greater then end position {range}.") lines = self.__get_lines() (start_line, start_col), (end_line, end_col) = range_from_utf16(lines, range) if start_line == len(lines): self._text = self._text + text return with io.StringIO() as new_text: for i, line in enumerate(lines): if i < start_line or i > end_line: new_text.write(line) continue if i == start_line: new_text.write(line[:start_col]) new_text.write(text) if i == end_line: new_text.write(line[end_col:]) self._text = new_text.getvalue() finally: self._lines = None self._invalidate_cache() def __get_lines(self) -> List[str]: if self._lines is None: self._lines = self._text.splitlines(True) return self._lines def get_lines(self) -> List[str]: with self._lock: if self._lines is None: return self.__get_lines() return self._lines @async_event async def cache_invalidate(sender) -> None: # NOSONAR ... @async_event async def cache_invalidated(sender) -> None: # NOSONAR ... def _invalidate_cache(self) -> None: create_sub_task(self.cache_invalidate(self)) self._cache.clear() create_sub_task(self.cache_invalidated(self)) def invalidate_cache(self) -> None: with self._lock: self._invalidate_cache() def _invalidate_data(self) -> None: self._data.clear() def invalidate_data(self) -> None: with self._lock: self._invalidate_data() def __remove_cache_entry(self, ref: Any) -> None: with self._lock: if ref in self._cache: self._cache.pop(ref) def __get_cache_reference(self, entry: Callable[..., Any], /, *, add_remove: bool = True) -> weakref.ref[Any]: if inspect.ismethod(entry): return weakref.WeakMethod(entry, self.__remove_cache_entry if add_remove else None) return weakref.ref(entry, self.__remove_cache_entry if add_remove else None) def get_cache_value( self, entry: Union[Callable[[TextDocument], Awaitable[_T]], Callable[..., Awaitable[_T]]], ) -> Optional[_T]: reference = self.__get_cache_reference(entry) e = self._cache.get(reference, None) if e is None: return None return cast(Optional[_T], e.data) def get_cache_sync( self, entry: Union[Callable[[TextDocument], _T], Callable[..., _T]], *args: Any, **kwargs: Any, ) -> _T: reference = self.__get_cache_reference(entry) e = self._cache[reference] with e.lock: if not e.has_data: e.data = entry(self, *args, **kwargs) e.has_data = True return cast(_T, e.data) async def get_cache( self, entry: Union[Callable[[TextDocument], Awaitable[_T]], Callable[..., Awaitable[_T]]], *args: Any, **kwargs: Any, ) -> _T: reference = self.__get_cache_reference(entry) e = self._cache[reference] with e.lock: if not e.has_data: e.data = await entry(self, *args, **kwargs) e.has_data = True return cast(_T, e.data) async def remove_cache_entry( self, entry: Union[Callable[[TextDocument], Awaitable[_T]], Callable[..., Awaitable[_T]]] ) -> None: self.__remove_cache_entry(self.__get_cache_reference(entry, add_remove=False)) def set_data(self, key: Any, data: Any) -> None: self._data[key] = data def remove_data(self, key: Any) -> None: try: self._data.pop(key) except KeyError: pass def get_data(self, key: Any, default: Optional[_T] = None) -> _T: return self._data.get(key, default) def _clear(self) -> None: self._lines = None self._invalidate_cache() self._invalidate_data() @_logger.call def clear(self) -> None: with self._lock: self._clear() def position_from_utf16(self, position: Position) -> Position: return position_from_utf16(self.get_lines(), position) def position_to_utf16(self, position: Position) -> Position: return position_to_utf16(self.get_lines(), position) def range_from_utf16(self, range: Range) -> Range: return range_from_utf16(self.get_lines(), range) def range_to_utf16(self, range: Range) -> Range: return range_to_utf16(self.get_lines(), range)
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/text_document.py
0.782372
0.204084
text_document.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( LinkedEditingRangeOptions, LinkedEditingRangeParams, LinkedEditingRanges, Position, Range, ServerCapabilities, TextDocumentIdentifier, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import ( HasExtendCapabilities, ) from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol from .protocol_part import LanguageServerProtocolPart class LinkedEditingRangeProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if len(self.collect): capabilities.linked_editing_range_provider = LinkedEditingRangeOptions(work_done_progress=True) @async_tasking_event async def collect(sender, document: TextDocument, position: Position) -> Optional[LinkedEditingRanges]: # NOSONAR ... @rpc_method(name="textDocument/linkedEditingRange", param_type=LinkedEditingRangeParams) @threaded() async def _text_document_linked_editing_range( self, text_document: TextDocumentIdentifier, position: Position, *args: Any, **kwargs: Any, ) -> Optional[LinkedEditingRanges]: linked_ranges: List[Range] = [] word_pattern: Optional[str] = None document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect( self, document, document.position_from_utf16(position), callback_filter=language_id_filter(document) ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: linked_ranges.extend(result.ranges) if result.word_pattern is not None: word_pattern = result.word_pattern return LinkedEditingRanges([document.range_to_utf16(r) for r in linked_ranges], word_pattern)
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/linked_editing_ranges.py
0.897937
0.175892
linked_editing_ranges.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional, Union from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( ImplementationParams, Location, LocationLink, Position, ServerCapabilities, TextDocumentIdentifier, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import HasExtendCapabilities from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol from .protocol_part import LanguageServerProtocolPart class ImplementationProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) self.link_support = False @async_tasking_event async def collect( sender, document: TextDocument, position: Position # NOSONAR ) -> Union[Location, List[Location], List[LocationLink], None]: ... def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if ( self.parent.client_capabilities is not None and self.parent.client_capabilities.text_document is not None and self.parent.client_capabilities.text_document.implementation ): self.link_support = self.parent.client_capabilities.text_document.implementation.link_support or False if len(self.collect): capabilities.implementation_provider = True @rpc_method(name="textDocument/implementation", param_type=ImplementationParams) @threaded() async def _text_document_implementation( self, text_document: TextDocumentIdentifier, position: Position, *args: Any, **kwargs: Any ) -> Optional[Union[Location, List[Location], List[LocationLink]]]: locations: List[Location] = [] location_links: List[LocationLink] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect( self, document, position, callback_filter=language_id_filter(document), ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: if isinstance(result, Location): locations.append(result) else: for e in result: if isinstance(e, Location): locations.append(e) elif isinstance(e, LocationLink): location_links.append(e) if len(locations) == 0 and len(location_links) == 0: return None if locations: for location in locations: doc = await self.parent.documents.get(location.uri) if doc is not None: location.range = doc.range_to_utf16(location.range) if location_links: for location_link in location_links: doc = await self.parent.documents.get(location_link.target_uri) if doc is not None: location_link.target_range = doc.range_to_utf16(location_link.target_range) location_link.target_selection_range = doc.range_to_utf16(location_link.target_selection_range) if location_link.origin_selection_range is not None: location_link.origin_selection_range = document.range_to_utf16(location_link.origin_selection_range) if len(locations) > 0 and len(location_links) == 0: if len(locations) == 1: return locations[0] return locations if len(locations) > 0 and len(location_links) > 0: self._logger.warning("can't mix Locations and LocationLinks") if self.link_support: return location_links self._logger.warning("client has no link_support capability, convert LocationLinks to Location") return [Location(uri=e.target_uri, range=e.target_range) for e in location_links]
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/implementation.py
0.863406
0.177205
implementation.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional, Union from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( DefinitionParams, Location, LocationLink, Position, ServerCapabilities, TextDocumentIdentifier, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import HasExtendCapabilities from robotcode.language_server.common.parts.protocol_part import LanguageServerProtocolPart from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol class DefinitionProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) self.link_support = False @async_tasking_event async def collect( sender, document: TextDocument, position: Position # NOSONAR ) -> Union[Location, List[Location], List[LocationLink], None]: ... def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if ( self.parent.client_capabilities is not None and self.parent.client_capabilities.text_document is not None and self.parent.client_capabilities.text_document.definition ): self.link_support = self.parent.client_capabilities.text_document.definition.link_support or False if len(self.collect): capabilities.definition_provider = True @rpc_method(name="textDocument/definition", param_type=DefinitionParams) @threaded() async def _text_document_definition( self, text_document: TextDocumentIdentifier, position: Position, *args: Any, **kwargs: Any ) -> Optional[Union[Location, List[Location], List[LocationLink]]]: locations: List[Location] = [] location_links: List[LocationLink] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect( self, document, document.position_from_utf16(position), callback_filter=language_id_filter(document) ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: if isinstance(result, Location): locations.append(result) else: for e in result: if isinstance(e, Location): locations.append(e) elif isinstance(e, LocationLink): location_links.append(e) if len(locations) == 0 and len(location_links) == 0: return None if locations: for location in locations: doc = await self.parent.documents.get(location.uri) if doc is not None: location.range = doc.range_to_utf16(location.range) if location_links: for location_link in location_links: doc = await self.parent.documents.get(location_link.target_uri) if doc is not None: location_link.target_range = doc.range_to_utf16(location_link.target_range) location_link.target_selection_range = doc.range_to_utf16(location_link.target_selection_range) if location_link.origin_selection_range is not None: location_link.origin_selection_range = document.range_to_utf16(location_link.origin_selection_range) if len(locations) > 0 and len(location_links) == 0: if len(locations) == 1: return locations[0] return locations if len(locations) > 0 and len(location_links) > 0: self._logger.warning("can't mix Locations and LocationLinks") if self.link_support: return location_links self._logger.warning("client has no link_support capability, convert LocationLinks to Location") return [Location(uri=e.target_uri, range=e.target_range) for e in location_links]
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/definition.py
0.865679
0.179531
definition.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional, Union from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( DeclarationParams, Location, LocationLink, Position, ServerCapabilities, TextDocumentIdentifier, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import ( HasExtendCapabilities, ) from robotcode.language_server.common.parts.protocol_part import LanguageServerProtocolPart from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol class DeclarationProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) self.link_support = False @async_tasking_event async def collect( sender, document: TextDocument, position: Position # NOSONAR ) -> Union[Location, List[Location], List[LocationLink], None]: ... def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if ( self.parent.client_capabilities is not None and self.parent.client_capabilities.text_document is not None and self.parent.client_capabilities.text_document.declaration ): self.link_support = self.parent.client_capabilities.text_document.declaration.link_support or False if len(self.collect): capabilities.declaration_provider = True @rpc_method(name="textDocument/declaration", param_type=DeclarationParams) @threaded() async def _text_document_declaration( self, text_document: TextDocumentIdentifier, position: Position, *args: Any, **kwargs: Any, ) -> Optional[Union[Location, List[Location], List[LocationLink]]]: locations: List[Location] = [] location_links: List[LocationLink] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect(self, document, position, callback_filter=language_id_filter(document)): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: if isinstance(result, Location): locations.append(result) else: for e in result: if isinstance(e, Location): locations.append(e) elif isinstance(e, LocationLink): location_links.append(e) if len(locations) == 0 and len(location_links) == 0: return None if locations: for location in locations: doc = await self.parent.documents.get(location.uri) if doc is not None: location.range = doc.range_to_utf16(location.range) if location_links: for location_link in location_links: doc = await self.parent.documents.get(location_link.target_uri) if doc is not None: location_link.target_range = doc.range_to_utf16(location_link.target_range) location_link.target_selection_range = doc.range_to_utf16(location_link.target_selection_range) if location_link.origin_selection_range is not None: location_link.origin_selection_range = document.range_to_utf16(location_link.origin_selection_range) if len(locations) > 0 and len(location_links) == 0: if len(locations) == 1: return locations[0] return locations if len(locations) > 0 and len(location_links) > 0: self._logger.warning("can't mix Locations and LocationLinks") if self.link_support: return location_links self._logger.warning("client has no link_support capability, convert LocationLinks to Location") return [Location(uri=e.target_uri, range=e.target_range) for e in location_links]
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/declaration.py
0.857783
0.181082
declaration.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( Position, SelectionRange, SelectionRangeOptions, SelectionRangeParams, ServerCapabilities, TextDocumentIdentifier, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import HasExtendCapabilities from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol from .protocol_part import LanguageServerProtocolPart class SelectionRangeProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if len(self.collect): capabilities.selection_range_provider = SelectionRangeOptions(work_done_progress=True) @async_tasking_event async def collect( sender, document: TextDocument, positions: List[Position] # NOSONAR ) -> Optional[List[SelectionRange]]: ... @rpc_method(name="textDocument/selectionRange", param_type=SelectionRangeParams) @threaded() async def _text_document_selection_range( self, text_document: TextDocumentIdentifier, positions: List[Position], *args: Any, **kwargs: Any, ) -> Optional[List[SelectionRange]]: results: List[SelectionRange] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect( self, document, [document.position_from_utf16(p) for p in positions], callback_filter=language_id_filter(document), ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: results.extend(result) if not results: return None def traverse(selection_range: SelectionRange, doc: TextDocument) -> None: selection_range.range = doc.range_to_utf16(selection_range.range) if selection_range.parent is not None: traverse(selection_range.parent, doc) for result in results: traverse(result, document) return results
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/selection_range.py
0.902983
0.191725
selection_range.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( DocumentFormattingOptions, DocumentFormattingParams, DocumentRangeFormattingOptions, DocumentRangeFormattingParams, FormattingOptions, ProgressToken, Range, ServerCapabilities, TextDocumentIdentifier, TextEdit, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import ( HasExtendCapabilities, ) from robotcode.language_server.common.parts.protocol_part import ( LanguageServerProtocolPart, ) from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol class FormattingProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) @async_tasking_event async def format( sender, document: TextDocument, options: FormattingOptions, **further_options: Any, # NOSONAR ) -> Optional[List[TextEdit]]: ... @async_tasking_event async def format_range( sender, document: TextDocument, range: Range, options: FormattingOptions, **further_options: Any, # NOSONAR ) -> Optional[List[TextEdit]]: ... def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if len(self.format): capabilities.document_formatting_provider = DocumentFormattingOptions(work_done_progress=True) if len(self.format_range): capabilities.document_range_formatting_provider = DocumentRangeFormattingOptions(work_done_progress=True) @rpc_method(name="textDocument/formatting", param_type=DocumentFormattingParams) @threaded() async def _text_document_formatting( self, params: DocumentFormattingParams, text_document: TextDocumentIdentifier, options: FormattingOptions, work_done_token: Optional[ProgressToken], *args: Any, **kwargs: Any, ) -> Optional[List[TextEdit]]: results: List[TextEdit] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.format( self, document, options, callback_filter=language_id_filter(document), **kwargs, ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: results += result if len(results) > 0: return results return None @rpc_method(name="textDocument/rangeFormatting", param_type=DocumentRangeFormattingParams) @threaded() async def _text_document_range_formatting( self, params: DocumentFormattingParams, text_document: TextDocumentIdentifier, range: Range, options: FormattingOptions, work_done_token: Optional[ProgressToken], *args: Any, **kwargs: Any, ) -> Optional[List[TextEdit]]: results: List[TextEdit] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.format_range( self, document, range, options, callback_filter=language_id_filter(document), **kwargs, ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: results += result if len(results) > 0: return results return None
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/formatting.py
0.87081
0.214054
formatting.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( Location, Position, ReferenceContext, ReferenceOptions, ReferenceParams, ServerCapabilities, TextDocumentIdentifier, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import HasExtendCapabilities from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol from .protocol_part import LanguageServerProtocolPart class ReferencesProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if len(self.collect): capabilities.references_provider = ReferenceOptions(work_done_progress=True) @async_tasking_event async def collect( sender, document: TextDocument, position: Position, context: ReferenceContext # NOSONAR ) -> Optional[List[Location]]: ... @rpc_method(name="textDocument/references", param_type=ReferenceParams) @threaded() async def _text_document_references( self, text_document: TextDocumentIdentifier, position: Position, context: ReferenceContext, *args: Any, **kwargs: Any, ) -> Optional[List[Location]]: await self.parent.diagnostics.ensure_workspace_loaded() locations: List[Location] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect( self, document, document.position_from_utf16(position), context, callback_filter=language_id_filter(document), ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: locations.extend(result) if not locations: return None for location in locations: doc = await self.parent.documents.get(location.uri) if doc is not None: location.range = doc.range_to_utf16(location.range) return locations
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/references.py
0.888879
0.160398
references.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( Hover, HoverOptions, HoverParams, Position, ServerCapabilities, TextDocumentIdentifier, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import ( HasExtendCapabilities, ) from robotcode.language_server.common.parts.protocol_part import ( LanguageServerProtocolPart, ) from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol class HoverProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) @async_tasking_event async def collect(sender, document: TextDocument, position: Position) -> Optional[Hover]: # NOSONAR ... def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if len(self.collect): capabilities.hover_provider = HoverOptions(work_done_progress=True) @rpc_method(name="textDocument/hover", param_type=HoverParams) @threaded() async def _text_document_hover( self, text_document: TextDocumentIdentifier, position: Position, *args: Any, **kwargs: Any, ) -> Optional[Hover]: results: List[Hover] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect( self, document, document.position_from_utf16(position), callback_filter=language_id_filter(document), ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: results.append(result) for result in results: if result.range is not None: result.range = document.range_to_utf16(result.range) if len(results) > 0 and results[-1].contents: # TODO: how can we combine hover results? return results[-1] return None
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/hover.py
0.77949
0.15511
hover.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( ErrorCodes, Position, PrepareRenameParams, PrepareRenameResult, PrepareRenameResultType1, Range, RenameOptions, RenameParams, ServerCapabilities, TextDocumentEdit, TextDocumentIdentifier, WorkspaceEdit, ) from robotcode.jsonrpc2.protocol import JsonRPCErrorException, rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import ( HasExtendCapabilities, ) from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol from .protocol_part import LanguageServerProtocolPart class CantRenameError(Exception): pass class RenameProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if len(self.collect): capabilities.rename_provider = RenameOptions( prepare_provider=len(self.collect_prepare) > 0, work_done_progress=True ) @async_tasking_event async def collect( sender, document: TextDocument, position: Position, new_name: str # NOSONAR ) -> Optional[WorkspaceEdit]: ... @async_tasking_event async def collect_prepare( sender, document: TextDocument, position: Position # NOSONAR ) -> Optional[PrepareRenameResult]: ... @rpc_method(name="textDocument/rename", param_type=RenameParams) @threaded() async def _text_document_rename( self, text_document: TextDocumentIdentifier, position: Position, new_name: str, *args: Any, **kwargs: Any, ) -> Optional[WorkspaceEdit]: edits: List[WorkspaceEdit] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect( self, document, document.position_from_utf16(position), new_name, callback_filter=language_id_filter(document), ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: edits.append(result) if not edits: return None for we in edits: if we.changes: for uri, changes in we.changes.items(): if changes: doc = await self.parent.documents.get(uri) for change in changes: if doc is not None: change.range = doc.range_to_utf16(change.range) if we.document_changes: for doc_change in [v for v in we.document_changes if isinstance(v, TextDocumentEdit)]: doc = await self.parent.documents.get(doc_change.text_document.uri) if doc is not None: for edit in doc_change.edits: edit.range = doc.range_to_utf16(edit.range) result = WorkspaceEdit() for we in edits: if we.changes: if result.changes is None: result.changes = {} result.changes.update(we.changes) if we.document_changes: if result.document_changes is None: result.document_changes = [] result.document_changes.extend(we.document_changes) if we.change_annotations: if result.change_annotations is None: result.change_annotations = {} result.change_annotations.update(we.change_annotations) return result @rpc_method(name="textDocument/prepareRename", param_type=PrepareRenameParams) @threaded() async def _text_document_prepare_rename( self, text_document: TextDocumentIdentifier, position: Position, *args: Any, **kwargs: Any, ) -> Optional[PrepareRenameResult]: results: List[PrepareRenameResult] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect_prepare( self, document, document.position_from_utf16(position), callback_filter=language_id_filter(document) ): if isinstance(result, BaseException): if isinstance(result, CantRenameError): raise JsonRPCErrorException(ErrorCodes.INVALID_PARAMS, str(result)) if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: results.append(result) if not results: return None result = results[-1] if isinstance(result, Range): result = document.range_to_utf16(result) elif isinstance(result, PrepareRenameResultType1): result.range = document.range_to_utf16(result.range) return result
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/rename.py
0.869313
0.182826
rename.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( FoldingRange, FoldingRangeParams, Position, ServerCapabilities, TextDocumentIdentifier, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import HasExtendCapabilities from robotcode.language_server.common.parts.protocol_part import LanguageServerProtocolPart from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol # pragma: no cover class FoldingRangeProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) @async_tasking_event async def collect(sender, document: TextDocument) -> Optional[List[FoldingRange]]: # pragma: no cover, NOSONAR ... def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if len(self.collect): capabilities.folding_range_provider = True @rpc_method(name="textDocument/foldingRange", param_type=FoldingRangeParams) @threaded() async def _text_document_folding_range( self, text_document: TextDocumentIdentifier, *args: Any, **kwargs: Any ) -> Optional[List[FoldingRange]]: results: List[FoldingRange] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect(self, document, callback_filter=language_id_filter(document)): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: results += result if not results: return None for result in results: if result.start_character is not None: result.start_character = document.position_to_utf16( Position(result.start_line, result.start_character) ).character if result.end_character is not None: result.end_character = document.position_to_utf16( Position(result.end_line, result.end_character) ).character return results
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/folding_range.py
0.880322
0.170404
folding_range.py
pypi
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, Final, List, Optional from robotcode.core.async_tools import async_tasking_event, threaded from robotcode.core.logging import LoggingDescriptor from robotcode.core.lsp.types import ( DocumentHighlight, DocumentHighlightOptions, DocumentHighlightParams, Position, ServerCapabilities, TextDocumentIdentifier, ) from robotcode.jsonrpc2.protocol import rpc_method from robotcode.language_server.common.decorators import language_id_filter from robotcode.language_server.common.has_extend_capabilities import HasExtendCapabilities from robotcode.language_server.common.parts.protocol_part import LanguageServerProtocolPart from robotcode.language_server.common.text_document import TextDocument if TYPE_CHECKING: from robotcode.language_server.common.protocol import LanguageServerProtocol class DocumentHighlightProtocolPart(LanguageServerProtocolPart, HasExtendCapabilities): _logger: Final = LoggingDescriptor() def __init__(self, parent: LanguageServerProtocol) -> None: super().__init__(parent) def extend_capabilities(self, capabilities: ServerCapabilities) -> None: if len(self.collect): capabilities.document_highlight_provider = DocumentHighlightOptions(work_done_progress=True) @async_tasking_event async def collect( sender, document: TextDocument, position: Position # NOSONAR ) -> Optional[List[DocumentHighlight]]: ... @rpc_method(name="textDocument/documentHighlight", param_type=DocumentHighlightParams) @threaded() async def _text_document_document_highlight( self, text_document: TextDocumentIdentifier, position: Position, *args: Any, **kwargs: Any, ) -> Optional[List[DocumentHighlight]]: highlights: List[DocumentHighlight] = [] document = await self.parent.documents.get(text_document.uri) if document is None: return None for result in await self.collect( self, document, document.position_from_utf16(position), callback_filter=language_id_filter(document) ): if isinstance(result, BaseException): if not isinstance(result, CancelledError): self._logger.exception(result, exc_info=result) else: if result is not None: highlights.extend(result) if len(highlights) == 0: return None for highlight in highlights: highlight.range = document.range_to_utf16(highlight.range) return highlights
/robotcode_language_server-0.54.3.tar.gz/robotcode_language_server-0.54.3/src/robotcode/language_server/common/parts/document_highlight.py
0.91257
0.156234
document_highlight.py
pypi