text
stringlengths
12
786k
let drawMode = ref 0
let maxVertices = ref 0
let maxIndices = ref 0
let ( += ) a b = ( a := ! a . + b ) ; ;
let vertices = Bigarray . Array1 . of_array Bigarray . float32 Bigarray . c_layout [ | 1 . ; 1 . ; 1 . ; - 1 . ; 1 . ; 1 . ; - 1 . ; - 1 . ; 1 . ; 1 . ; - 1 . ; 1 . ; 1 . ; 1 . ; 1 . ; 1 . ; - 1 . ; 1 . ; 1 . ; - 1 . ; - 1 . ; 1 . ; 1 . ; - 1 . ; 1 . ; 1 . ; 1 . ; 1 . ; 1 . ; - 1 . ; - 1 . ; 1 . ; - 1 . ; - 1 . ; 1 . ; 1 . ; - 1 . ; 1 . ; 1 . ; - 1 . ; 1 . ; - 1 . ; - 1 . ; - 1 . ; - 1 . ; - 1 . ; - 1 . ; 1 . ; - 1 . ; - 1 . ; - 1 . ; 1 . ; - 1 . ; - 1 . ; 1 . ; - 1 . ; 1 . ; - 1 . ; - 1 . ; 1 . ; 1 . ; - 1 . ; - 1 . ; - 1 . ; - 1 . ; - 1 . ; - 1 . ; 1 . ; - 1 . ; 1 . ; 1 . ; - 1 . ] |
let normals = Bigarray . Array1 . of_array Bigarray . float32 Bigarray . c_layout [ | 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; - 1 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; - 1 . ; 0 . ; 0 . ; - 1 . ] |
let colors = Bigarray . Array1 . of_array Bigarray . float32 Bigarray . c_layout [ | 1 . ; 1 . ; 1 . ; 1 . ; 1 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 1 . ; 1 . ; 1 . ; 1 . ; 1 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 1 . ; 1 . ; 1 . ; 1 . ; 1 . ; 0 . ; 1 . ; 1 . ; 0 . ; 1 . ; 0 . ; 1 . ; 1 . ; 0 . ; 1 . ; 1 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ; 1 . ; 0 . ; 1 . ; 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 0 . ; 0 . ; 1 . ; 0 . ; 0 . ; 1 . ; 1 . ] |
let indices = Bigarray . Array1 . of_array Bigarray . int16_unsigned Bigarray . c_layout [ | 0 ; 1 ; 2 ; 3 ; 4 ; 5 ; 6 ; 7 ; 8 ; 9 ; 10 ; 11 ; 12 ; 13 ; 14 ; 15 ; 16 ; 17 ; 18 ; 19 ; 20 ; 21 ; 22 ; 23 ] |
let draw1 ( ) = glPushMatrix ( ) ; glTranslate ( - 2 . ) ( 2 . ) ( 0 . ) ; glBegin GL_QUADS ; glNormal3 0 . 0 . 1 . ; glColor3 1 . 1 . 1 . ; glVertex3 1 . 1 . 1 . ; glColor3 1 . 1 . 0 . ; glVertex3 ( - 1 . ) 1 . 1 . ; glColor3 1 . 0 . 0 . ; glVertex3 ( - 1 . ) ( - 1 . ) 1 . ; glColor3 1 . 0 . 1 . ; glVertex3 1 . ( - 1 . ) 1 . ; glNormal3 1 . 0 . 0 . ; glColor3 1 . 1 . 1 . ; glVertex3 1 . 1 . 1 . ; glColor3 1 . 0 . 1 . ; glVertex3 1 . ( - 1 . ) 1 . ; glColor3 0 . 0 . 1 . ; glVertex3 1 . ( - 1 . ) ( - 1 . ) ; glColor3 0 . 1 . 1 . ; glVertex3 1 . 1 . ( - 1 . ) ; glNormal3 0 . 1 . 0 . ; glColor3 1 . 1 . 1 . ; glVertex3 1 . 1 . 1 . ; glColor3 0 . 1 . 1 . ; glVertex3 1 . 1 . ( - 1 . ) ; glColor3 0 . 1 . 0 . ; glVertex3 ( - 1 . ) 1 . ( - 1 . ) ; glColor3 1 . 1 . 0 . ; glVertex3 ( - 1 . ) 1 . 1 . ; glNormal3 ( - 1 . ) 0 . 0 . ; glColor3 1 . 1 . 0 . ; glVertex3 ( - 1 . ) 1 . 1 . ; glColor3 0 . 1 . 0 . ; glVertex3 ( - 1 . ) 1 . ( - 1 . ) ; glColor3 0 . 0 . 0 . ; glVertex3 ( - 1 . ) ( - 1 . ) ( - 1 . ) ; glColor3 1 . 0 . 0 . ; glVertex3 ( - 1 . ) ( - 1 . ) 1 . ; glNormal3 0 . ( - 1 . ) 0 . ; glColor3 0 . 0 . 0 . ; glVertex3 ( - 1 . ) ( - 1 . ) ( - 1 . ) ; glColor3 0 . 0 . 1 . ; glVertex3 1 . ( - 1 . ) ( - 1 . ) ; glColor3 1 . 0 . 1 . ; glVertex3 1 . ( - 1 . ) 1 . ; glColor3 1 . 0 . 0 . ; glVertex3 ( - 1 . ) ( - 1 . ) 1 . ; glNormal3 0 . 0 . ( - 1 . ) ; glColor3 0 . 0 . 1 . ; glVertex3 1 . ( - 1 . ) ( - 1 . ) ; glColor3 0 . 0 . 0 . ; glVertex3 ( - 1 . ) ( - 1 . ) ( - 1 . ) ; glColor3 0 . 1 . 0 . ; glVertex3 ( - 1 . ) 1 . ( - 1 . ) ; glColor3 0 . 1 . 1 . ; glVertex3 1 . 1 . ( - 1 . ) ; glEnd ( ) ; glPopMatrix ( ) ; ; ;
let draw2 ( ) = glEnableClientState GL_NORMAL_ARRAY ; glEnableClientState GL_COLOR_ARRAY ; glEnableClientState GL_VERTEX_ARRAY ; glNormalPointer Norm . GL_FLOAT 0 normals ; glColorPointer 3 Color . GL_FLOAT 0 colors ; glVertexPointer 3 Coord . GL_FLOAT 0 vertices ; glPushMatrix ( ) ; glTranslate 2 . 2 . 0 . ; glDrawArrays GL_QUADS 0 24 ; glPopMatrix ( ) ; glDisableClientState GL_VERTEX_ARRAY ; glDisableClientState GL_COLOR_ARRAY ; glDisableClientState GL_NORMAL_ARRAY ; ; ;
let draw3 ( ) = glEnableClientState GL_NORMAL_ARRAY ; glEnableClientState GL_COLOR_ARRAY ; glEnableClientState GL_VERTEX_ARRAY ; glNormalPointer Norm . GL_FLOAT 0 normals ; glColorPointer 3 Color . GL_FLOAT 0 colors ; glVertexPointer 3 Coord . GL_FLOAT 0 vertices ; glPushMatrix ( ) ; glTranslate ( - 2 . ) ( - 2 . ) ( 0 . ) ; glDrawElements GL_QUADS 24 Elem . GL_UNSIGNED_SHORT indices ; glPopMatrix ( ) ; glDisableClientState GL_VERTEX_ARRAY ; glDisableClientState GL_COLOR_ARRAY ; glDisableClientState GL_NORMAL_ARRAY ; ; ;
let draw4 ( ) = glEnableClientState GL_NORMAL_ARRAY ; glEnableClientState GL_COLOR_ARRAY ; glEnableClientState GL_VERTEX_ARRAY ; glNormalPointer Norm . GL_FLOAT 0 normals ; glColorPointer 3 Color . GL_FLOAT 0 colors ; glVertexPointer 3 Coord . GL_FLOAT 0 vertices ; glPushMatrix ( ) ; glTranslate ( 2 . ) ( - 2 . ) ( 0 . ) ; glDrawRangeElements GL_QUADS 0 11 12 Elem . GL_UNSIGNED_SHORT indices ; glDrawRangeElements GL_QUADS 12 23 12 Elem . GL_UNSIGNED_SHORT ( Bigarray . Array1 . sub indices 12 12 ) ; glPopMatrix ( ) ; glDisableClientState GL_VERTEX_ARRAY ; glDisableClientState GL_COLOR_ARRAY ; glDisableClientState GL_NORMAL_ARRAY ; ; ;
let draw_string str x y ( r , g , b , a ) font = glPushAttrib [ Attrib . GL_LIGHTING_BIT ; Attrib . GL_CURRENT_BIT ] ; glDisable GL_LIGHTING ; glColor4 r g b a ; glRasterPos2 ( float x ) ( float y ) ; let len = String . length str in for i = 0 to pred len do glutBitmapCharacter font str . [ i ] ; done ; glEnable GL_LIGHTING ; glPopAttrib ( ) ; ; ;
let draw_string_3D str ( x , y , z ) ( r , g , b , a ) font = glPushAttrib [ Attrib . GL_LIGHTING_BIT ; Attrib . GL_CURRENT_BIT ] ; glDisable GL_LIGHTING ; glColor4 r g b a ; glRasterPos3 x y z ; let len = String . length str in for i = 0 to pred len do glutBitmapCharacter font str . [ i ] ; done ; glEnable GL_LIGHTING ; glPopAttrib ( ) ; ; ;
let show_info ( ) = glPushMatrix ( ) ; glLoadIdentity ( ) ; glMatrixMode GL_PROJECTION ; glPushMatrix ( ) ; glLoadIdentity ( ) ; gluOrtho2D 0 . 400 . 0 . 300 . ; let color = ( 1 . , 1 . , 1 . , 1 . ) in let str = Printf . sprintf " Max Elements Vertices : % d " ! maxVertices in draw_string str 1 286 color font ; let str = Printf . sprintf " Max Elements Indices : % d " ! maxIndices in draw_string str 1 272 color font ; glPopMatrix ( ) ; glMatrixMode GL_MODELVIEW ; glPopMatrix ( ) ; ; ;
let display ( ) = glClear [ GL_COLOR_BUFFER_BIT ; GL_DEPTH_BUFFER_BIT ; GL_STENCIL_BUFFER_BIT ] ; glPushMatrix ( ) ; glTranslate 0 . 0 . ! cameraDistance ; glRotate ! cameraAngleX 1 . 0 . 0 . ; glRotate ! cameraAngleY 0 . 1 . 0 . ; draw1 ( ) ; draw2 ( ) ; draw3 ( ) ; draw4 ( ) ; let color = ( 1 . , 1 . , 1 . , 1 . ) in let pos = ( - 4 . 0 , 3 . 5 , 0 . 0 ) in draw_string_3D " Immediate " pos color font ; let pos = ( 1 . 0 , 0 . 6 , 0 . 0 ) in draw_string_3D " glDrawArrays ( ) " pos color font ; let pos = ( - 4 . 0 , - 0 . 8 , 0 . 0 ) in draw_string_3D " glDrawElements ( ) " pos color font ; let pos = ( 1 . 0 , - 3 . 8 , 0 . 0 ) in draw_string_3D " glDrawRangeElements ( ) " pos color font ; show_info ( ) ; glPopMatrix ( ) ; glutSwapBuffers ( ) ; ; ;
let reshape ~ width : w ~ height : h = glViewport 0 0 w h ; let aspect = ( float w ) . / ( float h ) in glMatrixMode GL_PROJECTION ; glLoadIdentity ( ) ; ) * gluPerspective ~ fovy : 60 . 0 ~ aspect ~ zNear : 0 . 5 ~ zFar : 80 . 0 ; glMatrixMode GL_MODELVIEW ; ; ;
let rec timer ~ value : millisec = glutTimerFunc ~ msecs : millisec ~ timer ~ value : millisec ; glutPostRedisplay ( ) ; ; ;
let motion ~ x ~ y = if ( ! mouseLeftDown ) then begin cameraAngleY += ( float x . - ! mouseX ) ; cameraAngleX += ( float y . - ! mouseY ) ; mouseX := float x ; mouseY := float y ; end ; if ( ! mouseRightDown ) then begin cameraDistance += ( float y . - ! mouseY ) . * 0 . 2 ; mouseY := float y ; end ; glutPostRedisplay ( ) ; ; ;
let mouse ~ button ~ state ~ x ~ y = mouseX := float x ; mouseY := float y ; match button , state with | GLUT_LEFT_BUTTON , GLUT_DOWN -> mouseLeftDown := true ; | GLUT_LEFT_BUTTON , GLUT_UP -> mouseLeftDown := false ; | GLUT_RIGHT_BUTTON , GLUT_DOWN -> mouseRightDown := true ; | GLUT_RIGHT_BUTTON , GLUT_UP -> mouseRightDown := false ; | GLUT_MIDDLE_BUTTON , GLUT_DOWN -> mouseMiddleDown := true ; | GLUT_MIDDLE_BUTTON , GLUT_UP -> mouseMiddleDown := false ; | _ -> ( ) ; ;
let keyboard ~ key ~ x ~ y = begin match key with | ' \ 027 ' -> exit 0 ; | ' D ' | ' d ' -> drawMode := ( ! drawMode + 1 ) mod 3 ; if ( ! drawMode = 0 ) then begin glPolygonMode GL_FRONT_AND_BACK GL_FILL ; glEnable GL_DEPTH_TEST ; glEnable GL_CULL_FACE ; end else if ( ! drawMode = 1 ) then begin glPolygonMode GL_FRONT_AND_BACK GL_LINE ; glDisable GL_DEPTH_TEST ; glDisable GL_CULL_FACE ; end else begin glPolygonMode GL_FRONT_AND_BACK GL_POINT ; glDisable GL_DEPTH_TEST ; glDisable GL_CULL_FACE ; end ; | _ -> ( ) end ; glutPostRedisplay ( ) ; ; ;
let init_lights ( ) = let lightKa = ( 0 . 2 , 0 . 2 , 0 . 2 , 1 . 0 ) and lightKd = ( 0 . 7 , 0 . 7 , 0 . 7 , 1 . 0 ) and lightKs = ( 1 . 0 , 1 . 0 , 1 . 0 , 1 . 0 ) in glLight ( GL_LIGHT 0 ) ( Light . GL_AMBIENT lightKa ) ; glLight ( GL_LIGHT 0 ) ( Light . GL_DIFFUSE lightKd ) ; glLight ( GL_LIGHT 0 ) ( Light . GL_SPECULAR lightKs ) ; let lightPos = ( 0 . , 0 . , 20 . , 1 . ) in glLight ( GL_LIGHT 0 ) ( Light . GL_POSITION lightPos ) ; glEnable GL_LIGHT0 ; ; ;
let set_camera ~ posX ~ posY ~ posZ ~ targetX ~ targetY ~ targetZ = glMatrixMode GL_MODELVIEW ; glLoadIdentity ( ) ; gluLookAt posX posY posZ targetX targetY targetZ 0 . 1 . 0 . ; ; ;
let initGLUT ( ) = ignore ( glutInit Sys . argv ) ; glutInitDisplayMode [ GLUT_RGB ; GLUT_DOUBLE ; GLUT_DEPTH ; GLUT_STENCIL ] ; glutInitWindowSize 400 300 ; glutInitWindowPosition 100 100 ; let handle = glutCreateWindow Sys . argv . ( 0 ) in glutDisplayFunc ~ display ; glutTimerFunc ~ msecs : 100 ~ timer ~ value : 100 ; glutReshapeFunc ~ reshape ; glutKeyboardFunc ~ keyboard ; glutMouseFunc ~ mouse ; glutMotionFunc ~ motion ; ( handle ) ; ;
let initGL ( ) = glShadeModel GL_SMOOTH ; glPixelStorei GL_UNPACK_ALIGNMENT 4 ; glHint GL_PERSPECTIVE_CORRECTION_HINT GL_NICEST ; glEnable GL_DEPTH_TEST ; glEnable GL_LIGHTING ; glEnable GL_TEXTURE_2D ; glEnable GL_CULL_FACE ; glColorMaterial GL_FRONT_AND_BACK GL_AMBIENT_AND_DIFFUSE ; glEnable GL_COLOR_MATERIAL ; glClearColor 0 . 0 . 0 . 0 . ; glClearStencil 0 ; glClearDepth 1 . 0 ; glDepthFunc GL_LEQUAL ; init_lights ( ) ; set_camera 0 . 0 . 10 . 0 . 0 . 0 . ; ; ;
let ( ) = let _ = initGLUT ( ) in initGL ( ) ; maxVertices := glGetInteger1 Get . GL_MAX_ELEMENTS_VERTICES ; maxIndices := glGetInteger1 Get . GL_MAX_ELEMENTS_INDICES ; glutMainLoop ( ) ; ; ;
module Bigint = struct module R = struct include Field . Bigint let of_data _ = failwith __LOC__ let to_field = Field . of_bigint let of_field = Field . to_bigint end end
let field_size : Bigint . R . t = Field . size
module Verification_key = struct type t = ( Pasta_bindings . Fp . t , Kimchi_bindings . Protocol . SRS . Fp . t , Pasta_bindings . Fq . t Kimchi_types . or_infinity Kimchi_types . poly_comm ) Kimchi_types . VerifierIndex . verifier_index let to_string _ = failwith __LOC__ let of_string _ = failwith __LOC__ let shifts ( t : t ) t = t . shifts end
module R1CS_constraint_system = Plonk_constraint_system . Make ( Field ) Field ( Kimchi_bindings . Protocol . Gates . Vector . Fp ) Fp ( struct let params = Sponge . Params ( . map pasta_p_kimchi ~ f ( : fun x -> Field . of_bigint ( Bigint256 . of_decimal_string x ) x ) ) end ) end
let lagrange : int -> _ Kimchi_types . poly_comm array = Memo . general ~ hashable : Int . hashable ( fun domain_log2 -> Array . map Precomputed . Lagrange_precomputations ( . vesta ( . index_of_domain_log2 domain_log2 ) domain_log2 ) domain_log2 ~ f ( : fun unshifted -> { Kimchi_types . unshifted = Array . map unshifted ~ f ( : fun ( x , y ) y -> Kimchi_types . Finite ( x , y ) y ) y ; shifted = None } ) )
let with_lagrange f ( vk : Verification_key . t ) t = f ( lagrange vk . domain . log_size_of_group ) log_size_of_group vk
let with_lagranges f ( vks : Verification_key . t array ) array = let lgrs = Array . map vks ~ f ( : fun vk -> lagrange vk . domain . log_size_of_group ) log_size_of_group in f lgrs vks
module Keypair = Dlog_plonk_based_keypair . Make ( struct let name = " vesta " module Rounds = Rounds module Urs = Kimchi_bindings . Protocol . SRS . Fp module Index = Kimchi_bindings . Protocol . Index . Fp module Curve = Curve module Poly_comm = Fp_poly_comm module Scalar_field = Field module Verifier_index = Kimchi_bindings . Protocol . VerifierIndex . Fp module Gate_vector = Kimchi_bindings . Protocol . Gates . Vector . Fp module Constraint_system = R1CS_constraint_system end ) end
module Proof = Plonk_dlog_proof . Make ( struct let id = " pasta_vesta " module Scalar_field = Field module Base_field = Fq module Backend = struct type t = ( Pasta_bindings . Fq . t Kimchi_types . or_infinity , Pasta_bindings . Fp . t ) Kimchi_types . prover_proof include Kimchi_bindings . Protocol . Proof . Fp let batch_verify vks ts = Promise . run_in_thread ( fun ( ) -> batch_verify vks ts ) ts let create_aux ~ f : create ( pk : Keypair . t ) t primary auxiliary prev_chals prev_comms = let external_values i = let open Field . Vector in if i = 0 then Field . one else if i - 1 < length primary then get primary ( i - 1 ) 1 else get auxiliary ( i - 1 - length primary ) primary in let computed_witness = R1CS_constraint_system . compute_witness pk . cs external_values in let num_rows = Array . length computed_witness ( . 0 ) 0 in let witness_cols = Array . init Kimchi_backend_common . Constants . columns ~ f ( : fun col -> let witness = Field . Vector . create ( ) in for row = 0 to num_rows - 1 do Field . Vector . emplace_back witness computed_witness ( . col ) col ( . row ) row done ; witness ) in create pk . index witness_cols prev_chals prev_comms let create_async ( pk : Keypair . t ) t primary auxiliary prev_chals prev_comms = create_aux pk primary auxiliary prev_chals prev_comms ~ f ( : fun pk auxiliary_input prev_challenges prev_sgs -> Promise . run_in_thread ( fun ( ) -> create pk auxiliary_input prev_challenges prev_sgs ) ) let create ( pk : Keypair . t ) t primary auxiliary prev_chals prev_comms = create_aux pk primary auxiliary prev_chals prev_comms ~ f : create end module Verifier_index = Kimchi_bindings . Protocol . VerifierIndex . Fp module Index = Keypair module Evaluations_backend = struct type t = Scalar_field . t Kimchi_types . proof_evaluations end module Opening_proof_backend = struct type t = ( Curve . Affine . Backend . t , Scalar_field . t ) t Kimchi_types . opening_proof end module Poly_comm = Fp_poly_comm module Curve = Curve end ) end
module Proving_key = struct type t = Keypair . t include Core_kernel . Binable . Of_binable ( Core_kernel . Unit ) Unit ( struct type nonrec t = t let to_binable _ = ( ) let of_binable ( ) = failwith " TODO " end ) end let is_initialized _ = ` Yes let set_constraint_system _ _ = ( ) let to_string _ = failwith " TODO " let of_string _ = failwith " TODO " end
module Oracles = Plonk_dlog_oracles . Make ( struct module Verifier_index = Verification_key module Field = Field module Proof = Proof module Backend = struct include Kimchi_bindings . Protocol . Oracles . Fp let create = with_lagrange create end end ) end
let relu = Layer . of_fn_ ( fun xs ~ is_training : _ -> Tensor . relu xs )
let relu_ = Layer . of_fn_ ( fun xs ~ is_training : _ -> Tensor . relu_ xs )
type t = | C of int | M
let layers_cfg = function | ` A -> [ C 64 ; M ; C 128 ; M ; C 256 ; C 256 ; M ; C 512 ; C 512 ; M ; C 512 ; C 512 ; M ] | ` B -> [ C 64 ; C 64 ; M ; C 128 ; C 128 ; M ; C 256 ; C 256 ; M ; C 512 ; C 512 ; M ; C 512 ; C 512 ; M ] | ` D -> [ C 64 ; C 64 ; M ; C 128 ; C 128 ; M ; C 256 ; C 256 ; C 256 ; M ; C 512 ; C 512 ; C 512 ; M ; C 512 ; C 512 ; C 512 ; M ] | ` E -> [ C 64 ; C 64 ; M ; C 128 ; C 128 ; M ; C 256 ; C 256 ; C 256 ; C 256 ; M ; C 512 ; C 512 ; C 512 ; C 512 ; M ; C 512 ; C 512 ; C 512 ; C 512 ; M ]
let make_layers vs cfg ~ batch_norm ~ in_place_relu = let relu = if in_place_relu then relu_ else relu in let sub_vs index = Var_store . sub vs ( Int . to_string index ) in let ( _output_dim , _output_idx ) , layers = List . fold_map ( layers_cfg cfg ) ~ init ( : 3 , 0 ) ~ f ( : fun ( input_dim , idx ) v -> match v with | M -> ( ( input_dim , idx + 1 ) , [ Layer . of_fn ( Tensor . max_pool2d ~ ksize ( : 2 , 2 ) ) |> Layer . with_training ] ) | C output_dim -> let conv2d = Layer . conv2d_ ( sub_vs idx ) ~ ksize : 3 ~ stride : 1 ~ padding : 1 ~ input_dim output_dim |> Layer . with_training in if batch_norm then ( let batch_norm = Layer . batch_norm2d ( sub_vs ( idx + 1 ) ) output_dim in ( output_dim , idx + 3 ) , [ conv2d ; batch_norm ; relu ] ) else ( output_dim , idx + 2 ) , [ conv2d ; relu ] ) in List . concat layers
let vgg ~ num_classes vs cfg ~ batch_norm = let cls_vs i = Var_store . ( vs / " classifier " / Int . to_string i ) in let layers = make_layers ( Var_store . sub vs " features " ) cfg ~ batch_norm ~ in_place_relu : true |> Layer . sequential_ in let fc1 = Layer . linear ( cls_vs 0 ) ~ input_dim ( : 512 * 7 * 7 ) 4096 in let fc2 = Layer . linear ( cls_vs 3 ) ~ input_dim : 4096 4096 in let fc3 = Layer . linear ( cls_vs 6 ) ~ input_dim : 4096 num_classes in Layer . of_fn_ ( fun xs ~ is_training -> let batch_size = Tensor . shape xs |> List . hd_exn in Layer . forward_ layers xs ~ is_training |> Tensor . view ~ size [ : batch_size ; - 1 ] |> Layer . forward fc1 |> Tensor . relu |> Tensor . dropout ~ p : 0 . 5 ~ is_training |> Layer . forward fc2 |> Tensor . relu |> Tensor . dropout ~ p : 0 . 5 ~ is_training |> Layer . forward fc3 )
let vgg11 vs ~ num_classes = vgg ~ num_classes vs ` A ~ batch_norm : false
let vgg11_bn vs ~ num_classes = vgg ~ num_classes vs ` A ~ batch_norm : true
let vgg13 vs ~ num_classes = vgg ~ num_classes vs ` B ~ batch_norm : false
let vgg13_bn vs ~ num_classes = vgg ~ num_classes vs ` B ~ batch_norm : true
let vgg16 vs ~ num_classes = vgg ~ num_classes vs ` D ~ batch_norm : false
let vgg16_bn vs ~ num_classes = vgg ~ num_classes vs ` D ~ batch_norm : true
let vgg19 vs ~ num_classes = vgg ~ num_classes vs ` E ~ batch_norm : false
let vgg19_bn vs ~ num_classes = vgg ~ num_classes vs ` E ~ batch_norm : true
let vgg16_layers ( ? max_layer = Int . max_value ) vs ~ batch_norm = let layers = List . take ( make_layers ( Var_store . sub vs " features " ) ` D ~ batch_norm ~ in_place_relu : false ) max_layer in Staged . stage ( fun xs -> List . fold_mapi layers ~ init : xs ~ f ( : fun i xs layer -> let xs = Layer . forward_ layer xs ~ is_training : false in xs , ( i , xs ) ) |> fun ( _ , indexed_layers ) -> Map . of_alist_exn ( module Int ) indexed_layers )
let vgg19 ( ) = let block iter ~ block_idx ~ out_channels x = List . init iter ~ f : Fn . id |> List . fold ~ init : x ~ f ( : fun acc idx -> Fnn . conv2d ( ) acc ~ name ( : Printf . sprintf " conv % d_ % d " block_idx ( idx + 1 ) 1 ) 1 ~ w_init ( ` : normal 0 . 1 ) 1 ~ filter ( : 3 , 3 ) 3 ~ strides ( : 1 , 1 ) 1 ~ padding ` : same ~ out_channels |> Fnn . relu ) relu |> Fnn . max_pool ~ filter ( : 2 , 2 ) 2 ~ strides ( : 2 , 2 ) 2 ~ padding ` : same in let input , input_id = Fnn . input ~ shape ( : D3 ( img_size , img_size , 3 ) 3 ) 3 in let model = Fnn . reshape input ~ shape ( : D3 ( img_size , img_size , 3 ) 3 ) 3 |> block 2 ~ block_idx : 1 ~ out_channels : 64 |> block 2 ~ block_idx : 2 ~ out_channels : 128 |> block 4 ~ block_idx : 3 ~ out_channels : 256 |> block 4 ~ block_idx : 4 ~ out_channels : 512 |> block 4 ~ block_idx : 5 ~ out_channels : 512 |> Fnn . flatten |> Fnn . dense ~ name " : fc6 " ~ w_init ( ` : normal 0 . 1 ) 1 4096 |> Fnn . relu |> Fnn . dense ~ name " : fc7 " ~ w_init ( ` : normal 0 . 1 ) 1 4096 |> Fnn . relu |> Fnn . dense ~ name " : fc8 " ~ w_init ( ` : normal 0 . 1 ) 1 1000 |> Fnn . softmax |> Fnn . Model . create Float in input_id , model
let ( ) = let { Image . tensor ; _ } = Image . load " input . jpg " in let input_id , model = vgg19 ( ) in Fnn . Model . load model ~ filename ( : Caml . Sys . getcwd ( ) ^ " / vgg19 . cpkt ) " ; let results = Fnn . Model . predict model [ input_id , tensor ] in let pr , category = List . init 1000 ~ f ( : fun i -> Tensor . get results [ | 0 ; i ] , | i + 1 ) 1 |> List . reduce_exn ~ f : Caml . max in Stdio . printf " % d : . % 2f %%\ n " category ( 100 . . * pr ) pr
module type Image = sig type t val create : int -> int -> t val size : t -> int val blit_all : t -> t -> unit val copy : t -> t val blank : t -> unit val randomize : t -> unit end
module Image = struct include Mm_image . Image . YUV420 let create w h = create w h let scale = scale ~ proportional : false end
module Make ( Image : Image ) = struct module I = Image type t = Image . t array type buffer = t let make len width height = Array . init len ( fun _ -> Image . create width height ) let single img = [ | img ] | let blit sbuf sofs dbuf dofs len = for i = 0 to len - 1 do Image . blit_all sbuf . ( sofs + i ) dbuf . ( dofs + i ) done let copy vid = Array . map Image . copy vid let length vid = Array . length vid let size vid = let n = ref 0 in for i = 0 to Array . length vid - 1 do n := ! n + Image . size vid . ( i ) done ; ! n let get vid i = vid . ( i ) let set vid i img = vid . ( i ) <- img let iter f vid off len = for i = off to off + len - 1 do f vid . ( i ) done let blank vid off len = iter Image . blank vid off len let randomize vid off len = iter Image . randomize vid off len end
module Canvas = struct module Image = Mm_image . Image . Canvas ( Image ) type image = Image . t type t = Image . t array let make len ( width , height ) : t = Array . init len ( fun _ -> Image . create width height ) let single img = [ | img ] | let single_image img = single ( Image . make img ) let length ( v : t ) = Array . length v let copy ( v : t ) = Array . init ( length v ) ( fun i -> v . ( i ) ) let size ( v : t ) = let n = ref 0 in for i = 0 to Array . length v - 1 do n := ! n + Image . size v . ( i ) done ; ! n let get v i = v . ( i ) let set v i img = v . ( i ) <- img let map_image f v i = v . ( i ) <- f v . ( i ) let render v i = Image . render v . ( i ) let put v i img = v . ( i ) <- Image . make img let blit sbuf sofs dbuf dofs len = for i = 0 to len - 1 do dbuf . ( dofs + i ) <- sbuf . ( sofs + i ) done let map f buf ofs len = for i = ofs to ofs + len - 1 do buf . ( i ) <- f buf . ( i ) done let blank buf ofs len = map ( fun img -> Image . create ( Image . width img ) ( Image . height img ) ) buf ofs len let iter f buf ofs len = for i = ofs to ofs + len - 1 do buf . ( i ) <- Image . iter f buf . ( i ) done end
module FPS = struct type t = float let to_frac f = let n = floor ( ( f . * 100 . ) . + 0 . 5 ) in let n = int_of_float n in if n mod 100 = 0 then ( n / 100 , 1 ) else ( n , 100 ) end
module AVI = struct module Writer = struct let word n = let s = Bytes . create 2 in Bytes . set_int16_le s 0 n ; Bytes . unsafe_to_string s let dword n = let s = Bytes . create 4 in Bytes . set_int32_le s 0 ( Int32 . of_int n ) ; Bytes . unsafe_to_string s module Chunk = struct let create id len = let pad = len mod 2 = 1 in assert ( String . length id = 4 ) ; let s = Bytes . create ( 8 + len + if pad then 1 else 0 ) in Bytes . blit_string id 0 s 0 4 ; Bytes . blit_string ( dword len ) 0 s 4 4 ; if pad then Bytes . set s ( 8 + len ) ( char_of_int 0 ) ; s let make id data = let len = String . length data in let s = create id len in Bytes . blit_string data 0 s 8 len ; Bytes . unsafe_to_string s let audio_s16le buf = let len = Audio . length buf in let channels = Audio . channels buf in let s = create " 01wb " ( len * channels * 2 ) in Audio . S16LE . of_audio buf 0 s 8 len ; Bytes . unsafe_to_string s let video_yuv420 img = let open Mm_image in let width = Image . YUV420 . width img in let height = Image . YUV420 . height img in let y , u , v = Image . YUV420 . data img in let y = Image . Data . to_string y in let u = Image . Data . to_string u in let v = Image . Data . to_string v in let y_stride = Image . YUV420 . y_stride img in let uv_stride = Image . YUV420 . uv_stride img in let s = create " 00db " ( width * height + 2 * ( width / 2 ) * ( height / 2 ) ) in let o = ref 8 in let add_sub data off len = Bytes . blit_string data off s ! o len ; o := ! o + len in let add data = add_sub data 0 ( String . length data ) in if y_stride = width then add y else for j = 0 to height - 1 do add_sub y ( j * y_stride ) width done ; if uv_stride = width / 2 then ( add u ; add v ) else ( for j = 0 to ( height / 2 ) - 1 do add_sub u ( j * uv_stride ) ( width / 2 ) done ; for j = 0 to ( height / 2 ) - 1 do add_sub v ( j * uv_stride ) ( width / 2 ) done ) ; Bytes . unsafe_to_string s let list = make " LIST " end let header ( ? format ` = YUV420 ) ~ width ~ height ~ framerate ? channels ? samplerate ? vendor ( ) = ignore format ; let has_audio = channels <> None in let channels = Option . value ~ default : 0 channels in let samplerate = Option . value ~ default : 0 samplerate in assert ( not has_audio || samplerate > 0 ) ; let dword_max ( ) = word 0xffff ^ word 0xffff in let avi_header = Chunk . make " avih " ( dword ( 1000000 / framerate ) ^ dword 0 ^ dword 0 ^ dword 0x0100 ^ dword_max ( ) ^ dword 0 ^ dword ( 1 + if has_audio then 1 else 0 ) ^ dword 0 ^ dword width ^ dword height ^ dword 0 ^ dword 0 ^ dword 0 ^ dword 0 ) in let video_header = let stream_header = Chunk . make " strh " ( " vids " ^ " I420 " ^ dword 0 ^ word 0 ^ word 0 ^ dword 0 ^ dword 1 ^ dword framerate ^ dword 0 ^ dword_max ( ) ^ dword 0 ^ dword_max ( ) ^ dword 0 ^ word 0 ^ word 0 ^ word width ^ word height ) in let stream_format = Chunk . make " strf " ( dword 40 ^ dword width ^ dword height ^ word 1 ^ word 12 ^ " I420 " ^ dword ( width * height * 6 / 4 ) ^ dword 0 ^ dword 0 ^ dword 0 ^ dword 0 ) in Chunk . list ( " strl " ^ stream_header ^ stream_format ) in let audio_header = if not has_audio then " " else let stream_header = Chunk . make " strh " ( " auds " ^ dword 0 ^ dword 0 ^ word 0 ^ word 0 ^ dword 0 ^ dword 1 ^ dword samplerate ^ dword 0 ^ dword_max ( ) ^ dword 0 ^ dword_max ( ) ^ dword ( 2 * channels ) ^ word 0 ^ word 0 ^ word 0 ^ word 0 ) in let stream_format = Chunk . make " strf " ( word 1 ^ word channels ^ dword samplerate ^ dword ( 2 * channels * samplerate ) ^ word ( 2 * channels ) ^ word 16 ^ word 0 ) in Chunk . list ( " strl " ^ stream_header ^ stream_format ) in let headers = Chunk . list ( " hdrl " ^ avi_header ^ video_header ^ audio_header ) in let info = match vendor with | Some vendor -> let producer = Chunk . make " ISFT " vendor in Chunk . list ( " INFO " ^ producer ) | None -> " " in " RIFF " ^ dword_max ( ) ^ " AVI " ^ headers ^ info ^ " LIST " ^ dword_max ( ) ^ " movi " end end
module IO = struct exception Invalid_file module Reader = struct class type t = object method width : int method height : int method frame_rate : float method read : buffer -> int -> int -> int method close : unit end end module Writer = struct class type t = object method write : buffer -> int -> int -> unit method close : unit end class virtual avi frame_rate w h = let frames_per_chunk = int_of_float ( frame_rate . + 0 . 5 ) in let frame_size = w * h * 3 in object ( self ) inherit IO . helper method virtual private stream_write : string -> int -> int -> int method virtual private stream_seek : int -> unit method virtual private stream_close : unit initializer self # output " RIFF " ; self # output_int 0 ; self # output " AVI " ; self # output " LIST " ; self # output_int 192 ; self # output " hdrl " ; self # output " avih " ; self # output_int 56 ; self # output_int ( int_of_float ( 1000000 . . / frame_rate ) ) ; self # output_int 0 ; self # output_int 0 ; self # output_byte 0 ; self # output_byte 1 ; self # output_byte 0 ; self # output_byte 0 ; self # output_int 0 ; self # output_int 0 ; self # output_int 1 ; self # output_int 0 ; self # output_int w ; self # output_int h ; self # output_int 0 ; self # output_int 0 ; self # output_int 0 ; self # output_int 0 ; self # output " LIST " ; self # output_int 116 ; self # output " strl " ; self # output " strh " ; self # output_int 56 ; self # output " vids " ; self # output " RGB " ; self # output_int 0 ; self # output_int 0 ; self # output_int 0 ; self # output_int 10 ; self # output_int ( int_of_float ( frame_rate . * 10 . ) ) ; self # output_int 0 ; self # output_int 0 ; self # output_int ( frames_per_chunk * frame_size ) ; self # output_int 0 ; self # output_int 0 ; self # output_short 0 ; self # output_short 0 ; self # output_short w ; self # output_short h ; self # output " strf " ; self # output_int 40 ; self # output_int 40 ; self # output_int w ; self # output_int h ; self # output_short 1 ; self # output_short 24 ; self # output_int 0 ; self # output_int frame_size ; self # output_int 0 ; self # output_int 0 ; self # output_int 0 ; self # output_int 0 ; self # output " LIST " ; self # output_int 0 ; self # output " movi " ; self # output " 00dc " ; self # output_int 0 val mutable datalen = 0 val mutable dataframes = 0 method write ( _ : buffer ) ofs len = for _ = ofs to ofs + len - 1 do let s = failwith " TODO : output YUV420 avi " in self # output s ; datalen <- datalen + String . length s done ; dataframes <- dataframes + len method close = Printf . printf " completing . . . ( % d frames ) \ n " %! dataframes ; self # stream_seek 4 ; self # output_int ( datalen + ( 56 * 4 ) ) ; self # stream_seek ( 12 * 4 ) ; self # output_int dataframes ; self # stream_seek ( 35 * 4 ) ; self # output_int dataframes ; self # stream_seek ( 54 * 4 ) ; self # output_int ( datalen + ( 3 * 4 ) ) ; self # stream_seek ( 57 * 4 ) ; self # output_int datalen ; self # stream_close end class to_avi_file fname fr w h = object inherit avi fr w h inherit IO . Unix . rw ~ write : true fname end end end
type t = { duration : int option ; h : int option ; w : int option ; mimetype : string option ; size : int option ; thumbnail_url : string option ; thumbnail_file : Encrypted_file . t option ; thumbnail_info : Thumbnail_info . t option ; }
let encoding = let to_tuple t = ( t . duration , t . h , t . w , t . mimetype , t . size , t . thumbnail_url , t . thumbnail_file , t . thumbnail_info ) in let of_tuple v = let ( duration , h , w , mimetype , size , thumbnail_url , thumbnail_file , thumbnail_info ) = v in { duration ; h ; w ; mimetype ; size ; thumbnail_url ; thumbnail_file ; thumbnail_info ; } in let with_tuple = obj8 ( opt " duration " int ) ( opt " h " int ) ( opt " w " int ) ( opt " mimetype " string ) ( opt " size " int ) ( opt " thumbnail_url " string ) ( opt " thumbnail_file " Encrypted_file . encoding ) ( opt " thumbnail_info " Thumbnail_info . encoding ) in conv to_tuple of_tuple with_tuple
module Make ( Node_id : S . NODE_ID ) ( Node : S . NODE with type nid := Node_id . t ) : S . VIEW with type nid := Node_id . t and type node := Node . t = struct let min x y = if x < y then x else y let max x y = if x < y then y else x module I = struct type t = int let compare ( a : int ) b = compare a b end module IntSet = Set . Make ( I ) module View = Map . Make ( Node_id ) type t = Node . t View . t let empty = View . empty let mem = View . mem let find = View . find_opt let length = View . cardinal let is_empty = View . is_empty let filter = View . filter let fold = View . fold let iter = View . iter let map = View . mapi let remove = View . remove let add node t = let nid = Node . id node in View . add nid node t let zero_age t = View . map ( fun node -> Node . zero_age node ) t let inc_age t = View . map ( fun node -> Node . inc_age node ) t let adjust_trust r t = View . map ( fun node -> let node = Node . set_known node false in Node . adjust_trust node r ) t let filter_trust min_trust t = View . filter ( fun _nid node -> min_trust <= Node . trust node ) t let filter_overlap view t = View . filter ( fun nid _node -> not ( View . mem nid view ) ) t let min_trust t = View . fold ( fun _nid node min_trust -> min min_trust ( Node . trust node ) ) t 2 . 0 let max_trust t = View . fold ( fun _nid node max_trust -> max max_trust ( Node . trust node ) ) t ( - 1 . 0 ) let sum_trust t = View . fold ( fun _nid node sum -> sum . + Node . trust node ) t 0 . 0 let oldest t = match View . fold ( fun nid node oldest -> match oldest with | None -> Some ( nid , node , 1 ) | Some ( _onid , onode , _n ) when ( Node . age onode ) < ( Node . age node ) -> Some ( nid , node , 1 ) | Some ( onid , onode , n ) when ( Node . age onode ) = ( Node . age node ) -> let n = n + 1 in let max = 1000 in if float_of_int ( Rng . Int . gen max ) . / float_of_int max < 1 . . / float_of_int n then Some ( nid , node , n ) else Some ( onid , onode , n ) | _ -> oldest ) t None with | Some ( _nid , node , _n ) -> Some node | None -> None let random t = let len = length t in if 0 < len then let r = Rng . Int . gen len in let ( rnode , _ ) = View . fold ( fun _nid node a -> let ( rnode , n ) = a in if ( n = r ) then ( Some node , n + 1 ) else ( rnode , n + 1 ) ) t ( None , 0 ) in rnode else None let rnd ( ) = Float . of_int ( ( Rng . Int . gen 1000 ) + 1 ) . / 1000 . let uniform_sample len t = if len < length t then begin let wlist = View . fold ( fun _nid node lst -> ( node , ( 0 . . - ( Float . log ( rnd ( ) ) ) ) . / ( Node . trust node ) ) :: lst ) t [ ] in let swlist = List . fast_sort ( fun a b -> Float . compare ( snd a ) ( snd b ) ) wlist in let rview = let rec add_head rview swlist = if length rview < len then match swlist with | hd :: tl -> add_head ( add ( fst hd ) rview ) tl | [ ] -> rview else rview in add_head View . empty swlist in rview end else t let weighted_sample len t = if len < length t then begin let wlist = View . fold ( fun _nid node lst -> ( node , ( 0 . . - ( Float . log ( rnd ( ) ) ) ) . / ( Node . trust node ) ) :: lst ) t [ ] in let swlist = List . fast_sort ( fun a b -> Float . compare ( snd a ) ( snd b ) ) wlist in let rview = let rec add_head rview swlist = if length rview < len then match swlist with | hd :: tl -> add_head ( add ( fst hd ) rview ) tl | [ ] -> rview else rview in add_head View . empty swlist in rview end else t let union t1 t2 = View . union ( fun _nid node1 node2 -> let newer_node = if ( Node . version node1 ) < ( Node . version node2 ) then node2 else node1 in let trust = if ( Node . known node1 ) then ( Node . trust node1 ) else if ( Node . known node2 ) then ( Node . trust node2 ) else max ( Node . trust node1 ) ( Node . trust node2 ) in Some ( Node . set_trust newer_node trust ) ) t1 t2 let choose_view x y = if View . is_empty x then y else if View . is_empty y then x else if 0 = Rng . Int . gen 1 then x else y let to_list t = List . map ( fun ( _nid , node ) -> node ) ( View . bindings t ) let of_list l = List . fold_left ( fun t node -> add node t ) empty l let pp ppf t = View . iter ( fun _nid node -> Fmt . pf ppf " - % a \ n " Node . pp node ) t end
let list_modules ~ path = List . fold_left path ~ init [ ] : ~ f : begin fun modules dir -> let l = List . filter ( Useunix . get_files_in_directory dir ) ~ f ( : fun x -> Filename . check_suffix x " . cmi " ) in let l = List . map l ~ f : begin fun x -> String . capitalize ( Filename . chop_suffix x " . cmi " ) end in List . fold_left l ~ init : modules ~ f ( : fun modules item -> if List . mem item modules then modules else item :: modules ) end
let reset_modules box = Listbox . delete box ~ first ( ` : Num 0 ) ~ last ` : End ; module_list := Sort . list ( Jg_completion . lt_string ~ nocase : true ) ( list_modules ~ path :! Config . load_path ) ; Listbox . insert box ~ index ` : End ~ texts :! module_list ; Jg_box . recenter box ~ index ( ` : Num 0 )
let view_symbol ~ kind ~ env ? path id = let name = match id with Lident x -> x | Ldot ( _ , x ) -> x | _ -> match kind with Pvalue | Ptype | Plabel -> " z " | _ -> " Z " in match kind with Pvalue -> let path , vd = lookup_value id env in view_signature_item ~ path ~ env [ Tsig_value ( Ident . create name , vd ) ] | Ptype -> view_type_id id ~ env | Plabel -> let ld = lookup_label id env in begin match ld . lbl_res . desc with Tconstr ( path , _ , _ ) -> view_type_decl path ~ env | _ -> ( ) end | Pconstructor -> let cd = lookup_constructor id env in begin match cd . cstr_res . desc with Tconstr ( cpath , _ , _ ) -> if Path . same cpath Predef . path_exn then view_signature ~ title ( : string_of_longident id ) ~ env ? path [ Tsig_exception ( Ident . create name , cd . cstr_args ) ] else view_type_decl cpath ~ env | _ -> ( ) end | Pmodule -> view_module_id id ~ env | Pmodtype -> view_modtype_id id ~ env | Pclass -> view_class_id id ~ env | Pcltype -> view_cltype_id id ~ env
let choose_symbol ~ title ~ env ? signature ? path l = if match path with None -> false | Some path -> is_shown_module path then ( ) else let tl = Jg_toplevel . titled title in Jg_bind . escape_destroy tl ; top_widgets := coe tl :: ! top_widgets ; let buttons = Frame . create tl in let all = Button . create buttons ~ text " : Show all " ~ padx : 20 and ok = Jg_button . create_destroyer tl ~ parent : buttons and detach = Button . create buttons ~ text " : Detach " and edit = Button . create buttons ~ text " : Impl " and intf = Button . create buttons ~ text " : Intf " in let l = List . sort l ~ cmp ( : fun ( li1 , _ ) ( li2 , _ ) -> compare li1 li2 ) in let nl = List . map l ~ f : begin fun ( li , k ) -> string_of_longident li ^ " ( " ^ string_of_kind k ^ " ) " end in let fb = Frame . create tl in let box = new Jg_multibox . c fb ~ cols : 3 ~ texts : nl ~ maxheight : 3 ~ width : 21 in box # init ; box # bind_kbd ~ events [ ` : KeyPressDetail " Escape " ] ~ action ( : fun _ ~ index -> destroy tl ; break ( ) ) ; if List . length nl > 9 then ignore ( Jg_multibox . add_scrollbar box ) ; Jg_multibox . add_completion box ~ action : begin fun pos -> let li , k = List . nth l pos in let path = match path , li with None , Ldot ( lip , _ ) -> begin try Some ( fst ( lookup_module lip env ) ) with Not_found -> None end | _ -> path in view_symbol li ~ kind : k ~ env ? path end ; pack [ buttons ] ~ side ` : Bottom ~ fill ` : X ; pack [ fb ] ~ side ` : Top ~ fill ` : Both ~ expand : true ; begin match signature with None -> pack [ ok ] ~ fill ` : X ~ expand : true | Some signature -> Button . configure all ~ command : begin fun ( ) -> view_signature signature ~ title ~ env ? path end ; pack [ ok ; all ] ~ side ` : Right ~ fill ` : X ~ expand : true end ; begin match path with None -> ( ) | Some path -> let frame = Frame . create tl in pack [ frame ] ~ side ` : Bottom ~ fill ` : X ; add_shown_module path ~ widgets { : mw_frame = frame ; mw_title = None ; mw_detach = detach ; mw_edit = edit ; mw_intf = intf } end
let choose_symbol_ref = ref choose_symbol
let guess_search_mode s : [ ` Type | ` Long | ` Pattern ] = let is_type = ref false and is_long = ref false in for i = 0 to String . length s - 2 do if s . [ i ] = ' ' - && s . [ i + 1 ] = ' ' > then is_type := true ; if s . [ i ] = ' . ' then is_long := true done ; if ! is_type then ` Type else if ! is_long then ` Long else ` Pattern
let search_string ( ? mode " = symbol " ) ew = let text = Entry . get ew in try if text = " " then ( ) else let l = match mode with " Name " -> begin match guess_search_mode text with ` Long -> search_string_symbol text | ` Pattern -> search_pattern_symbol text | ` Type -> search_string_type text ~ mode ` : Included end | " Type " -> search_string_type text ~ mode ` : Included | " Exact " -> search_string_type text ~ mode ` : Exact | _ -> assert false in match l with [ ] -> ( ) | [ lid , kind ] -> view_symbol lid ~ kind ~ env :! start_env | l -> choose_symbol ~ title " : Choose symbol " ~ env :! start_env l with Searchid . Error ( s , e ) -> Entry . icursor ew ~ index ( ` : Num s )
let search_which = ref " Name "
let search_symbol ( ) = if ! module_list = [ ] then module_list := List . sort ~ cmp : compare ( list_modules ~ path :! Config . load_path ) ; let tl = Jg_toplevel . titled " Search symbol " in Jg_bind . escape_destroy tl ; let ew = Entry . create tl ~ width : 30 in let choice = Frame . create tl and which = Textvariable . create ~ on : tl ( ) in let itself = Radiobutton . create choice ~ text " : Itself " ~ variable : which ~ value " : Name " and extype = Radiobutton . create choice ~ text " : Exact type " ~ variable : which ~ value " : Exact " and iotype = Radiobutton . create choice ~ text " : Included type " ~ variable : which ~ value " : Type " and buttons = Frame . create tl in let search = Button . create buttons ~ text " : Search " ~ command : begin fun ( ) -> search_which := Textvariable . get which ; search_string ew ~ mode :! search_which end and ok = Jg_button . create_destroyer tl ~ parent : buttons ~ text " : Cancel " in Focus . set ew ; Jg_bind . return_invoke ew ~ button : search ; Textvariable . set which ! search_which ; pack [ itself ; extype ; iotype ] ~ side ` : Left ~ anchor ` : W ; pack [ search ; ok ] ~ side ` : Left ~ fill ` : X ~ expand : true ; pack [ coe ew ; coe choice ; coe buttons ] ~ side ` : Top ~ fill ` : X ~ expand : true
let ident_of_decl ~ modlid = function Tsig_value ( id , _ ) -> Lident ( Ident . name id ) , Pvalue | Tsig_type ( id , _ , _ ) -> Lident ( Ident . name id ) , Ptype | Tsig_exception ( id , _ ) -> Ldot ( modlid , Ident . name id ) , Pconstructor | Tsig_module ( id , _ , _ ) -> Lident ( Ident . name id ) , Pmodule | Tsig_modtype ( id , _ ) -> Lident ( Ident . name id ) , Pmodtype | Tsig_class ( id , _ , _ ) -> Lident ( Ident . name id ) , Pclass | Tsig_cltype ( id , _ , _ ) -> Lident ( Ident . name id ) , Pcltype
let view_defined ~ env ( ? show_all = false ) modlid = try match lookup_module modlid env with path , Tmty_signature sign -> let rec iter_sign sign idents = match sign with [ ] -> List . rev idents | decl :: rem -> let rem = match decl , rem with Tsig_class _ , cty :: ty1 :: ty2 :: rem -> rem | Tsig_cltype _ , ty1 :: ty2 :: rem -> rem | _ , rem -> rem in iter_sign rem ( ident_of_decl ~ modlid decl :: idents ) in let l = iter_sign sign [ ] in let title = string_of_path path in let env = open_signature path sign env in ! choose_symbol_ref l ~ title ~ signature : sign ~ env ~ path ; if show_all then view_signature sign ~ title ~ env ~ path | _ -> ( ) with Not_found -> ( ) | Env . Error err -> let tl , tw , finish = Jg_message . formatted ~ title " : Error " ! ( ) in Env . report_error Format . std_formatter err ; finish ( )
let close_all_views ( ) = List . iter ! top_widgets ~ f ( : fun tl -> try destroy tl with Protocol . TkError _ -> ( ) ) ; top_widgets := [ ]
let shell_counter = ref 1
let default_shell = ref " ocaml "
let start_shell master = let tl = Jg_toplevel . titled " Start New Shell " in Wm . transient_set tl ~ master ; let input = Frame . create tl and buttons = Frame . create tl in let ok = Button . create buttons ~ text " : Ok " and cancel = Jg_button . create_destroyer tl ~ parent : buttons ~ text " : Cancel " and labels = Frame . create input and entries = Frame . create input in let l1 = Label . create labels ~ text " : Command " : and l2 = Label . create labels ~ text " : Title " : and e1 = Jg_entry . create entries ~ command ( : fun _ -> Button . invoke ok ) and e2 = Jg_entry . create entries ~ command ( : fun _ -> Button . invoke ok ) and names = List . map ~ f : fst ( Shell . get_all ( ) ) in Entry . insert e1 ~ index ` : End ~ text :! default_shell ; let shell_name ( ) = " Shell " # ^ string_of_int ! shell_counter in while List . mem ( shell_name ( ) ) names do incr shell_counter done ; Entry . insert e2 ~ index ` : End ~ text ( : shell_name ( ) ) ; Button . configure ok ~ command ( : fun ( ) -> if not ( List . mem ( Entry . get e2 ) names ) then begin default_shell := Entry . get e1 ; Shell . f ~ prog :! default_shell ~ title ( : Entry . get e2 ) ; destroy tl end ) ; pack [ l1 ; l2 ] ~ side ` : Top ~ anchor ` : W ; pack [ e1 ; e2 ] ~ side ` : Top ~ fill ` : X ~ expand : true ; pack [ labels ; entries ] ~ side ` : Left ~ fill ` : X ~ expand : true ; pack [ ok ; cancel ] ~ side ` : Left ~ fill ` : X ~ expand : true ; pack [ input ; buttons ] ~ side ` : Top ~ fill ` : X ~ expand : true
let show_help ( ) = let tl = Jg_toplevel . titled " OCamlBrowser Help " in Jg_bind . escape_destroy tl ; let fw , tw , sb = Jg_text . create_with_scrollbar tl in let ok = Jg_button . create_destroyer ~ parent : tl ~ text " : Ok " tl in Text . insert tw ~ index : tend ~ text : Help . text ; Text . configure tw ~ state ` : Disabled ; Jg_bind . enter_focus tw ; pack [ tw ] ~ side ` : Left ~ fill ` : Both ~ expand : true ; pack [ sb ] ~ side ` : Right ~ fill ` : Y ; pack [ fw ] ~ side ` : Top ~ expand : true ~ fill ` : Both ; pack [ ok ] ~ side ` : Bottom ~ fill ` : X
let f ( ? dir = Unix . getcwd ( ) ) ? on ( ) = let ( top , tl ) = match on with None -> let tl = Jg_toplevel . titled " Module viewer " in ignore ( Jg_bind . escape_destroy tl ) ; ( tl , coe tl ) | Some top -> Wm . title_set top " OCamlBrowser " ; Wm . iconname_set top " OCamlBrowser " ; let tl = Frame . create top in bind tl ~ events [ ` : Destroy ] ~ action ( : fun _ -> exit 0 ) ; pack [ tl ] ~ expand : true ~ fill ` : Both ; ( top , coe tl ) in let menus = Jg_menu . menubar top in let filemenu = new Jg_menu . c " File " ~ parent : menus and modmenu = new Jg_menu . c " Modules " ~ parent : menus in let fmbox , mbox , msb = Jg_box . create_with_scrollbar tl in Jg_box . add_completion mbox ~ nocase : true ~ action : begin fun index -> view_defined ( Lident ( Listbox . get mbox ~ index ) ) ~ env :! start_env end ; Setpath . add_update_hook ( fun ( ) -> reset_modules mbox ) ; let ew = Entry . create tl in let buttons = Frame . create tl in let search = Button . create buttons ~ text " : Search " ~ pady : 1 ~ command ( : fun ( ) -> search_string ew ) and close = Button . create buttons ~ text " : Close all " ~ pady : 1 ~ command : close_all_views in Jg_bind . enter_focus ew ; Jg_bind . return_invoke ew ~ button : search ; bind close ~ events [ ` : Modified ( [ ` Double ] , ` ButtonPressDetail 1 ) ] ~ action ( : fun _ -> destroy tl ) ; filemenu # add_command " Open . . . " ~ command ( : fun ( ) -> ! editor_ref ~ opendialog : true ( ) ) ; filemenu # add_command " Editor . . . " ~ command ( : fun ( ) -> ! editor_ref ( ) ) ; filemenu # add_command " Shell . . . " ~ command ( : fun ( ) -> start_shell tl ) ; filemenu # add_command " Quit " ~ command ( : fun ( ) -> destroy tl ) ; modmenu # add_command " Path editor . . . " ~ command ( : fun ( ) -> Setpath . set ~ dir ) ; modmenu # add_command " Reset cache " ~ command ( : fun ( ) -> reset_modules mbox ; Env . reset_cache ( ) ) ; modmenu # add_command " Search symbol . . . " ~ command : search_symbol ; pack [ close ; search ] ~ fill ` : X ~ side ` : Right ~ expand : true ; pack [ coe buttons ; coe ew ] ~ fill ` : X ~ side ` : Bottom ; pack [ msb ] ~ side ` : Right ~ fill ` : Y ; pack [ mbox ] ~ side ` : Left ~ fill ` : Both ~ expand : true ; pack [ fmbox ] ~ fill ` : Both ~ expand : true ~ side ` : Top ; reset_modules mbox let ( top , tl ) = match on with None -> let tl = Jg_toplevel . titled " Module viewer " in ignore ( Jg_bind . escape_destroy tl ) ; ( tl , coe tl ) | Some top -> Wm . title_set top " OCamlBrowser " ; Wm . iconname_set top " OCamlBrowser " ; let tl = Frame . create top in bind tl ~ events [ ` : Destroy ] ~ action ( : fun _ -> exit 0 ) ; pack [ tl ] ~ side ` : Bottom ~ expand : true ~ fill ` : Both ; ( top , coe tl ) in let menus = Menu . create top ~ name " : menubar " ~ typ ` : Menubar in let ( ) = Toplevel . configure top ~ menu : menus in let filemenu = new Jg_menu . c " File " ~ parent : menus and modmenu = new Jg_menu . c " Modules " ~ parent : menus and viewmenu = new Jg_menu . c " View " ~ parent : menus and helpmenu = new Jg_menu . c " Help " ~ parent : menus in let search_frame = Frame . create tl in let boxes_frame = Frame . create tl ~ name " : boxes " in let label = Label . create tl ~ anchor ` : W ~ padx : 5 in let view = Frame . create tl in let buttons = Frame . create tl in let _all = Button . create buttons ~ text " : Show all " ~ padx : 20 and close = Button . create buttons ~ text " : Close all " ~ command : close_all_views and detach = Button . create buttons ~ text " : Detach " and edit = Button . create buttons ~ text " : Impl " and intf = Button . create buttons ~ text " : Intf " in val mutable boxes = [ ] val mutable show_all = fun ( ) -> ( ) method create_box = let fmbox , mbox , sb = Jg_box . create_with_scrollbar boxes_frame in bind mbox ~ events [ ` : Modified ( [ ` Double ] , ` ButtonPressDetail 1 ) ] ~ action ( : fun _ -> show_all ( ) ) ; bind mbox ~ events [ ` : Modified ( [ ` Double ] , ` KeyPressDetail " Return " ) ] ~ action ( : fun _ -> show_all ( ) ) ; boxes <- boxes @ [ fmbox , mbox ] ; pack [ sb ] ~ side ` : Right ~ fill ` : Y ; pack [ mbox ] ~ side ` : Left ~ fill ` : Both ~ expand : true ; pack [ fmbox ] ~ side ` : Left ~ fill ` : Both ~ expand : true ; fmbox , mbox initializer let ew = Entry . create search_frame and searchtype = Textvariable . create ~ on : tl ( ) in bind ew ~ events [ ` : KeyPressDetail " Return " ] ~ action : ( fun _ -> search_string ew ~ mode ( : Textvariable . get searchtype ) ) ; Jg_bind . enter_focus ew ; let search_button ? value text = Radiobutton . create search_frame ~ text ~ variable : searchtype ~ value : text in let symbol = search_button " Name " and atype = search_button " Type " in Radiobutton . select symbol ; pack [ Label . create search_frame ~ text " : Search " ] ~ side ` : Left ~ ipadx : 5 ; pack [ ew ] ~ fill ` : X ~ expand : true ~ side ` : Left ; pack [ Label . create search_frame ~ text " : by " ] ~ side ` : Left ~ ipadx : 5 ; pack [ symbol ; atype ] ~ side ` : Left ; pack [ Label . create search_frame ] ~ side ` : Right initializer let fmbox , mbox = self # create_box in Jg_box . add_completion mbox ~ nocase : true ~ double : false ~ action : begin fun index -> view_defined ( Lident ( Listbox . get mbox ~ index ) ) ~ env :! start_env end ; Setpath . add_update_hook ( fun ( ) -> reset_modules mbox ; self # hide_after 1 ) ; List . iter [ 1 ; 2 ] ~ f ( : fun _ -> ignore self # create_box ) ; Searchpos . default_frame := Some { mw_frame = view ; mw_title = Some label ; mw_detach = detach ; mw_edit = edit ; mw_intf = intf } ; Searchpos . set_path := self # set_path ; pack [ close ] ~ side ` : Right ~ fill ` : X ~ expand : true ; bind close ~ events [ ` : Modified ( [ ` Double ] , ` ButtonPressDetail 1 ) ] ~ action ( : fun _ -> destroy tl ) ; filemenu # add_command " Open . . . " ~ command ( : fun ( ) -> ! editor_ref ~ opendialog : true ( ) ) ; filemenu # add_command " Editor . . . " ~ command ( : fun ( ) -> ! editor_ref ( ) ) ; filemenu # add_command " Shell . . . " ~ command ( : fun ( ) -> start_shell tl ) ; filemenu # add_command " Quit " ~ command ( : fun ( ) -> destroy tl ) ; viewmenu # add_command " Show all defs " ~ command ( : fun ( ) -> show_all ( ) ) ; let show_search = Textvariable . create ~ on : tl ( ) in Textvariable . set show_search " 1 " ; Menu . add_checkbutton viewmenu # menu ~ label " : Search Entry " ~ variable : show_search ~ indicatoron : true ~ state ` : Active ~ command : begin fun ( ) -> let v = Textvariable . get show_search in if v = " 1 " then begin pack [ search_frame ] ~ after : menus ~ fill ` : X end else Pack . forget [ search_frame ] end ; modmenu # add_command " Path editor . . . " ~ command ( : fun ( ) -> Setpath . set ~ dir ) ; modmenu # add_command " Reset cache " ~ command ( : fun ( ) -> reset_modules mbox ; Env . reset_cache ( ) ) ; modmenu # add_command " Search symbol . . . " ~ command : search_symbol ; helpmenu # add_command " Manual . . . " ~ command : show_help ; pack [ search_frame ] ~ fill ` : X ; pack [ boxes_frame ] ~ fill ` : Both ~ expand : true ; pack [ buttons ] ~ fill ` : X ~ side ` : Bottom ; pack [ view ] ~ fill ` : Both ~ side ` : Bottom ~ expand : true ; reset_modules mbox val mutable shown_paths = [ ] method hide_after n = for i = n to List . length boxes - 1 do let fm , box = List . nth boxes i in if i < 3 then Listbox . delete box ~ first ( ` : Num 0 ) ~ last ` : End else destroy fm done ; let rec firsts n = function [ ] -> [ ] | a :: l -> if n > 0 then a :: firsts ( pred n ) l else [ ] in shown_paths <- firsts ( n - 1 ) shown_paths ; boxes <- firsts ( max 3 n ) boxes method get_box ~ path = let rec path_index p = function [ ] -> raise Not_found | a :: l -> if Path . same p a then 1 else path_index p l + 1 in try let n = path_index path shown_paths in self # hide_after ( n + 1 ) ; n with Not_found -> match path with Path . Pdot ( path ' , _ , _ ) -> let n = self # get_box ~ path : path ' in shown_paths <- shown_paths @ [ path ] ; if n + 1 >= List . length boxes then ignore self # create_box ; n + 1 | _ -> self # hide_after 2 ; shown_paths <- [ path ] ; 1 method set_path path ~ sign = let rec path_elems l path = match path with Path . Pdot ( path , _ , _ ) -> path_elems ( path :: l ) path | _ -> [ ] in let path_elems path = match path with | Path . Pident _ -> [ path ] | _ -> path_elems [ ] path in let see_path ~ box : n ( ? sign [ ] ) = path = let ( _ , box ) = List . nth boxes n in let texts = Listbox . get_range box ~ first ( ` : Num 0 ) ~ last ` : End in let rec index s = function [ ] -> raise Not_found | a :: l -> if a = s then 0 else 1 + index s l in try let modlid , s = match path with Path . Pdot ( p , s , _ ) -> longident_of_path p , s | Path . Pident i -> Longident . Lident " M " , Ident . name i | _ -> assert false in let li , k = if sign = [ ] then Longident . Lident s , Pmodule else ident_of_decl ~ modlid ( List . hd sign ) in let s = if n = 0 then string_of_longident li else string_of_longident li ^ " ( " ^ string_of_kind k ^ " ) " in let n = index s texts in Listbox . see box ( ` Num n ) ; Listbox . activate box ( ` Num n ) with Not_found -> ( ) in let l = path_elems path in if l <> [ ] then begin List . iter l ~ f : begin fun path -> if not ( List . mem path shown_paths ) then view_symbol ( longident_of_path path ) ~ kind : Pmodule ~ env : Env . initial ~ path ; let n = self # get_box path - 1 in see_path path ~ box : n end ; see_path path ~ box ( : self # get_box path ) ~ sign end method choose_symbol ~ title ~ env ? signature ? path l = let n = match path with None -> 1 | Some path -> self # get_box ~ path in let l = List . sort l ~ cmp ( : fun ( li1 , _ ) ( li2 , _ ) -> compare li1 li2 ) in let nl = List . map l ~ f : begin fun ( li , k ) -> string_of_longident li ^ " ( " ^ string_of_kind k ^ " ) " end in let _ , box = List . nth boxes n in Listbox . delete box ~ first ( ` : Num 0 ) ~ last ` : End ; Listbox . insert box ~ index ` : End ~ texts : nl ; let current = ref None in let display index = let ` Num pos = Listbox . index box ~ index in try let li , k = List . nth l pos in self # hide_after ( n + 1 ) ; if ! current = Some ( li , k ) then ( ) else let path = match path , li with None , Ldot ( lip , _ ) -> begin try Some ( fst ( lookup_module lip env ) ) with Not_found -> None end | _ -> path in current := Some ( li , k ) ; view_symbol li ~ kind : k ~ env ? path with Failure " nth " -> ( ) in Jg_box . add_completion box ~ double : false ~ action : display ; bind box ~ events [ ` : KeyRelease ] ~ fields [ ` : Char ] ~ action ( : fun ev -> display ` Active ) ; begin match signature with None -> ( ) | Some signature -> show_all <- begin fun ( ) -> current := None ; view_signature signature ~ title ~ env ? path end end end
let st_viewer ? dir ? on ( ) = let viewer = new st_viewer ? dir ? on ( ) in choose_symbol_ref := viewer # choose_symbol
let pi = 4 . . * atan 1 .
module F ( M : sig type font type color type text val white : color type ctx val save : ctx -> unit val restore : ctx -> unit val scale : ctx -> sx : float -> sy : float -> unit val translate : ctx -> tx : float -> ty : float -> unit val begin_path : ctx -> unit val close_path : ctx -> unit val move_to : ctx -> x : float -> y : float -> unit val line_to : ctx -> x : float -> y : float -> unit val curve_to : ctx -> x1 : float -> y1 : float -> x2 : float -> y2 : float -> x3 : float -> y3 : float -> unit val arc : ctx -> xc : float -> yc : float -> radius : float -> angle1 : float -> angle2 : float -> unit val rectangle : ctx -> x : float -> y : float -> width : float -> height : float -> unit val fill : ctx -> color -> unit val stroke : ctx -> color -> unit val clip : ctx -> unit val draw_text : ctx -> float -> float -> text -> font -> color option -> color option -> unit type window type drawable type pixmap val get_drawable : window -> drawable val make_pixmap : window -> int -> int -> pixmap val drawable_of_pixmap : pixmap -> drawable val get_context : pixmap -> ctx val put_pixmap : dst : drawable -> x : int -> y : int -> xsrc : int -> ysrc : int -> width : int -> height : int -> pixmap -> unit type rectangle = { x : int ; y : int ; width : int ; height : int } val compute_extents : ctx -> ( color , font , text ) Scene . element array -> ( float * float * float * float ) array struct open M let empty_rectangle = { x = 0 ; y = 0 ; width = 0 ; height = 0 } let rectangle_is_empty r = r . width = 0 || r . height = 0 type pixmap = { mutable pixmap : M . pixmap option ; mutable p_width : int ; mutable p_height : int ; mutable valid_rect : rectangle } let make_pixmap ( ) = { pixmap = None ; p_width = 0 ; p_height = 0 ; valid_rect = empty_rectangle } let invalidate_pixmap p = p . valid_rect <- empty_rectangle let grow_pixmap pm window width height = let width = max width pm . p_width in let height = max height pm . p_height in if width > pm . p_width || height > pm . p_height then ( let old_p = pm . pixmap in let p = M . make_pixmap window width height in let r = pm . valid_rect in ( match old_p with | Some old_p -> put_pixmap ~ dst ( : drawable_of_pixmap p ) ~ x : 0 ~ y : 0 ~ xsrc : 0 ~ ysrc : 0 ~ width : r . width ~ height : r . height old_p | None -> ( ) ) ; pm . pixmap <- Some p ; pm . p_width <- width ; pm . p_height <- height ) let get_pixmap pm = match pm . pixmap with | Some p -> p | None -> assert false type st = { mutable bboxes : ( float * float * float * float ) array ; scene : ( color , font , text ) Scene . element array ; mutable zoom_factor : float ; st_x : float ; st_y : float ; st_width : float ; st_height : float ; st_pixmap : pixmap } let perform_draw ctx fill stroke = ( match fill with | Some c -> M . fill ctx c | None -> ( ) ) ; match stroke with | Some c -> M . stroke ctx c | None -> ( ) let draw_element ctx e = begin_path ctx ; match e with | Path ( cmd , fill , stroke ) -> Array . iter ( fun c -> match c with | Move_to ( x , y ) -> move_to ctx ~ x ~ y | Curve_to ( x1 , y1 , x2 , y2 , x3 , y3 ) -> curve_to ctx ~ x1 ~ y1 ~ x2 ~ y2 ~ x3 ~ y3 ) cmd ; perform_draw ctx fill stroke | Ellipse ( cx , cy , rx , ry , fill , stroke ) -> save ctx ; translate ctx ~ tx : cx ~ ty : cy ; scale ctx ~ sx : rx ~ sy : ry ; arc ctx ~ xc : 0 . ~ yc : 0 . ~ radius : 1 . ~ angle1 : 0 . ~ angle2 ( : 2 . . * pi ) ; restore ctx ; perform_draw ctx fill stroke | Polygon ( points , fill , stroke ) -> Array . iteri ( fun i ( x , y ) -> if i = 0 then move_to ctx ~ x ~ y else line_to ctx ~ x ~ y ) points ; close_path ctx ; perform_draw ctx fill stroke | Text ( x , y , txt , font , fill , stroke ) -> draw_text ctx x y txt font fill stroke let intersects ( ( x1 , y1 , x2 , y2 ) : float * float * float * float ) ( x3 , y3 , x4 , y4 ) = x1 <= x4 && y1 <= y4 && x3 <= x2 && y3 <= y2 let redraw st scale x y x ' y ' w h = let ctx = get_context ( get_pixmap st . st_pixmap ) in save ctx ; if Array . length st . bboxes = 0 && Array . length st . scene > 0 then st . bboxes <- compute_extents ctx st . scene ; begin_path ctx ; rectangle ctx ~ x ( : float x ' ) ~ y ( : float y ' ) ~ width ( : float w ) ~ height ( : float h ) ; M . fill ctx M . white ; clip ctx ; let x = float x . / scale in let y = float y . / scale in M . scale ctx ~ sx : scale ~ sy : scale ; translate ctx ~ tx ( . :- st . st_x . - x ) ~ ty ( . :- st . st_y . - y ) ; let bbox = let x = st . st_x . + x . + ( float x ' . / scale ) in let y = st . st_y . + y . + ( float y ' . / scale ) in ( x , y , x . + ( float st . st_pixmap . p_width . / scale ) , y . + ( float st . st_pixmap . p_height . / scale ) ) in for i = 0 to Array . length st . scene - 1 do let box = st . bboxes . ( i ) in let e = st . scene . ( i ) in if intersects box bbox then draw_element ctx e done ; restore ctx let redraw st scale x0 y0 window a x y width height = let pm = st . st_pixmap in grow_pixmap pm window a . width a . height ; let round x = truncate ( ( x . * scale ) . + 0 . 5 ) in let x0 = round x0 in let x0 ' = round ( ( ( float a . width . / scale ) . - st . st_width ) . / 2 . ) in let x0 = if x0 ' > 0 then - x0 ' else x0 in let y0 = round y0 in let y0 ' = round ( ( ( float a . height . / scale ) . - st . st_height ) . / 2 . ) in let y0 = if y0 ' > 0 then - y0 ' else y0 in let dx = pm . valid_rect . x - x0 in let dy = pm . valid_rect . y - y0 in if ( dx > 0 && pm . valid_rect . width + dx < a . width ) || ( dy > 0 && pm . valid_rect . height + dy < a . height ) then pm . valid_rect <- empty_rectangle else if not ( rectangle_is_empty pm . valid_rect ) then ( let p = get_pixmap pm in let r = pm . valid_rect in if dx <> 0 || dy <> 0 then put_pixmap ~ dst ( : drawable_of_pixmap p ) ~ x : dx ~ y : dy ~ xsrc : 0 ~ ysrc : 0 ~ width : r . width ~ height : r . height p ; let offset p l d m = if p + d + l <= 0 then 0 , 0 else if p + d < 0 then 0 , l + p + d else if p + d >= m then m , 0 else if p + d + l > m then p + d , m - p - d else p + d , l in let x , width = offset 0 r . width dx pm . p_width in let y , height = offset 0 r . height dy pm . p_height in if height > 0 then if x > 0 then ( assert ( x + width >= a . width ) ; redraw st scale x0 y0 0 y x height ) else ( assert ( x = 0 ) ; if a . width > width then redraw st scale x0 y0 width y ( a . width - width ) height ) ; if y > 0 then ( assert ( y + height >= a . height ) ; redraw st scale x0 y0 0 0 a . width y ) else ( assert ( y = 0 ) ; if a . height > height then redraw st scale x0 y0 0 height a . width ( a . height - height ) ) ; pm . valid_rect <- { x = x0 ; y = y0 ; width = a . width ; height = a . height } ) ; let r = pm . valid_rect in if x < 0 || y < 0 || x + width > r . width || y + height > r . height then ( redraw st scale x0 y0 0 0 a . width a . height ; pm . valid_rect <- { x = x0 ; y = y0 ; width = a . width ; height = a . height } ) ; put_pixmap ~ dst ( : get_drawable window ) ~ x ~ y ~ xsrc : x ~ ysrc : y ~ width ~ height ( get_pixmap pm ) end
type rect = { x : int ; y : int ; width : int ; height : int }
let create_canvas w h = let c = Html . createCanvas Html . document in c . ## width := w ; c . ## height := h ; c
module Common = Viewer_common . F ( struct type font = Js . js_string Js . t type color = Js . js_string Js . t type text = Js . js_string Js . t let white = Js . string " white " type ctx = Html . canvasRenderingContext2D Js . t let save ctx = ctx ## save let restore ctx = ctx ## restore let scale ctx ~ sx ~ sy = ctx ## scale sx sy let translate ctx ~ tx ~ ty = ctx ## translate tx ty let begin_path ctx = ctx ## beginPath let close_path ctx = ctx ## closePath let move_to ctx ~ x ~ y = ctx ## moveTo x y let line_to ctx ~ x ~ y = ctx ## lineTo x y let curve_to ctx ~ x1 ~ y1 ~ x2 ~ y2 ~ x3 ~ y3 = ctx ## bezierCurveTo x1 y1 x2 y2 x3 y3 let arc ctx ~ xc ~ yc ~ radius ~ angle1 ~ angle2 = ctx ## arc xc yc radius angle1 angle2 Js . _true let rectangle ctx ~ x ~ y ~ width ~ height = ctx ## rect x y width height let fill ctx c = ctx . ## fillStyle := c ; ctx ## fill let stroke ctx c = ctx . ## strokeStyle := c ; ctx ## stroke let clip ctx = ctx ## clip let draw_text ( ctx : ctx ) x y txt font fill_color stroke_color = ctx . ## font := font ; ctx . ## textAlign := Js . string " center " ; ctx . ## textBaseline := Js . string " middle " ; ( match fill_color with | Some c -> ctx . ## fillStyle := c ; ctx ## fillText txt x y | None -> ( ) ) ; match stroke_color with | Some c -> ctx . ## strokeStyle := c ; ctx ## strokeText txt x y | None -> ( ) type window = Html . canvasElement Js . t type drawable = window * ctx type pixmap = drawable let get_drawable w = let ctx = w ## getContext Html . _2d_ in ctx . ## lineWidth := 2 . ; w , ctx let make_pixmap _ width height = let c = Html . createCanvas Html . document in c . ## width := width ; c . ## height := height ; get_drawable c let drawable_of_pixmap p = p let get_context ( _p , c ) = c let put_pixmap ~ dst ( ( : _p , c ) : drawable ) ~ x ~ y ~ xsrc ~ ysrc ~ width ~ height ( ( p , _ ) : pixmap ) = c ## drawImage_fullFromCanvas p ( float xsrc ) ( float ysrc ) ( float width ) ( float height ) ( float x ) ( float y ) ( float width ) ( float height ) type rectangle = rect = { x : int ; y : int ; width : int ; height : int } let compute_extents _ = assert false end )
let redraw st s h v ( canvas : Html . canvasElement Js . t ) = let width = canvas . ## width in let height = canvas . ## height in redraw st s h v canvas { x = 0 ; y = 0 ; width ; height } 0 0 width height
let json : < parse : Js . js_string Js . t -> ' a > Js . t = Js . Unsafe . pure_js_expr " JSON "
let ( >>= ) = Lwt . bind
let http_get url = XmlHttpRequest . get url >>= fun { XmlHttpRequest . code = cod ; content = msg ; _ } -> if cod = 0 || cod = 200 then Lwt . return msg else fst ( Lwt . wait ( ) )
let getfile f = try Lwt . return ( Sys_js . read_file ~ name : f ) with Not_found -> http_get f ( ? value = 0 . ) ( ? lower = 0 . ) ( ? upper = 100 . ) ( ? step_incr = 1 . ) ( ? page_incr = 10 . ) ( ? page_size = 10 . ) ( ) = object val mutable _value = value method value = _value val mutable _lower = lower method lower = _lower val mutable _upper = upper method upper = _upper val mutable _step_incr = step_incr method step_increment = _step_incr val mutable _page_incr = page_incr method page_increment = _page_incr val mutable _page_size = page_size method page_size = _page_size method set_value v = _value <- v method set_bounds ? lower ? upper ? step_incr ? page_incr ? page_size ( ) = ( match lower with | Some v -> _lower <- v | None -> ( ) ) ; ( match upper with | Some v -> _upper <- v | None -> ( ) ) ; ( match step_incr with | Some v -> _step_incr <- v | None -> ( ) ) ; ( match page_incr with | Some v -> _page_incr <- v | None -> ( ) ) ; match page_size with | Some v -> _page_size <- v | None -> ( ) end
let handle_drag element f = let mx = ref 0 in let my = ref 0 in element . ## onmousedown := Html . handler ( fun ev -> mx := ev . ## clientX ; my := ev . ## clientY ; element . ## style . ## cursor := Js . string " move " ; let c1 = Html . addEventListener Html . document Html . Event . mousemove ( Html . handler ( fun ev -> let x = ev . ## clientX and y = ev . ## clientY in let x ' = ! mx and y ' = ! my in mx := x ; my := y ; f ( x - x ' ) ( y - y ' ) ; Js . _true ) ) Js . _true in let c2 = ref Js . null in c2 := Js . some ( Html . addEventListener Html . document Html . Event . mouseup ( Html . handler ( fun _ -> Html . removeEventListener c1 ; Js . Opt . iter ! c2 Html . removeEventListener ; element . ## style . ## cursor := Js . string " " ; Js . _true ) ) Js . _true ) ; Js . _true )
let start ( ) = let doc = Html . document in let page = doc . ## documentElement in page . ## style . ## overflow := Js . string " hidden " ; doc . ## body . ## style . ## overflow := Js . string " hidden " ; doc . ## body . ## style . ## margin := Js . string " 0px " ; let started = ref false in let p = Html . createP doc in p . ## innerHTML := Js . string " Loading graph . . . " ; p . ## style . ## display := Js . string " none " ; Dom . appendChild doc . ## body p ; ignore ( Lwt_js . sleep 0 . 5 >>= fun ( ) -> if not ! started then p . ## style . ## display := Js . string " inline " ; Lwt . return ( ) ) ; getfile " scene . json " >>= fun s -> let ( x1 , y1 , x2 , y2 ) , bboxes , scene = json ## parse ( Js . string s ) in started := true ; Dom . removeChild doc . ## body p ; let st = { bboxes ; scene ; zoom_factor = 1 . . / 20 . ; st_x = x1 ; st_y = y1 ; st_width = x2 . - x1 ; st_height = y2 . - y1 ; st_pixmap = Common . make_pixmap ( ) } in let canvas = create_canvas page . ## clientWidth page . ## clientHeight in Dom . appendChild doc . ## body canvas ; let allocation ( ) = { x = 0 ; y = 0 ; width = canvas . ## width ; height = canvas . ## height } in let hadj = new adjustment ( ) in let vadj = new adjustment ( ) in let sadj = new adjustment ~ upper : 20 . ~ step_incr : 1 . ~ page_incr : 0 . ~ page_size : 0 . ( ) in let zoom_steps = 8 . in let set_zoom_factor f = let count = ceil ( log f . / log 2 . . * zoom_steps ) in let f = 2 . ** ( count . / zoom_steps ) in sadj # set_bounds ~ upper : count ( ) ; st . zoom_factor <- f in let get_scale ( ) = ( 2 . ** ( sadj # value . / zoom_steps ) ) . / st . zoom_factor in let redraw_queued = ref false in let update_view _force = let a = allocation ( ) in let scale = get_scale ( ) in let aw = ceil ( float a . width . / scale ) in let ah = ceil ( float a . height . / scale ) in hadj # set_bounds ~ step_incr ( : aw . / 20 . ) ~ page_incr ( : aw . / 2 . ) ~ page_size ( : min aw st . st_width ) ~ upper : st . st_width ( ) ; let mv = st . st_width . - hadj # page_size in if hadj # value < 0 . then hadj # set_value 0 . ; if hadj # value > mv then hadj # set_value mv ; vadj # set_bounds ~ step_incr ( : ah . / 20 . ) ~ page_incr ( : ah . / 2 . ) ~ page_size ( : min ah st . st_height ) ~ upper : st . st_height ( ) ; let mv = st . st_height . - vadj # page_size in if vadj # value < 0 . then vadj # set_value 0 . ; if vadj # value > mv then vadj # set_value mv ; if not ! redraw_queued then ( redraw_queued := true ; let ( _ : Html . animation_frame_request_id ) = Html . window ## requestAnimationFrame ( Js . wrap_callback ( fun ( _ : float ) -> redraw_queued := false ; redraw st ( get_scale ( ) ) hadj # value vadj # value canvas ) ) in ( ) ) Lwt_js . yield ( ) >>= fun ( ) -> redraw_queued := false ; redraw st ( get_scale ( ) ) hadj # value vadj # value canvas ; Lwt . return ( ) ) ) * in let a = allocation ( ) in let zoom_factor = max ( st . st_width . / float a . width ) ( st . st_height . / float a . height ) in set_zoom_factor zoom_factor ; let prev_scale = ref ( get_scale ( ) ) in let rescale x y = let scale = get_scale ( ) in let r = 1 . . - ( ! prev_scale . / scale ) in hadj # set_value ( hadj # value . + ( hadj # page_size . * r . * x ) ) ; vadj # set_value ( vadj # value . + ( vadj # page_size . * r . * y ) ) ; prev_scale := scale ; invalidate_pixmap st . st_pixmap ; update_view false in let size = 16 in let height = 300 - size in let points d = Js . string ( Printf . sprintf " % dpx " d ) in let size_px = points size in let pos = ref height in let thumb = Html . createDiv doc in let style = thumb . ## style in style . ## position := Js . string " absolute " ; style . ## width := size_px ; style . ## height := size_px ; style . ## top := points ! pos ; style . ## left := Js . string " 0px " ; style . ## margin := Js . string " 1px " ; style . ## backgroundColor := Js . string " black " ; let slider = Html . createDiv doc in let style = slider . ## style in style . ## position := Js . string " absolute " ; style . ## width := size_px ; style . ## height := points ( height + size ) ; style . ## border := Js . string " 2px solid black " ; style . ## padding := Js . string " 1px " ; style . ## top := Js . string " 10px " ; style . ## left := Js . string " 10px " ; Dom . appendChild slider thumb ; Dom . appendChild doc . ## body slider ; let set_slider_position pos ' = if pos ' <> ! pos then ( thumb . ## style . ## top := points pos ' ; pos := pos ' ; sadj # set_value ( float ( height - pos ' ) . * sadj # upper . / float height ) ; rescale 0 . 5 0 . 5 ) in handle_drag thumb ( fun _dx dy -> set_slider_position ( min height ( max 0 ( ! pos + dy ) ) ) ) ; slider . ## onmousedown := Html . handler ( fun ev -> let ey = ev . ## clientY in let _ , sy = Dom_html . elementClientPosition slider in set_slider_position ( max 0 ( min height ( ey - sy - ( size / 2 ) ) ) ) ; Js . _false ) ; let adjust_slider ( ) = let pos ' = height - truncate ( ( sadj # value . * float height . / sadj # upper ) . + 0 . 5 ) in thumb . ## style . ## top := points pos ' ; pos := pos ' in Html . window . ## onresize := Html . handler ( fun _ -> let page = doc . ## documentElement in canvas . ## width := page . ## clientWidth ; canvas . ## height := page . ## clientHeight ; update_view true ; Js . _true ) ; handle_drag canvas ( fun dx dy -> let scale = get_scale ( ) in let offset a d = a # set_value ( min ( a # value . - ( float d . / scale ) ) ( a # upper . - a # page_size ) ) in offset hadj dx ; offset vadj dy ; update_view true ) ; let bump_scale x y v = let a = allocation ( ) in let x = x . / float a . width in let y = y . / float a . height in let prev = sadj # value in let vl = min sadj # upper ( max sadj # lower ( prev . + ( v . * sadj # step_increment ) ) ) in if vl <> prev then ( sadj # set_value vl ; adjust_slider ( ) ; if x >= 0 . && x <= 1 . && y >= 0 . && y <= 1 . then rescale x y else rescale 0 . 5 0 . 5 ) ; Js . _false in ignore ( Html . addMousewheelEventListener canvas ( fun ev ~ dx : _ ~ dy -> let ex , ey = Dom_html . elementClientPosition canvas in let x = float ( ev . ## clientX - ex ) in let y = float ( ev . ## clientY - ey ) in if dy < 0 then bump_scale x y 1 . else if dy > 0 then bump_scale x y ( - 1 . ) else Js . _false ) Js . _true ) ; Js . _false | 38 -> Js . _false | 39 -> Js . _false | 40 -> Js . _false | _ -> Firebug . console ## log ( - 1 - e ## keyCode ) ; Js . _true ) ) Js . _true ; ) * let handle_key_event ev = match ev . ## keyCode with | 37 -> hadj # set_value ( hadj # value . - hadj # step_increment ) ; update_view false ; Js . _false | 38 -> vadj # set_value ( vadj # value . - vadj # step_increment ) ; update_view false ; Js . _false | 39 -> hadj # set_value ( hadj # value . + hadj # step_increment ) ; update_view false ; Js . _false | 40 -> vadj # set_value ( vadj # value . + vadj # step_increment ) ; update_view false ; Js . _false | _ -> Js . _true in let ignored_keycode = ref ( - 1 ) in Html . document . ## onkeydown := Html . handler ( fun e -> ignored_keycode := e . ## keyCode ; handle_key_event e ) ; Html . document . ## onkeypress := Html . handler ( fun e -> let k = ! ignored_keycode in ignored_keycode := - 1 ; if e . ## keyCode = k then Js . _true else handle_key_event e ) ; update_view true ; Lwt . return ( )
let _ = Html . window . ## onload := Html . handler ( fun _ -> ignore ( start ( ) ) ; Js . _false )
type t_point = float * float
type t_coord = t_point * t_point
type t_shape = Srect | Sellipse
type t_gtk_obj = GnomeCanvas . re_p GnoCanvas . item
module Node = struct type t = string * ( t_shape * t_coord * t_gtk_obj ) option let id n = fst n let coord n = match snd n with None -> None | Some ( _ , c , _ ) -> Some c let item n = match snd n with None -> None | Some ( _ , _ , r ) -> Some r end