diff --git "a/dataset.csv" "b/dataset.csv" new file mode 100644--- /dev/null +++ "b/dataset.csv" @@ -0,0 +1,95651 @@ +procedure ejercicio1 is,"s : String := ""Comenzamos las prácticas de STR""; + numero : Natural := 0; +begin + Put(""Hola Mundo!!!""); + Put_Line(s); + pkg_ejercicio2c.OtroProcedimiento; + + -- Ejercicio 3 + begin + Put(""Introduce un numero:""); + Ada.Integer_Text_IO.Get(numero); + + case numero is + when 12 | 1 | 2 => Put_Line(""Invierno""); + when 3 | 4 | 5 => Put_Line(""Primavera""); + when 6 | 7 | 8 => Put_Line(""Verano""); + when 9 | 10 | 11 => Put_Line(""Otoño""); + when others => Put_Line(""Mes incorrecto""); + end case; + + -- Ejercicio 5 + + exception + when Constraint_Error => Put_Line(""El numero de mes debe ser > 0"");" +procedure Simular_Sistema IS,"BEGIN + Gtk.Main.Main; + END Simular_Sistema; + + + ------------------------------------------------------------------------ + -- Procedure que se encarga de inicializar la interfaz gráfica + ------------------------------------------------------------------------ + procedure Inicializar_Interfaz_Grafica is + Win : Gtk_Window; + Buffer : Gtk_Double_Buffer; + Vbox, Hbox : Gtk_Box; + Id : G_Source_Id;--Timeout_Handler_Id; + Button : Gtk_Button; + inbuilt_font : Pango.Font.Pango_Font_Description; + --ventana : Gdk_Window; + --TAM_BUTTON_EXIT : constant GLib.Gint := 20; + alinea_button_exit: Gtk.Alignment.Gtk_Alignment; + A_Check_Button1, A_Check_Button2 : Gtk_Check_Button; + begin + -- ventana principal + Gtk.Window.Gtk_New (Win, Window_Toplevel); + Set_Title (Win, ""PRACTICA STR: CONTROL DE TRAFICO""); + Win.Set_Default_Size(CANVAS_WIDTH, CANVAS_HEIGHT);--+TAM_BUTTON_EXIT); + Void_Cb.Connect (Win, ""destroy"", Void_Cb.To_Marshaller (Quit'Access)); + + + -- botón Exit + Gtk_New (Button, ""EXIT""); + Destroyed.Object_Connect (Button, + ""clicked"", + Destroyed.To_Marshaller (Quit'Access), + Slot_Object => Win); + + Button.Set_Size_Request(100, 20);--TAM_BUTTON_EXIT); + Gtk.Alignment.Gtk_New(alinea_button_exit, 0.5, 0.5, 0.0, 0.0); + alinea_button_exit.Add(Button); + + + -- Double buffer + Double_Buffer.Gtk_New(Buffer); + Buffer.Set_Size_Request(CANVAS_WIDTH, CANVAS_HEIGHT);-- -TAM_BUTTON_EXIT); + + + -- Botones para la generación de averías + Gtk_New (A_Check_Button1, ""Averia en Carril 1""); + Widget_Handler.Object_Connect(A_Check_Button1, ""clicked"", + Widget_Handler.To_Marshaller (Averia1_Generada'ACCESS), + Slot_Object => Win); + + Gtk_New (A_Check_Button2, ""Averia en Carril 2""); + Widget_Handler.Object_Connect(A_Check_Button2, ""clicked"", + Widget_Handler.To_Marshaller (Averia2_Generada'ACCESS), + Slot_Object => Win); + + + + -- Asociar widgets a la ventana principal y mostrarla + Gtk_New_Hbox (Hbox, Homogeneous => True, Spacing => 10); + Gtk_New_Vbox (Vbox, Homogeneous => False, Spacing => 0); + + Pack_Start (Vbox, Buffer); + --Pack_Start (Vbox, Button, Expand => False, Fill => False); + Pack_Start (Vbox, alinea_button_exit);--, Expand => False, Fill => False); + + Pack_Start (Vbox, A_Check_Button1); + Pack_Start (Vbox, A_Check_Button2); + + Pack_Start (Hbox, Vbox); + + + + + + + Win.Add(Hbox); + + Show_All (Win); + + --ventana := Get_Window(Gtk_Widget(Buffer)); + --Gdk.Window.Move(ventana, 0, 0); + + + Id := Main_Context_Sources.Timeout_Add (PERIODICIDAD_REDIBUJAR_MILISEGUNDOS, + Draw_Complex_Buffer'Access, + Gtk_Drawing_Area (Buffer)); + + + Gdk_New(pangoLayout, Get_Pango_Context(Buffer)); + inbuilt_font := Pango.Font.From_String(""Courier""); + Pango.Layout.Set_Font_Description(pangoLayout, inbuilt_font); + + + -- INICIALIZACIÓN DEL ESTADO DE TODOS LOS OBJETOS VISUALIZADOS + Inicializar_Buffer_Coches; + + end Inicializar_Interfaz_Grafica; + + + ------------------ + -- Draw_Complex -- + ------------------ + procedure Draw_Complex (Pixmap : Cairo_Context) is + begin + + Draw_Rectangle (Pixmap, Black_Gc, Filled => True, + X => 0, Y => 0, + Width => CANVAS_WIDTH, Height => CANVAS_HEIGHT); + + + -- DIBUJAR EN EL CANVAS EL ESTADO ACTUAL DE TODOS LOS OBJETOS + Dibujar_Canvas_Calle(Pixmap); + + end Draw_Complex; + + + ------------------------- + -- Draw_Complex_Buffer -- + ------------------------- + function Draw_Complex_Buffer (Area : Gtk_Drawing_Area) return Boolean is + Buffer : Gtk_Double_Buffer := Gtk_Double_Buffer (Area); + + begin + Draw_Complex (Get_Pixmap (Buffer)); + + Double_Buffer.Thaw(Buffer); + + --Double_Buffer.Draw (Buffer); + + return True; + end Draw_Complex_Buffer; + + + + ---------- + -- Quit -- + ---------- + procedure Quit (Win : access Gtk_Window_Record'Class) is + pragma Warnings (Off, Win); + begin + Gnat.OS_Lib.OS_Exit(0); + --Gtk.Main.Main_Quit; + --Ada.Task_Identification.Abort_Task(Ada.Task_Identification.Current_Task); + end Quit; + + + + ------------------------------------------------------------------------ + -- Procedure que inicializa el buffer de coches + ------------------------------------------------------------------------ + procedure Inicializar_Buffer_Coches is + coche : T_RecordCoche; + BEGIN + for carril IN T_Carril loop + FOR I IN T_RangoBufferCoches LOOP + Coche.Id := 0; + Coche.Pos.X := 0; + Coche.Pos.Y := y_carril(carril); + coche.velocidad := (VELOCIDAD_COCHE, 0); + Coche.Color:= T_ColorCoche'First; + coche.carril := carril; + Pkg_Buffer_Coches.Actualiza_Item(i, Coche, Buffer_Coches(carril)); + + -- Inicializamos también el buffer de coches accidentados + Pkg_Buffer_Accidentes.Actualiza_Item(i, Coche, Buffer_Accidentes(carril)); + END LOOP; + END LOOP; + + exception + when event: others => + PKG_debug.Escribir(""ERROR en Inicializar_Buffer_Coches: "" & Exception_Name(Exception_Identity(event))); + + end Inicializar_Buffer_Coches; + + + + ------------------------------------------------------------------------ + -- Función que devuelve la posición de un coche dentro del buffer + ----------------------------------------------------------------------- + FUNCTION Posicion_Buffer(Id : T_IdCoche; + Buffer: Pkg_Buffer_Coches.T_Buffer) RETURN T_RangoBufferCoches is + coche_aux : T_RecordCoche; + pos : T_RangoBufferCoches; + BEGIN + BEGIN + Pos := Pkg_Buffer_Coches.Posicion_Primer_Item(Buffer); + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + WHILE Coche_Aux.Id /= Id LOOP + Pos := Pos+1; + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + END LOOP; + exception + when event: others => + PKG_debug.Escribir(""ERROR en Posicion_Buffer: "" & Exception_Name(Exception_Identity(event)));" +procedure Simular_Sistema IS,"BEGIN + Gtk.Main.Main; + END Simular_Sistema; + + + ------------------------------------------------------------------------ + -- Procedure que se encarga de inicializar la interfaz gráfica + ------------------------------------------------------------------------ + procedure Inicializar_Interfaz_Grafica is + Win : Gtk_Window; + Buffer : Gtk_Double_Buffer; + Vbox, Hbox : Gtk_Box; + Id : G_Source_Id;--Timeout_Handler_Id; + Button : Gtk_Button; + inbuilt_font : Pango.Font.Pango_Font_Description; + --ventana : Gdk_Window; + --TAM_BUTTON_EXIT : constant GLib.Gint := 20; + alinea_button : Gtk.Alignment.Gtk_Alignment; + begin + -- ventana principal + Gtk.Window.Gtk_New (Win, Window_Toplevel); + Set_Title (Win, ""PRACTICA STR: CONTROL DE TRAFICO""); + Win.Set_Default_Size(CANVAS_WIDTH, CANVAS_HEIGHT);--+TAM_BUTTON_EXIT); + Void_Cb.Connect (Win, ""destroy"", Void_Cb.To_Marshaller (Quit'Access)); + + + -- botón Exit + Gtk_New (Button, ""EXIT""); + Destroyed.Object_Connect (Button, + ""clicked"", + Destroyed.To_Marshaller (Quit'Access), + Slot_Object => Win); + + Button.Set_Size_Request(100, 20);--TAM_BUTTON_EXIT); + Gtk.Alignment.Gtk_New(alinea_button, 0.5, 0.5, 0.0, 0.0); + alinea_button.Add(Button); + + + -- Double buffer + Double_Buffer.Gtk_New(Buffer); + Buffer.Set_Size_Request(CANVAS_WIDTH, CANVAS_HEIGHT);-- -TAM_BUTTON_EXIT); + + + -- Asociar widgets a la ventana principal y mostrarla + Gtk_New_Hbox (Hbox, Homogeneous => True, Spacing => 10); + Gtk_New_Vbox (Vbox, Homogeneous => False, Spacing => 0); + + Pack_Start (Vbox, Buffer); + --Pack_Start (Vbox, Button, Expand => False, Fill => False); + Pack_Start (Vbox, alinea_button);--, Expand => False, Fill => False); + + Pack_Start (Hbox, Vbox); + + + Win.Add(Hbox); + + Show_All (Win); + + --ventana := Get_Window(Gtk_Widget(Buffer)); + --Gdk.Window.Move(ventana, 0, 0); + + + Id := Main_Context_Sources.Timeout_Add (PERIODICIDAD_REDIBUJAR_MILISEGUNDOS, + Draw_Complex_Buffer'Access, + Gtk_Drawing_Area (Buffer)); + + + Gdk_New(pangoLayout, Get_Pango_Context(Buffer)); + inbuilt_font := Pango.Font.From_String(""Courier""); + Pango.Layout.Set_Font_Description(pangoLayout, inbuilt_font); + + + -- INICIALIZACIÓN DEL ESTADO DE TODOS LOS OBJETOS VISUALIZADOS + Inicializar_Buffer_Coches; + + end Inicializar_Interfaz_Grafica; + + + ------------------ + -- Draw_Complex -- + ------------------ + procedure Draw_Complex (Pixmap : Cairo_Context) is + begin + + Draw_Rectangle (Pixmap, Black_Gc, Filled => True, + X => 0, Y => 0, + Width => CANVAS_WIDTH, Height => CANVAS_HEIGHT); + + + -- DIBUJAR EN EL CANVAS EL ESTADO ACTUAL DE TODOS LOS OBJETOS + Dibujar_Canvas_Calle(Pixmap); + + end Draw_Complex; + + + ------------------------- + -- Draw_Complex_Buffer -- + ------------------------- + function Draw_Complex_Buffer (Area : Gtk_Drawing_Area) return Boolean is + Buffer : Gtk_Double_Buffer := Gtk_Double_Buffer (Area); + + begin + Draw_Complex (Get_Pixmap (Buffer)); + + Double_Buffer.Thaw(Buffer); + + --Double_Buffer.Draw (Buffer); + + return True; + end Draw_Complex_Buffer; + + + + ---------- + -- Quit -- + ---------- + procedure Quit (Win : access Gtk_Window_Record'Class) is + pragma Warnings (Off, Win); + begin + Gnat.OS_Lib.OS_Exit(0); + --Gtk.Main.Main_Quit; + --Ada.Task_Identification.Abort_Task(Ada.Task_Identification.Current_Task); + end Quit; + + + + ------------------------------------------------------------------------ + -- Procedure que inicializa el buffer de coches + ------------------------------------------------------------------------ + procedure Inicializar_Buffer_Coches is + coche : T_RecordCoche; + BEGIN + for carril IN T_Carril loop + FOR I IN T_RangoBufferCoches LOOP + Coche.Id := 0; + Coche.Pos.X := 0; + Coche.Pos.Y := y_carril(carril); + coche.velocidad := (VELOCIDAD_COCHE, 0); + Coche.Color:= T_ColorCoche'First; + coche.carril := carril; + Pkg_Buffer_Coches.Actualiza_Item(i, Coche, Buffer_Coches(carril)); + + -- Inicializamos también el buffer de coches accidentados + Pkg_Buffer_Accidentes.Actualiza_Item(i, Coche, Buffer_Accidentes(carril)); + END LOOP; + END LOOP; + + exception + when event: others => + PKG_debug.Escribir(""ERROR en Inicializar_Buffer_Coches: "" & Exception_Name(Exception_Identity(event))); + + end Inicializar_Buffer_Coches; + + + + ------------------------------------------------------------------------ + -- Función que devuelve la posición de un coche dentro del buffer + ----------------------------------------------------------------------- + FUNCTION Posicion_Buffer(Id : T_IdCoche; + Buffer: Pkg_Buffer_Coches.T_Buffer) RETURN T_RangoBufferCoches is + coche_aux : T_RecordCoche; + pos : T_RangoBufferCoches; + BEGIN + BEGIN + Pos := Pkg_Buffer_Coches.Posicion_Primer_Item(Buffer); + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + WHILE Coche_Aux.Id /= Id LOOP + Pos := Pos+1; + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + END LOOP; + exception + when event: others => + PKG_debug.Escribir(""ERROR en Posicion_Buffer: "" & Exception_Name(Exception_Identity(event)));" +procedure Simular_Sistema IS,"BEGIN + Gtk.Main.Main; + END Simular_Sistema; + + + ------------------------------------------------------------------------ + -- Procedure que se encarga de inicializar la interfaz gráfica + ------------------------------------------------------------------------ + procedure Inicializar_Interfaz_Grafica is + Win : Gtk_Window; + Buffer : Gtk_Double_Buffer; + Vbox, Hbox : Gtk_Box; + Id : G_Source_Id;--Timeout_Handler_Id; + Button : Gtk_Button; + inbuilt_font : Pango.Font.Pango_Font_Description; + --ventana : Gdk_Window; + --TAM_BUTTON_EXIT : constant GLib.Gint := 20; + alinea_button_exit: Gtk.Alignment.Gtk_Alignment; + A_Check_Button1, A_Check_Button2 : Gtk_Check_Button; + begin + -- ventana principal + Gtk.Window.Gtk_New (Win, Window_Toplevel); + Set_Title (Win, ""PRACTICA STR: CONTROL DE TRAFICO""); + Win.Set_Default_Size(CANVAS_WIDTH, CANVAS_HEIGHT);--+TAM_BUTTON_EXIT); + Void_Cb.Connect (Win, ""destroy"", Void_Cb.To_Marshaller (Quit'Access)); + + + -- botón Exit + Gtk_New (Button, ""EXIT""); + Destroyed.Object_Connect (Button, + ""clicked"", + Destroyed.To_Marshaller (Quit'Access), + Slot_Object => Win); + + Button.Set_Size_Request(100, 20);--TAM_BUTTON_EXIT); + Gtk.Alignment.Gtk_New(alinea_button_exit, 0.5, 0.5, 0.0, 0.0); + alinea_button_exit.Add(Button); + + + -- Double buffer + Double_Buffer.Gtk_New(Buffer); + Buffer.Set_Size_Request(CANVAS_WIDTH, CANVAS_HEIGHT);-- -TAM_BUTTON_EXIT); + + + -- Botones para la generación de averías + Gtk_New (A_Check_Button1, ""Averia en Carril 1""); + Widget_Handler.Object_Connect(A_Check_Button1, ""clicked"", + Widget_Handler.To_Marshaller (Averia1_Generada'ACCESS), + Slot_Object => Win); + + Gtk_New (A_Check_Button2, ""Averia en Carril 2""); + Widget_Handler.Object_Connect(A_Check_Button2, ""clicked"", + Widget_Handler.To_Marshaller (Averia2_Generada'ACCESS), + Slot_Object => Win); + + + + -- Asociar widgets a la ventana principal y mostrarla + Gtk_New_Hbox (Hbox, Homogeneous => True, Spacing => 10); + Gtk_New_Vbox (Vbox, Homogeneous => False, Spacing => 0); + + Pack_Start (Vbox, Buffer); + --Pack_Start (Vbox, Button, Expand => False, Fill => False); + Pack_Start (Vbox, alinea_button_exit);--, Expand => False, Fill => False); + + Pack_Start (Vbox, A_Check_Button1); + Pack_Start (Vbox, A_Check_Button2); + + Pack_Start (Hbox, Vbox); + + + + + + + Win.Add(Hbox); + + Show_All (Win); + + --ventana := Get_Window(Gtk_Widget(Buffer)); + --Gdk.Window.Move(ventana, 0, 0); + + + Id := Main_Context_Sources.Timeout_Add (PERIODICIDAD_REDIBUJAR_MILISEGUNDOS, + Draw_Complex_Buffer'Access, + Gtk_Drawing_Area (Buffer)); + + + Gdk_New(pangoLayout, Get_Pango_Context(Buffer)); + inbuilt_font := Pango.Font.From_String(""Courier""); + Pango.Layout.Set_Font_Description(pangoLayout, inbuilt_font); + + + -- INICIALIZACIÓN DEL ESTADO DE TODOS LOS OBJETOS VISUALIZADOS + Inicializar_Buffer_Coches; + + end Inicializar_Interfaz_Grafica; + + + ------------------ + -- Draw_Complex -- + ------------------ + procedure Draw_Complex (Pixmap : Cairo_Context) is + begin + + Draw_Rectangle (Pixmap, Black_Gc, Filled => True, + X => 0, Y => 0, + Width => CANVAS_WIDTH, Height => CANVAS_HEIGHT); + + + -- DIBUJAR EN EL CANVAS EL ESTADO ACTUAL DE TODOS LOS OBJETOS + Dibujar_Canvas_Calle(Pixmap); + + end Draw_Complex; + + + ------------------------- + -- Draw_Complex_Buffer -- + ------------------------- + function Draw_Complex_Buffer (Area : Gtk_Drawing_Area) return Boolean is + Buffer : Gtk_Double_Buffer := Gtk_Double_Buffer (Area); + + begin + Draw_Complex (Get_Pixmap (Buffer)); + + Double_Buffer.Thaw(Buffer); + + --Double_Buffer.Draw (Buffer); + + return True; + end Draw_Complex_Buffer; + + + + ---------- + -- Quit -- + ---------- + procedure Quit (Win : access Gtk_Window_Record'Class) is + pragma Warnings (Off, Win); + begin + Gnat.OS_Lib.OS_Exit(0); + --Gtk.Main.Main_Quit; + --Ada.Task_Identification.Abort_Task(Ada.Task_Identification.Current_Task); + end Quit; + + + + ------------------------------------------------------------------------ + -- Procedure que inicializa el buffer de coches + ------------------------------------------------------------------------ + procedure Inicializar_Buffer_Coches is + coche : T_RecordCoche; + BEGIN + for carril IN T_Carril loop + FOR I IN T_RangoBufferCoches LOOP + Coche.Id := 0; + Coche.Pos.X := 0; + Coche.Pos.Y := y_carril(carril); + coche.velocidad := (VELOCIDAD_COCHE, 0); + Coche.Color:= T_ColorCoche'First; + coche.carril := carril; + Pkg_Buffer_Coches.Actualiza_Item(i, Coche, Buffer_Coches(carril)); + + -- Inicializamos también el buffer de coches accidentados + Pkg_Buffer_Accidentes.Actualiza_Item(i, Coche, Buffer_Accidentes(carril)); + END LOOP; + END LOOP; + + exception + when event: others => + PKG_debug.Escribir(""ERROR en Inicializar_Buffer_Coches: "" & Exception_Name(Exception_Identity(event))); + + end Inicializar_Buffer_Coches; + + + + ------------------------------------------------------------------------ + -- Función que devuelve la posición de un coche dentro del buffer + ----------------------------------------------------------------------- + FUNCTION Posicion_Buffer(Id : T_IdCoche; + Buffer: Pkg_Buffer_Coches.T_Buffer) RETURN T_RangoBufferCoches is + coche_aux : T_RecordCoche; + pos : T_RangoBufferCoches; + BEGIN + BEGIN + Pos := Pkg_Buffer_Coches.Posicion_Primer_Item(Buffer); + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + WHILE Coche_Aux.Id /= Id LOOP + Pos := Pos+1; + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + END LOOP; + exception + when event: others => + PKG_debug.Escribir(""ERROR en Posicion_Buffer: "" & Exception_Name(Exception_Identity(event)));" +procedure Simular_Sistema IS,"BEGIN + Gtk.Main.Main; + END Simular_Sistema; + + + ------------------------------------------------------------------------ + -- Procedure que se encarga de inicializar la interfaz gráfica + ------------------------------------------------------------------------ + procedure Inicializar_Interfaz_Grafica is + Win : Gtk_Window; + Buffer : Gtk_Double_Buffer; + Vbox, Hbox : Gtk_Box; + Id : G_Source_Id;--Timeout_Handler_Id; + Button : Gtk_Button; + inbuilt_font : Pango.Font.Pango_Font_Description; + --ventana : Gdk_Window; + --TAM_BUTTON_EXIT : constant GLib.Gint := 20; + alinea_button : Gtk.Alignment.Gtk_Alignment; + begin + -- ventana principal + Gtk.Window.Gtk_New (Win, Window_Toplevel); + Set_Title (Win, ""PRACTICA STR: CONTROL DE TRAFICO""); + Win.Set_Default_Size(CANVAS_WIDTH, CANVAS_HEIGHT);--+TAM_BUTTON_EXIT); + Void_Cb.Connect (Win, ""destroy"", Void_Cb.To_Marshaller (Quit'Access)); + + + -- botón Exit + Gtk_New (Button, ""EXIT""); + Destroyed.Object_Connect (Button, + ""clicked"", + Destroyed.To_Marshaller (Quit'Access), + Slot_Object => Win); + + Button.Set_Size_Request(100, 20);--TAM_BUTTON_EXIT); + Gtk.Alignment.Gtk_New(alinea_button, 0.5, 0.5, 0.0, 0.0); + alinea_button.Add(Button); + + + -- Double buffer + Double_Buffer.Gtk_New(Buffer); + Buffer.Set_Size_Request(CANVAS_WIDTH, CANVAS_HEIGHT);-- -TAM_BUTTON_EXIT); + + + -- Asociar widgets a la ventana principal y mostrarla + Gtk_New_Hbox (Hbox, Homogeneous => True, Spacing => 10); + Gtk_New_Vbox (Vbox, Homogeneous => False, Spacing => 0); + + Pack_Start (Vbox, Buffer); + --Pack_Start (Vbox, Button, Expand => False, Fill => False); + Pack_Start (Vbox, alinea_button);--, Expand => False, Fill => False); + + Pack_Start (Hbox, Vbox); + + + Win.Add(Hbox); + + Show_All (Win); + + --ventana := Get_Window(Gtk_Widget(Buffer)); + --Gdk.Window.Move(ventana, 0, 0); + + + Id := Main_Context_Sources.Timeout_Add (PERIODICIDAD_REDIBUJAR_MILISEGUNDOS, + Draw_Complex_Buffer'Access, + Gtk_Drawing_Area (Buffer)); + + + Gdk_New(pangoLayout, Get_Pango_Context(Buffer)); + inbuilt_font := Pango.Font.From_String(""Courier""); + Pango.Layout.Set_Font_Description(pangoLayout, inbuilt_font); + + + -- INICIALIZACIÓN DEL ESTADO DE TODOS LOS OBJETOS VISUALIZADOS + Inicializar_Buffer_Coches; + + end Inicializar_Interfaz_Grafica; + + + ------------------ + -- Draw_Complex -- + ------------------ + procedure Draw_Complex (Pixmap : Cairo_Context) is + begin + + Draw_Rectangle (Pixmap, Black_Gc, Filled => True, + X => 0, Y => 0, + Width => CANVAS_WIDTH, Height => CANVAS_HEIGHT); + + + -- DIBUJAR EN EL CANVAS EL ESTADO ACTUAL DE TODOS LOS OBJETOS + Dibujar_Canvas_Calle(Pixmap); + + end Draw_Complex; + + + ------------------------- + -- Draw_Complex_Buffer -- + ------------------------- + function Draw_Complex_Buffer (Area : Gtk_Drawing_Area) return Boolean is + Buffer : Gtk_Double_Buffer := Gtk_Double_Buffer (Area); + + begin + Draw_Complex (Get_Pixmap (Buffer)); + + Double_Buffer.Thaw(Buffer); + + --Double_Buffer.Draw (Buffer); + + return True; + end Draw_Complex_Buffer; + + + + ---------- + -- Quit -- + ---------- + procedure Quit (Win : access Gtk_Window_Record'Class) is + pragma Warnings (Off, Win); + begin + Gnat.OS_Lib.OS_Exit(0); + --Gtk.Main.Main_Quit; + --Ada.Task_Identification.Abort_Task(Ada.Task_Identification.Current_Task); + end Quit; + + + + ------------------------------------------------------------------------ + -- Procedure que inicializa el buffer de coches + ------------------------------------------------------------------------ + procedure Inicializar_Buffer_Coches is + coche : T_RecordCoche; + BEGIN + for carril IN T_Carril loop + FOR I IN T_RangoBufferCoches LOOP + Coche.Id := 0; + Coche.Pos.X := 0; + Coche.Pos.Y := y_carril(carril); + coche.velocidad := (VELOCIDAD_COCHE, 0); + Coche.Color:= T_ColorCoche'First; + coche.carril := carril; + Pkg_Buffer_Coches.Actualiza_Item(i, Coche, Buffer_Coches(carril)); + + -- Inicializamos también el buffer de coches accidentados + Pkg_Buffer_Accidentes.Actualiza_Item(i, Coche, Buffer_Accidentes(carril)); + END LOOP; + END LOOP; + + exception + when event: others => + PKG_debug.Escribir(""ERROR en Inicializar_Buffer_Coches: "" & Exception_Name(Exception_Identity(event))); + + end Inicializar_Buffer_Coches; + + + + ------------------------------------------------------------------------ + -- Función que devuelve la posición de un coche dentro del buffer + ----------------------------------------------------------------------- + FUNCTION Posicion_Buffer(Id : T_IdCoche; + Buffer: Pkg_Buffer_Coches.T_Buffer) RETURN T_RangoBufferCoches is + coche_aux : T_RecordCoche; + pos : T_RangoBufferCoches; + BEGIN + BEGIN + Pos := Pkg_Buffer_Coches.Posicion_Primer_Item(Buffer); + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + WHILE Coche_Aux.Id /= Id LOOP + Pos := Pos+1; + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + END LOOP; + exception + when event: others => + PKG_debug.Escribir(""ERROR en Posicion_Buffer: "" & Exception_Name(Exception_Identity(event)));" +procedure Simular_Sistema IS,"BEGIN + Gtk.Main.Main; + END Simular_Sistema; + + + ------------------------------------------------------------------------ + -- Procedure que se encarga de inicializar la interfaz gráfica + ------------------------------------------------------------------------ + procedure Inicializar_Interfaz_Grafica is + Win : Gtk_Window; + Buffer : Gtk_Double_Buffer; + Vbox, Hbox : Gtk_Box; + Id : G_Source_Id;--Timeout_Handler_Id; + Button : Gtk_Button; + inbuilt_font : Pango.Font.Pango_Font_Description; + --ventana : Gdk_Window; + --TAM_BUTTON_EXIT : constant GLib.Gint := 20; + alinea_button : Gtk.Alignment.Gtk_Alignment; + begin + -- ventana principal + Gtk.Window.Gtk_New (Win, Window_Toplevel); + Set_Title (Win, ""PRACTICA STR: CONTROL DE TRAFICO""); + Win.Set_Default_Size(CANVAS_WIDTH, CANVAS_HEIGHT);--+TAM_BUTTON_EXIT); + Void_Cb.Connect (Win, ""destroy"", Void_Cb.To_Marshaller (Quit'Access)); + + + -- botón Exit + Gtk_New (Button, ""EXIT""); + Destroyed.Object_Connect (Button, + ""clicked"", + Destroyed.To_Marshaller (Quit'Access), + Slot_Object => Win); + + Button.Set_Size_Request(100, 20);--TAM_BUTTON_EXIT); + Gtk.Alignment.Gtk_New(alinea_button, 0.5, 0.5, 0.0, 0.0); + alinea_button.Add(Button); + + + -- Double buffer + Double_Buffer.Gtk_New(Buffer); + Buffer.Set_Size_Request(CANVAS_WIDTH, CANVAS_HEIGHT);-- -TAM_BUTTON_EXIT); + + + -- Asociar widgets a la ventana principal y mostrarla + Gtk_New_Hbox (Hbox, Homogeneous => True, Spacing => 10); + Gtk_New_Vbox (Vbox, Homogeneous => False, Spacing => 0); + + Pack_Start (Vbox, Buffer); + --Pack_Start (Vbox, Button, Expand => False, Fill => False); + Pack_Start (Vbox, alinea_button);--, Expand => False, Fill => False); + + Pack_Start (Hbox, Vbox); + + + Win.Add(Hbox); + + Show_All (Win); + + --ventana := Get_Window(Gtk_Widget(Buffer)); + --Gdk.Window.Move(ventana, 0, 0); + + + Id := Main_Context_Sources.Timeout_Add (PERIODICIDAD_REDIBUJAR_MILISEGUNDOS, + Draw_Complex_Buffer'Access, + Gtk_Drawing_Area (Buffer)); + + + Gdk_New(pangoLayout, Get_Pango_Context(Buffer)); + inbuilt_font := Pango.Font.From_String(""Courier""); + Pango.Layout.Set_Font_Description(pangoLayout, inbuilt_font); + + + -- INICIALIZACIÓN DEL ESTADO DE TODOS LOS OBJETOS VISUALIZADOS + Inicializar_Buffer_Coches; + + end Inicializar_Interfaz_Grafica; + + + ------------------ + -- Draw_Complex -- + ------------------ + procedure Draw_Complex (Pixmap : Cairo_Context) is + begin + + Draw_Rectangle (Pixmap, Black_Gc, Filled => True, + X => 0, Y => 0, + Width => CANVAS_WIDTH, Height => CANVAS_HEIGHT); + + + -- DIBUJAR EN EL CANVAS EL ESTADO ACTUAL DE TODOS LOS OBJETOS + Dibujar_Canvas_Calle(Pixmap); + + end Draw_Complex; + + + ------------------------- + -- Draw_Complex_Buffer -- + ------------------------- + function Draw_Complex_Buffer (Area : Gtk_Drawing_Area) return Boolean is + Buffer : Gtk_Double_Buffer := Gtk_Double_Buffer (Area); + + begin + Draw_Complex (Get_Pixmap (Buffer)); + + Double_Buffer.Thaw(Buffer); + + --Double_Buffer.Draw (Buffer); + + return True; + end Draw_Complex_Buffer; + + + + ---------- + -- Quit -- + ---------- + procedure Quit (Win : access Gtk_Window_Record'Class) is + pragma Warnings (Off, Win); + begin + Gnat.OS_Lib.OS_Exit(0); + --Gtk.Main.Main_Quit; + --Ada.Task_Identification.Abort_Task(Ada.Task_Identification.Current_Task); + end Quit; + + + + ------------------------------------------------------------------------ + -- Procedure que inicializa el buffer de coches + ------------------------------------------------------------------------ + procedure Inicializar_Buffer_Coches is + coche : T_RecordCoche; + BEGIN + for carril IN T_Carril loop + FOR I IN T_RangoBufferCoches LOOP + Coche.Id := 0; + Coche.Pos.X := 0; + Coche.Pos.Y := y_carril(carril); + coche.velocidad := (VELOCIDAD_COCHE, 0); + Coche.Color:= T_ColorCoche'First; + coche.carril := carril; + Pkg_Buffer_Coches.Actualiza_Item(i, Coche, Buffer_Coches(carril)); + + -- Inicializamos también el buffer de coches accidentados + Pkg_Buffer_Accidentes.Actualiza_Item(i, Coche, Buffer_Accidentes(carril)); + END LOOP; + END LOOP; + + exception + when event: others => + PKG_debug.Escribir(""ERROR en Inicializar_Buffer_Coches: "" & Exception_Name(Exception_Identity(event))); + + end Inicializar_Buffer_Coches; + + + + ------------------------------------------------------------------------ + -- Función que devuelve la posición de un coche dentro del buffer + ----------------------------------------------------------------------- + FUNCTION Posicion_Buffer(Id : T_IdCoche; + Buffer: Pkg_Buffer_Coches.T_Buffer) RETURN T_RangoBufferCoches is + coche_aux : T_RecordCoche; + pos : T_RangoBufferCoches; + BEGIN + BEGIN + Pos := Pkg_Buffer_Coches.Posicion_Primer_Item(Buffer); + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + WHILE Coche_Aux.Id /= Id LOOP + Pos := Pos+1; + Coche_Aux := Pkg_Buffer_Coches.Consulta_Item(Pos, Buffer); + END LOOP; + exception + when event: others => + PKG_debug.Escribir(""ERROR en Posicion_Buffer: "" & Exception_Name(Exception_Identity(event)));" +procedure Wsl_Launch is,"-- Ada_Launch is the default name, but is meant to be renamed + -- to the executable name that this executable launches + + package Env renames Ada.Environment_Variables; + package CL renames Ada.Command_Line; + package CLenv renames Ada.Command_Line.Environment; + -- Env, CL, and CLenv are just abbreviations for: + -- Environment_Variables, Command_Line, and Command_Line.Environment + + package AdaList is + new Ada.Containers.Indefinite_Doubly_Linked_Lists (String); + + function Exec_In_Path (Exec_Name : String) return String is + begin + if not (Locate_Exec_On_Path (Exec_Name) = null) + then + return Locate_Exec_On_Path (Exec_Name).all; + else + Put_Line (Standard_Error, Exec_Name & "" not found in PATH.""); + return """"; + end if;" +procedure Startx is,"-- XTerminal is a terminal bast in Xorg -- meant to be used as a login + -- terminal. + + use GNAT.OS_Lib; + + package Env renames Ada.Environment_Variables; + package Cl renames Ada.Command_Line; + package Files renames Ada.Directories; + package Os renames GNAT.OS_Lib; + package Os_Files renames GNAT.Directory_Operations; + package Regex renames GNAT.Regpat; + +-- package OS renames gnat.os_lib; + -- Env, CL, and CLenv are just abbreviations for: Environment_Variables, + -- Command_Line, and Command_Line.Environment + + -- xterm -bg black -fg white +sb +sm -fn 10x20 -sl 4000 -cr yellow + + -- /usr/bin/Xnest :1 -geometry 1024x768+0+0 -ac -name Windowmaker & wmaker + -- -display :1 + + Empty_Argument_List : constant Os.String_List (1 .. 0) := (others => null); + Empty_List_Access : Os.String_List_Access := + new Os.String_List'(Empty_Argument_List); + + function Image (Num : Natural) return String is + N : Natural := Num; + S : String (1 .. 48) := (others => ' '); + L : Natural := 0; + procedure Image_Natural + (N : in Natural; + S : in out String; + L : in out Natural) is + begin + null; + if N >= 10 then + Image_Natural (N / 10, S, L); + L := L + 1; + S (L) := Character'Val (48 + (N rem 10)); + else + L := L + 1; + S (L) := Character'Val (48 + (N rem 10)); + end if; + end Image_Natural; + begin + null; + Image_Natural (N, S, L); + return S (1 .. L); + end Image; + + function Create_Display_Number return String is + use Ada.Directories; + New_Number : Natural := 0; + + begin + if Exists (""/tmp"") then + loop + if Exists (""/tmp/.X"" & Image (New_Number) & ""-lock"") then + New_Number := New_Number + 1; + + else + return Image (New_Number); + + end if; + + end loop; + + else + return ""0""; + + end if; + end Create_Display_Number; + + -- Using GNAT.Directory_Operations, make given filesystem path compatible + -- with the current Operating System: Path (""to/file"") => ""to\file""(windows) + function Path (Original : String) return String is + use Os_Files; + Result : Path_Name := + Os_Files.Format_Pathname + (Path => Path_Name (Original), + Style => System_Default); + begin + return String (Result); + end Path; + + -- Using GNAT.Directory_Operations, make given filesystem path compatible + -- with the current Operating System: + -- Path (""${HOME}/to/file"") => ""C:\msys\home\user\to\file"" (windows) + function Expand_Path (Original : String) return String is + use Os_Files; + Result : Path_Name := + Os_Files.Format_Pathname + (Path => + Os_Files.Expand_Path (Path => Path_Name (Original), Mode => Both), + Style => System_Default); + begin + return String (Result); + end Expand_Path; + + -- Using GNAT.Directory_Operations and GNAT.OS_LIB, make given filesystem + -- path compatible with the current Operating System, returning the full + -- path: Full_Path (""../to/file"") => ""C:\dir\dir\to\file"" (windows) + function Full_Path (Original : String) return String is + use Os; + begin + return Os.Normalize_Pathname (Path (Original)); + end Full_Path; + + User_Clientrc : String := Expand_Path (""${HOME}/.xinitrc""); + System_Clientrc : String := Path (""/etc/X11/xinit/xinitrc""); + + User_Serverrc : String := Expand_Path (""${HOME}/.xserverrc""); + System_Serverrc : String := Path (""/etc/X11/xinit/xserverrc""); + Default_Client : String := ""xterm""; + Default_Server : String := Path (""/usr/bin/X""); + + Default_Client_Arguments_Access : Os.String_List_Access := + Os.Argument_String_To_List (""""); + + Default_Server_Arguments_Access : Os.String_List_Access := + Os.Argument_String_To_List (""""); + + Default_Client_Arguments : Os.String_List := + (if + Default_Client_Arguments_Access /= null + then + Default_Client_Arguments_Access.all + else Empty_List_Access.all); + + Default_Server_Arguments : Os.String_List := + (if + Default_Server_Arguments_Access /= null + then + Default_Server_Arguments_Access.all + else Empty_List_Access.all); + +-- Defaultdisplay = "":0"" +-- Clientargs = """" +-- Serverargs = """" +-- Vtarg = """" +-- Enable_Xauth = 1 + + Env_Display : String := Env.Value (""DISPLAY"", """"); + New_Display : String := "":"" & Create_Display_Number; + + Custom_Client_Access : Os.String_Access := + (if + Ada.Command_Line.Argument_Count > 0 + then + Os.Locate_Exec_On_Path (Ada.Command_Line.Argument (1)) + else null); + Manager_Command_Access : Os.String_Access := + Os.Locate_Exec_On_Path (""/usr/bin/dbus-launch""); + Xterm_Command_Access : Os.String_Access := + Os.Locate_Exec_On_Path (""/usr/bin/xterm""); + Xnest_Command_Access : Os.String_Access := + Os.Locate_Exec_On_Path (""/usr/bin/Xnest""); + Xserver_Command_Access : Os.String_Access := + Os.Locate_Exec_On_Path (""/usr/bin/Xserver""); + Xinit_Command_Access : Os.String_Access := Os.Locate_Exec_On_Path (""xinit""); + + Xterm_Background : String := ""black""; + Xterm_Foreground : String := ""white""; + Xterm_Scrollbar : Boolean := False; + Xterm_Session_Management_Callbacks : Boolean := False; + Xterm_Loginshell : Boolean := False; +-- Xterm_Font : String := ""adobe-source code pro*""; +-- Xterm_Font : String := ""gnu-unifont*""; + Xterm_Font : String := + ""-gnu-unifont-medium-r-normal-sans-16-160-75-75-c-80-iso10646-1""; + Xterm_Font_Size : String := ""9""; + Xterm_Lineshistory : String := ""4000""; + Xterm_Cursorcolor : String := ""yellow""; + Xterm_Border : String := ""256""; + Xterm_Geometry : String := ""200x50+-128+-128""; +-- Xterm_Geometry : String := ""260x70+-128+-128""; + + Xterm_Arguments : Os.Argument_List := + (new String'(""-bg""), + new String'(Xterm_Background), + new String'(""-fg""), + new String'(Xterm_Foreground), + (if Xterm_Scrollbar then new String'(""-sb"") else new String'(""+sb"")), + (if Xterm_Session_Management_Callbacks then new String'(""-sm"") + else new String'(""+sm"")), + (if Xterm_Loginshell then new String'(""-ls"") else new String'(""+ls"")), + new String'(""-fs""), + new String'(Xterm_Font_Size), + new String'(""-fn""), + new String' + (""-gnu-unifont-medium-r-normal-sans-16-160-75-75-c-80-iso10646-1""), + new String'(""-sl""), + new String'(Xterm_Lineshistory), + new String'(""-cr""), + new String'(Xterm_Cursorcolor), + new String'(""-geometry""), + new String'(Xterm_Geometry), + new String'(""-b""), + new String'(Xterm_Border), + new String'(""-xrm""), + new String'(""*overrideRedirect: True"")); + Xterm_Command_Arguments : Os.Argument_List := + (new String'(""--""), Xterm_Command_Access) & Xterm_Arguments; + + Xnest_Title : String := ""Graphical Session""; +-- Xnest_Foreground : String := ""white""; +-- Xnest_Background : String := ""black""; + Xnest_Geometry : String := ""1920x1080+-0+-0""; + Xnest_Border : String := ""64""; + + Empty_Arguments : GNAT.OS_Lib.Argument_List (1 .. 0) := (others => null); + + Xnest_Arguments : GNAT.OS_Lib.Argument_List := + (new String'(New_Display), + new String'(""-display""), + new String'(Env_Display), + new String'(""-geometry""), + new String'(Xnest_Geometry), + new String'(""-name""), + new String'(Xnest_Title), + new String'(""-reset""), + new String'(""-terminate""), + new String'(""-fn""), + new String' + (""-gnu-unifont-medium-r-normal-sans-16-160-75-75-c-80-iso10646-1""), + new String'(""-bw""), + new String'(Xnest_Border)); + + Xserver_Arguments : GNAT.OS_Lib.Argument_List := + (new String'(New_Display), + new String'(""-display""), + new String'(Env_Display), + new String'(""-geometry""), + new String'(Xnest_Geometry), + new String'(""-name""), + new String'(Xnest_Title), + new String'(""-reset""), + new String'(""-terminate""), + new String'(""-fn""), + new String' + (""-gnu-unifont-medium-r-normal-sans-16-160-75-75-c-80-iso10646-1""), + new String'(""-bw""), + new String'(Xnest_Border)); + + Launch_Status : Boolean := True; + -- The return status of the command + arguments + + function Command_Arguments return GNAT.OS_Lib.Argument_List is + Command_Words : GNAT.OS_Lib.Argument_List (1 .. Argument_Count) := + (others => null); + Xterm_Command_Words : Os.String_List := Xterm_Command_Arguments; + + begin + for N in 1 .. Argument_Count loop + Command_Words (N) := new String'(Argument (N)); + + end loop; + + if Command_Words'Length > 0 then + return Command_Words; + else + return Xterm_Command_Words; + end if; + end Command_Arguments; + + procedure Launch + (Command : String; + Arguments : GNAT.OS_Lib.Argument_List) is + Launch_Arguments : GNAT.OS_Lib.Argument_List := Arguments; + begin + GNAT.OS_Lib.Spawn (Command, Launch_Arguments, Launch_Status); + end Launch; + + Launch_Error_Count : Integer := 0; + +begin + Env.Clear (""SESSION_MANAGER""); + Env.Set (""DISPLAY"", Env_Display); + + declare + Arguments : Os.Argument_List := Command_Arguments; + Xnest : Os.Process_Id; + Xserver : Os.Process_Id; + Session_Manager : Os.Process_Id; + Process_With_Exit : Os.Process_Id; + -- Arguments => checked and tweaked argument list given at progam start + -- Xnest => The instance of Xnest or Xorg that will be monitored, Session_Manager + +-- Xterm : OS.Process_Id; + + begin + + if Env_Display /= """" then + if Xnest_Command_Access /= null + and then Manager_Command_Access /= null + then + Xnest := + Os.Non_Blocking_Spawn + (Xnest_Command_Access.all, + Xnest_Arguments); + Env.Set (""DISPLAY"", New_Display); + delay 0.02; + Session_Manager := + Os.Non_Blocking_Spawn (Manager_Command_Access.all, Arguments); + Os.Wait_Process (Process_With_Exit, Launch_Status); + + else + Launch_Status := False; + Xnest := Os.Invalid_Pid; + Session_Manager := Invalid_Pid; + + end if; + else + --- Remaining startx operations go here. --- + if Xserver_Command_Access /= null + and then Manager_Command_Access /= null + then + Xserver := + Os.Non_Blocking_Spawn + (Xserver_Command_Access.all, + Xserver_Arguments); + Env.Set (""DISPLAY"", New_Display); + delay 0.02; + Session_Manager := + Os.Non_Blocking_Spawn (Manager_Command_Access.all, Arguments); + Os.Wait_Process (Process_With_Exit, Launch_Status); + + else + Launch_Status := False; + Xnest := Os.Invalid_Pid; + Session_Manager := Invalid_Pid; + + end if; + + end if; + + if not Launch_Status then + Launch_Error_Count := Launch_Error_Count + 1; + Set_Exit_Status (Failure); + + else + Launch_Error_Count := 0; + Set_Exit_Status (Success); + end if; + --Give return status back to calling os/environment. + + for I in Arguments'Range loop + Free (Arguments (I)); + end loop;" +procedure Ada_Time is,"use Ada.Text_IO; + use Ada.Characters.Latin_1; + use Ada.Text_IO.Text_Streams; + use Ada.Calendar; + use Ada.Calendar.Time_Zones; + use Ada.Command_Line; + use GNAT.Calendar.Time_IO; + + Now : Time := Clock; + + function Unix_Time return Time is + use Ada.Calendar.Formatting; + + U_Year : Year_Number; + U_Month : Month_Number; + U_Day : Day_Number; + U_Hour : Hour_Number; + U_Minute : Minute_Number; + U_Second : Second_Number; + U_Duration : Second_Duration; + begin + Split + (Date => Now, + Year => U_Year, + Month => U_Month, + Day => U_Day, + Hour => U_Hour, + Minute => U_Minute, + Second => U_Second, + Sub_Second => U_Duration, + Time_Zone => 0); + + return Time_Of + (Year => U_Year, + Month => U_Month, + Day => U_Day, + Hour => U_Hour, + Minute => U_Minute, + Second => U_Second, + Sub_Second => U_Duration, + Time_Zone => UTC_Time_Offset); + end Unix_Time; + + function To_Multimedia + (Time : String; + Fraction : Boolean := True) return String + -- Convert pure seconds ***.*** to multimedia time string **h**m**s Fraction + -- boolean value specifies whether to include the fractional part of the + -- time: **h**m**.***s + is + begin + null; + return """"; + end To_Multimedia; + + function To_Clock + (Time : String; + Fraction : Boolean := True) return String + -- Convert pure seconds ***.*** to multimedia time string **:**:** Fraction + -- boolean value specifies whether to include the fractional part of the + -- time: **h**m**.***s + is + begin + null; + return """"; + end To_Clock; + + function To_Seconds (Time : String) return String + -- Convert a Multimedia time string **h**m**s or **:**:**.*** to pure + -- seconds ***.*** + is + begin + null; + return """"; + end To_Seconds; + + function ""+"" (Left : String; Right : String) return String is + use Ada.Characters.Latin_1; + begin + return Left & LF & Right; + end ""+""; + +-- Unix_Time : Time := +-- Value (Date => Image (Date => Now, Include_Time_Fraction => True), +-- Time_Zone => UTC_Time_Offset); +begin + + for A in 1 .. Argument_Count loop + if Argument (A) = ""-iso"" or + Argument (A) = ""-I"" or + Argument (A) = ""-i"" + then + String'Write + (Stream (Current_Output), + Image (Date => Now, Picture => ""%Y-%m-%d"")); + + elsif Argument (A) = ""-n"" or Argument (A) = ""-nano"" then + String'Write + (Stream (Current_Output), + Image (Date => Unix_Time, Picture => ""%s.%o"")); + + elsif Argument (A) (1) = '+' then + declare + Feature_Argument : String := Argument (A); + + begin + String'Write + (Stream (Current_Output), + Image + (Date => Now, + Picture => + Picture_String + (Feature_Argument + (Feature_Argument'First + 1 .. + Feature_Argument'Last))));" +procedure ArrivalForRepair is,"package FloatIO is new Ada.Text_IO.Float_IO(float); + use FloatIO; + package IntIO is new Ada.Text_IO.Integer_IO(Integer); + use IntIO; + package Fix_IO is new Ada.Text_IO.Fixed_IO(DAY_DURATION); + use Fix_IO; + + function intToChar is new Unchecked_Conversion(Integer, Character); + charStar, charTie : Character := 'A'; + intStar, intTie : Integer := 64; + + subtype getChar is Character range 'A'..'Z'; + lastCharOfTie, lastCharOfStar : getChar := getChar'First; + + type vehicle is + (Star_Destroyer, Tie_Fighter); + package vechileIO is new Ada.Text_IO.Enumeration_IO(vehicle); + + type vName is + (Tie, Star); + package nameIO is new Ada.Text_IO.Enumeration_IO(vName); + + -- Maintainance bay record + type garageBay is record + vehicleType : vehicle; + vehicleName: String(1..5); + time2Fix: integer; + startTime: Time; + finishTime: Time; + --elapsedTime: DAY_DURATION; + end record; + a : garageBay; + + -- Function to determine if the arriving planes are Star or Tie + function StarOrTie(x: in out integer) return garageBay is + randNum: float; + z,b,c,d : garageBay; + e : Time := Clock; + + --seed: integer; + begin + + randNum := next_float(x); -- 0.0 <= randNumm <= 1.0. + + if randNum <= 0.25 then + z := (vehicleType => Tie_Fighter, vehicleName => ""Tie "", time2Fix => 0, startTime => e, finishTime => e); + return a; -- return tie + elsif randNum <= 0.5 then + b := (vehicleType => Tie_Fighter, vehicleName => ""Tie "", time2Fix => 0, startTime => e, finishTime => e); + return b; -- return tie + elsif randNum <= 0.75 then + c := (vehicleType => Tie_Fighter, vehicleName => ""Tie "", time2Fix => 0, startTime => e, finishTime => e); + return c; -- return tie + else + d := (vehicleType => Star_Destroyer, vehicleName => ""Star "", time2Fix => 0, startTime => e, finishTime => e); + return d; -- return stsr + end if; + + end StarOrTie; + + + + -- Determine the number of new arrivals for Step 1 in the lab. + -- Either 1, 2, 3 or 4 uniformly distributed on each call. + function NumberNewArrivals(x: in out integer) return Integer is + randNum: float; + begin + randNum := next_float(x); -- 0.0 <= randNumm <= 1.0. + + if randNum <= 0.25 then + return 1; -- return tie + elsif randNum <= 0.5 then + return 2; -- return tie + elsif + randNum <= 0.75 then + return 3; -- return tie + else + return 4; -- return stsr + end if; + + end NumberNewArrivals; + + Start,Finish, elapsed, secondus : DAY_DURATION; + StartTime, ArrivTime, departTime, ElapsTime : Time := clock; + -- Procedure to get start time + + --function startTime return DAY_DURATION is + -- Year,Month,Day : INTEGER; + --Start : DAY_DURATION; + --Time_And_Date : TIME; + --begin + --Time_And_Date := Clock; -- gets system time + --Split(Time_And_Date,Year, Month,Day,Start); + --return Start; -- gets start time ( stores it in seconds in the variable Start) + --end startTime; + + -- Procedure to get finish time + + function finishTime return DAY_DURATION is + Year,Month,Day : INTEGER; + Finish : DAY_DURATION; + Time_And_Date : TIME; + begin + Time_And_Date := Clock; -- gets system time + Split(Time_And_Date,Year, Month,Day,Finish); + return Finish; -- gets start time ( stores it in seconds in the variable Start) + end finishTime; + + + numberArrivals,seed,upperbound,starKnt,tieKnt, dagobah, repairStar, repairTie: Integer := 0; + decision: garageBay; + ET: DAY_DURATION; + + + + + +begin +-- Get upperbound of the stack. + put(""Enter The Maximum Number Of Vehicles Allowed In The Garagebay:""); new_line; + get(upperbound); + + declare + -- Instantiate the generic package for type garageBay. + package genericS is new gstack(upperbound, garageBay); + use genericS; + begin + -- Lab Step 0. write start time to service log. + --start := startTime; + --finish := finishTime; + --elapsed := finish - start; + --ET := elapsed; + startTime := clock; + put(Image(startTime, Time_Zone => -5*60) ); put("" Garagebay is open ""); + new_line; + + + + -- Seed the random number generator appropriately. + put(""Seed the random number generator:""); new_line; + get(seed); + put(""-----------------------------------------------------------------------------------"");new_line; + -- do the operations + --numberArrivals := 3; -- Assuming 3 vehicles at open. + Loop + numberArrivals := NumberNewArrivals(seed); + put(""Number of Arrivals: "");new_line;put(numberArrivals,0);new_line; + put(""-----------------------------------------------------------------------------------"");new_line; + for j in 1..numberArrivals + loop + + --Determine if the arrival is a Tie Fighter or a Star Destroyer. + --Prepare the maintenance record and place it in the appropriate queue. + decision := StarOrTie(seed); + if decision.vehicleType = Star_Destroyer + then + intStar := intStar + 1; + if intStar = 91 then + intStar := 65; + end if; + charStar := intToChar(intStar); + decision.vehicleName(1..4) := ""Star""; + decision.vehicleName(5) := charStar; + decision.time2Fix := 7; + ArrivTime := clock; + decision.startTime := ArrivTime; + + spush(decision); + --- + --if dagobah > 0 then + --put(""Dagobah Count: "");put(dagobah);new_line; + --put(""-----------------------------------------------------------------------------------"");new_line; + --end if; + --- + starKnt := starKnt +1; + --put(""Number of Arrivals: "");put(numberArrivals);new_line; + put(Image(startTime, Time_Zone => -5*60) );put("":"");new_line; + put(decision.vehicleName & "" Arrived"");new_line(2); + -- put(""-----------------------------------------------------------------------------------"");new_line; + else + intTie := intTie + 1; + if intTie = 91 then + intTie := 65; + end if; + charTie := intToChar(intTie); + decision.vehicleName(4) := charTie; + decision.time2Fix := 3; + ArrivTime := clock; + decision.startTime := ArrivTime; + departTime := clock; + decision.finishTime := departTime; + tpush(decision); + -- + + + -- + tieKnt := tieKnt + 1; + put(Image(startTime, Time_Zone => -5*60) );put("":"");new_line; + put(decision.vehicleName & "" Arrived"");new_line(2); + end if; + if tieKnt + starKnt > 20 then + dagobah := dagobah + 1; + end if; + if dagobah > 0 then + put(""Dagobah Count: "");put(dagobah);new_line; + put(""-----------------------------------------------------------------------------------"");new_line; + end if; + end loop; + + + + + --Lab Step 2. + if starKnt > 0 then + spop(decision); starKnt := starKnt - 1;repairStar:= repairStar+ 1; + delay 3.0; + put(""-----------------------------------------------------------------------------------"");new_line; + + put(""Vehicle Type: "");put(vehicle'image(decision.vehicleType));new_line; + put(""Vehicle Name: "" & decision.vehicleName);new_line; + put(""Time to Fix: "");put(decision.time2Fix,0);new_line; + put(""Start Time: "");put(Image(decision.startTime, Time_Zone => -5*60) );new_line; + departTime := clock; + --finishTime := departTime; + put(""Finish Time: "");put(Image(departTime, Time_Zone => -5*60 ));new_line; + put(""-----------------------------------------------------------------------------------"");new_line; + --if dagobah > 0 then + -- put(""Dagobah Count: "");put(dagobah);new_line; + --end if; + + elsif starKnt = 0 then --and tieKnt > 0 + tpop(decision); tieKnt := tieKnt - 1;repairTie := repairTie + 1; + delay 1.00; + put(""-----------------------------------------------------------------------------------"");new_line; + put(""Vehicle Type: "");put(vehicle'image(decision.vehicleType));new_line; + --put(""Vehicle Name: "" & decision.vehicleName);new_line; + put(""Vehicle Name: "" & decision.vehicleName);new_line; + put(""Time to Fix: "");put(decision.time2Fix,0);new_line; + put(""Start Time: "");put(Image(decision.startTime, Time_Zone => -5*60) );new_line; + departTime := clock; + --finishTime := departTime; + put(""Finish Time: "");put(Image(departTime, Time_Zone => -5*60));new_line; + --put(""Start Time: "");put(Image(decision.startTime, Time_Zone => -5*60) );new_line; + put(""-----------------------------------------------------------------------------------"");new_line; + + + end if; + + + -- do the operations. + + --Lab Step 3. + -- do the operations. + + --Lab Step 4. + -- do the operations, prepare for the vext repair operations. + if dagobah >= 5 then + put(""Total Time Elpased: "");put(Duration'image(Clock - startTime));put("" Seconds"");new_line; + put(""No of Vehicles Repaired: "");put(repairStar + repairTie);put("" Vehicles"");new_line; + --put(""No of Vehicles Repaired: "");put(repairStar + repairTie);put("" Vehicles"");new_line; + put(""No of Star Destroyers Repaired: "");put(repairStar);new_line; + put(""No of Tie Fighters Repaired: "");put(repairTie);new_line; + + exit; + end if; + delay 2.0; + end loop; + + -- Lab Step 5 + --Five vehicles rejected. + --Calculate and print results" +function Object_Distance( Obj: Thing_Type; Ray: Ray_Type ) return Float15 is,"begin + + case Obj.Kind is + + when Sphere => + + declare + Eo: constant Vector := Obj.Center - Ray.Start; + V: constant Float15 := Eo * Ray.Dir; + begin + + if V > 0.0 then + declare + Disc: constant Float15 := Obj.Radius2 - ( Eo * Eo - V * V ); + begin + if Disc > 0.0 then + return V - Sqrt(Disc); + end if;" +function Convert is new Ada.Unchecked_Conversion,"(A, + B); + Configure : B := Convert (My_Event); + begin + GPU.Resize + (Context, + C.unsigned (Configure.width), + C.unsigned (Configure.height));" +procedure Run is,"begin + for II in 1 .. Int (Len) loop + My_Queue.Enqueue (II); + end loop; + + for II in 1 .. Int (Len) loop + declare + Current : Int; + begin + My_Queue.Dequeue (Current); + if Current /= II then + raise Program_Error with Int'Image (Current) & "" /= "" & Int'Image (II); + end if;" +procedure Do_Work is,"begin + loop + declare + New_Command : Any_Command; + begin + My_Command_Queue.Dequeue (New_Command); + + case New_Command.C.T is + when Invalid_Type => + raise Program_Error; + + when Write_Type => + Do_Write (New_Command.C.Write_Object); + when Read_Type => + Do_Read (New_Command.C.Read_Object); + when Poll_Type => + Do_Poll (New_Command.C.Poll_Object); + when Remind_Me_Type => + Do_Remind_Me (New_Command.C.Remind_Me_Object); + end case;" +procedure init_simulation_engine_choice is,"begin + simulation_engine_choice := QComboBoxH (QObject_findChild (QObjectH (covidsim_form), s2qs (""simulation_engine_choice""))); + + for s in simulation_engine loop + QStringList_append(handle => simulation_engines, s => s2qs(enum_image_to_beautiful_image(s'Image))); + end loop; + + QComboBox_addItems (handle => simulation_engine_choice, texts => simulation_engines);" +procedure update_simulation is,"scenario_name : String := beautiful_image_to_enum_image(qs2s(QComboBox_currentText(scenario_choice))); + results : Simulation_Data := Simulation(Scenario'Value(scenario_name), QSpinBox_value(number_population), QSpinBox_value(number_iterations)); + begin + update_line_chart(results, QComboBox_currentText(scenario_choice));" +procedure set_simulation_engine_panel is,"simulation_engine_name : String := beautiful_image_to_enum_image(qs2s(QComboBox_currentText(simulation_engine_choice))); + simulation_choice : Simulation_Engine := Simulation_Engine'Value(simulation_engine_name); + stack : QStackedWidgetH := QStackedWidgetH (QObject_findChild (QObjectH (covidsim_form), s2qs (""simulation_panels""))); + begin + + if simulation_choice = XPH_Pharmaceutical then + QStackedWidget_setCurrentIndex (stack, 0); + slot_change_country_choice (s2qs ("""")); + end if; + + if simulation_choice = Lancet then + QStackedWidget_setCurrentIndex (stack, 1); + update_simulation; -- lancet model stuff TODO : move to lancet_model + end if;" +procedure init_chart is,"legend : QLegendH; + chart_view : QGraphicsViewH; + horizontal_layout : QBoxLayoutH := QHBoxLayout_create; + begin + chart := QChart_create; + + legend := QChart_legend (chart); + QLegend_setVisible (legend, true); + + chart_view := QChartView_create (chart); + QGraphicsView_setRenderHint (chart_view, QPainterAntialiasing); + QBoxLayout_addWidget (horizontal_layout, QWidgetH(chart_view)); + + QWidget_setLayout (QwidgetH (graphic_view), horizontal_layout);" +procedure init_scenario_choices is,"begin + scenario_choice := QComboBoxH (QObject_findChild (QObjectH (covidsim_form), s2qs (""scenario_choice""))); + + for s in Scenario loop + QStringList_append(handle => scenarios, s => s2qs(enum_image_to_beautiful_image(s'Image))); + end loop; + + QComboBox_addItems (handle => scenario_choice, texts => scenarios);" +procedure slot_export_to_csv is,"scenario_name : String := beautiful_image_to_enum_image(qs2s(QComboBox_currentText(scenario_choice))); + results : Simulation_Data := Simulation(Scenario'Value(scenario_name), QSpinBox_value(number_population), QSpinBox_value(number_iterations)); + begin + Export_To_CSV (results, Scenario'Value(scenario_name), QSpinBox_value(number_population), QSpinBox_value(number_iterations));" +procedure covidsim is,"begin + + covidsim_form_init; + QWidget_show(covidsim_form); + QApplication_invoke;" +procedure init_country_choices is,"countries : QStringListH := QStringList_create; + disable : integer := 0; + begin + for c in country loop + QComboBox_addItem (country_choice, s2qs(all_countries(c).name)); + + declare + raw_ce : country_entries_array := get_country_data (data_filename, c); + begin + if raw_ce'length < 5 then + QComboBox_setItemData (country_choice, country'pos(c), QVariant_create(disable), QtUserRole-1); + end if;" +procedure update_forecast_range_chart is,"axes : QObjectListH; + forecast_last : qreal := qreal (QSpinBox_value (forecast_days_value)); + begin + axes := QChart_axes(chart); + QValueAxis_setRange(QAxisH(QObjectList_at(axes, 0)), 0.0, forecast_last);" +procedure update_chart is,"current_index : integer := QComboBox_currentIndex (country_choice); + c : country := country'val(current_index); + + start_date : QDateH := QDateTimeEdit_date (start_date_value); + start_time : Time := time_of (QDate_year (start_date), QDate_month (start_date), QDate_day (start_date)); + + end_date : QDateH := QDateTimeEdit_date (end_date_value); + end_time : Time := time_of (QDate_year (end_date), QDate_month (end_date), QDate_day (end_date)); + + country_ground_truth_first : QSeriesH; + country_ground_truth_date_range : QSeriesH; + country_ground_truth_last : QSeriesH; + + country_forecast : QSeriesH; + + procedure init_series is + pen_first : QPenH := QPen_create(QColor_create(0,255,0)); + pen_date_range : QPenH := QPen_create(QColor_create(255,0,0)); + pen_last : QPenH := QPen_create(QColor_create(0,255,0)); + pen_forecast: QPenH := QPen_create(QColor_create(255,255,0)); + begin + country_ground_truth_first := QLineSeries_create; + QPen_setWidth(pen_first, 3); + QAreaSeries_setPen(country_ground_truth_first, pen_first); + + country_ground_truth_date_range := QLineSeries_create; + QPen_setWidth(pen_date_range, 3); + QAreaSeries_setPen(country_ground_truth_date_range, pen_date_range); + + country_ground_truth_last := QLineSeries_create; + QPen_setWidth(pen_last, 3); + QAreaSeries_setPen(country_ground_truth_last, pen_last); + + country_forecast := QLineSeries_create; + QPen_setWidth(pen_forecast, 3); + QAreaSeries_setPen(country_forecast, pen_forecast);" +procedure reset_chart is,"begin + country_forecast_entries.clear; + update_chart; + update_forecast_range_chart;" +procedure set_initial_date_limits is,"function find_first_case_date return integer is + begin + for i in country_entries.first_index .. country_entries.last_index loop + if country_entries.element (i).cumulative_cases > 0.0 then + return i; + end if; + end loop; + return -1;" +procedure update_min_max_date_limits is,"function get_maximum_start_time(end_time : time) return Time is + begin + return ada.calendar.arithmetic.""-"" (end_time, 5);" +procedure slot_compute_xph is,"c : country := country'val(QComboBox_currentIndex (country_choice)); + steps : integer := QSpinBox_value (steps_value); + i,j,k,l,m : integer := steps + 1; + size : integer := i*j*k*l*m; + + covid_data : country_entries_array := to_country_entries_array (country_entries); + + start_date : QDateH := QDateTimeEdit_date (start_date_value); + start_time : Time := Ada.Calendar.Formatting.time_of (QDate_year (start_date), QDate_month (start_date), QDate_day (start_date)); + + end_date : QDateH := QDateTimeEdit_date (end_date_value); + end_time : Time := Ada.Calendar.Formatting.time_of (QDate_year (end_date), QDate_month (end_date), QDate_day (end_date)); + + + function get_date_index (date_time : time) return integer is + begin + for i in covid_data'range loop + if covid_data (i).date = date_time then + return i; + end if; + end loop; + + return -1;" +procedure slot_export_to_csv;,"pragma Convention (C, slot_export_to_csv);" +function Conversion is new Ada.Unchecked_Conversion(,"Source => Stream_Element_Array, + Target => Element_Type + ); + begin + Stream.Read(Buffer, Buffer_Last); + Element_Count := Natural(Buffer_Last / Element_Length); + Last := Item'First; -- + (Element_Count - 1); + Buffer_I := 1; + for I in 1..Element_Count loop + Item(Last) := Conversion(Buffer(Buffer_I .. Buffer_I + Element_Length - 1)); + Last := Index_Type'Succ(Last); + Buffer_I := Buffer_I + Element_Length; + end loop; + Last := Index_Type'Pred(Last);" +"procedure Inst is new Read_Array(Element_Type => Character, Index_Type => Positive, Array_Type => String);","begin + Inst(Stream, Item, Last);" +procedure Test is,"B : Block_Header; + C : Block_Header := Block_Header'(Status => Occupied, + Prev_Block_Address => Address_Null, + Prev_Block_Status => Absent, + Next_Block_Status => Free, + Size => 1); + A : System.Address := SSE.To_Address(0); + begin + Set_Block_At_Address(A, 0, C); + pragma Assert(Proof.Block_Present_At_Address(0)); + pragma Assert(Proof.Block_At_Address(0) = C); + end Test; + + + --------------------------- + -- Work with Free Blocks -- + --------------------------- + + procedure Unlink_From_Free_List (Base : System.Address; + Address : Aligned_Address; + Block : in out Block_Header; + Free_List : in out Free_Blocks_List) + is + Prev_Address : constant Aligned_Address := Block.Free_List.Prev_Address; + Next_Address : constant Aligned_Address := Block.Free_List.Next_Address; + begin + pragma Assert(Proof.Block_Present_At_Address(Address)); + Remove_Block_At_Address(Base, Address); + Proof.Remove_Block_From_Free_List_For_Size(Block.Size, Address); + if Is_Block_Last_In_Free_List(Block) then + Block.Free_List := Empty_Free_List; + Free_List := Empty_Free_List; + else + declare + Prev_Block : Block_Header := Get_Block_At_Address(Base, Prev_Address); + Next_Block : Block_Header := Get_Block_At_Address(Base, Next_Address); + begin + Remove_Block_At_Address(Base, Prev_Address); + Remove_Block_At_Address(Base, Next_Address); + + Prev_Block.Free_List.Next_Address := Next_Address; + Next_Block.Free_List.Prev_Address := Prev_Address; + + Set_Block_At_Address(Base, Prev_Address, Prev_Block); + Set_Block_At_Address(Base, Next_Address, Next_Block);" +procedure Main is,"function ""+"" + (Item : Wide_Wide_String) return League.Strings.Universal_String + renames League.Strings.To_Universal_String; + + function Get_OAuth_Parameter + (Name : Wide_Wide_String) return League.Strings.Universal_String; + function Get_Auth_URL return League.Strings.Universal_String; + function Encode (Text : String) return League.Strings.Universal_String; + + procedure Get_Tokens + (Code : Wide_Wide_String; + Access_Token : out League.Strings.Universal_String); + + ------------ + -- Encode -- + ------------ + + function Encode (Text : String) return League.Strings.Universal_String is + begin + return League.Strings.From_UTF_8_String (AWS.URL.Encode (Text)); + end Encode; + + ------------------ + -- Get_Auth_URL -- + ------------------ + + function Get_Auth_URL return League.Strings.Universal_String is + Result : League.Strings.Universal_String; + begin + Result.Append (""https://accounts.google.com/o/oauth2/v2/auth""); + + Result.Append (""?client_id=""); + Result.Append (Get_OAuth_Parameter (""client_id"")); + + Result.Append (""&redirect_uri=urn:ietf:wg:oauth:2.0:oob""); + + Result.Append (""&response_type=code""); + + Result.Append (""&scope=""); + Result.Append + (Encode (""https://www.googleapis.com/auth/photoslibrary.readonly"")); + + return Result; + end Get_Auth_URL; + + ------------------- + -- Get_OAuth_Parameter -- + ------------------- + + function Get_OAuth_Parameter + (Name : Wide_Wide_String) return League.Strings.Universal_String + is + Key : constant Wide_Wide_String := ""oauth/"" & Name; + Settings : League.Settings.Settings; + begin + return League.Holders.Element (Settings.Value (+Key)); + end Get_OAuth_Parameter; + + procedure Get_Tokens + (Code : Wide_Wide_String; + Access_Token : out League.Strings.Universal_String) + is + Result : AWS.Response.Data; + Parameters : League.Strings.Universal_String; + begin + Parameters.Append (""code=""); + Parameters.Append (Code); + Parameters.Append (""&client_id=""); + Parameters.Append (Get_OAuth_Parameter (""client_id"")); + Parameters.Append (""&client_secret=""); + Parameters.Append (Get_OAuth_Parameter (""client_secret"")); + Parameters.Append (""&grant_type=authorization_code""); + Parameters.Append (""&redirect_uri=urn:ietf:wg:oauth:2.0:oob""); + + Result := AWS.Client.Post + (URL => ""https://oauth2.googleapis.com/token"", + Data => Parameters.To_UTF_8_String, + Content_Type => ""application/x-www-form-urlencoded""); + + if AWS.Response.Status_Code (Result) not in AWS.Messages.Success then + Ada.Wide_Wide_Text_IO.Put_Line + (AWS.Messages.Status_Code'Wide_Wide_Image + (AWS.Response.Status_Code (Result))); + Ada.Wide_Wide_Text_IO.Put_Line + (AWS.Response.Content_Length_Type'Wide_Wide_Image + (AWS.Response.Content_Length (Result))); + Ada.Text_IO.Put_Line (AWS.Response.Content_Type (Result)); + Ada.Text_IO.Put_Line (AWS.Response.Message_Body (Result)); + raise Program_Error with ""Unexpected response""; + end if; + + declare + Document : constant League.JSON.Documents.JSON_Document := + League.JSON.Documents.From_JSON + (AWS.Response.Message_Body (Result)); + begin + Access_Token := + Document.To_JSON_Object.Value (+""access_token"").To_String;" +procedure Offmt_Tool is,"package Helpers renames Libadalang.Helpers; + package LAL renames Libadalang.Analysis; + package LALU renames Libadalang.Unparsing; + package LALCO renames Libadalang.Common; + package LALRW renames Libadalang.Rewriting; + package LALEXPR renames Libadalang.Expr_Eval; + + All_Traces : Offmt_Lib.Trace_Map; + + function Base_Name (Full_Path : String) return String; + + procedure Setup (Ctx : Helpers.App_Context; + Jobs : Helpers.App_Job_Context_Array); + + procedure Process_Unit (Job_Ctx : Helpers.App_Job_Context; + Unit : LAL.Analysis_Unit); + + procedure Post_Process (Ctx : Helpers.App_Context; + Jobs : Helpers.App_Job_Context_Array); + + procedure Output_Unit + (Job_Ctx : Libadalang.Helpers.App_Job_Context; + Unit : Libadalang.Analysis.Analysis_Unit; + Out_Dir_Path : GNATCOLL.Strings.XString); + + procedure Output_Map (Map : Offmt_Lib.Trace_Map); + + function Map_Filename return String; + + procedure Handle_Log_Call (RH : LALRW.Rewriting_Handle; + Node : LAL.Call_Stmt'Class); + + package App is new Helpers.App + (Name => To_String (Offmt_Lib.Log_Root_Pkg), + Description => ""Offloaded string format"", + App_Setup => Setup, + App_Post_Process => Post_Process, + Process_Unit => Process_Unit); + + package Output_Dir is new GNATCOLL.Opt_Parse.Parse_Option + (Parser => App.Args.Parser, + Long => ""--output-dir"", + Arg_Type => GNATCOLL.Strings.XString, + Convert => GNATCOLL.Opt_Parse.Convert, + Default_Val => GNATCOLL.Strings.Null_XString, + Help => + ""The directory in which to output the instrumented ada units."" + & ""When invoked with a project file, this path is treated as "" + & ""relative to the (sub-)projects' object directories, unless "" + & ""this is an absolute path.""); + + Instr_Mode_Long : constant String := ""--instrument""; + Decode_Mode_Long : constant String := ""--decode""; + + package Instrument_Mode is new GNATCOLL.Opt_Parse.Parse_Flag + (Parser => App.Args.Parser, + Long => Instr_Mode_Long, + Help => ""Enable instrumentation mode""); + + package Decode_Mode is new GNATCOLL.Opt_Parse.Parse_Flag + (Parser => App.Args.Parser, + Long => Decode_Mode_Long, + Help => ""Enable decode mode""); + + --------------- + -- Base_Name -- + --------------- + + function Base_Name (Full_Path : String) return String is + use GNATCOLL.VFS; + begin + return +Create (+Full_Path).Base_Name; + end Base_Name; + + ------------------ + -- Map_Filename -- + ------------------ + + function Map_Filename return String is + + Out_Dir : constant VFS.Virtual_File := + VFS.Create_From_Base (VFS.""+"" (Strings.To_String (Output_Dir.Get))); + + Out_File : constant VFS.Virtual_File := + VFS.Join (Out_Dir, ""offmt_map.toml""); + + begin + return VFS.""+"" (Out_File.Full_Name); + end Map_Filename; + + --------------------- + -- Handle_Log_Call -- + --------------------- + + procedure Handle_Log_Call (RH : LALRW.Rewriting_Handle; + Node : LAL.Call_Stmt'Class) + is + Call : LAL.Call_Expr; + begin + if Offmt_Lib.Detection.Check_Defmt_Log_Call (Node, Call) then + declare + S : constant LAL.Ada_Node := Call.F_Suffix; + Arg : LAL.Expr; + begin + + Arg := S.Child (1).As_Param_Assoc.F_R_Expr; + declare + Arg_Val : constant LALEXPR.Eval_Result := + LALEXPR.Expr_Eval (Arg); + begin + case Arg_Val.Kind is + when LALEXPR.String_Lit => + declare + use Langkit_Support.Text; + Txt : constant Text_Type + := To_Text (Arg_Val.String_Result); + Str : constant String := Image (Txt); + Trace : constant Offmt_Lib.Trace := + Offmt_Lib.Parser.Parse (Str); + begin + Put_Line (Str); + Offmt_Lib.Pretty_Print (Trace); + Offmt_Lib.Rewrite.Rewrite_Log_Call (RH, Node, Trace); + All_Traces.Include (Trace.Id, Trace);" +procedure adainit is,"Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + null; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + + E78 := E78 + 1; + Cortex_M.Nvic'Elab_Spec; + E76 := E76 + 1; + E68 := E68 + 1; + E28 := E28 + 1; + E70 := E70 + 1; + Nrf.Interrupts'Elab_Body; + E72 := E72 + 1; + E34 := E34 + 1; + E37 := E37 + 1; + E56 := E56 + 1; + E54 := E54 + 1; + E84 := E84 + 1; + E80 := E80 + 1; + E41 := E41 + 1; + E44 := E44 + 1; + E48 := E48 + 1; + Nrf.Device'Elab_Spec; + Nrf.Device'Elab_Body; + E06 := E06 + 1; + NRF52_DK.IOS'ELAB_SPEC; + NRF52_DK.IOS'ELAB_BODY; + E52 := E52 + 1; + NRF52_DK.TIME'ELAB_BODY; + E82 := E82 + 1; + E87 := E87 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + procedure main is + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + adainit; + Ada_Main_Program;" +procedure adainit is,"Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + null; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + + E78 := E78 + 1; + Cortex_M.Nvic'Elab_Spec; + E76 := E76 + 1; + E68 := E68 + 1; + E28 := E28 + 1; + E70 := E70 + 1; + Nrf.Interrupts'Elab_Body; + E72 := E72 + 1; + E34 := E34 + 1; + E37 := E37 + 1; + E56 := E56 + 1; + E54 := E54 + 1; + E84 := E84 + 1; + E80 := E80 + 1; + E41 := E41 + 1; + E44 := E44 + 1; + E48 := E48 + 1; + Nrf.Device'Elab_Spec; + Nrf.Device'Elab_Body; + E06 := E06 + 1; + NRF52_DK.IOS'ELAB_SPEC; + NRF52_DK.IOS'ELAB_BODY; + E52 := E52 + 1; + NRF52_DK.TIME'ELAB_BODY; + E82 := E82 + 1; + E87 := E87 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + procedure main is + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + adainit; + Ada_Main_Program;" +procedure Free is,"new Ada.Unchecked_Deallocation (Object => File_Type, + Name => File_Pt); + begin + case What.Class is + when None | Standard_Output => + null; + + when File => + Close (What.F.all); + Free (What.F); + end case; + + end Close; + + function To_File_Access (What : Extended_File) return File_Access + is (case What.Class is + when None => + null, + + when Standard_Output => + Standard_Output, + + when File => + File_Access (What.F)); + + + -------------------------- + -- Print_Warning_Header -- + -------------------------- + + procedure Print_Warning_Header (To : File_Access) + is + + begin + Put_Line (To.all, ""%""); + Put_Line (To.all, ""%---""); + Put_Line (To.all, ""% WARNING: Automatically generated file""); + Put_Line (To.all, ""% WARNING: If you edit this your changes will be lost""); + Put_Line (To.all, ""%---""); + Put_Line (To.all, ""%""); + New_Page (To.all); + end Print_Warning_Header; + + + -------------------- + -- Print_Partners -- + -------------------- + + procedure Print_Partners (Input : EU_Projects.Projects.Project_Descriptor; + Target : Target_Spec) + is + use EU_Projects.Nodes.Partners; + + procedure Print_Partners (To : File_Access) is + procedure Print_Single_Partner (To : File_Type; Partner : Partner_Access) is + begin + Put_Line (To, ""\newpartner"" + & ""{"" & Partner.Short_Name & ""}"" + & ""{"" & To_String (Partner.Label) & ""}"" + & ""{"" & Partner.Name & ""}"" + & ""{"" & Partner.Country & ""}""); + end Print_Single_Partner; + begin + for Idx in Input.All_Partners loop + Print_Single_Partner (To.all, Element (Idx)); + end loop; + end Print_Partners; + + Output : Extended_File := Open (Target); + begin + if Output.Class = None then + return; + end if; + + Within (Output => To_File_Access (Output), + Env_Name => ""partnerlist"", + Callback => Print_Partners'Access); + + Close (Output); + end Print_Partners; + + + ------------------ + -- Define_Label -- + ------------------ + + procedure Define_Label (Output : File_Type; + Item : Node_Type'Class; + Prefix : String; + Add_New_Line : Boolean := True) + is + begin + Put (Output, + ""\failabel{"" & Image (Item.Label) & ""}"" + & ""{"" & Prefix & ""}"" + & ""{"" & Item.Short_Name & ""}"" + & ""{"" & Item.Full_Index (False) & ""}""); + + if Add_New_Line then + New_Line (Output); + end if; + end Define_Label; + ------------------ + -- Join_Indexes -- + ------------------ + + function Join_Indexes (Input : EU_Projects.Projects.Project_Descriptor; + Labels : Node_Label_Lists.Vector; + Separator : String) + return String + is + Result : Unbounded_String; + begin + for Idx in Labels.Iterate loop + Result := Result & Input.Find (Labels (Idx)).Full_Index (Prefixed => True); + + if Node_Label_Lists.To_Index (Idx) < Labels.Last_Index then + Result := Result & Separator; + end if; + end loop; + + return To_String (Result); + end Join_Indexes; + + procedure Print_WP (Input : Project_Descriptor; + Output : Extended_File; + WP : WPs.Project_WP_Access) is + + + Efforts : constant Action_Nodes.Effort_List := + WP.Efforts_Of (Input.Partner_Names); + + + function Short_Name (X : Partners.Partner_Label) return String + is + N : constant Node_Access := Input.Find (Node_Label (X)); + begin + if N = null then + raise Processor_Error + with ""Unknown partner '"" & Image (Node_Label (X)) & ""'""; + else + return N.Short_Name; + end if; + end Short_Name; + + procedure Write_WP_Header (Output : File_Access; + Table : in out Table_Handler) + is + pragma Unreferenced (Output); + + Headstyle : constant String := ""\stilehead""; + + procedure Put_Pair (Title, Content : String) is + begin + Table.Put (Title, Headstyle); + Table.Put (Content); + end Put_Pair; + + procedure First_Row_Standard_Style is + begin + Table.Cline (1, 4); + Put_Pair (""WP Number"", WP.Index_Image); + Put_Pair (""Leader"", Short_Name (WP.Leader)); + Table.Hline; + + Table.Put (""WP Name"", Headstyle); + Table.Multicolumn (Span => Efforts'Length + 1, + Spec => ""|l|"", + Content => WP.Name); + + end First_Row_Standard_Style; + + procedure First_Row_Compact_Style is + begin + Table.Hline; + Put_Pair (""WP N."", WP.Index_Image); + + Table.Put (""WP Name"", Headstyle); + Table.Multicolumn (Span => Efforts'Length - 4, + Spec => ""|l|"", + Content => WP.Name); + + Table.Put (""\WPleadertitle""); + Table.Multicolumn (Span => 2, + Spec => ""c|"", + Content => + ""\WPleadername{"" & Short_Name (WP.Leader) & ""}""); + end First_Row_Compact_Style; + begin + if True then + First_Row_Compact_Style; + else + First_Row_Standard_Style; + end if; + + Table.Hline; + + Table.Put (""N. Partner"", Headstyle); + + for Idx in Efforts'Range loop + Table.Put (Image (Idx)); + end loop; + Table.Put (""""); + Table.Hline; + + Table.Put (""Name"", Headstyle); + + for Idx in Efforts'Range loop + Table.Put (Short_Name (Efforts (Idx).Partner)); + end loop; + Table.Put (""all""); + Table.Hline; + + Table.Put (""PM"", Headstyle); + + declare + use EU_Projects.Efforts; + + Total_Effort : Person_Months := 0; + begin + for Idx in Efforts'Range loop + Table.Put (Chop (Efforts (Idx).Effort'Image)); + + Total_Effort := Total_Effort + Efforts (Idx).Effort; + end loop; + + Table.Put (Chop (Total_Effort'Image));" +-- procedure Full_Header is,"-- + -- begin + -- Table.Hline; + -- Table.Head (""WP""); + -- Table.Head (""WP Name""); + -- Table.Multicolumn (2, ""|c|"", ""\stilehead{Leader}""); + -- -- Table.Put (""Leader N."", ""\stilehead""); + -- -- Table.Put (""Leader""""); + -- Table.Head (""PM""); + -- Table.Head (""Start""); + -- Table.Head (""End""); + -- Table.Cline (3, 4); + -- + -- Table.Put (""""); + -- Table.Put (""""); + -- Table.Head (""Name""); + -- Table.Head (""N.""); + -- Table.Put (""""); + -- Table.Put (""""); + -- Table.Put (""""); + -- end Full_Header; + -- + -- procedure Light_Header is + -- + -- begin + -- Table.Put (""""); + -- Table.Put (""""); + -- Table.Multicolumn (2, ""c"", ""\stilehead{Leader}""); + -- -- Table.Put (""Leader N."", ""\stilehead""); + -- -- Table.Put (""Leader""""); + -- Table.Put (""""); + -- Table.Put (""""); + -- Table.Put (""""); + -- Table.Put (""""); + -- Table.Cline (3, 4); + -- + -- Table.Multicolumn (1, ""c"", ""WP""); + -- Table.Multicolumn (1, ""c"", ""WP Name""); + -- Table.Multicolumn (1, ""c"", ""Name""); + -- Table.Multicolumn (1, ""c"", ""N.""); + -- Table.Multicolumn (1, ""c"", ""~""); + -- Table.Multicolumn (1, ""c"", ""PM""); + -- Table.Multicolumn (1, ""c"", ""Start""); + -- Table.Multicolumn (1, ""c"", ""End""); + -- end Light_Header; + + Project_Effort : Person_Months := 0; + + begin + -- case Style is + -- when Full => Full_Header; + -- when Light => Light_Header; + -- end case; + + Put_Line (Output.all, ""\summarywptableheader""); + + -- Table.Hline; + + + for Pos in Input.All_WPs loop + declare + use EU_Projects.Nodes.Partners; + + procedure Put_Arg (X : String) is + begin + Put (Output.all, ""{"" & X & ""}""); + end Put_Arg; + + WP : constant Project_WP_Access := Element (Pos); + Wp_Effort : constant Person_Months := Total_Effort (Wp); + Leader : constant Partner_Access := + Partner_Access (Input.Find (Node_Label (WP.Leader))); + begin + Put (Output.all, ""\summarywpitem""); + + Put_Arg (WP.Full_Index (Prefixed => False)); + Put_Arg (WP.Short_Name); + Put_Arg (Leader.Short_Name); + Put_Arg (Leader.Full_Index (Prefixed => False)); + Put_Arg (Chop (Wp_Effort'Image)); + Put_Arg (EU_Projects.Times.Image (Formatter, Wp.Starting_Time)); + Put_Arg (EU_Projects.Times.Image (Formatter, Wp.Ending_Time)); + + New_Line (Output.all); + Project_Effort := Project_Effort + Wp_Effort; + -- Table.Hline (Style = Full);" +procedure Compact_Header_Line is,"begin + Table.Multicolumn (2, ""c"", """"); + + for M in 1 .. Last_Month loop + if M mod Step = 0 then + Table.Multicolumn + (Span => 1, + Spec => ""c"", + Content => ""\stilemese{"" & Image (M) & ""}""); + else + Table.Put (""""); + end if; + + Table.Put (""""); + end loop; + + Table.New_Row; + end Compact_Header_Line; + + procedure First_Header_Line is + begin + Table.Put (""""); + Table.Put (""""); + for M in 1 .. Last_Month loop + if M mod Step = 0 and M > 9 then + Table.Put (Image (M / 10)); + else + Table.Put (""""); + end if; + + Table.Put (""""); + end loop; + + Table.New_Row; + end First_Header_Line; + + procedure Second_Header_Line is + begin + Table.Put (""""); + Table.Put (""""); + for M in 1 .. Last_Month loop + if M mod Step = 0 then + Table.Put (Image (M mod 10)); + else + Table.Put (""""); + end if; + + Table.Put (""""); + end loop; + + Table.New_Row; + end Second_Header_Line; + + procedure Show_Busy_Time (Item : EU_Projects.Nodes.Action_Nodes.Action_Node'Class) + is + + From : constant Instant := Item.Starting_Time; + To : constant Instant := Item.Ending_Time; + begin + if From = To_Be_Decided or To = To_Be_Decided then + for M in 1 .. Last_Month loop + Table.Put (""\TBDcell""); + + Table.Put (""""); + end loop; + else + declare + T : Instant; + begin + for M in 1 .. Last_Month loop + T := To_Instant (M); + + Table.Put ((if T >= From and then T <= To + then + ""\busytimecell"" + else + ""\freetimecell"")); + + + Table.Put (""""); + end loop;" +procedure Make_WP_Separator;,"Current_V_Pos : Picture_Length; + + function Month_Position (Month : Projects.Month_Number; + Setup : Graphic_Setup_Descriptor) + return Picture_Length + is (Setup.Label_Size + (Integer (Month) - 1) * Setup.Month_Width); + + function To_Length (L : Picture_Length; + Setup : Graphic_Setup_Descriptor) + return Latex_Length + is (Float (L) * Setup.Unit_Length); + + procedure Next_Row is + begin + -- Put_Line (Current_V_Pos'Image); + -- Put_Line (Graphic_Setup.Month_Heigth'Image); + -- Put_Line (Graphic_Setup.Interline'image); + Current_V_Pos := Current_V_Pos - Graphic_Setup.Line_Heigth; + end Next_Row; + + procedure Show_Busy_Time (Item : EU_Projects.Nodes.Action_Nodes.Action_Node'Class; + Style : String; + Intensity : EU_Projects.Nodes.Action_Nodes.Tasks.Task_Intensity) + is + + procedure Make_Bar (From, To : Month_Number; + Command : String; + Show_Intensity : Boolean) is + Start : constant Picture_Length := + Month_Position (From, Graphic_Setup); + + Len : constant Latex_Length := + To_Length (Month_Position (To, Graphic_Setup)-Start, Graphic_Setup); + + Shrink : constant Float := 0.8; + H : constant Latex_Length := + Shrink * To_Length (Graphic_Setup.Line_Heigth, Graphic_Setup); + + H2 : constant Latex_Length := Float'Max (Intensity, 0.15) * H; + + Box_Raise : constant Latex_Length := + (1.0 - Shrink) * 0.5 * To_Length (Graphic_Setup.Line_Heigth, Graphic_Setup); + begin + if Show_Intensity then + Put_Line (Output.all, Put (X => Start, + Y => Current_V_Pos, + What => Style + & ""{"" + & ( + ""\shadedrule"" + & ""["" & Image (Box_Raise) & ""]"" + & ""{"" & Image (Len) & ""}"" + & ""{"" & Image (H) & ""}"" + ) + & ""}"")); + + Put_Line (Output.all, Put (X => Start, + Y => Current_V_Pos, + What => Style + & ""{"" + & ( + Command + & ""["" & Image (Box_Raise) & ""]"" + & ""{"" & Image (Len) & ""}"" + & ""{"" & Image (H2) & ""}"" + ) + & ""}"")); + else + Put_Line (Output.all, Put (X => Start, + Y => Current_V_Pos, + What => Style + & ""{"" + & ( + Command + & ""["" & Image (Box_Raise) & ""]"" + & ""{"" & Image (Len) & ""}"" + & ""{"" & Image (H) & ""}"" + ) + & ""}"")); + end if; + + declare + Dx : constant Picture_Length := Picture_Length (Len / Graphic_Setup.Unit_Length); + Dy : constant Picture_Length := Picture_Length (H / Graphic_Setup.Unit_Length); + B : constant Picture_Length := Picture_Length (Box_Raise / Graphic_Setup.Unit_Length); + Y0 : constant Picture_Length := Current_V_Pos + B; + begin + Put_Line (Output.all, Put (X => Start, + Y => Y0, + What => HLine (Dx))); + + + Put_Line (Output.all, Put (X => Start, + Y => Y0, + What => Vline (Dy))); + + Put_Line (Output.all, Put (X => Start, + Y => Y0 + Dy, + What => HLine (Dx))); + + + Put_Line (Output.all, Put (X => Start + Dx, + Y => Y0, + What => VLine (Dy)));" +procedure Prova_Parser is,"type Class is (Wp, Tsk, Deliv); + + package My_Parser is new Node_List_Parsers (Class); + use My_Parser; + + Eol : constant Character := Character'Val (10); + X : constant String := """" & Eol + & """" & Eol + & """" & Eol + & "" [ Wp ]"" & Eol + & ""name : zorro"" & Eol + & ""label : pluto "" & Eol + & ""Viva la pappa col pomodoro"" & Eol + & """" & Eol + & """" & Eol + & ""[task]"" & Eol + & ""begin:12"" & Eol; + + Names : My_Parser.Name_Maps.Map; +begin + Names.Insert (Key => +""task"", + New_Item => Tsk); + + declare + Result : constant Node_List := Parse (Line_Arrays.Split (X), Names); + begin + Dump (Result);" +function Missing_Message (Missing : String_Lists.List),"return String + is + function Join (Item : String_Lists.List) return String is + Result : Unbounded_String; + + procedure Append (Pos : String_Lists.Cursor) is + begin + if Result /= Null_Unbounded_String then + Result := Result & "", ""; + end if; + + Result := Result & ""'"" & String_Lists.Element (Pos) & ""'""; + end Append; + begin + Item.Iterate (Append'Access); + + return To_String (Result); + end Join; + + use type Ada.Containers.Count_Type; + begin + if Missing.Length = 1 then + return ""Missing mandatory option "" & Join (Missing); + else + return ""Missing mandatory options: "" & Join (Missing); + end if; + end Missing_Message; + + function Collect_Parameters (Extra : String_Vectors.Vector) + return String_Vectors.Vector + is + Result : String_Vectors.Vector; + begin + for Idx in 1 .. Command_Line.Argument_Count loop + Result.Append (Command_Line.Argument (Idx)); + end loop; + + Result.Append (Extra); + + return Result; + end Collect_Parameters; + + + Name : Unbounded_String; + Value : Unbounded_String; + + use Name_To_Index_Maps; + + Position : Name_To_Index_Maps.Cursor; + Param_Idx : Parameter_Index; + + Arguments : constant String_Vectors.Vector := Collect_Parameters (Extend_By); + begin + for Pos in Arguments.First_Index .. Arguments.Last_Index loop + Split_Parameter (Arguments (Pos), Name, Value); + declare + N : String := To_S (Name); + V : constant String := To_S (Value); + Handler : Handler_Access; + This_Parameter : Parameter_Descriptor; + begin + Case_Normalize (N, Parser.Case_Sensitive); + + Position := Parser.Name_Table.Find (N); + + if Position = No_Element then + raise Bad_Command with ""Option '"" & To_S (Name) & ""' unknown""; + end if; + + Param_Idx := Name_To_Index_Maps.Element (Position); + This_Parameter := Parser.Parameters (Param_Idx); + Handler := This_Parameter.Handler; + + if Handler.Is_Set and not Handler.Reusable then + raise Bad_Command with ""Option '"" & N & ""' given twice""; + end if; + + Handler.Receive (Name => ( + if Parser.Normalize_Name then + To_S (This_Parameter.Standard_Name) + else + N + ), + Value => V, + Position => Pos);" +procedure Initialize is,"use Line_Parsers; + + Parser : Line_Parser := Create (Case_Sensitive => False); + begin + Add_Parameter (Parser, + Name => ""in,input"", + If_Missing => Die, + Default => """", + Handler => Input_File'Access); + + Add_Parameter (Parser, + Name => ""p,proc,processor"", + If_Missing => Ignore, + Default => """", + Handler => Processors'Access); + + + Add_Parameter (Parser, + Name => ""f,fmt,format"", + If_Missing => Ignore, + Default => """", + Handler => Format'Access); + + Parse_Command_Line (Parser, Slurp (""pjp.conf"")); + end Initialize; + + ----------------------------- + -- Parse_Plugin_Parameters -- + ----------------------------- + + generic + type Plugin_Name_Type is private; + + with function To_Name (X : String) return Plugin_Name_Type; + procedure Parse_Plugin_Specs + (Input : String; + Plugin_Name : out Plugin_Name_Type; + Parameters : out Plugins.Parameter_Map; + Plugin_Name_Separator : Character := ':'; + Pair_Separator : Character := ';'; + Value_Separator : Character := '='); + + procedure Parse_Plugin_Specs + (Input : String; + Plugin_Name : out Plugin_Name_Type; + Parameters : out Plugins.Parameter_Map; + Plugin_Name_Separator : Character := ':'; + Pair_Separator : Character := ';'; + Value_Separator : Character := '=') + is + use Tokenize; + + procedure Parse_Params (Result : out Plugins.Parameter_Maps.Map; + Input : Unbounded_String) + is + use Tokenize.Token_Vectors; + + Pairs : constant Token_Vectors.Vector := + To_Vector (Split (To_Be_Splitted => To_String (Input), + Separator => Pair_Separator, + Collate_Separator => True)); + begin + for P of Pairs loop + declare + -- Name_And_Value : constant Token_Array := + -- Split (To_Be_Splitted => P, + -- Separator => Value_Separator, + -- Max_Token_Count => 2); + -- + -- Name : constant String := To_String (Name_And_Value (Name_And_Value'First)); + -- Value : constant String := + -- (if Name_And_Value'Length = 1 + -- then """" + -- else To_String (Name_And_Value (Name_And_Value'First + 1))); + Name : Unbounded_String; + Value : Unbounded_String; + begin + Head_And_Tail (To_Be_Splitted => P, + Separator => Value_Separator, + Head => Name, + Tail => Value, + Trimming => Both); + + Result.Include (Key => To_String (Name), + New_Item => To_String (Value));" +procedure Init_Scanner is,"begin + Cursor := Buffer'First; + + while Cursor <= Buffer'Last and then Buffer (Cursor) = ' ' loop + Cursor := Cursor + 1; + end loop; + + if Cursor <= Buffer'Last then + Current_Char := Buffer (Cursor); + else + Current_Char := EOS; + end if; + end Init_Scanner; + + procedure Next_Char (Skip_Spaces : Boolean := True) is + begin + loop + if Cursor >= Buffer'Last then + Current_Char := EOS; + else + Cursor := Cursor + 1; + Current_Char := Buffer (Cursor); + end if; + + exit when (not Skip_Spaces) or Current_Char /= ' '; + end loop; + end Next_Char; + + procedure Expect (What : Character) is + begin + if Current_Char /= What then + raise Parsing_Error + with ""Expecting '"" & What & ""' got '"" & Current_Char & ""'""; + else + Next_Char; + end if; + end Expect; + + function Remaining return String is + begin + return Buffer (Cursor .. Buffer'Last); + end Remaining; + + Level : Natural := 0; + + function Indent return String is + use Ada.Strings.Fixed; + begin + return (Level * 3) * "" ""; + end Indent; + + procedure Down_Level is + begin + Level := Level + 1; + end Down_Level; + + procedure Up_Level is + begin + Level := Level - 1; + end Up_Level; + + procedure Ecco (X : String) is + begin + if Verbose then + Ada.Text_Io.Put_Line (Indent + & ""Calling "" + & X & ""["" & Remaining & ""]"" + & ""'"" & Current_Char & ""'""); + Down_Level; + end if; + end Ecco; + + procedure Fine is + begin + if Verbose then + Up_Level; + Ada.Text_Io.Put_Line (Indent & ""done "" & ""["" & Remaining & ""]"" + & ""'"" & Current_Char & ""'""); + end if; + end Fine; + + procedure Advance (N : Positive) is + begin + Cursor := Cursor + N - 1; + Next_Char; + end Advance; + + function Parse_Expr return Node_Access; + + -- function Parse_Identifier return Bounded_ID is + -- use Ada.Strings.Maps; + -- use Bounded_IDs; + -- + -- Result : Bounded_ID; + -- ID_Chars : constant Character_Set := + -- To_Set (Character_Range'('a', 'z')) or + -- To_Set (Character_Range'('A', 'Z')) or + -- To_Set (Character_Range'('0', '9')) or + -- To_Set ('.') or + -- To_Set ('_'); + -- begin + -- Ecco (""ID""); + -- + -- while Is_In (Current_Char, ID_Chars) loop + -- Result := Result & Current_Char; + -- Next_Char (Skip_Spaces => False); + -- end loop; + -- + -- if Current_Char = ' ' then + -- Next_Char; + -- end if; + -- + -- Fine; + -- return Result; + -- end Parse_Identifier; + + procedure Parse_Parameter_List (Parameters : out Parameter_Array; + N_Params : out Natural) + is + begin + Ecco (""par-list""); + + if Current_Char = ')' then + N_Params := 0; + + else + N_Params := 1; + Parameters (1) := Parse_Expr; + + while Current_Char = ',' loop + Next_Char; + N_Params := N_Params + 1; + Parameters (N_Params) := Parse_Expr; + end loop; + end if; + + Expect (')'); + Fine; + exception + when others => + for I in Parameters'First .. N_Params - 1 loop + Free (Parameters (I)); + end loop; + + raise; + end Parse_Parameter_List; + + procedure Resolve_Identifier (Raw_ID : in Identifier; + Pos : out ID_Tables.Cursor; + N_Matches : out Natural; + Resolved : out Identifier; + No_Prefix_Needed : out Boolean) + with Post => + ( + (ID_Tables.""="" (Pos, ID_Tables.No_Element) = (N_Matches = 0)) + ); + + + procedure Resolve_Identifier (Raw_ID : in Identifier; + Pos : out ID_Tables.Cursor; + N_Matches : out Natural; + Resolved : out Identifier; + No_Prefix_Needed : out Boolean) + is + use ID_Tables; + begin + No_Prefix_Needed := False; + N_Matches := 0; + + Pos := ID_Table.T.Find (Raw_ID); + + if Pos /= No_Element then + Resolved := Raw_ID; + No_Prefix_Needed := True; + N_Matches := 1; + end if; + + + declare + Tmp : Identifier; + begin + for I in Prefix_List'Range loop + Tmp := Join (Prefix_List (I), Raw_ID); + + Pos := ID_Table.T.Find (Tmp); + + if Pos /= No_Element then + N_Matches := N_Matches + 1; + + if N_Matches = 1 then + Resolved := Tmp; + end if; + end if; + end loop;" +procedure Do_Checks is,"new Do_Suite (Test_Case => Test_Case, + Test_Case_Array => Test_Case_Array, + Check => Check); + + type Syntax_ID_Case is + record + Expr : Unbounded_String; + Action : Unknown_ID_Action_Type; + Success : Boolean; + end record; + + type Syntax_ID_Case_Array is + array (Positive range <>) of Syntax_ID_Case; + + Syntax_Cases : constant Syntax_ID_Case_Array := + ((Expr => +""4*foo"", + Action => Die, + Success => False), + (Expr => +""4*foo"", + Action => OK, + Success => True), + (Expr => +""4*foo()"", + Action => Accept_As_Var, + Success => False), + (Expr => +""4*bar(2,3) + pippo"", + Action => Die, + Success => True), + (Expr => +""4*pippo(2,3)"", + Action => OK, + Success => False), + (Expr => +""4*bar"", + Action => OK, + Success => False), + (Expr => +""4*bar(2)"", + Action => OK, + Success => False), + (Expr => +""4*bar(2,3,4)"", + Action => OK, + Success => False), + (Expr => +""4*pluto(2)"", + Action => OK, + Success => False), + (Expr => +""4*pluto(2,3)"", + Action => OK, + Success => True), + (Expr => +""4*pluto(2,3,4)"", + Action => OK, + Success => True), + (Expr => +""zorro()"", + Action => OK, + Success => False), + (Expr => +""zorro(1)"", + Action => OK, + Success => False), + (Expr => +"" zorro (1, 2)"", + Action => OK, + Success => True), + (Expr => +""zorro(1, 2, 3)"", + Action => OK, + Success => True), + (Expr => +""zorro(1, 2, 3,4)"", + Action => OK, + Success => True), + (Expr => +""zorro(1, 2, 3,4,x)"", + Action => OK, + Success => False)); + + + + + + ID_Table : ID_Table_Type; + + function Check_Syntax (This : Syntax_ID_Case) return Boolean is + Tmp : Symbolic_Expression; + pragma Unreferenced (Tmp); + Raised : Boolean; + Expected : Boolean; + begin + Raised := False; + Expected := False; + + begin + Tmp := Parse (Input => +This.Expr, + ID_Table => ID_Table, + On_Unknown_ID => This.Action); + exception + when Parsing_Error => + Raised := True; + Expected := True; + when others => + Raised := True; + Expected := False;" +procedure Do_Syntax_ID_Checks is,"new Do_Suite (Test_Case => Syntax_ID_Case, + Test_Case_Array => Syntax_ID_Case_Array, + Check => Check_Syntax); + + + + Reporter : Reporter_Type; +begin + -- Be_Verbose (Reporter); + Define_Function (ID_Table, ""bar"", Exactly (2)); + Define_Function (ID_Table, ""pluto"", At_Least (2)); + Define_Function (ID_Table, ""zorro"", Between (2, 4)); + Define_Variable (ID_Table, ""pippo""); + + for I in Variables'Range loop + Var_Table.Insert (+Variables (I).Name, Variables (I).Value); + end loop; + + Do_Checks (Reporter, Test_Cases, ""Basic""); + + Do_Syntax_ID_Checks (Reporter, Syntax_Cases, ""Syntax""); + + declare + X : constant Symbolic_Expression := Variable (""x""); + Y : constant Symbolic_Expression := Variable (""y""); + T : constant Symbolic_Expression := (X + Y) * (X - Y); + U : constant Symbolic_Expression := Function_Call (""max"", (X, Y)); + R : constant Symbolic_Expression := Function_Call (""min"", (X, Y)); + S : constant Symbolic_Expression := R * U; + K : constant Symbolic_Expression := To_Expr (42); + M : constant Symbolic_Expression := X + Y * U / (K - S); + Q : constant Symbolic_Expression := Replace (S, ""x"", T); + Z : constant Symbolic_Expression := T * (- Q); + W : constant Symbolic_Expression := +T * (+T); + A : constant Symbolic_Expression := W * 3-(2 + U) / (Q - 1); + + Val_X : constant Integer := 12; + Val_Y : constant Integer := -3; + Val_T : constant Integer := (Val_X + Val_Y) * (Val_X - Val_Y); + Val_U : constant Integer := Integer'Max (Val_X, Val_Y); + Val_R : constant Integer := Integer'Min (Val_X, Val_Y); + Val_S : constant Integer := Val_R * Val_U; + Val_K : constant Integer := 42; + Val_M : constant Integer := Val_X + Val_Y * Val_U / (Val_K - Val_S); + Val_Q : constant Integer := + Integer'Max (Val_Y, Val_T) * Integer'Min (Val_Y, Val_T); + Val_Z : constant Integer := Val_T * (-Val_Q); + Val_W : constant Integer := +Val_T * (+Val_T); + Val_A : constant Integer := Val_W * 3-(2 + Val_U) / (Val_Q - 1); + + function Check (Item : Symbolic_Expression; + Expected : Integer) + return Boolean + is + Tmp : Symbolic_Expression; + begin + Tmp := Replace (Item, ""x"", Val_X); + Tmp := Replace (Tmp, ""y"", Val_Y); + + return Is_Constant (Tmp) and then Eval (Tmp) = Expected; + end Check; + begin + New_Suite (Reporter, ""Operators""); + New_Result (Reporter, Check (X, Val_X)); + New_Result (Reporter, Check (Y, Val_Y)); + New_Result (Reporter, Check (T, Val_T)); + New_Result (Reporter, Check (U, Val_U)); + New_Result (Reporter, Check (R, Val_R)); + New_Result (Reporter, Check (S, Val_S)); + New_Result (Reporter, Check (K, Val_K)); + New_Result (Reporter, Check (M, Val_M)); + New_Result (Reporter, Check (Q, Val_Q)); + New_Result (Reporter, Check (Z, Val_Z)); + New_Result (Reporter, Check (W, Val_W)); + New_Result (Reporter, Check (A, Val_A));" +function Deliverable_Type_Check is,"new Generic_Enumerative (Deliverables.Deliverable_Type); + + + function Dissemination_Level_Check is + new Generic_Enumerative (Deliverables.Dissemination_Level); + + Basic_Checker : constant Attribute_Checker := + Mandatory (""label"") + + Mandatory (""name"") + + Mandatory (""short""); + + Project_Checker : constant Attribute_Checker := + Basic_Checker + Default (""end"", Event_Names.Default_Time); + + Event_Checker : constant Attribute_Checker := + Basic_Checker + Default (""when"", ""default""); + + Activity_Checker : constant Attribute_Checker := + Basic_Checker + + Mandatory (""begin"") + + Alternative (""end|duration"") + + Default (""objective"", """") + + Default (""dependencies"", """"); + + WP_Checker : constant Attribute_Checker := Activity_Checker + Mandatory (""leader""); + + Task_Checker : constant Attribute_Checker := WP_Checker + + Mandatory (""effort"") + + Default (""intensity"", ""100%""); + + Milestone_Checker : constant Attribute_Checker := Event_Checker + + Default (""verification"", """"); + -- + Default (""deliverables"", """"); + + Deliverable_Checker : constant Attribute_Checker := Event_Checker + + Default (""tasks"", """") + + Default (""milestones"", """") + + Deliverable_Type_Check (""type"") + + Dissemination_Level_Check (""dissemination""); + + Partner_Checker : constant Attribute_Checker := Basic_Checker + + Mandatory (""country""); + + Role_Checker : constant Attribute_Checker := Mandatory (""name"") + + Default (""monthly-cost"", ""0"") + + Default (""description"", """"); + + function Get_Times (Node : Node_Type) return Nodes.Action_Nodes.Action_Time + is + use Nodes.Action_Nodes; + + End_Given : constant Boolean := Node.Contains (+""end""); + Duration_Given : constant Boolean := Node.Contains (+""duration""); + begin + + if End_Given and Duration_Given then + -- This should never happen + raise Program_Error with ""end and duration together""; + + elsif (not End_Given) and (not Duration_Given) then + -- This neither + raise Program_Error with ""neither end nor duration""; + + elsif End_Given and (not Duration_Given) then + -- Put_Line (Node (""begin"") & ""|"" & Node (""end"")); + + return Create (Start_On => Instant_Raw (Node (""begin"")), + End_On => Instant_Raw (Node (""end""))); + + else + return Create (Start_On => Instant_Raw (Node.Value (""begin"")), + Duration => Duration_Raw (Node.Value (""duration""))); + end if; + end Get_Times; + + ------------ + -- Create -- + ------------ + + + function Create + (Params : not null access Plugins.Parameter_Maps.Map) + return Parser_Type + is + pragma Unreferenced (Params); + Result : Parser_Type; + begin + return Result; + end Create; + + procedure Parse_Deliverable (WP : EU_Projects.Nodes.Action_Nodes.WPs.Project_WP_Access; + Node_Seq : in out Node_Parser.Node_Scanner; + Node_Dir : in out Node_Tables.Node_Table) + with Pre => Class_Is (Node_Seq, Deliverable); + + ----------------------- + -- Parse_Deliverable -- + ----------------------- + + ----------------------- + -- Parse_Deliverable -- + ----------------------- + + procedure Parse_Deliverable (WP : EU_Projects.Nodes.Action_Nodes.WPs.Project_WP_Access; + Node_Seq : in out Node_Parser.Node_Scanner; + Node_Dir : in out Node_Tables.Node_Table) + is + use EU_Projects.Nodes.Timed_Nodes.Deliverables; + + Deliv_Node : Node_Type := Peek (Node_Seq); + This_Deliv : Deliverable_Access; + begin + Node_Images.Set_Current_Node (Deliv_Node); + + Next (Node_Seq); + Check (Deliverable_Checker, Deliv_Node); + + declare + use Tokenize; + Label : constant Deliverable_Label := + Deliverable_Label'(To_ID (Deliv_Node (""label""))); + + Delivered_By : constant EU_Projects.Nodes.Node_Label_Lists.Vector := + Nodes.Parse_Label_List (Deliv_Node (""tasks"")); + + Due_Times : Token_Vectors.Vector := + Token_Vectors.To_Vector (Split (Deliv_Node (""when""), ';')); + + begin + if Node_Dir.Contains (EU_Projects.Nodes.Node_Label (Label)) then + raise Parsing_Error + with ""Duplicated label '"" & Image (Label) & ""' in deliverable""; + end if; + + + This_Deliv := + Create (Label => Label, + Name => Deliv_Node (""name""), + Short_Name => Deliv_Node (""short""), + Description => Deliv_Node.Description, + Delivered_By => Delivered_By, + Linked_Milestones => Nodes.Parse_Label_List (Deliv_Node (""milestones"")), + Due_On => Due_Times.First_Element, + Node_Dir => Node_Dir, + Parent_WP => EU_Projects.Nodes.Node_Access (WP), + Deliv_Type => Deliverable_Type'Value (Deliv_Node (""type"")), + Dissemination => Dissemination_Level'Value (Deliv_Node (""dissemination""))); + + for Idx in Due_Times.First_Index + 1 .. Due_Times.Last_Index loop + Clone (Item => This_Deliv.all, + Due_On => Due_Times (Idx), + Node_Dir => Node_Dir); + + end loop; + + WP.Add_Deliverable (This_Deliv);" +procedure Test_Config_String_Parsers is,"function Identity (X : String) return String + is (X); + + package Test_Parsers is + new Config_String_Parsers (Name_Type => string, + Value_Type => String, + No_Value => ""(null)"", + To_Name => Identity, + To_Value => Identity); + + procedure Dump (Y : Test_Parsers.Parsing_Result) is + use Test_Parsers.Parameter_Maps, Test_Parsers; + + X : constant Test_Parsers.Parameter_Maps.Map := Parameters (Y); + begin + Put_Line (""##################""); + Put_line (""header: '"" + & (if Has_Header (Y) then Header (Y) else """") + & ""'""); + + for Pos in X.Iterate loop + Put_Line (""'"" & Key (Pos) & ""' -> '"" & Element (Pos) & ""'""); + end loop; + end Dump; + + Params : Test_Parsers.Parsing_Result; + +begin + Params := Test_Parsers.Parse ("" ciao , pluto= 33 ,zimo-xamo={ 42,33 }""); + Dump (Params); + + Params := Test_Parsers.Parse + (Input => ""zorro : ciao , pluto= 33 ,zimo-xamo={}"", + Options => Test_Parsers.Config (Expect_Header => Test_Parsers.Maybe)); + Dump (Params); + + declare + use Test_Parsers; + Syntax : Syntax_Descriptor; + begin + Add_Parameter_Syntax (Syntax => Syntax, + Parameter_Name => ""ciao"", + If_Missing => die); + + Add_Parameter_Syntax(Syntax => Syntax, + Parameter_Name => ""pippo"", + If_Missing => Use_Default, + Default => ""minima veniali""); + + Params := Test_Parsers.Parse + (Input => ""zorro : ciao , pluto=,zimo-xamo={ 42,33 }"", + Syntax => Syntax, + Options => Test_Parsers.Config (Expect_Header => Test_Parsers.Maybe), + On_Unknown_Name => OK); + Dump (Params); + + Params := Test_Parsers.Parse + (Input => ""zorro : ciao , pippo= 37 ,zimo-xamo={ 42,33 }"", + Syntax => Syntax, + Options => Test_Parsers.Config (Expect_Header => Test_Parsers.Maybe), + On_Unknown_Name => OK); + Dump (Params); + + Params := Test_Parsers.Parse + (Input => ""zorro : ciao=112, pippo={33,11},zimo--xamo={ 42,33 }"", + Syntax => Syntax, + Options => Test_Parsers.Config (Expect_Header => Test_Parsers.Maybe), + On_Unknown_Name => OK); + Dump (Params);" +procedure Check_Missing is,"begin + + for C in Syntax.S.Iterate loop + declare + Name : constant Name_Type := Key (C); + Descr : constant Syntax_Entry := Element (C); + begin + if not Item.Contains (Name) then + case Descr.If_Missing is + when Die => + raise Parsing_Error with ""Missing parameter""; + + when Ignore => + null; + + when Use_Default => + Item.Insert (Key => Name, + New_Item => Descr.Default.Element); + end case; + end if;" +procedure Register,"(ID : Plugin_ID; + Tag : Ada.Tags.Tag) + is + OK : Boolean; + Pos : Plugin_Maps.Cursor; + begin + Plugin_Map.Insert (Key => ID, + New_Item => Tag, + Position => Pos, + Inserted => OK); + end Register; + + --------- + -- Get -- + --------- + + function Get (ID : Plugin_ID; + Params : not null access Plugin_Parameters; + Search_If_Missing : Boolean := False) + return Root_Plugin_Type'Class is + OK : Boolean; + Tag : Ada.Tags.Tag; + + function New_Plugin is + new Ada.Tags.Generic_Dispatching_Constructor + (T => Root_Plugin_Type, + Parameters => Plugin_Parameters, + Constructor => Constructor); + begin + if not Plugin_Map.Contains (ID) then + if Search_If_Missing then + Find_Plugin (ID => ID, + Success => OK); + else + OK := False; + end if; + + if not OK then + raise Unknown_Plugin_ID; + end if; + + if not Plugin_Map.Contains (ID) then + raise Program_Error; + end if; + end if; + + Tag := Plugin_Map.Element (ID); + + return New_Plugin (Tag, Params); + end Get; + + function Exists (ID : Plugin_ID; + Search_If_Missing : Boolean := False) + return Boolean + is + OK : Boolean; + begin + if Plugin_Map.Contains (ID) then + return True; + elsif Search_If_Missing then + Find_Plugin (ID => ID, + Success => OK); + + return OK; + else + return False; + end if; + end Exists; + + procedure For_All_Plugins + (Callback : not null access procedure (ID : Plugin_ID)) + is + begin + for I in Plugin_Map.Iterate loop + Callback (Plugin_Maps.Key (I)); + end loop; + end For_All_Plugins; + + subtype Valid_Finder_ID is Finder_ID range 1 .. Finder_ID'Last; + + package Finder_Vectors is + new Ada.Containers.Vectors (Index_Type => Valid_Finder_ID, + Element_Type => Finder_Access); + + protected Finder_Table is + procedure Add (Finder : in Finder_Access; + ID : out Finder_ID); + + procedure Remove (ID : Finder_ID); + + procedure Find (ID : in Plugin_ID; + Success : out Boolean); + private + Finder_Array : Finder_Vectors.Vector; + end Finder_Table; + + protected body Finder_Table is + procedure Add (Finder : in Finder_Access; + ID : out Finder_ID) + is + begin + Finder_Array.Append (Finder); + ID := Finder_Array.Last_Index; + end Add; + + procedure Remove (ID : Finder_ID) is + begin + if ID > Finder_Array.Last_Index then + raise Constraint_Error; + else + declare + procedure Delete (Item : in out Finder_Access) is + begin + Item := null; + end Delete; + begin + Finder_Array.Update_Element (ID, Delete'Access);" +procedure Main is,"package SU renames Ada.Strings.Unbounded; + package Calendar renames Ada.Calendar; + + type Argument_Option is (verbose, input, output); + type Boolean_Flag is (True, False); + + File : File_Type; + Fields : Slice_Set; + Seconds_Per_Hour : Integer; + Start : Calendar.Time; + Clock : array(1..2) of Integer; + Verbose_Flag : Boolean := FALSE; + In_Filename : SU.Unbounded_String := SU.To_Unbounded_String (""input""); + Out_Filename : SU.Unbounded_String := SU.To_Unbounded_String (""output""); + T : Integer; -- number of trains + TT : Integer; -- number of Turntables + NT : Integer; -- number of NormalTracks + ST : Integer; -- number of StationTracks + Turntables : Turntables_Ptr; + Normal_Tracks : Normal_Tracks_Ptr; + Station_Tracks : Station_Tracks_Ptr; + Trains : Trains_Ptr; + Connections : Connections_Ptr; + + type Command is ('c', 'p', 't', 'u', 'n', 's', 'h', 'q'); + + task Talk is + entry Start; + end Talk; + + task body Talk is + C : String (1..1); + Last : Natural; + begin + accept Start; + + Put_Line(""Input char for action, availble commands:""); + Put_Line("" 'p' - current trains positions,""); + Put_Line("" 't' - list trains,""); + Put_Line("" 'u' - list turntables,""); + Put_Line("" 'n' - list normal tracks,""); + Put_Line("" 's' - list station tracks,""); + Put_Line("" 'h' - print this menu again,""); + Put_Line("" 'q' - to quit simulation.""); + + while TRUE loop + + Get_Line(C, Last); + + case C(1) is + when 'p' => + null; + for I in 0 .. T-1 loop + Put_Line(As_String(Trains (I)) & "": "" & Trains (I).Att.As_String); + end loop; + when 't' => + for I in 0 .. T-1 loop + Put_Line(As_Verbose_String(Trains (I))); + end loop; + when 'u' => + for I in 0 .. TT-1 loop + Put_Line(Turntables (I).As_Verbose_String); + end loop; + when 'n' => + for I in 0 .. NT-1 loop + Put_Line(Normal_Tracks (I).As_Verbose_String); + end loop; + when 's' => + for I in 0 .. ST-1 loop + Put_Line(Station_Tracks (I).As_Verbose_String); + end loop; + when 'h' => + Put_Line(""Input char for action, availble commands:""); + Put_Line("" 'p' - current trains positions,""); + Put_Line("" 't' - list trains,""); + Put_Line("" 'u' - list turntables,""); + Put_Line("" 'n' - list normal tracks,""); + Put_Line("" 's' - list station tracks,""); + Put_Line("" 'h' - print this menu again,""); + Put_Line("" 'q' - to quit simulation.""); + when 'q' => OS_Exit(0); + when others => null; + end case; + + C := ""#""; + + end loop; + end Talk; + + function Read_Fields(F: File_Type; Expected: Positive) return Slice_Set is + File_Line : SU.Unbounded_String; + Fields : Slice_Set; + Seps : constant String := "" ""; + Fields_Exception : exception; + begin + File_Line := SU.To_Unbounded_String (Get_Line (F)); + + loop + exit when SU.To_String (File_Line)'Length > 0 and then SU.To_String (File_Line) (1) /= '#'; + + File_Line := SU.To_Unbounded_String (Get_Line (F)); + end loop; + + Create (S => Fields, + From => SU.To_String (File_Line), + Separators => Seps, + Mode => Multiple); + + if Positive (Slice_Count (Fields)) /= Expected then + Raise_Exception (Fields_Exception'Identity, ""Expected to read"" & Positive'Image (Expected) & "" fields""); + end if; + + return Fields; + exception + when Fail: Fields_Exception => + Put_Line (Exception_Message (Fail)); + return Fields; + end Read_Fields; + +begin + + for Arg in 1 .. Argument_Count/2 loop + declare + A : Argument_Option; + begin + A := Argument_Option'Value (Argument(Arg*2-1)); + case A is + when Argument_Option'(Verbose) => + case Boolean_Flag'Value (Argument(Arg*2)) is + when Boolean_Flag'(true) => + Verbose_Flag := TRUE; + Put_Line (""Verbose mode""); + when others => + Verbose_Flag := FALSE; + Put_Line (""Silent mode""); + end case; + when Input => + In_Filename := SU.To_Unbounded_String (Argument(Arg*2)); + when Output => + Out_Filename := SU.To_Unbounded_String (Argument(Arg*2)); + when others => + null; + end case; + exception + when Constraint_Error => + Put_Line (""Wrong arguments""); + OS_Exit(1);" +procedure Free_Logger_Msg_Ptr is new Ada.Unchecked_Deallocation,"(Object => Logger_Message_Packet, Name => Logger_Message_Packet_Ptr); + + function Format_Log_Level + (Use_Color : Boolean; + Log_Level : Log_Levels) + return Unbounded_String + is + Color_Prefix : Unbounded_String; + Log_Level_Str : Unbounded_String; + Now : constant Time := Clock; + begin + + -- Add ANSI color codes if we're using color on Linux + if Use_Color + then + case Log_Level is + when EMERGERENCY => + Color_Prefix := To_Unbounded_String (ANSI_Light_Red); + when ALERT => + Color_Prefix := To_Unbounded_String (ANSI_Light_Red); + when CRITICAL => + Color_Prefix := To_Unbounded_String (ANSI_Light_Red); + when ERROR => + Color_Prefix := To_Unbounded_String (ANSI_Red); + when WARNING => + Color_Prefix := To_Unbounded_String (ANSI_Light_Yellow); + when NOTICE => + Color_Prefix := To_Unbounded_String (ANSI_Yellow); + when INFO => + Color_Prefix := To_Unbounded_String (ANSI_Green); + when DEBUG => + Color_Prefix := To_Unbounded_String (ANSI_Light_Blue); + end case; + + Log_Level_Str := + Color_Prefix & To_Unbounded_String (Log_Level'Image) & ANSI_Reset; + else + Log_Level_Str := To_Unbounded_String (Log_Level'Image); + end if; + + return To_Unbounded_String + (Image (Date => Now) & "" ["" & To_String (Log_Level_Str) & ""]""); + end Format_Log_Level; + + function Create_String_From_Components + (Components : Component_Vector.Vector) + return Unbounded_String + is + Components_String : Unbounded_String; + procedure Component_To_String (c : Component_Vector.Cursor) is + Scratch_String : Unbounded_String; + begin + Scratch_String := Components (c); + Components_String := Components_String & ""["" & Scratch_String & ""]""; + end Component_To_String; + begin + -- If there's no component, just leave it blank + if Components.Length = 0 + then + return To_Unbounded_String (""""); + end if; + + Components.Iterate (Component_To_String'Access); + return Components_String; + end Create_String_From_Components; + + protected body Logger_Queue_Type is + -- Handles queue of packets for the logger thread + entry Add_Packet (Queue : Logger_Message_Packet_Ptr) when True is + begin + Queued_Packets.Append (Queue); + end Add_Packet; + + entry Get (Queue : out Logger_Message_Packet_Ptr) + when Queued_Packets.Length > 0 is + begin + Queue := Queued_Packets.First_Element; + Queued_Packets.Delete_First; + end Get; + + entry Count (Count : out Integer) when True is + begin + Count := Integer (Queued_Packets.Length); + end Count; + + entry Empty when True is + begin + declare + procedure Dump_Vector_Data + (c : Logger_Message_Packet_Vector.Cursor) + is + begin + Free_Logger_Msg_Ptr (Queued_Packets (c)); + end Dump_Vector_Data; + begin + Queued_Packets.Iterate (Dump_Vector_Data'access);" +procedure Process_Queue is,"procedure Print_Messages (c : Log_Message_Vector.Cursor) is + Current_Msg : constant Log_Message_Record := + Log_Message_Vector.Element (c); + begin + -- This is so ugly :( + if Log_Levels'Enum_Rep (Logger_Cfg.Log_Level) >= + Log_Levels'Enum_Rep (Current_Msg.Log_Level) + then + Msg_String := + Format_Log_Level + (Logger_Cfg.Use_Color, Current_Msg.Log_Level); + Msg_String := + Msg_String & + Create_String_From_Components (Current_Msg.Component); + Msg_String := Msg_String & "" "" & Current_Msg.Message; + Put_Line (To_String (Msg_String)); + end if; + end Print_Messages; + + begin + Logger_Queue.Count (Queues_To_Process); + while Queues_To_Process > 0 + loop + Logger_Queue.Get (Current_Queue); + + -- Get a local copy and then empty it; we don't care past that + -- point + if Current_Queue /= null + then + Current_Queue.Get_All_And_Empty (Msg_Packets); + Msg_Packets.Iterate (Print_Messages'Access); + Free_Logger_Msg_Ptr (Current_Queue); + end if; + + Logger_Queue.Count (Queues_To_Process); + end loop; + + exception + -- Not sure if there's a better way to do this, but avoids a race + -- condition + when Constraint_Error => + begin + null;" +function To_Domain_Section is new Ada.Unchecked_Conversion,"(Source => Stream_Element_Array, Target => Domain_Section); + begin + Domain_Name := Domain_Name & To_Domain_Section (Raw_Data.all + (Offset .. Stream_Element_Offset (Section_Length))); + + Offset := Offset + Stream_Element_Offset (Section_Length);" +function Get_Byte_Fixed_Header is new Ada.Unchecked_Conversion,"(Source => Stream_Element_Array, Target => Packer_Pointer); + begin + -- Oh, and for more fuckery, the pointer is 16-bit ... + Packet_Ptr := Get_Byte_Fixed_Header (Raw_Data.all + (Offset .. Offset + 1)); -- Make the top bytes vanish + + -- We subtract 12-1 for the packet header + Packet_Ptr.Packet_Offset := + (Packet_Ptr.Packet_Offset and 16#3fff#) - 11; + + -- Sanity check ourselves + if (Section_Length and 2#11#) /= 0 + then + -- Should never happen but you never know ... + raise Unknown_Compression_Method; + end if; + + -- Now we need to decode the whole old string ... ugh + Decompressed_Domain_String := + Parse_DNS_Packet_Name_Records + (Raw_Data, + Stream_Element_Offset (Packet_Ptr.Packet_Offset)); + Offset := Offset + 2; + return Domain_Name & Decompressed_Domain_String;" +function To_RData is new Ada.Unchecked_Conversion,"(Source => Stream_Element_Array, Target => RData); + begin + Parsed_Response.RData := To_Unbounded_String (To_RData (Raw_Data + (Offset .. Stream_Element_Offset (RData_Length)))); + Offset := Offset + Stream_Element_Offset (RData_Length);" +procedure Start_Server is,"-- Input and Output Sockets + Capture_Config : DNSCatcher.Config.Configuration; + + DNS_Transactions : DNSCatcher.DNS.Transaction_Manager + .DNS_Transaction_Manager_Task; + Receiver_Interface : DNSCatcher.Network.UDP.Receiver + .UDP_Receiver_Interface; + Sender_Interface : DNSCatcher.Network.UDP.Sender.UDP_Sender_Interface; + Logger_Task : DNSCatcher.Utils.Logger.Logger; + Transaction_Manager_Ptr : DNS_Transaction_Manager_Task_Ptr; + Socket : Socket_Type; + Logger_Packet : DNSCatcher.Utils.Logger.Logger_Message_Packet_Ptr; + + procedure Free_Transaction_Manager is new Ada.Unchecked_Deallocation + (Object => DNS_Transaction_Manager_Task, + Name => DNS_Transaction_Manager_Task_Ptr); + begin + -- Load the config file from disk + DNSCatcher.Config.Initialize (Capture_Config); + DNSCatcher.Config.Read_Cfg_File + (Capture_Config, ""conf/dnscatcherd.conf""); + + -- Configure the logger + Capture_Config.Logger_Config.Log_Level := DEBUG; + Capture_Config.Logger_Config.Use_Color := True; + + Logger_Task.Initialize (Capture_Config.Logger_Config); + Transaction_Manager_Ptr := new DNS_Transaction_Manager_Task; + + -- Connect the packet queue and start it all up + Logger_Task.Start; + Logger_Packet := new DNSCatcher.Utils.Logger.Logger_Message_Packet; + Logger_Packet.Log_Message (NOTICE, ""DNSCatcher starting up ...""); + DNSCatcher.Utils.Logger.Logger_Queue.Add_Packet (Logger_Packet); + + -- Socket has to be shared between receiver and sender. This likely needs + -- to move to to a higher level class + begin + Create_Socket + (Socket => Socket, + Mode => Socket_Datagram); + Set_Socket_Option + (Socket => Socket, + Level => IP_Protocol_For_IP_Level, + Option => (GNAT.Sockets.Receive_Timeout, Timeout => 1.0)); + Bind_Socket + (Socket => Socket, + Address => + (Family => Family_Inet, Addr => Any_Inet_Addr, + Port => Capture_Config.Local_Listen_Port)); + exception + when Exp_Error : GNAT.Sockets.Socket_Error => + begin + Logger_Packet := + new DNSCatcher.Utils.Logger.Logger_Message_Packet; + Logger_Packet.Log_Message + (ERROR, ""Socket error: "" & Exception_Information (Exp_Error)); + Logger_Packet.Log_Message (ERROR, ""Refusing to start!""); + Logger_Queue.Add_Packet (Logger_Packet); + goto Shutdown_Procedure;" +function Uint8_To_Character is new Ada.Unchecked_Conversion,"(Source => Unsigned_8, Target => Character); + function Uint16_To_String is new Ada.Unchecked_Conversion + (Source => Unsigned_16, Target => QAttributes); + -- Actually does the dirty work of creating a question + function Create_QName_Record + (Domain_Section : String) + return String + is + Label : String (1 .. Domain_Section'Length + 1); + begin + if Domain_Section /= ""."" + then + Label (1) := + Uint8_To_Character (Unsigned_8 (Domain_Section'Length)); + Label + (2 .. Domain_Section'Length + 1) := Domain_Section; + else + -- If this is a ""."" by itself, it's the terminator, and we need to + -- do special handling + declare + Empty_Label : String (1 .. 1); + begin + Empty_Label (1) := Uint8_To_Character (Unsigned_8 (0)); + return Empty_Label;" +function String_To_Packet is new Ada.Unchecked_Conversion,"(Source => String, Target => QData_SEA); + + begin + Outbound_Packet.Raw_Data.Data := + new Stream_Element_Array (1 .. QData'Length); + Outbound_Packet.Raw_Data.Data.all := String_To_Packet (QData); + Outbound_Packet.Raw_Data_Length := + DNS_PACKET_HEADER_SIZE + QData'Length;" +-- Parse_Procedure is an access procedure that is used as a common prototype,"-- for all parsing functionality dispatched from GCP_Management and other + -- vectors. + -- + -- @value Config + -- Configuration struct to update + -- + -- @value Value_Str + -- Pure text version of the configuration argument + -- + type Parse_Procedure is access procedure + (Config : in out Configuration; + Value_Str : String); + + -- GCP_Management is a vector that handles dynamic dispatch to the + -- parsing parameters above; it is used to match key/values from the + -- config file to + package GCP_Management is new Ada.Containers.Indefinite_Ordered_Maps + (String, Parse_Procedure); + + GCP_Map : GCP_Management.Map; + + -- Configuration constructor + procedure Initialize (Config : in out Configuration) is + begin + -- We initialize the ports to 53 by default + Config.Local_Listen_Port := 53; + Config.Upstream_DNS_Server_Port := 53; + + -- No upstream server is set + Config.Upstream_DNS_Server := To_Unbounded_String (""""); + end Initialize; + + -- Loads the load listen value and sets it in the config record + -- + -- @value Config + -- Configuration struct to update + -- + -- @value Value_Str + -- Pure text version of the configuration argument + -- + procedure Parse_Local_Listen_Port + (Config : in out Configuration; + Value_Str : String) + is + begin + Config.Local_Listen_Port := Port_Type'Value (Value_Str); + exception + when Constraint_Error => + raise Malformed_Line with ""Local_Listen_Port not a valid port number""; + end Parse_Local_Listen_Port; + + -- Loads the upstream DNS Server from the config file + -- + -- @value Config + -- Configuration struct to update + -- + -- @value Value_Str + -- Pure text version of the configuration argument + -- + procedure Parse_Upstream_DNS_Server + (Config : in out Configuration; + Value_Str : String) + is + begin + Config.Upstream_DNS_Server := To_Unbounded_String (Value_Str); + exception + when Constraint_Error => + raise Malformed_Line with ""Invalid upstrema DNS Server""; + end Parse_Upstream_DNS_Server; + + -- Loads the upstream DNS Server port from the config file + -- + -- @value Config + -- Configuration struct to update + -- + -- @value Value_Str + -- Pure text version of the configuration argument + -- + procedure Parse_Upstream_DNS_Server_Port + (Config : in out Configuration; + Value_Str : String) + is + begin + Config.Upstream_DNS_Server_Port := Port_Type'Value (Value_Str); + exception + when Constraint_Error => + raise Malformed_Line + with ""Upstream_DNS_Server_Port not a valid port number""; + end Parse_Upstream_DNS_Server_Port; + + procedure Initialize_Config_Parse is + begin + -- Load String to Type Mapping + GCP_Map.Insert (""LOCAL_LISTEN_PORT"", Parse_Local_Listen_Port'Access); + GCP_Map.Insert (""UPSTREAM_DNS_SERVER"", Parse_Upstream_DNS_Server'Access); + GCP_Map.Insert + (""UPSTREAM_DNS_SERVER_PORT"", Parse_Upstream_DNS_Server_Port'Access); + end Initialize_Config_Parse; + + procedure Read_Cfg_File + (Config : in out Configuration; + Config_File_Path : String) + is + Config_File : Ada.Text_IO.File_Type; + Line_Count : Integer := 1; + Exception_Message : Unbounded_String; + use GCP_Management; + begin + Initialize_Config_Parse; + + -- Try to open the configuration file + Open + (File => Config_File, + Mode => Ada.Text_IO.In_File, + Name => Config_File_Path); + + while not End_Of_File (Config_File) + loop + declare + Current_Line : constant String := Get_Line (Config_File); + Key_End_Loc : Integer := 0; + Equals_Loc : Integer := 0; + Value_Loc : Integer := 0; + Is_Whitespace : Boolean := True; + begin + -- Skip lines starting with a comment or blank + if Current_Line = """" + then + goto Config_Parse_Continue; + end if; + + -- Has to be done seperately or it blows an index check + if Current_Line (1) = '#' + then + goto Config_Parse_Continue; + end if; + + -- Skip line if its all whitespace + for I in Current_Line'range + loop + if Current_Line (I) /= ' ' and + Current_Line (I) /= Ada.Characters.Latin_1.HT + then + Is_Whitespace := False; + end if; + + if Current_Line (I) = '=' + then + Equals_Loc := I; + end if; + + -- Determine length of the key + -- + -- This is a little non-obvious at first glance. We subtract 2 + -- here to remove the character we want, and the previous char + -- because a 17 char string will be 1..18 in the array. + + if (Is_Whitespace or Current_Line (I) = '=') and Key_End_Loc = 0 + then + Key_End_Loc := I - 2; + end if; + + exit when Is_Whitespace and Equals_Loc /= 0; + -- We also want to confirm there's a = in there somewhere + end loop; + + -- It's all whitespace, skip it + if Is_Whitespace + then + goto Config_Parse_Continue; + end if; + + if Equals_Loc = 0 + then + Exception_Message := + To_Unbounded_String (""Malformed line (no = found) at""); + Append (Exception_Message, Line_Count'Image); + Append (Exception_Message, "": ""); + Append (Exception_Message, Current_Line); + + raise Malformed_Line with To_String (Exception_Message); + end if; + + -- Read in the essential values + for C in GCP_Map.Iterate + loop + -- Slightly annoying, but need to handle not reading past the + -- end of Current_Line. We also need to check that the next char + -- is a space or = so we don't match substrings by accident. + if Key_End_Loc = Key (C)'Length + then + if Key (C) = To_Upper (Current_Line + (1 .. Key (C)'Length)) + then + -- Determine the starting character of the value + for I in Current_Line + (Equals_Loc + 1 .. Current_Line'Length)'range + loop + if Current_Line (I) /= ' ' and + Current_Line (I) /= Ada.Characters.Latin_1.HT + then + Value_Loc := I; + exit; + end if; + end loop; + + -- If Value_Loc is zero, pass an empty string in + if Value_Loc = 0 + then + Element (C).all (Config, """"); + else + Element (C).all (Config, Current_Line + (Value_Loc .. Current_Line'Length)); + end if; + end if; + end if; + end loop; + + <> + Line_Count := Line_Count + 1;" +procedure DNSC is,"DClient : DNSCatcher.DNS.Client.Client; + Capture_Config : DNSCatcher.Config.Configuration; + Logger_Task : DNSCatcher.Utils.Logger.Logger; + Transaction_Manager_Ptr : DNS_Transaction_Manager_Task_Ptr; + Sender_Interface : DNSCatcher.Network.UDP.Sender.UDP_Sender_Interface; + Receiver_Interface : DNSCatcher.Network.UDP.Receiver.UDP_Receiver_Interface; + Outbound_Packet : Raw_Packet_Record_Ptr; + Logger_Packet : DNSCatcher.Utils.Logger.Logger_Message_Packet_Ptr; + Socket : Socket_Type; + +begin + Capture_Config.Local_Listen_Port := 41231; + Capture_Config.Upstream_DNS_Server := To_Unbounded_String (""4.2.2.2""); + Capture_Config.Upstream_DNS_Server_Port := 53; + + -- Configure the logger + Capture_Config.Logger_Config.Log_Level := DEBUG; + Capture_Config.Logger_Config.Use_Color := True; + + Logger_Task.Initialize (Capture_Config.Logger_Config); + Logger_Task.Start; + Logger_Packet := new Logger_Message_Packet; + + Transaction_Manager_Ptr := new DNS_Transaction_Manager_Task; + + -- Socket has to be shared between receiver and sender. This likely needs to + -- move to to a higher level class + begin + Create_Socket + (Socket => Socket, + Mode => Socket_Datagram); + Set_Socket_Option + (Socket => Socket, + Level => IP_Protocol_For_IP_Level, + Option => (GNAT.Sockets.Receive_Timeout, Timeout => 1.0)); + Bind_Socket + (Socket => Socket, + Address => + (Family => Family_Inet, Addr => Any_Inet_Addr, + Port => Capture_Config.Local_Listen_Port)); + exception + when Exp_Error : GNAT.Sockets.Socket_Error => + begin + Logger_Packet := new DNSCatcher.Utils.Logger.Logger_Message_Packet; + Logger_Packet.Log_Message + (ERROR, ""Socket error: "" & Exception_Information (Exp_Error)); + Logger_Packet.Log_Message (ERROR, ""Refusing to start!""); + Logger_Queue.Add_Packet (Logger_Packet); + goto Shutdown_Procedure;" +procedure DNSCatcherD is,"begin + Install_Handler (Handler => Signal_Handlers.SIGINT_Handler'Access); + DNSCatcher.DNS.Server.Start_Server; +exception + when Error : Ada.IO_Exceptions.Name_Error => + begin + Put (Standard_Error, ""FATAL: Unable to open config file: ""); + Put_Line (Standard_Error, Exception_Message (Error)); + DNSCatcher.DNS.Server.Stop_Server;" +procedure finalize_library is,"begin + E099 := E099 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__text_io__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""system__file_io__finalize_body""); + begin + E111 := E111 - 1; + F2;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (Ada, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + pragma Favor_Top_Level (No_Param_Proc); + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 0; + Default_Stack_Size := -1; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E025 := E025 + 1; + Ada.Containers'Elab_Spec; + E040 := E040 + 1; + Ada.Io_Exceptions'Elab_Spec; + E068 := E068 + 1; + Ada.Strings'Elab_Spec; + E052 := E052 + 1; + Ada.Strings.Maps'Elab_Spec; + E054 := E054 + 1; + Ada.Strings.Maps.Constants'Elab_Spec; + E058 := E058 + 1; + Interfaces.C'Elab_Spec; + E078 := E078 + 1; + System.Exceptions'Elab_Spec; + E027 := E027 + 1; + System.Object_Reader'Elab_Spec; + E080 := E080 + 1; + System.Dwarf_Lines'Elab_Spec; + E047 := E047 + 1; + System.Os_Lib'Elab_Body; + E072 := E072 + 1; + System.Soft_Links.Initialize'Elab_Body; + E021 := E021 + 1; + E013 := E013 + 1; + System.Traceback.Symbolic'Elab_Body; + E039 := E039 + 1; + E008 := E008 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E103 := E103 + 1; + Ada.Streams'Elab_Spec; + E101 := E101 + 1; + Interfaces.C.Strings'Elab_Spec; + E158 := E158 + 1; + System.File_Control_Block'Elab_Spec; + E115 := E115 + 1; + System.Finalization_Root'Elab_Spec; + E114 := E114 + 1; + Ada.Finalization'Elab_Spec; + E112 := E112 + 1; + System.File_Io'Elab_Body; + E111 := E111 + 1; + System.Task_Info'Elab_Spec; + E171 := E171 + 1; + Ada.Real_Time'Elab_Spec; + Ada.Real_Time'Elab_Body; + E152 := E152 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E099 := E099 + 1; + E183 := E183 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + if gnat_argc = 0 then + gnat_argc := argc; + gnat_argv := argv; + end if; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure Main is,"Agent_Port : constant Port_Type := 10_161; + -- Changed from 161 to 10161 to avoid Linux permission issues. + Agent_Addr : constant Sock_Addr_Type := + (Addr => Inet_Addr (""127.0.0.1""), Port => Agent_Port, others => <>); + Peer_Addr : Sock_Addr_Type; + + Buffer : + Stream_Element_Array + (1 .. Stream_Element_Offset (Snowpeak.Max_UDP_Payload_Size)); + Last : Stream_Element_Offset; + + Socket : Snowpeak.UDP_Socket.UDP_Socket; + Querier : Snowpeak.Querier.Map_Querier; + + Count : Integer := 0; + + -- REQUIRED FOR DUMMY QUERIER + package Types renames RFLX.RFLX_Types; + Dummy_Contact_OID : Types.Bytes := [43, 6, 1, 2, 1, 1, 4, 0]; + Dummy_Contact : Types.Bytes_Ptr := + new Types.Bytes'([102, 111, 46, 111, 98, 64, 97, 114, 98, 46, 97, 122]); + Dummy_Name_OID : Types.Bytes := [43, 6, 1, 2, 1, 1, 5, 0]; + Dummy_Name : Types.Bytes_Ptr := new Types.Bytes'([70, 54, 51, 48, 48]); +begin + -- INIT OF DUMMY QUERIER + declare + Element : Varbind; + begin + for B of Dummy_Contact_OID loop + Element.OID.Push (Types.Byte (B)); + end loop; + Element.Variable := (Tag_Num => 4, Data => Dummy_Contact, others => <>); + Querier.Data.Push (Element);" +"function As_Bytes is new Ada.Unchecked_Conversion (BE_I64, I64_Bytes);","Len : constant Short_Length := I64_Length (I); + begin + return As_Bytes ((Inner => I)) (Types.Index (8 - Len + 1) .. 8); + end To_BE_Bytes; + -- Encodes an interger with ASN.1 BER. + + function Length (Self : TLV) return Short_Length is + (Short_Length (if Self.Data = null then 0 else Self.Data.all'Length)); + -- Returns the length of Data in bytes. + + function Length (Self : Varbind) return Short_Length is + (Short_Length (Self.OID.Length) + Self.Variable.Length + 2 * 2); + -- Returns the length of the ASN.1 BER encoding of this record. + + function Length (Self : PDU) return Short_Length is + Res : Short_Length := + Short_Length + (I64_Length (Self.Request_ID) + I64_Length (Self.Error_Status) + + I64_Length (Self.Error_Index)) + + 4 * 2; + -- + [for V of Self.Variable_Bindings.View => V.Length + 2]'Reduce(""+"", 0) + begin + -- HACK: Workaround for compiler internal error in version `23.0w-20220508`. + for V of Self.Variable_Bindings.View loop + Res := @ + V.Length + 2; + end loop; + return Res; + end Length; + -- Returns the length of the ASN.1 BER encoding of this record. + + function Length (Self : Message) return Short_Length is + (I64_Length (Self.Version) + Short_Length (Self.Community.Length) + + Self.Data.Length + 3 * 2); + + function Write (Item : Message) return Stream_Element_Array is + Buffer : Types.Bytes_Ptr := + new Types.Bytes (1 .. Types.Index (Snowpeak.Max_UDP_Payload_Size)); + Context : Packet.Context; + Item_Full_Length : constant Stream_Element_Offset := + 2 + Stream_Element_Offset (Item.Length); + Res : Stream_Element_Array (1 .. Item_Full_Length); + + procedure Free is new Ada.Unchecked_Deallocation + (Types.Bytes, Types.Bytes_Ptr); + begin + Packet.Initialize (Context, Buffer); + + + Packet.Set_Tag_Class (Context, RFLX.Prelude.Asn_Tag_Class (0)); + Packet.Set_Tag_Form (Context, RFLX.Prelude.Asn_Tag_Form (1)); + Packet.Set_Tag_Num (Context, RFLX.Prelude.Asn_Tag_Num (16)); + Packet.Set_Untagged_Length (Context, RFLX.Prelude.Asn_Length (Item.Length)); + + -- version: int + Packet.Set_Untagged_Value_version_Tag_Class (Context, RFLX.Prelude.Asn_Tag_Class (0)); + Packet.Set_Untagged_Value_version_Tag_Form (Context, RFLX.Prelude.Asn_Tag_Form (0)); + Packet.Set_Untagged_Value_version_Tag_Num (Context, RFLX.Prelude.Asn_Tag_Num (2)); + Packet.Set_Untagged_Value_version_Untagged_Length (Context, RFLX.Prelude.Asn_Length (I64_Length (Item.Version))); + Packet.Set_Untagged_Value_version_Untagged_Value (Context, To_BE_Bytes (Item.Version)); + + -- community: Bytes + Packet.Set_Untagged_Value_community_Tag_Class (Context, RFLX.Prelude.Asn_Tag_Class (0)); + Packet.Set_Untagged_Value_community_Tag_Form (Context, RFLX.Prelude.Asn_Tag_Form (0)); + Packet.Set_Untagged_Value_community_Tag_Num (Context, RFLX.Prelude.Asn_Tag_Num (4)); + Packet.Set_Untagged_Value_community_Untagged_Length (Context, RFLX.Prelude.Asn_Length (Item.Community.Length)); + Packet.Set_Untagged_Value_community_Untagged_Value (Context, Types.Bytes (Item.Community.View)); + + Packet.Set_Untagged_Value_data_Tag_Class (Context, RFLX.Prelude.Asn_Tag_Class (Item.Data.Tag_Class)); + Packet.Set_Untagged_Value_data_Tag_Form (Context, RFLX.Prelude.Asn_Tag_Form (Item.Data.Tag_Form)); + Packet.Set_Untagged_Value_data_Tag_Num (Context, RFLX.Prelude.Asn_Tag_Num (Item.Data.Tag_Num)); + Packet.Set_Untagged_Value_data_get_response_Length (Context, RFLX.Prelude.Asn_Length (Item.Data.Length)); + + -- data_get_response@request_id: int + Packet.Set_Untagged_Value_data_get_response_Value_request_id_Tag_Class (Context, RFLX.Prelude.Asn_Tag_Class (0)); + Packet.Set_Untagged_Value_data_get_response_Value_request_id_Tag_Form (Context, RFLX.Prelude.Asn_Tag_Form (0)); + Packet.Set_Untagged_Value_data_get_response_Value_request_id_Tag_Num (Context, RFLX.Prelude.Asn_Tag_Num (2)); + Packet.Set_Untagged_Value_data_get_response_Value_request_id_Untagged_Length (Context, RFLX.Prelude.Asn_Length (I64_Length (Item.Data.Request_ID))); + Packet.Set_Untagged_Value_data_get_response_Value_request_id_Untagged_Value (Context, To_BE_Bytes (Item.Data.Request_ID)); + + -- data_get_response@error_status: int + Packet.Set_Untagged_Value_data_get_response_Value_error_status_Tag_Class (Context, RFLX.Prelude.Asn_Tag_Class (0)); + Packet.Set_Untagged_Value_data_get_response_Value_error_status_Tag_Form (Context, RFLX.Prelude.Asn_Tag_Form (0)); + Packet.Set_Untagged_Value_data_get_response_Value_error_status_Tag_Num (Context, RFLX.Prelude.Asn_Tag_Num (2)); + Packet.Set_Untagged_Value_data_get_response_Value_error_status_Untagged_Length (Context, RFLX.Prelude.Asn_Length (I64_Length (Item.Data.Error_Status))); + Packet.Set_Untagged_Value_data_get_response_Value_error_status_Untagged_Value (Context, To_BE_Bytes (Item.Data.Error_Status)); + + -- data_get_response@error_index: int + Packet.Set_Untagged_Value_data_get_response_Value_error_index_Tag_Class (Context, RFLX.Prelude.Asn_Tag_Class (0)); + Packet.Set_Untagged_Value_data_get_response_Value_error_index_Tag_Form (Context, RFLX.Prelude.Asn_Tag_Form (0)); + Packet.Set_Untagged_Value_data_get_response_Value_error_index_Tag_Num (Context, RFLX.Prelude.Asn_Tag_Num (2)); + Packet.Set_Untagged_Value_data_get_response_Value_error_index_Untagged_Length (Context, RFLX.Prelude.Asn_Length (I64_Length (Item.Data.Error_Index))); + Packet.Set_Untagged_Value_data_get_response_Value_error_index_Untagged_Value (Context, To_BE_Bytes (Item.Data.Error_Index)); + + -- data_get_response@variable_bindings: Seq + Packet.Set_Untagged_Value_data_get_response_Value_variable_bindings_Tag_Class (Context, RFLX.Prelude.Asn_Tag_Class (0)); + Packet.Set_Untagged_Value_data_get_response_Value_variable_bindings_Tag_Form (Context, RFLX.Prelude.Asn_Tag_Form (1)); + Packet.Set_Untagged_Value_data_get_response_Value_variable_bindings_Tag_Num (Context, RFLX.Prelude.Asn_Tag_Num (16)); + Packet.Set_Untagged_Value_data_get_response_Value_variable_bindings_Untagged_Length (Context, RFLX.Prelude.Asn_Length ([for E of Item.Data.Variable_Bindings.View => E.Length + 2]'Reduce(""+"", Short_Length (0)))); + + declare + Varbind_Seq_Context : Varbind_Seq.Context; + Varbind_Context : Varbind_Packet.Context; + begin + Packet.Switch_To_Untagged_Value_data_get_response_Value_variable_bindings_Untagged_Value + (Context, Varbind_Seq_Context); + + for Element of Item.Data.Variable_Bindings.View loop + Varbind_Seq.Switch (Varbind_Seq_Context, Varbind_Context); + + Varbind_Packet.Set_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (0)); + Varbind_Packet.Set_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (1)); + Varbind_Packet.Set_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (16)); + Varbind_Packet.Set_Untagged_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Length)); + + Varbind_Packet.Set_Untagged_Value_name_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (0)); + Varbind_Packet.Set_Untagged_Value_name_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_name_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (6)); + Varbind_Packet.Set_Untagged_Value_name_Untagged_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.OID.Length)); + Varbind_Packet.Set_Untagged_Value_name_Untagged_Value (Varbind_Context, Types.Bytes (Element.OID.View)); + + -- Write `Element.Variable` to `Untagged_Value_value`. + + if Element.Variable.Tag_Class = 0 and then Element.Variable.Tag_Form = 0 and then Element.Variable.Tag_Num = 2 then + Varbind_Packet.Set_Untagged_Value_value_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (2)); + Varbind_Packet.Set_Untagged_Value_value_simple_number_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Variable.Length)); + Varbind_Packet.Set_Untagged_Value_value_simple_number_Value (Varbind_Context, Element.Variable.Data.all); + elsif Element.Variable.Tag_Class = 0 and then Element.Variable.Tag_Form = 0 and then Element.Variable.Tag_Num = 4 then + Varbind_Packet.Set_Untagged_Value_value_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (4)); + Varbind_Packet.Set_Untagged_Value_value_simple_string_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Variable.Length)); + Varbind_Packet.Set_Untagged_Value_value_simple_string_Value (Varbind_Context, Element.Variable.Data.all); + elsif Element.Variable.Tag_Class = 0 and then Element.Variable.Tag_Form = 0 and then Element.Variable.Tag_Num = 5 then + Varbind_Packet.Set_Untagged_Value_value_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (5)); + Varbind_Packet.Set_Untagged_Value_value_simple_empty_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Variable.Length)); + elsif Element.Variable.Tag_Class = 0 and then Element.Variable.Tag_Form = 0 and then Element.Variable.Tag_Num = 6 then + Varbind_Packet.Set_Untagged_Value_value_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (6)); + Varbind_Packet.Set_Untagged_Value_value_simple_object_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Variable.Length)); + Varbind_Packet.Set_Untagged_Value_value_simple_object_Value (Varbind_Context, Element.Variable.Data.all); + elsif Element.Variable.Tag_Class = 1 and then Element.Variable.Tag_Form = 0 and then Element.Variable.Tag_Num = 0 then + Varbind_Packet.Set_Untagged_Value_value_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (1)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (0)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_address_internet_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Variable.Length)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_address_internet_Value (Varbind_Context, Element.Variable.Data.all); + elsif Element.Variable.Tag_Class = 1 and then Element.Variable.Tag_Form = 0 and then Element.Variable.Tag_Num = 1 then + Varbind_Packet.Set_Untagged_Value_value_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (1)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (1)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_counter_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Variable.Length)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_counter_Value (Varbind_Context, Element.Variable.Data.all); + elsif Element.Variable.Tag_Class = 1 and then Element.Variable.Tag_Form = 0 and then Element.Variable.Tag_Num = 2 then + Varbind_Packet.Set_Untagged_Value_value_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (1)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (2)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_gauge_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Variable.Length)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_gauge_Value (Varbind_Context, Element.Variable.Data.all); + elsif Element.Variable.Tag_Class = 1 and then Element.Variable.Tag_Form = 0 and then Element.Variable.Tag_Num = 3 then + Varbind_Packet.Set_Untagged_Value_value_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (1)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (3)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_ticks_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Variable.Length)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_ticks_Value (Varbind_Context, Element.Variable.Data.all); + elsif Element.Variable.Tag_Class = 1 and then Element.Variable.Tag_Form = 0 and then Element.Variable.Tag_Num = 4 then + Varbind_Packet.Set_Untagged_Value_value_Tag_Class (Varbind_Context, RFLX.Prelude.Asn_Tag_Class (1)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Form (Varbind_Context, RFLX.Prelude.Asn_Tag_Form (0)); + Varbind_Packet.Set_Untagged_Value_value_Tag_Num (Varbind_Context, RFLX.Prelude.Asn_Tag_Num (4)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_arbitrary_Length (Varbind_Context, RFLX.Prelude.Asn_Length (Element.Variable.Length)); + Varbind_Packet.Set_Untagged_Value_value_application_wide_arbitrary_Value (Varbind_Context, Element.Variable.Data.all); + else raise Constraint_Error with ""Unsupported ASN.1 tag found""; end if; + Varbind_Seq.Update (Varbind_Seq_Context, Varbind_Context); + end loop; + + Packet.Update_Untagged_Value_data_get_response_Value_variable_bindings_Untagged_Value + (Context, Varbind_Seq_Context);" +procedure main is,"use Ada.Strings.Unbounded; + + package Suite is new Ada.Containers.Vectors( Index_Type => Natural, + Element_Type => Solution_Case); + + Test_Suite : Suite.Vector; + Count : Integer := 1; + Failed : Integer := 0; + +begin + + Test_Suite.Append(Problem_1.Get_Solutions); + Test_Suite.Append(Problem_2.Get_Solutions); + Test_Suite.Append(Problem_3.Get_Solutions); + Test_Suite.Append(Problem_4.Get_Solutions); + Test_Suite.Append(Problem_5.Get_Solutions); + Test_Suite.Append(Problem_6.Get_Solutions); + Test_Suite.Append(Problem_7.Get_Solutions); + Test_Suite.Append(Problem_8.Get_Solutions); + Test_Suite.Append(Problem_9.Get_Solutions); + Test_Suite.Append(Problem_10.Get_Solutions); + Test_Suite.Append(Problem_11.Get_Solutions); + Test_Suite.Append(Problem_12.Get_Solutions); + Test_Suite.Append(Problem_13.Get_Solutions); + Test_Suite.Append(Problem_14.Get_Solutions); + Test_Suite.Append(Problem_15.Get_Solutions); + Test_Suite.Append(Problem_16.Get_Solutions); + Test_Suite.Append(Problem_17.Get_Solutions); + Test_Suite.Append(Problem_18.Get_Solutions); + Test_Suite.Append(Problem_19.Get_Solutions); + Test_Suite.Append(Problem_20.Get_Solutions); + Test_Suite.Append(Problem_21.Get_Solutions); + + for C of Test_Suite loop + Put_Line(""Running test case: "" & To_String(C.Name) ); + Count := 1; + for T of C.Tests loop + Put(""Running Test"" & Integer'Image(Count) & "" :""); + declare + begin + T.all; + Put("" Passed""); + exception + when Assertion_Error => + Failed := Failed + 1; + Put("" Failed"");" +procedure Test_Solution_1 is,"Solution : constant Integer := 837799; + begin + Assert( Solution_1 = Solution );" +"procedure Free is new Ada.Unchecked_Deallocation (Name => C.Strings.Char_Array_Access,","Object => C.Char_Array); + use type C.Size_T; + Size : C.Size_T := C_Value'Length - 1; + begin + if C_Setsockopt (C.Int (Obj.Fd), + C.Int (Level), + C.Int (Name), + C_Value.all'Address, + Size) < 0 then + raise Socket_Exception with ""Setopt error"" & Nanomsg.Errors.Errno_Text; + end if; + Free (C_Value); + end Set_Option; + + + + + function Get_Option (Obj : in Socket_T; + Level : in Nanomsg.Sockopt.Option_Level_T; + Name : in Nanomsg.Sockopt.Option_Type_T) return String is + type String_Access_T is access all String; + procedure Free is new Ada.Unchecked_Deallocation (Name => String_Access_T, + Object => String); + + function Nn_Getsockopt (Socket : in C.Int; + Level : in C.Int; + Option_Name : in C.Int; + Value : in out String_Access_T; + Size : in System.Address) return C.Int + with Import, Convention => C, External_Name => ""nn_getsockopt""; + + + use Nanomsg.Sockopt; + Max_Size : constant := 63; + Ptr : String_Access_T := new String(1..Max_Size); + Size : C.Size_T := Max_Size; + use type C.Size_T; + begin + if Nn_Getsockopt (Socket => C.Int (Obj.Fd), + Level => C.Int (Level), + Option_Name => C.Int (Name), + Value => Ptr, + Size => Size'Address) < 0 then + raise Socket_Exception with ""Getopt error"" & Nanomsg.Errors.Errno_Text; + end if; + declare + Retval : constant String := Ptr.all(1.. Integer (Size)); + begin + Free (Ptr); + return Retval;" +"function Convert is new Ada.Unchecked_Conversion (chars_ptr, Void_Ptr);","begin + Send_Signal (Plugin, ""irc_input_send"", String_Type, Convert (Signal_Message)); + Free (Signal_Message); + exception + when others => + Free (Signal_Message); + raise; + end Send_Message; + + function Get_Nick (Host : String) return String is + Sender : constant String := SU.To_String (Split (Host, Separator => ""!"", Maximum => 2) (1)); + begin + return Sender (Sender'First + 1 .. Sender'Last); + end Get_Nick; + + function Name (Plugin : Plugin_Ptr) return String is + (Value (Plugin.Plugin_Get_Name (Plugin))); + + procedure Print (Plugin : Plugin_Ptr; Prefix : Prefix_Kind; Message : String) is + package CH renames Ada.Characters.Handling; + + Prefix_String : constant chars_ptr := Plugin.Prefix (CH.To_Lower (Prefix'Image) & L1.NUL); + Message_String : constant C_String := Value (Prefix_String) & Message & L1.NUL; + begin + Plugin.Printf_Date_Tags + (System.Null_Address, 0, Null_Ptr, Message_String); + end Print; + + procedure Print (Plugin : Plugin_Ptr; Prefix : String; Message : String) is + begin + Plugin.Printf_Date_Tags + (System.Null_Address, 0, Null_Ptr, Prefix & L1.HT & Message & L1.NUL); + end Print; + + procedure Print (Plugin : Plugin_Ptr; Message : String) is + begin + Print (Plugin, "" "", Message); + end Print; + + procedure Log (Plugin : Plugin_Ptr; Message : String) is + begin + Plugin.Log_Printf (Message & L1.NUL); + end Log; + + procedure Print_Error (Plugin : Plugin_Ptr; Value : Ada.Exceptions.Exception_Occurrence) is + begin + Print (Plugin, Error, Ada.Exceptions.Exception_Information (Value)); + end Print_Error; + + function Command_Callback + (Callback : On_Command_Callback; + Data : Data_Ptr; + Buffer : Buffer_Ptr; + Argc : int; + Argv : access chars_ptr; + Unused_Argv_EOL : access chars_ptr) return Callback_Result + is + Raw_Arguments : chars_ptr_array (1 .. size_t (Argc)) + with Address => (if Argv /= null then Argv.all'Address else System.Null_Address), + Import => True; + + function Get_Argument (Index : Positive) return String + with Pre => Index <= Integer (Argc) or else + raise Constraint_Error with ""Index"" & Index'Image & "" not in 1 .."" & Argc'Image; + + function Get_Argument (Index : Positive) return String is + (Value (Raw_Arguments (size_t (Index)))); + + Arguments : String_List (1 .. Raw_Arguments'Length); + begin + for Index in Arguments'Range loop + Arguments (Index) := SU.To_Unbounded_String (Get_Argument (Index)); + end loop; + + return Callback (Data.Plugin, Buffer, Arguments); + exception + when E : others => + Print_Error (Data.Plugin, E); + return Error; + end Command_Callback; + + function Command_Run_Callback + (Callback : On_Command_Run_Callback; + Data : Data_Ptr; + Buffer : Buffer_Ptr; + Command : chars_ptr) return Callback_Result is + begin + return Callback (Data.Plugin, Buffer, Value (Command)); + exception + when E : others => + Print_Error (Data.Plugin, E); + return Error; + end Command_Run_Callback; + + function Completion_Callback + (Callback : On_Completion_Callback; + Data : Data_Ptr; + Item : chars_ptr; + Buffer : Buffer_Ptr; + Completion : Completion_Ptr) return Callback_Result is + begin + return Callback (Data.Plugin, Value (Item), Buffer, Completion); + exception + when E : others => + Print_Error (Data.Plugin, E); + return Error; + end Completion_Callback; + + function Modifier_Callback + (Callback : On_Modifier_Callback; + Data : Data_Ptr; + Modifier : chars_ptr; + Modifier_Data : chars_ptr; + Text : chars_ptr) return chars_ptr is + begin + return New_String + (Callback (Data.Plugin, Value (Modifier), Value (Modifier_Data), Value (Text))); + exception + when E : others => + Print_Error (Data.Plugin, E); + return Text; + end Modifier_Callback; + + ---------------------------------------------------------------------------- + + function Get_Value (Plugin : Plugin_Ptr; Data : Hashtable_Ptr; Key : String) return String is + Result : constant chars_ptr := Plugin.Hashtable_Get (Data, Key & L1.NUL); + begin + if Result /= Null_Ptr then + return Value (Result); + else + raise Constraint_Error with ""Key '"" & Key & ""' does not exist""; + end if; + end Get_Value; + + function Get_Value (Plugin : Plugin_Ptr; Data : Hashtable_Ptr; Key : String) return Integer is + (Integer'Value (Get_Value (Plugin, Data, Key))); + + function Get_Value (Plugin : Plugin_Ptr; Data : Hashtable_Ptr; Key : String) return Boolean is + (Get_Value (Plugin, Data, Key) = 1); + + function Get_Value + (Plugin : Plugin_Ptr; + Data : Hashtable_Ptr; + Key : String) return SU.Unbounded_String + is (SU.To_Unbounded_String (String'(Get_Value (Plugin, Data, Key)))); + + function Get_Value + (Plugin : Plugin_Ptr; + Data : Hashtable_Ptr; + Key : String) return Line_Buffer_Kind + is + Value : constant String := Get_Value (Plugin, Data, Key); + begin + if Value = ""formatted"" then + return Formatted; + elsif Value = ""free"" then + return Free; + else + raise Constraint_Error; + end if; + end Get_Value; + + function Get_Value + (Plugin : Plugin_Ptr; + Data : Hashtable_Ptr; + Key : String) return Notify_Level + is + Value : constant Integer := Get_Value (Plugin, Data, Key); + begin + return + (case Value is + when -1 => None, + when 0 => Low, + when 1 => Message, + when 2 => Private_Message, + when 3 => Highlight, + when others => raise Constraint_Error); + end Get_Value; + + function Unix_Time_To_Ada (Value : Duration) return Ada.Calendar.Time is + use Ada.Calendar; + + Time_Epoch : constant Time := Time_Of (Year => 1970, Month => 1, Day => 1); + Time_Offset : constant Duration := Duration (Time_Zones.UTC_Time_Offset (Time_Epoch)) * 60; + begin + return Time_Epoch + Time_Offset + Value; + end Unix_Time_To_Ada; + + function Ada_To_Unix_Time (Value : Ada.Calendar.Time) return Duration is + use Ada.Calendar; + + Time_Epoch : constant Time := Time_Of (Year => 1970, Month => 1, Day => 1); + Time_Offset : constant Duration := Duration (Time_Zones.UTC_Time_Offset (Time_Epoch)) * 60; + begin + return Value - (Time_Epoch + Time_Offset); + end Ada_To_Unix_Time; + + function Get_Value + (Plugin : Plugin_Ptr; + Table : Hashtable_Ptr; + Key : String) return Ada.Calendar.Time + is + Value : constant Integer := Get_Value (Plugin, Table, Key); + begin + return Unix_Time_To_Ada (Duration (Value)); + end Get_Value; + + procedure Set_Value + (Plugin : Plugin_Ptr; + Table : Hashtable_Ptr; + Key : String; + Value : String) + is + Unused_Item : constant System.Address := + Plugin.Hashtable_Set (Table, Key & L1.NUL, Value & L1.NUL); + begin + null; + end Set_Value; + + procedure Set_Value + (Plugin : Plugin_Ptr; + Table : Hashtable_Ptr; + Key : String; + Value : Ada.Calendar.Time) is + begin + Set_Value (Plugin, Table, Key, Integer'Image (Integer (Ada_To_Unix_Time (Value)))); + end Set_Value; + + procedure Set_Value + (Plugin : Plugin_Ptr; + Table : Hashtable_Ptr; + Key : String; + Value : Notify_Level) is + begin + Set_Value (Plugin, Table, Key, + (case Value is + when None => ""-1"", + when Low => ""0"", + when Message => ""1"", + when Private_Message => ""2"", + when Highlight => ""3"")); + end Set_Value; + + procedure Set_Value + (Plugin : Plugin_Ptr; + Table : Hashtable_Ptr; + Key : String; + Value : Boolean) is + begin + Set_Value (Plugin, Table, Key, (if Value then ""1"" else ""0"")); + end Set_Value; + + function Create_Line_Data (Plugin : Plugin_Ptr; Line : Hashtable_Ptr) return Line_Data is + Kind : constant Line_Buffer_Kind := Get_Value (Plugin, Line, ""buffer_type""); + Name : constant SU.Unbounded_String := Get_Value (Plugin, Line, ""buffer_name""); + Message : constant SU.Unbounded_String := Get_Value (Plugin, Line, ""message""); + + Displayed : constant Boolean := Get_Value (Plugin, Line, ""displayed""); + + Buffer : constant SU.Unbounded_String := Get_Value (Plugin, Line, ""buffer""); + begin + case Kind is + when Formatted => + return + (Kind => Formatted, + Buffer => Buffer, + Name => Name, + Message => Message, + Displayed => Displayed, + Date => Get_Value (Plugin, Line, ""date""), + Date_Printed => Get_Value (Plugin, Line, ""date_printed""), + Date_Display => Get_Value (Plugin, Line, ""str_time""), + Tags => Get_Value (Plugin, Line, ""tags""), + Level => Get_Value (Plugin, Line, ""notify_level""), + Highlight => Get_Value (Plugin, Line, ""highlight""), + Prefix => Get_Value (Plugin, Line, ""prefix"")); + when Free => + return + (Kind => Free, + Buffer => Buffer, + Name => Name, + Message => Message, + Displayed => Displayed, + Line_Number => Get_Value (Plugin, Line, ""y"")); + end case; + end Create_Line_Data; + + ---------------------------------------------------------------------------- + + function Line_Callback + (Callback : On_Line_Callback; + Data : Data_Ptr; + Line : Hashtable_Ptr) return Hashtable_Ptr + is + use type Ada.Calendar.Time; + use type SU.Unbounded_String; + + Keys_Count : constant := 10; + Long_Bytes : constant := long'Size / System.Storage_Unit; + begin + declare + Value : constant Line_Data := Create_Line_Data (Data.Plugin, Line); + Result : Line_Data := Value; + begin + Callback (Data.Plugin, Result); + + return Table : constant Hashtable_Ptr := + Data.Plugin.Hashtable_New + (Long_Bytes * Keys_Count, + Weechat_Hashtable_String, Weechat_Hashtable_String, null, null) + do + if Value.Buffer /= Result.Buffer then + Set_Value (Data.Plugin, Table, ""buffer"", +Result.Buffer); + end if; + + if Value.Name /= Result.Name then + Set_Value (Data.Plugin, Table, ""name"", +Result.Name); + end if; + + if Value.Message /= Result.Message then + Set_Value (Data.Plugin, Table, ""message"", +Result.Message); + end if; + + case Result.Kind is + when Formatted => + if Value.Date /= Result.Date then + Set_Value (Data.Plugin, Table, ""date"", Result.Date); + end if; + + if Value.Date_Printed /= Result.Date_Printed then + Set_Value (Data.Plugin, Table, ""date_printed"", Result.Date_Printed); + end if; + + if Value.Date_Display /= Result.Date_Display then + Set_Value (Data.Plugin, Table, ""str_time"", +Result.Date_Display); + end if; + + if Value.Tags /= Result.Tags then + Set_Value (Data.Plugin, Table, ""tags"", +Result.Tags); + end if; + + if Value.Level /= Result.Level then + Set_Value (Data.Plugin, Table, ""notify_level"", Result.Level); + end if; + + if Value.Highlight /= Result.Highlight then + Set_Value (Data.Plugin, Table, ""highlight"", Result.Highlight); + end if; + + if Value.Prefix /= Result.Prefix then + Set_Value (Data.Plugin, Table, ""prefix"", +Result.Prefix); + end if; + when Free => + if Value.Line_Number /= Result.Line_Number then + Set_Value (Data.Plugin, Table, ""y"", Integer'Image (Result.Line_Number)); + end if; + end case; + end return;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (Ada, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := 0; + Time_Slice_Value := 0; + WC_Encoding := 'b'; + Locking_Policy := 'C'; + Queuing_Policy := ' '; + Task_Dispatching_Policy := 'F'; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 1; + Default_Stack_Size := -1; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 4; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Ada.Strings.Text_Buffers'Elab_Spec; + E005 := E005 + 1; + System.Bb.Timing_Events'Elab_Spec; + E059 := E059 + 1; + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + Ada.Tags'Elab_Body; + E061 := E061 + 1; + System.Exception_Table'Elab_Body; + E096 := E096 + 1; + E098 := E098 + 1; + E012 := E012 + 1; + Ada.Streams'Elab_Spec; + E132 := E132 + 1; + System.Finalization_Root'Elab_Spec; + E138 := E138 + 1; + Ada.Finalization'Elab_Spec; + E136 := E136 + 1; + System.Storage_Pools'Elab_Spec; + E140 := E140 + 1; + System.Finalization_Masters'Elab_Spec; + System.Finalization_Masters'Elab_Body; + E135 := E135 + 1; + Ada.Real_Time'Elab_Body; + E126 := E126 + 1; + System.Bb.Execution_Time'Elab_Body; + E248 := E248 + 1; + System.Pool_Global'Elab_Spec; + E142 := E142 + 1; + System.Tasking.Protected_Objects'Elab_Body; + E214 := E214 + 1; + System.Tasking.Restricted.Stages'Elab_Body; + E221 := E221 + 1; + HAL.GPIO'ELAB_SPEC; + E163 := E163 + 1; + HAL.I2C'ELAB_SPEC; + E184 := E184 + 1; + HAL.SPI'ELAB_SPEC; + E177 := E177 + 1; + HAL.UART'ELAB_SPEC; + E130 := E130 + 1; + E194 := E194 + 1; + E192 := E192 + 1; + E196 := E196 + 1; + Nrf.Gpio'Elab_Spec; + Nrf.Gpio'Elab_Body; + E157 := E157 + 1; + E236 := E236 + 1; + E207 := E207 + 1; + E172 := E172 + 1; + Nrf.Spi_Master'Elab_Spec; + Nrf.Spi_Master'Elab_Body; + E175 := E175 + 1; + E209 := E209 + 1; + E234 := E234 + 1; + E228 := E228 + 1; + E238 := E238 + 1; + E226 := E226 + 1; + Nrf.Timers'Elab_Spec; + Nrf.Timers'Elab_Body; + E179 := E179 + 1; + Nrf.Twi'Elab_Spec; + Nrf.Twi'Elab_Body; + E182 := E182 + 1; + Nrf.Uart'Elab_Spec; + Nrf.Uart'Elab_Body; + E186 := E186 + 1; + Nrf.Device'Elab_Spec; + Nrf.Device'Elab_Body; + E148 := E148 + 1; + Microbit.Console'Elab_Body; + E128 := E128 + 1; + Microbit.Iosfortasking'Elab_Spec; + Microbit.Iosfortasking'Elab_Body; + E232 := E232 + 1; + Microbit.Radio'Elab_Spec; + E189 := E189 + 1; + Microbit.Timehighspeed'Elab_Body; + E242 := E242 + 1; + E230 := E230 + 1; + E244 := E244 + 1; + Controller'Elab_Spec; + Controller'Elab_Body; + E122 := E122 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + procedure main is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize;" +"function To_Bits is new Ada.Unchecked_Conversion (Address, Bits);","LE : constant := Standard'Default_Bit_Order; + -- Static constant set to 0 for big-endian, 1 for little-endian + + -- The following is an array of masks used to mask the final byte, either + -- at the high end (big-endian case) or the low end (little-endian case). + + Masks : constant array (1 .. 7) of Packed_Byte := ( + (1 - LE) * 2#1000_0000# + LE * 2#0000_0001#, + (1 - LE) * 2#1100_0000# + LE * 2#0000_0011#, + (1 - LE) * 2#1110_0000# + LE * 2#0000_0111#, + (1 - LE) * 2#1111_0000# + LE * 2#0000_1111#, + (1 - LE) * 2#1111_1000# + LE * 2#0001_1111#, + (1 - LE) * 2#1111_1100# + LE * 2#0011_1111#, + (1 - LE) * 2#1111_1110# + LE * 2#0111_1111#); + + ----------------------- + -- Local Subprograms -- + ----------------------- + + procedure Raise_Error; + -- Raise Constraint_Error, complaining about unequal lengths + + ------------- + -- Bit_And -- + ------------- + + procedure Bit_And + (Left : Address; + Llen : Natural; + Right : Address; + Rlen : Natural; + Result : Address) + is +-- LeftB : constant Bits := To_Bits (Left); +-- RightB : constant Bits := To_Bits (Right); +-- ResultB : constant Bits := To_Bits (Result); +-- pragma Unreferenced (Llen); + pragma Unreferenced (Rlen); + begin + -- for the time being we don't provide dynamic range checks + -- if Llen /= Rlen then + -- Raise_Error; + -- end if; + + -- this routine is called only for 1, 2, or 4 byte lengths. + -- The Rlen/Llen parameter is either, 8, 16, or 32. + if Llen = 8 then + declare + use Interfaces; + Left_Byte : Unsigned_8; + for Left_Byte'Address use Left; + Right_Byte : Unsigned_8; + for Right_Byte'Address use Right; + Result_Byte : Unsigned_8; + for Result_Byte'Address use Result; + begin + Result_Byte := Left_Byte and Right_Byte;" +"function To_Bits is new Ada.Unchecked_Conversion (Address, Bits);","LE : constant := Standard'Default_Bit_Order; + -- Static constant set to 0 for big-endian, 1 for little-endian + + -- The following is an array of masks used to mask the final byte, either + -- at the high end (big-endian case) or the low end (little-endian case). + + Masks : constant array (1 .. 7) of Packed_Byte := ( + (1 - LE) * 2#1000_0000# + LE * 2#0000_0001#, + (1 - LE) * 2#1100_0000# + LE * 2#0000_0011#, + (1 - LE) * 2#1110_0000# + LE * 2#0000_0111#, + (1 - LE) * 2#1111_0000# + LE * 2#0000_1111#, + (1 - LE) * 2#1111_1000# + LE * 2#0001_1111#, + (1 - LE) * 2#1111_1100# + LE * 2#0011_1111#, + (1 - LE) * 2#1111_1110# + LE * 2#0111_1111#); + + ----------------------- + -- Local Subprograms -- + ----------------------- + + procedure Raise_Error; + -- Raise Constraint_Error, complaining about unequal lengths + + ------------- + -- Bit_And -- + ------------- + + procedure Bit_And + (Left : Address; + Llen : Natural; + Right : Address; + Rlen : Natural; + Result : Address) + is +-- LeftB : constant Bits := To_Bits (Left); +-- RightB : constant Bits := To_Bits (Right); +-- ResultB : constant Bits := To_Bits (Result); +-- pragma Unreferenced (Llen); + pragma Unreferenced (Rlen); + begin + -- for the time being we don't provide dynamic range checks + -- if Llen /= Rlen then + -- Raise_Error; + -- end if; + + -- this routine is called only for 1, 2, or 4 byte lengths. + -- The Rlen/Llen parameter is either, 8, 16, or 32. + if Llen = 8 then + declare + use Interfaces; + Left_Byte : Unsigned_8; + for Left_Byte'Address use Left; + Right_Byte : Unsigned_8; + for Right_Byte'Address use Right; + Result_Byte : Unsigned_8; + for Result_Byte'Address use Result; + begin + Result_Byte := Left_Byte and Right_Byte;" +function To_Stack_Pool is new,"Ada.Unchecked_Conversion (Address, Stk_Pool_Access); + + pragma Warnings (Off); + function To_Global_Ptr is new + Ada.Unchecked_Conversion (Address, SS_Stack_Ptr); + pragma Warnings (On); + -- Suppress aliasing warning since the pointer we return will + -- be the only access to the stack. + + Local_Stk_Address : System.Address; + + begin + Num_Of_Assigned_Stacks := Num_Of_Assigned_Stacks + 1; + + Local_Stk_Address := + To_Stack_Pool + (Default_Sized_SS_Pool) (Num_Of_Assigned_Stacks)'Address; + Stack := To_Global_Ptr (Local_Stk_Address);" +procedure Draw_Glyph is new Hershey_Fonts.Draw_Glyph,"(Internal_Draw_Line); + + Current : Point := Start; + + begin + Buffer.Set_Source (Foreground); + for C of Msg loop + exit when Current.X > Buffer.Width; + Draw_Glyph + (Fnt => Font, + C => C, + X => Current.X, + Y => Current.Y, + Height => Height, + Bold => Bold); + end loop; + end Draw_String; + + ----------------- + -- Draw_String -- + ----------------- + + procedure Draw_String + (Buffer : in out Bitmap_Buffer'Class; + Area : Rect; + Msg : String; + Font : Hershey_Font; + Bold : Boolean; + Outline : Boolean; + Foreground : Bitmap_Color; + Fast : Boolean := True) + is + Length : constant Natural := + Hershey_Fonts.Strlen (Msg, Font, Area.Height); + Ratio : Float; + Current : Point := (0, 0); + Prev : UInt32; + FG : constant UInt32 := Bitmap_Color_To_Word (Buffer.Color_Mode, + Foreground); + Blk : constant UInt32 := Bitmap_Color_To_Word (Buffer.Color_Mode, + Black); + + procedure Internal_Draw_Line + (X0, Y0, X1, Y1 : Natural; + Width : Positive); + + procedure Internal_Draw_Line + (X0, Y0, X1, Y1 : Natural; + Width : Positive) + is + begin + Draw_Line (Buffer, + (Area.Position.X + Natural (Float (X0) * Ratio), + Area.Position.Y + Y0), + (Area.Position.X + Natural (Float (X1) * Ratio), + Area.Position.Y + Y1), + Width, + Fast); + end Internal_Draw_Line; + + procedure Draw_Glyph is new Hershey_Fonts.Draw_Glyph + (Internal_Draw_Line); + + begin + if Length > Area.Width then + Ratio := Float (Area.Width) / Float (Length); + else + Ratio := 1.0; + Current.X := (Area.Width - Length) / 2; + end if; + + Buffer.Set_Source (Foreground); + + for C of Msg loop + Draw_Glyph + (Fnt => Font, + C => C, + X => Current.X, + Y => Current.Y, + Height => Area.Height, + Bold => Bold); + end loop; + + if Outline and then Area.Height > 40 then + for Y in Area.Position.Y + 1 .. Area.Position.Y + Area.Height loop + Prev := Buffer.Pixel ((Area.Position.X, Y)); + if Prev = FG then + Buffer.Set_Pixel ((Area.Position.X, Y), Black); + end if; + + for X in Area.Position.X + 1 .. Area.Position.X + Area.Width loop + declare + Col : constant UInt32 := Buffer.Pixel ((X, Y)); + Top : constant UInt32 := Buffer.Pixel ((X, Y - 1)); + begin + + if Prev /= FG + and then Col = FG + then + Buffer.Set_Pixel ((X, Y), Blk); + + elsif Prev = FG + and then Col /= FG + then + Buffer.Set_Pixel ((X - 1, Y), Blk); + + elsif Top /= FG + and then Top /= Blk + and then Col = FG + then + Buffer.Set_Pixel ((X, Y), Blk); + + elsif Top = FG + and then Col /= FG + then + Buffer.Set_Pixel ((X, Y - 1), Blk); + end if; + + Prev := Col;" +procedure Convert_Card_Identification_Data_Register,"(W0, W1, W2, W3 : UInt32; + Res : out Card_Identification_Data_Register); + -- Convert the R2 reply to CID + + procedure Convert_Card_Specific_Data_Register + (W0, W1, W2, W3 : UInt32; + Card_Type : Supported_SD_Memory_Cards; + CSD : out Card_Specific_Data_Register); + -- Convert the R2 reply to CSD + + procedure Convert_SDCard_Configuration_Register + (W0, W1 : UInt32; + SCR : out SDCard_Configuration_Register); + -- Convert W0 (MSB) / W1 (LSB) to SCR. + + function Compute_Card_Capacity + (CSD : Card_Specific_Data_Register; + Card_Type : Supported_SD_Memory_Cards) return UInt64; + -- Compute the card capacity (in bytes) from the CSD + + function Compute_Card_Block_Size + (CSD : Card_Specific_Data_Register; + Card_Type : Supported_SD_Memory_Cards) return UInt32; + -- Compute the card block size (in bytes) from the CSD. + + function Get_Transfer_Rate + (CSD : Card_Specific_Data_Register) return Natural; + -- Compute transfer rate from CSD + + function Swap32 (Val : UInt32) return UInt32 with Inline_Always; + + function BE32_To_Host (Val : UInt32) return UInt32 with Inline_Always; + + -- Swap bytes in a word + ------------ + -- Swap32 -- + ------------ + + function Swap32 (Val : UInt32) return UInt32 is + begin + return Shift_Left (Val and 16#00_00_00_ff#, 24) + or Shift_Left (Val and 16#00_00_ff_00#, 8) + or Shift_Right (Val and 16#00_ff_00_00#, 8) + or Shift_Right (Val and 16#ff_00_00_00#, 24); + end Swap32; + + ------------------ + -- BE32_To_Host -- + ------------------ + + function BE32_To_Host (Val : UInt32) return UInt32 is + use System; + begin + if Default_Bit_Order = Low_Order_First then + return Swap32 (Val); + else + return Val; + end if; + end BE32_To_Host; + + --------------------------------- + -- Card_Identification_Process -- + --------------------------------- + + procedure Card_Identification_Process + (This : in out SDMMC_Driver'Class; + Info : out Card_Information; + Status : out SD_Error) + is + Rsp : UInt32; + W0, W1, W2, W3 : UInt32; + Rca : UInt32; + + begin + -- Reset controller + This.Reset (Status); + + if Status /= OK then + return; + end if; + + -- CMD0: Sets the SDCard state to Idle + Send_Cmd (This, Go_Idle_State, 0, Status); + + if Status /= OK then + return; + end if; + + -- CMD8: IF_Cond, voltage supplied: 0x1 (2.7V - 3.6V) + -- It is mandatory for the host compliant to Physical Spec v2.00 + -- to send CMD8 before ACMD41 + Send_Cmd (This, Send_If_Cond, 16#1a5#, Status); + + if Status = OK then + -- at least SD Card 2.0 + Info.Card_Type := STD_Capacity_SD_Card_v2_0; + + Read_Rsp48 (This, Rsp); + + if (Rsp and 16#fff#) /= 16#1a5# then + -- Bad voltage or bad pattern. + Status := Error; + return; + end if; + else + -- If SD Card, then it's v1.1 + Info.Card_Type := STD_Capacity_SD_Card_V1_1; + end if; + + for I in 1 .. 5 loop + This.Delay_Milliseconds (200); + + -- CMD55: APP_CMD + -- This is done manually to handle error (this command is not + -- supported by mmc). + Send_Cmd (This, Cmd_Desc (App_Cmd), 0, Status); + + if Status /= OK then + if Status = Command_Timeout_Error + and then I = 1 + and then Info.Card_Type = STD_Capacity_SD_Card_V1_1 + then + -- Not an SDCard. Suppose MMC. + Info.Card_Type := Multimedia_Card; + exit; + end if; + return; + end if; + + -- ACMD41: SD_SEND_OP_COND (no crc check) + -- Arg: HCS=1, XPC=0, S18R=0 + Send_Cmd + (This, Acmd_Desc (SD_App_Send_Op_Cond), 16#40ff_0000#, Status); + if Status /= OK then + return; + end if; + + Read_Rsp48 (This, Rsp); + + if (Rsp and SD_OCR_High_Capacity) = SD_OCR_High_Capacity then + Info.Card_Type := High_Capacity_SD_Card; + end if; + + if (Rsp and SD_OCR_Power_Up) = 0 then + Status := Error; + + else + Status := OK; + exit; + end if; + end loop; + + if Status = Command_Timeout_Error + and then Info.Card_Type = Multimedia_Card + then + for I in 1 .. 5 loop + This.Delay_Milliseconds (200); + + -- CMD1: SEND_OP_COND query voltage + Send_Cmd (This, Cmd_Desc (Send_Op_Cond), 16#00ff_8000#, Status); + if Status /= OK then + return; + end if; + + Read_Rsp48 (This, Rsp); + + if (Rsp and SD_OCR_Power_Up) = 0 then + Status := Error; + else + if (Rsp and 16#00ff_8000#) /= 16#00ff_8000# then + Status := Error; + return; + end if; + Status := OK; + exit; + end if; + end loop; + end if; + + if Status /= OK then + return; + end if; + + -- TODO: Switch voltage + + -- CMD2: ALL_SEND_CID (136 bits) + Send_Cmd (This, All_Send_CID, 0, Status); + if Status /= OK then + return; + end if; + + Read_Rsp136 (This, W0, W1, W2, W3); + Convert_Card_Identification_Data_Register (W0, W1, W2, W3, Info.SD_CID); + + -- CMD3: SEND_RELATIVE_ADDR + case Info.Card_Type is + when Multimedia_Card => + Rca := 16#01_0000#; + when others => + Rca := 0; + end case; + + Send_Cmd (This, Send_Relative_Addr, Rca, Status); + if Status /= OK then + return; + end if; + case Info.Card_Type is + when Multimedia_Card => + null; + when others => + Read_Rsp48 (This, Rsp); + Rca := Rsp and 16#ffff_0000#; + if (Rsp and 16#e100#) /= 16#0100# then + return; + end if; + end case; + Info.RCA := UInt16 (Shift_Right (Rca, 16)); + + -- Switch to 25Mhz + case Info.Card_Type is + when Multimedia_Card => + Set_Clock (This, Get_Transfer_Rate (Info.SD_CSD)); + when STD_Capacity_SD_Card_V1_1 + | STD_Capacity_SD_Card_v2_0 + | High_Capacity_SD_Card => + Set_Clock (This, 25_000_000); + when others => + -- Not yet handled + raise Program_Error; + end case; + + -- CMD10: SEND_CID (136 bits) + Send_Cmd (This, Send_CID, Rca, Status); + if Status /= OK then + return; + end if; + + -- CMD9: SEND_CSD + Send_Cmd (This, Send_CSD, Rca, Status); + if Status /= OK then + return; + end if; + Read_Rsp136 (This, W0, W1, W2, W3); + Convert_Card_Specific_Data_Register + (W0, W1, W2, W3, Info.Card_Type, Info.SD_CSD); + Info.Card_Capacity := + Compute_Card_Capacity (Info.SD_CSD, Info.Card_Type); + Info.Card_Block_Size := + Compute_Card_Block_Size (Info.SD_CSD, Info.Card_Type); + + -- CMD7: SELECT + Send_Cmd (This, Select_Card, Rca, Status); + if Status /= OK then + return; + end if; + + -- CMD13: STATUS + Send_Cmd (This, Send_Status, Rca, Status); + if Status /= OK then + return; + end if; + + -- Bus size + case Info.Card_Type is + when STD_Capacity_SD_Card_V1_1 + | STD_Capacity_SD_Card_v2_0 + | High_Capacity_SD_Card => + Send_ACmd (This, SD_App_Set_Bus_Width, Info.RCA, 2, Status); + if Status /= OK then + return; + else + Set_Bus_Size (This, Wide_Bus_4B); + end if; + when others => + null; + end case; + + if (Info.SD_CSD.Card_Command_Class and 2**10) /= 0 then + -- Class 10 supported. + declare + subtype Switch_Status_Type is UInt32_Array (1 .. 16); + + Switch_Status : Switch_Status_Type; + begin + -- CMD6 + Read_Cmd (This, Cmd_Desc (Switch_Func), 16#00_fffff0#, + Switch_Status, Status); + if Status /= OK then + return; + end if; + + -- Handle endianness + for I in Switch_Status'Range loop + Switch_Status (I) := BE32_To_Host (Switch_Status (I)); + end loop; + + -- Switch tp 50Mhz if possible. + if (Switch_Status (4) and 2**(16 + 1)) /= 0 then + Read_Cmd (This, Cmd_Desc (Switch_Func), 16#80_fffff1#, + Switch_Status, Status); + if Status /= OK then + return; + end if; + + -- Switch to 50Mhz + Set_Clock (This, 50_000_000); + end if;" +"function Convert is new Ada.Unchecked_Conversion (HALFS.Status_Code, Status_Code);","function Convert is new Ada.Unchecked_Conversion (File_Mode, HALFS.File_Mode); + function Convert is new Ada.Unchecked_Conversion (File_Size, HALFS.File_Size); + function Convert is new Ada.Unchecked_Conversion (HALFS.File_Size, File_Size); + function Convert is new Ada.Unchecked_Conversion (Seek_Mode, HALFS.Seek_Mode); + + type Mount_Record is record + Is_Free : Boolean := True; + Name : String (1 .. Max_Mount_Name_Length); + Name_Len : Positive; + FS : Any_Filesystem_Driver; + end record; + + subtype Mount_Index is Integer range 0 .. Max_Mount_Points; + subtype Valid_Mount_Index is Mount_Index range 1 .. Max_Mount_Points; + type Mount_Array is array (Valid_Mount_Index) of Mount_Record; + + type VFS_Directory_Handle is new Directory_Handle with record + Is_Free : Boolean := True; + Mount_Id : Mount_Index; + end record; + + overriding function Get_FS + (Dir : VFS_Directory_Handle) return Any_Filesystem_Driver; + -- Return the filesystem the handle belongs to. + + overriding function Read + (Dir : in out VFS_Directory_Handle; + Handle : out Any_Node_Handle) return HALFS.Status_Code; + -- Reads the next directory entry. If no such entry is there, an error + -- code is returned in Status. + + overriding procedure Reset (Dir : in out VFS_Directory_Handle); + -- Resets the handle to the first node + + overriding procedure Close (Dir : in out VFS_Directory_Handle); + -- Closes the handle, and free the associated resources. + + function Open + (Path : String; + Handle : out Any_Directory_Handle) + return Status_Code; + + function Open + (Path : String; + Mode : File_Mode; + Handle : out Any_File_Handle) + return Status_Code; + + Mount_Points : Mount_Array; + + Handles : array (1 .. 2) of aliased VFS_Directory_Handle; + + function Name (Point : Mount_Record) return Mount_Path; + procedure Set_Name (Point : in out Mount_Record; + Path : Mount_Path); + procedure Split + (Path : String; + FS : out Any_Filesystem_Driver; + Start_Index : out Natural); + + ---------- + -- Open -- + ---------- + + function Open + (File : in out File_Descriptor; + Name : String; + Mode : File_Mode) + return Status_Code + is + Ret : Status_Code; + begin + if Is_Open (File) then + return Invalid_Parameter; + end if; + Ret := Open (Name, Mode, File.Handle); + + if Ret /= OK then + File.Handle := null; + end if; + + return Ret; + end Open; + + ----------- + -- Close -- + ----------- + + procedure Close (File : in out File_Descriptor) is + begin + if File.Handle /= null then + File.Handle.Close; + File.Handle := null; + end if; + end Close; + + ------------- + -- Is_Open -- + ------------- + + function Is_Open + (File : File_Descriptor) + return Boolean + is (File.Handle /= null); + + ----------- + -- Flush -- + ----------- + + function Flush + (File : File_Descriptor) + return Status_Code + is + begin + if File.Handle /= null then + return Convert (File.Handle.Flush); + else + return Invalid_Parameter; + end if; + end Flush; + + ---------- + -- Size -- + ---------- + + function Size + (File : File_Descriptor) + return File_Size + is + begin + if File.Handle = null then + return 0; + else + return Convert (File.Handle.Size); + end if; + end Size; + + ---------- + -- Read -- + ---------- + + function Read + (File : File_Descriptor; + Addr : System.Address; + Length : File_Size) + return File_Size + is + Ret : HALFS.File_Size; + Status : Status_Code; + begin + if File.Handle = null then + return 0; + end if; + + Ret := Convert (Length); + Status := Convert (File.Handle.Read (Addr, Ret)); + + if Status /= OK then + return 0; + else + return Convert (Ret); + end if; + end Read; + + ----------- + -- Write -- + ----------- + + function Write + (File : File_Descriptor; + Addr : System.Address; + Length : File_Size) + return File_Size + is + Ret : HALFS.File_Size; + Status : Status_Code; + begin + if File.Handle = null then + return 0; + end if; + + Ret := Convert (Length); + Status := Convert (File.Handle.Write (Addr, Ret)); + + if Status /= OK then + return 0; + else + return Convert (Ret); + end if; + end Write; + + ------------ + -- Offset -- + ------------ + + function Offset + (File : File_Descriptor) + return File_Size + is + begin + if File.Handle /= null then + return Convert (File.Handle.Offset); + else + return 0; + end if; + end Offset; + + ---------- + -- Seek -- + ---------- + + function Seek + (File : in out File_Descriptor; + Origin : Seek_Mode; + Amount : in out File_Size) + return Status_Code + is + Ret : Status_Code; + HALFS_Amount : HALFS.File_Size; + begin + if File.Handle /= null then + HALFS_Amount := Convert (Amount); + Ret := Convert (File.Handle.Seek (Convert (Origin), HALFS_Amount)); + Amount := Convert (HALFS_Amount); + return Ret; + else + return Invalid_Parameter; + end if; + end Seek; + + ------------------- + -- Generic_Write -- + ------------------- + + function Generic_Write + (File : File_Descriptor; + Value : T) + return Status_Code + is + begin + if File.Handle /= null then + return Convert (File.Handle.Write (Value'Address, T'Size / 8)); + else + return Invalid_Parameter; + end if; + end Generic_Write; + + ------------------ + -- Generic_Read -- + ------------------ + + function Generic_Read + (File : File_Descriptor; + Value : out T) + return Status_Code + is + L : HALFS.File_Size := T'Size / 8; + begin + if File.Handle /= null then + return Convert (File.Handle.Read (Value'Address, L)); + else + return Invalid_Parameter; + end if; + end Generic_Read; + + ---------- + -- Open -- + ---------- + + function Open + (Dir : in out Directory_Descriptor; + Name : String) + return Status_Code + is + Ret : Status_Code; + begin + if Dir.Handle /= null then + return Invalid_Parameter; + end if; + Ret := Open (Name, Dir.Handle); + + if Ret /= OK then + Dir.Handle := null; + end if; + + return Ret; + end Open; + + ----------- + -- Close -- + ----------- + + procedure Close (Dir : in out Directory_Descriptor) is + begin + if Dir.Handle /= null then + Dir.Handle.Close; + end if; + end Close; + + ---------- + -- Read -- + ---------- + + function Read (Dir : in out Directory_Descriptor) + return Directory_Entry + is + Node : Any_Node_Handle; + Status : Status_Code; + begin + if Dir.Handle = null then + return Invalid_Dir_Entry; + end if; + + Status := Convert (Dir.Handle.Read (Node)); + if Status /= OK then + return Invalid_Dir_Entry; + end if; + + declare + Name : constant String := Node.Basename; + Ret : Directory_Entry (Name_Length => Name'Length); + begin + Ret.Name := Name; + Ret.Subdirectory := Node.Is_Subdirectory; + Ret.Read_Only := Node.Is_Read_Only; + Ret.Hidden := Node.Is_Hidden; + Ret.Symlink := Node.Is_Symlink; + Ret.Size := Convert (Node.Size); + Node.Close; + return Ret;" +function To_Data is new Ada.Unchecked_Conversion,"(FAT_Directory_Entry, Entry_Data); + function To_Data is new Ada.Unchecked_Conversion + (VFAT_Directory_Entry, Entry_Data); + + function Find_Empty_Entry_Sequence + (Parent : access FAT_Directory_Handle; + Num_Entries : Natural) return Entry_Index; + -- Finds a sequence of deleted entries that can fit Num_Entries. + -- Returns the first entry of this sequence + + -------------- + -- Set_Size -- + -------------- + + procedure Set_Size + (E : in out FAT_Node; + Size : FAT_File_Size) + is + begin + if E.Size /= Size then + E.Size := Size; + E.Is_Dirty := True; + end if; + end Set_Size; + + ---------- + -- Find -- + ---------- + + function Find + (Parent : FAT_Node; + Filename : FAT_Name; + DEntry : out FAT_Node) return Status_Code + is + -- We use a copy of the handle, so as not to touch the state of initial + -- handle + Status : Status_Code; + Cluster : Cluster_Type := Parent.Start_Cluster; + Block : Block_Offset := Parent.FS.Cluster_To_Block (Cluster); + Index : Entry_Index := 0; + + begin + loop + Status := Next_Entry + (FS => Parent.FS, + Current_Cluster => Cluster, + Current_Block => Block, + Current_Index => Index, + DEntry => DEntry); + + if Status /= OK then + return No_Such_File; + end if; + + if Long_Name (DEntry) = Filename or else + (DEntry.L_Name.Len = 0 and then Short_Name (DEntry) = Filename) + then + return OK; + end if; + end loop; + end Find; + + ---------- + -- Find -- + ---------- + + function Find + (FS : in out FAT_Filesystem; + Path : String; + DEntry : out FAT_Node) return Status_Code + is + Status : Status_Code; + Idx : Natural; -- Idx is used to walk through the Path + Token : FAT_Name; + + begin + DEntry := Root_Entry (FS); + + -- Looping through the Path. We start at 2 as we ignore the initial '/' + Idx := Path'First + 1; + + while Idx <= Path'Last loop + Token.Len := 0; + + for J in Idx .. Path'Last loop + if Path (J) = '/' then + exit; + end if; + + Token.Len := Token.Len + 1; + Token.Name (Token.Len) := Path (J); + end loop; + + Idx := Idx + Token.Len + 1; + + Status := Find (DEntry, Token, DEntry); + + if Status /= OK then + return No_Such_File; + end if; + + if Idx < Path'Last then + -- Intermediate entry: needs to be a directory + if not Is_Subdirectory (DEntry) then + return No_Such_Path; + end if; + end if; + end loop; + + return OK; + end Find; + + ------------------ + -- Update_Entry -- + ------------------ + + function Update_Entry + (Parent : FAT_Node; + Value : in out FAT_Node) return Status_Code + is + subtype Entry_Block is Block (1 .. 32); + function To_Block is new + Ada.Unchecked_Conversion (FAT_Directory_Entry, Entry_Block); + function To_Entry is new + Ada.Unchecked_Conversion (Entry_Block, FAT_Directory_Entry); + + Ent : FAT_Directory_Entry; + Cluster : Cluster_Type := Parent.Start_Cluster; + Offset : FAT_File_Size := FAT_File_Size (Value.Index) * 32; + Block_Off : Natural; + Block : Block_Offset; + Ret : Status_Code; + + begin + if not Value.Is_Dirty then + return OK; + end if; + + while Offset > Parent.FS.Cluster_Size loop + Cluster := Parent.FS.Get_FAT (Cluster); + Offset := Offset - Parent.FS.Cluster_Size; + end loop; + + Block := Block_Offset (Offset / Parent.FS.Block_Size); + Block_Off := Natural (Offset mod Parent.FS.Block_Size); + + Ret := Parent.FS.Ensure_Block + (Parent.FS.Cluster_To_Block (Cluster) + Block); + if Ret /= OK then + return Ret; + end if; + + Ent := To_Entry (Parent.FS.Window (Block_Off .. Block_Off + 31)); + + -- For now only the size can be modified, so just apply this + -- modification + Ent.Size := Value.Size; + Value.Is_Dirty := False; + + Parent.FS.Window (Block_Off .. Block_Off + 31) := To_Block (Ent); + Ret := Parent.FS.Write_Window; + + return Ret; + end Update_Entry; + + ---------------- + -- Root_Entry -- + ---------------- + + function Root_Entry (FS : in out FAT_Filesystem) return FAT_Node + is + Ret : FAT_Node; + begin + Ret.FS := FS'Unchecked_Access; + Ret.Attributes := (Subdirectory => True, + others => False); + Ret.Is_Root := True; + Ret.L_Name := (Name => (others => ' '), + Len => 0); + if FS.Version = FAT16 then + Ret.Start_Cluster := 0; + else + Ret.Start_Cluster := FS.Root_Dir_Cluster; + end if; + Ret.Index := 0; + + return Ret; + end Root_Entry; + + ---------------- + -- Next_Entry -- + ---------------- + + function Next_Entry + (FS : access FAT_Filesystem; + Current_Cluster : in out Cluster_Type; + Current_Block : in out Block_Offset; + Current_Index : in out Entry_Index; + DEntry : out FAT_Directory_Entry) return Status_Code + is + subtype Entry_Data is Block (1 .. 32); + function To_Entry is new Ada.Unchecked_Conversion + (Entry_Data, FAT_Directory_Entry); + + Ret : Status_Code; + Block_Off : Natural; + + begin + if Current_Index = 16#FFFF# then + return No_More_Entries; + end if; + + if Current_Cluster = 0 and then FS.Version = FAT16 then + if Current_Index > + Entry_Index (FS.FAT16_Root_Dir_Num_Entries) + then + return No_More_Entries; + else + Block_Off := + Natural (FAT_File_Size (Current_Index * 32) mod + FS.Block_Size); + Current_Block := + FS.Root_Dir_Area + + Block_Offset + (FAT_File_Size (Current_Index * 32) / FS.Block_Size); + end if; + + else + Block_Off := Natural + (FAT_File_Size (Current_Index * 32) mod FS.Block_Size); + + -- Check if we're on a block boundare + if Unsigned_32 (Block_Off) = 0 and then Current_Index /= 0 then + Current_Block := Current_Block + 1; + end if; + + -- Check if we're on the boundary of a new cluster + if Current_Block - FS.Cluster_To_Block (Current_Cluster) + = FS.Blocks_Per_Cluster + then + -- The block we need to read is outside of the current cluster. + -- Let's move on to the next + + -- Read the FAT table to determine the next cluster + Current_Cluster := FS.Get_FAT (Current_Cluster); + + if Current_Cluster = 1 + or else FS.Is_Last_Cluster (Current_Cluster) + then + return Internal_Error; + end if; + + Current_Block := FS.Cluster_To_Block (Current_Cluster); + end if; + end if; + + Ret := FS.Ensure_Block (Current_Block); + + if Ret /= OK then + return Ret; + end if; + + if FS.Window (Block_Off) = 0 then + -- End of entries: we stick the index here to make sure that further + -- calls to Next_Entry always end-up here + return No_More_Entries; + end if; + + DEntry := To_Entry (FS.Window (Block_Off .. Block_Off + 31)); + Current_Index := Current_Index + 1; + + return OK; + end Next_Entry; + + ---------------- + -- Next_Entry -- + ---------------- + + function Next_Entry + (FS : access FAT_Filesystem; + Current_Cluster : in out Cluster_Type; + Current_Block : in out Block_Offset; + Current_Index : in out Entry_Index; + DEntry : out FAT_Node) return Status_Code + is + procedure Prepend + (Name : Wide_String; + Full : in out String; + Idx : in out Natural); + -- Prepends Name to Full + + ------------- + -- Prepend -- + ------------- + + procedure Prepend + (Name : Wide_String; + Full : in out String; + Idx : in out Natural) + is + Val : Unsigned_16; + begin + for J in reverse Name'Range loop + Val := Wide_Character'Pos (Name (J)); + if Val /= 16#FFFF# + and then Val /= 0 + then + Idx := Idx - 1; + + exit when Idx not in Full'Range; + + if Val < 255 then + Full (Idx) := Character'Val (Val); + elsif Val = 16#F029# then + -- Path ends with a '.' + Full (Idx) := '.'; + elsif Val = 16#F028# then + -- Path ends with a ' ' + Full (Idx) := ' '; + else + Full (Idx) := '?'; + end if; + end if; + end loop; + end Prepend; + + Ret : Status_Code; + D_Entry : FAT_Directory_Entry; + V_Entry : VFAT_Directory_Entry; + function To_VFAT_Entry is new Ada.Unchecked_Conversion + (FAT_Directory_Entry, VFAT_Directory_Entry); + + C : Unsigned_8; + Last_Seq : VFAT_Sequence_Number := 0; + CRC : Unsigned_8 := 0; + Matches : Boolean; + Current_CRC : Unsigned_8; + L_Name : String (1 .. MAX_FILENAME_LENGTH); + L_Name_First : Natural; + + begin + L_Name_First := L_Name'Last + 1; + + loop + Ret := Next_Entry + (FS, + Current_Cluster => Current_Cluster, + Current_Block => Current_Block, + Current_Index => Current_Index, + DEntry => D_Entry); + + if Ret /= OK then + return Ret; + end if; + + -- Check if we have a VFAT entry here by checking that the + -- attributes are 16#0F# (e.g. all attributes set except + -- subdirectory and archive) + if D_Entry.Attributes = VFAT_Directory_Entry_Attribute then + V_Entry := To_VFAT_Entry (D_Entry); + + if V_Entry.VFAT_Attr.Stop_Bit then + L_Name_First := L_Name'Last + 1; + + else + if Last_Seq = 0 + or else Last_Seq - 1 /= V_Entry.VFAT_Attr.Sequence + then + L_Name_First := L_Name'Last + 1; + end if; + end if; + + Last_Seq := V_Entry.VFAT_Attr.Sequence; + + Prepend (V_Entry.Name_3, L_Name, L_Name_First); + Prepend (V_Entry.Name_2, L_Name, L_Name_First); + Prepend (V_Entry.Name_1, L_Name, L_Name_First); + + if V_Entry.VFAT_Attr.Sequence = 1 then + CRC := V_Entry.Checksum; + end if; + + -- Ignore Volumes and deleted files + elsif not D_Entry.Attributes.Volume_Label + and then Character'Pos (D_Entry.Filename (1)) /= 16#E5# + then + if L_Name_First not in L_Name'Range then + Matches := False; + else + Current_CRC := 0; + Last_Seq := 0; + + for Ch of String'(D_Entry.Filename & D_Entry.Extension) loop + C := Character'Enum_Rep (Ch); + Current_CRC := Shift_Right (Current_CRC and 16#FE#, 1) + or Shift_Left (Current_CRC and 16#01#, 7); + -- Modulo addition + Current_CRC := Current_CRC + C; + end loop; + + Matches := Current_CRC = CRC; + end if; + + DEntry := + (FS => FAT_Filesystem_Access (FS), + L_Name => <>, + S_Name => D_Entry.Filename, + S_Name_Ext => D_Entry.Extension, + Attributes => D_Entry.Attributes, + Start_Cluster => (if FS.Version = FAT16 + then Cluster_Type (D_Entry.Cluster_L) + else Cluster_Type (D_Entry.Cluster_L) or + Shift_Left + (Cluster_Type (D_Entry.Cluster_H), 16)), + Size => D_Entry.Size, + Index => Current_Index - 1, + Is_Root => False, + Is_Dirty => False); + + if Matches then + DEntry.L_Name := -L_Name (L_Name_First .. L_Name'Last); + else + DEntry.L_Name.Len := 0; + end if; + + return OK; + end if; + end loop; + end Next_Entry; + + ---------- + -- Read -- + ---------- + + function Read + (Dir : in out FAT_Directory_Handle; + DEntry : out FAT_Node) return Status_Code + is + begin + return Next_Entry + (Dir.FS, + Current_Cluster => Dir.Current_Cluster, + Current_Block => Dir.Current_Block, + Current_Index => Dir.Current_Index, + DEntry => DEntry); + end Read; + + ------------------- + -- Create_Subdir -- + ------------------- + + function Create_Subdir + (Dir : FAT_Node; + Name : FAT_Name; + New_Dir : out FAT_Node) return Status_Code + is + Handle : FAT_Directory_Handle_Access; + Ret : Status_Code; + Block : Block_Offset; + Dot : FAT_Directory_Entry; + Dot_Dot : FAT_Directory_Entry; + + begin + Ret := Dir.FAT_Open (Handle); + + if Ret /= OK then + return Ret; + end if; + + Ret := Allocate_Entry + (Parent => Handle, + Name => Name, + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => True, + Archive => False), + E => New_Dir); + + if Ret /= OK then + return Ret; + end if; + + Block := Dir.FS.Cluster_To_Block (New_Dir.Start_Cluster); + Ret := Handle.FS.Ensure_Block (Block); + if Ret /= OK then + return Ret; + end if; + + -- Allocate '.', '..' and the directory entry terminator + Dot := + (Filename => (1 => '.', others => ' '), + Extension => (others => ' '), + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => True, + Archive => False), + Reserved => (others => ASCII.NUL), + Cluster_H => + Unsigned_16 + (Shift_Right + (Unsigned_32 + (New_Dir.Start_Cluster) and 16#FFFF_0000#, 16)), + Time => 0, + Date => 0, + Cluster_L => Unsigned_16 (New_Dir.Start_Cluster and 16#FFFF#), + Size => 0); + Dot_Dot := + (Filename => (1 .. 2 => '.', others => ' '), + Extension => (others => ' '), + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => True, + Archive => False), + Reserved => (others => ASCII.NUL), + Cluster_H => + Unsigned_16 + (Shift_Right + (Unsigned_32 (Handle.Start_Cluster) and 16#FFFF_0000#, 16)), + Time => 0, + Date => 0, + Cluster_L => Unsigned_16 (Handle.Start_Cluster and 16#FFFF#), + Size => 0); + + Handle.FS.Window (0 .. 31) := To_Data (Dot); + Handle.FS.Window (32 .. 63) := To_Data (Dot_Dot); + Handle.FS.Window (64 .. 95) := (others => 0); + Ret := Handle.FS.Write_Window; + + Close (Handle.all); + + return Ret; + end Create_Subdir; + + ---------------------- + -- Create_File_Node -- + ---------------------- + + function Create_File_Node + (Dir : FAT_Node; + Name : FAT_Name; + New_File : out FAT_Node) return Status_Code + is + Handle : FAT_Directory_Handle_Access; + Ret : Status_Code; + + begin + Ret := Dir.FAT_Open (Handle); + + if Ret /= OK then + return Ret; + end if; + + Ret := Allocate_Entry + (Parent => Handle, + Name => Name, + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => False, + Archive => True), + E => New_File); + + Close (Handle.all); + + if Ret /= OK then + return Ret; + end if; + + return Ret; + end Create_File_Node; + + ------------------- + -- Delete_Subdir -- + ------------------- + + function Delete_Subdir + (Dir : FAT_Node; + Recursive : Boolean) return Status_Code + is + Parent : FAT_Node; + Handle : FAT_Directory_Handle_Access; + Ent : FAT_Node; + Ret : Status_Code; + + begin + Ret := Dir.FAT_Open (Handle); + + if Ret /= OK then + return Ret; + end if; + + while Read (Handle.all, Ent) = OK loop + if -Long_Name (Ent) = ""."" then + null; + elsif -Long_Name (Ent) = "".."" then + Parent := Ent; + elsif not Recursive then + return Non_Empty_Directory; + else + if Ent.Attributes.Subdirectory then + Ret := Delete_Subdir (Ent, True); + else + Ret := Delete_Entry (Dir, Ent); + end if; + + if Ret /= OK then + Close (Handle.all); + + return Ret; + end if; + end if; + end loop; + + Close (Handle.all); + + -- Free the clusters associated to the subdirectory + Ret := Delete_Entry (Parent, Dir); + + if Ret /= OK then + return Ret; + end if; + + return Ret; + end Delete_Subdir; + + ------------------ + -- Delete_Entry -- + ------------------ + + function Delete_Entry + (Dir : FAT_Node; + Ent : FAT_Node) return Status_Code + is + Current : Cluster_Type := Ent.Start_Cluster; + Handle : FAT_Directory_Handle_Access; + Next : Cluster_Type; + Child_Ent : FAT_Node; + Ret : Status_Code; + Block_Off : Natural; + + begin + -- Mark the entry's cluster chain as available + loop + Next := Ent.FS.Get_FAT (Current); + Ret := Ent.FS.Set_FAT (Current, FREE_CLUSTER_VALUE); + + exit when Ret /= OK; + exit when Ent.FS.Is_Last_Cluster (Next); + Current := Next; + end loop; + + -- Mark the parent's entry as deleted + Ret := Dir.FAT_Open (Handle); + if Ret /= OK then + return Ret; + end if; + + while Read (Handle.all, Child_Ent) = OK loop + if Long_Name (Child_Ent) = Long_Name (Ent) then + Block_Off := Natural + ((FAT_File_Size (Handle.Current_Index - 1) * 32) + mod Dir.FS.Block_Size); + -- Mark the entry as deleted: first basename character set to + -- 16#E5# + Handle.FS.Window (Block_Off) := 16#E5#; + Ret := Handle.FS.Write_Window; + + exit; + end if; + end loop; + + Close (Handle.all); + + return Ret; + end Delete_Entry; + + --------------------- + -- Adjust_Clusters -- + --------------------- + + function Adjust_Clusters (Ent : FAT_Node) return Status_Code + is + B_Per_Cluster : constant FAT_File_Size := + FAT_File_Size (Ent.FS.Blocks_Per_Cluster) * + Ent.FS.Block_Size; + Size : FAT_File_Size := Ent.Size; + Current : Cluster_Type := Ent.Start_Cluster; + Next : Cluster_Type; + Ret : Status_Code := OK; + + begin + if Ent.Attributes.Subdirectory then + -- ??? Do nothing for now + return OK; + end if; + + loop + Next := Ent.FS.Get_FAT (Current); + + if Size > B_Per_Cluster then + -- Current cluster is fully used + Size := Size - B_Per_Cluster; + elsif Size > 0 or else Current = Ent.Start_Cluster then + -- Partially used cluster, but the last one + Size := 0; + if Next /= LAST_CLUSTER_VALUE then + Ret := Ent.FS.Set_FAT (Current, LAST_CLUSTER_VALUE); + end if; + else + -- We don't need more clusters + Ret := Ent.FS.Set_FAT (Current, FREE_CLUSTER_VALUE); + end if; + + exit when Ret /= OK; + exit when Ent.FS.Is_Last_Cluster (Next); + Current := Next; + Size := Size - B_Per_Cluster; + end loop; + + return Ret; + end Adjust_Clusters; + + ------------------------------- + -- Find_Empty_Entry_Sequence -- + ------------------------------- + + function Find_Empty_Entry_Sequence + (Parent : access FAT_Directory_Handle; + Num_Entries : Natural) return Entry_Index + is + Status : Status_Code; + D_Entry : FAT_Directory_Entry; + Sequence : Natural := 0; + Ret : Entry_Index; + Cluster : Cluster_Type := Parent.Start_Cluster; + Block : Block_Offset := Cluster_To_Block (Parent.FS.all, Cluster); + begin + Parent.Current_Index := 0; + loop + Status := Next_Entry + (Parent.FS, + Current_Cluster => Cluster, + Current_Block => Block, + Current_Index => Parent.Current_Index, + DEntry => D_Entry); + + if Status /= OK then + return Null_Index; + end if; + + if D_Entry.Attributes = VFAT_Directory_Entry_Attribute then + if Sequence = 0 then + -- Parent.Current_Index points to the next unread value. + -- So the just read entry is at Parent.Current_Index - 1 + Ret := Parent.Current_Index - 1; + end if; + + Sequence := Sequence + 1; + + elsif Character'Pos (D_Entry.Filename (1)) = 16#E5# then + -- A deleted entry has been found + if Sequence >= Num_Entries then + return Ret; + else + Sequence := 0; + end if; + + else + Sequence := 0; + end if; + end loop; + end Find_Empty_Entry_Sequence; + + -------------------- + -- Allocate_Entry -- + -------------------- + + function Allocate_Entry + (Parent : access FAT_Directory_Handle; + Name : FAT_Name; + Attributes : FAT_Directory_Entry_Attribute; + E : out FAT_Node) return Status_Code + is + subtype Short_Name is String (1 .. 8); + subtype Extension is String (1 .. 3); + + function Is_Legal_Character (C : Character) return Boolean + is (C in 'A' .. 'Z' + or else C in '0' .. '9' + or else C = '!' + or else C = '#' + or else C = '$' + or else C = '%' + or else C = '&' + or else C = ''' + or else C = '(' + or else C = ')' + or else C = '-' + or else C = '@' + or else C = '^' + or else C = '_' + or else C = '`' + or else C = '{' + or else C = '}' + or else C = '~'); + + Block_Off : Natural; + Status : Status_Code; + DEntry : FAT_Node; + SName : Short_Name := (others => ' '); + SExt : Extension := (others => ' '); + Index : Entry_Index; + + -- Retrieve the number of VFAT entries that are needed, plus one for + -- the regular FAT entry. + N_Entries : Natural := Get_Num_VFAT_Entries (Name) + 1; + Bytes : Entry_Data; + + procedure To_Short_Name + (Name : FAT_Name; + SName : out Short_Name; + Ext : out Extension); + -- Translates a long name into short 8.3 name + -- If the long name is mixed or lower case. then 8.3 will be uppercased + -- If the long name contains characters not allowed in an 8.3 name, then + -- the name is stripped of invalid characters such as space and extra + -- periods. Other unknown characters are changed to underscores. + -- The stripped name is then truncated, followed by a ~1. Inc_SName + -- below will increase the digit number in case there's overloaded 8.3 + -- names. + -- If the long name is longer than 8.3, then ~1 suffix will also be + -- used. + + function To_Upper (C : Character) return Character is + (if C in 'a' .. 'z' + then Character'Val + (Character'Pos (C) + Character'Pos ('A') - Character'Pos ('a')) + else C); + + function Value (S : String) return Natural; + -- For a positive int represented in S, returns its value + + procedure Inc_SName (SName : in out String); + -- Increment the suffix of the short FAT name + -- e.g.: + -- ABCDEFGH => ABCDEF~1 + -- ABC => ABC~1 + -- ABC~9 => ABC~10 + -- ABCDEF~9 => ABCDE~10 + + procedure To_WString + (S : FAT_Name; + Idx : in out Natural; + WS : in out Wide_String); + -- Dumps S (Idx .. Idx + WS'Length - 1) into WS and increments Idx + + ----------- + -- Value -- + ----------- + + function Value (S : String) return Natural + is + Val : constant String := Trim (S); + Digit : Natural; + Ret : Natural := 0; + begin + for J in Val'Range loop + Digit := Character'Pos (Val (J)) - Character'Pos ('0'); + Ret := Ret * 10 + Digit; + end loop; + + return Ret; + end Value; + + ------------------- + -- To_Short_Name -- + ------------------- + + procedure To_Short_Name + (Name : FAT_Name; + SName : out Short_Name; + Ext : out Extension) + is + S_Idx : Natural := 0; + Add_Tilde : Boolean := False; + Last : Natural := Name.Len; + + begin + -- Copy the file extension + + Ext := (others => ' '); + + for J in reverse 1 .. Name.Len loop + if Name.Name (J) = '.' then + if J = Name.Len then + -- Take care of names ending with a '.' (e.g. no extension, + -- the final '.' is part of the basename) + Last := J; + Ext := (others => ' '); + else + Last := J - 1; + S_Idx := Ext'First; + + for K in J + 1 .. Name.Len loop + Ext (S_Idx) := To_Upper (Name.Name (K)); + S_Idx := S_Idx + 1; + -- In case the extension is more than 3 characters, we + -- keep the first 3 ones. + exit when S_Idx > Ext'Last; + end loop; + end if; + + exit; + end if; + end loop; + + S_Idx := 0; + SName := (others => ' '); + + for J in 1 .. Last loop + exit when Add_Tilde and then S_Idx >= 6; + exit when not Add_Tilde and then S_Idx = 8; + + if Name.Name (J) in 'a' .. 'z' then + S_Idx := S_Idx + 1; + SName (S_Idx) := To_Upper (Name.Name (J)); + + elsif Is_Legal_Character (Name.Name (J)) then + S_Idx := S_Idx + 1; + SName (S_Idx) := Name.Name (J); + + elsif Name.Name (J) = '.' + or else Name.Name (J) = ' ' + then + -- dots that are not used as extension delimiters are invalid + -- in FAT short names and ignored in long names to short names + -- translation + Add_Tilde := True; + + else + -- Any other character is translated as '_' + Add_Tilde := True; + S_Idx := S_Idx + 1; + SName (S_Idx) := '_'; + end if; + end loop; + + if Add_Tilde then + if S_Idx >= 6 then + SName (7 .. 8) := ""~1""; + else + SName (S_Idx + 1 .. S_Idx + 2) := ""~1""; + end if; + end if; + end To_Short_Name; + + --------------- + -- Inc_SName -- + --------------- + + procedure Inc_SName (SName : in out String) + is + Idx : Natural := 0; + Num : Natural := 0; + + begin + for J in reverse SName'Range loop + if Idx = 0 then + if SName (J) = ' ' then + null; + elsif SName (J) in '0' .. '9' then + Idx := J; + else + SName (SName'Last - 1 .. SName'Last) := ""~1""; + + return; + end if; + + elsif SName (J) in '0' .. '9' then + Idx := J; + + elsif SName (J) = '~' then + Num := Value (SName (Idx .. SName'Last)) + 1; + -- make Idx point to '~' + Idx := J; + + declare + N_Suffix : String := Natural'Image (Num); + begin + N_Suffix (N_Suffix'First) := '~'; + + if Idx + N_Suffix'Length - 1 > SName'Last then + SName (SName'Last - N_Suffix'Length + 1 .. SName'Last) := + N_Suffix; + else + SName (Idx .. Idx + N_Suffix'Length - 1) := N_Suffix; + end if; + + return;" +function To_Disk_Parameter is new Ada.Unchecked_Conversion,"(Disk_Parameter_Block, FAT_Disk_Parameter); + + subtype FSInfo_Block is Block (0 .. 11); + function To_FSInfo is new Ada.Unchecked_Conversion + (FSInfo_Block, FAT_FS_Info); + + begin + FS.Window_Block := 16#FFFF_FFFF#; + Status := FS.Ensure_Block (0); + + if Status /= OK then + return; + end if; + + if FS.Window (510 .. 511) /= (16#55#, 16#AA#) then + Status := No_Filesystem; + return; + end if; + + FS.Disk_Parameters := + To_Disk_Parameter (FS.Window (0 .. 91)); + + if FS.Version = FAT32 then + Status := + FS.Ensure_Block (Block_Offset (FS.FSInfo_Block_Number)); + + if Status /= OK then + return; + end if; + + -- Check the generic FAT block signature + if FS.Window (510 .. 511) /= (16#55#, 16#AA#) then + Status := No_Filesystem; + return; + end if; + + FS.FSInfo := + To_FSInfo (FS.Window (16#1E4# .. 16#1EF#)); + FS.FSInfo_Changed := False; + end if; + + declare + FAT_Size_In_Block : constant Unsigned_32 := + FS.FAT_Table_Size_In_Blocks * + Unsigned_32 (FS.Number_Of_FATs); + Root_Dir_Size : Block_Offset; + begin + FS.FAT_Addr := Block_Offset (FS.Reserved_Blocks); + FS.Data_Area := FS.FAT_Addr + Block_Offset (FAT_Size_In_Block); + + if FS.Version = FAT16 then + -- Add space for the root directory + FS.Root_Dir_Area := FS.Data_Area; + Root_Dir_Size := + (Block_Offset (FS.FAT16_Root_Dir_Num_Entries) * 32 + + Block_Offset (FS.Block_Size) - 1) / + Block_Offset (FS.Block_Size); + -- Align on clusters + Root_Dir_Size := + ((Root_Dir_Size + FS.Blocks_Per_Cluster - 1) / + FS.Blocks_Per_Cluster) * + FS.Blocks_Per_Cluster; + + FS.Data_Area := FS.Data_Area + Root_Dir_Size; + end if; + + FS.Num_Clusters := + Cluster_Type + ((FS.Total_Number_Of_Blocks - Unsigned_32 (FS.Data_Area)) / + Unsigned_32 (FS.Blocks_Per_Cluster));" +procedure List (Path : String);,"---------- + -- List -- + ---------- + + procedure List (Path : String) is + DD : Directory_Descriptor; + Status : Status_Code; + First : Boolean := True; + begin + Status := Open (DD, Path); + if Status /= OK then + Put (""Cannot open directory '"" & Path & ""': "" & Status'Img); + return; + end if; + + if Recursive then + Put_Line (Path & "":""); + end if; + + loop + declare + Ent : constant Directory_Entry := Read (DD); + begin + exit when Ent = Invalid_Dir_Entry; + + if not Ent.Hidden or else Show_All then + if First then + Put (Ent.Name); + First := False; + else + Put ("" "" & Ent.Name); + end if; + end if;" +procedure Display_File (Path : String);,"------------------ + -- Display_File -- + ------------------ + + procedure Display_File (Path : String) is + FD : File_Descriptor; + Status : Status_Code; + Data : String (1 .. 512); + Amount : File_Size; + begin + Status := Open (FD, Path, Read_Only); + if Status /= OK then + Put_Line (""Cannot open file '"" & Path & ""': "" & Status'Img); + return; + end if; + + loop + Amount := Read (FD, Data'Address, Data'Length); + exit when Amount = 0; + Put (Data (Data'First .. Data'First + Natural (Amount) - 1)); + end loop; + Close (FD); + end Display_File; + + begin + loop + declare + Arg : constant String := Args.Next; + begin + if Arg'Length = 0 then + return; + end if; + Display_File (Arg);" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2ENR.USART1EN := True; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1ENR.USART2EN := True; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1ENR.USART3EN := True; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1ENR.UART4EN := True; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1ENR.UART5EN := True; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2ENR.USART6EN := True; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1ENR.UART7ENR := True; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1ENR.UART8ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2RSTR.USART1RST := True; + RCC_Periph.APB2RSTR.USART1RST := False; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1RSTR.UART2RST := True; + RCC_Periph.APB1RSTR.UART2RST := False; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1RSTR.UART3RST := True; + RCC_Periph.APB1RSTR.UART3RST := False; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1RSTR.UART4RST := True; + RCC_Periph.APB1RSTR.UART4RST := False; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1RSTR.UART5RST := True; + RCC_Periph.APB1RSTR.UART5RST := False; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2RSTR.USART6RST := True; + RCC_Periph.APB2RSTR.USART6RST := False; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1RSTR.UART7RST := True; + RCC_Periph.APB1RSTR.UART7RST := False; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1RSTR.UART8RST := True; + RCC_Periph.APB1RSTR.UART8RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out SPI_Port'Class) is + begin + if This'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SAI_Port) + is + begin + pragma Assert (This'Address = SAI_Base); + RCC_Periph.APB2ENR.SAI1EN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SAI_Port) + is + begin + pragma Assert (This'Address = SAI_Base); + RCC_Periph.APB2RSTR.SAI1RST := True; + RCC_Periph.APB2RSTR.SAI1RST := False; + end Reset; + + --------------------- + -- Get_Input_Clock -- + --------------------- + + function Get_Input_Clock (Periph : SAI_Port) return UInt32 + is + Input_Selector : UInt2; + VCO_Input : UInt32; + SAI_First_Level : UInt32; + begin + if Periph'Address /= SAI_Base then + raise Unknown_Device; + end if; + + Input_Selector := RCC_Periph.DCKCFGR.SAI1ASRC; + + -- This driver doesn't support external source clock + if Input_Selector > 1 then + raise Constraint_Error + with ""External PLL SAI source clock unsupported""; + end if; + + if not RCC_Periph.PLLCFGR.PLLSRC then + -- PLLSAI SRC is HSI + VCO_Input := HSI_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + else + -- PLLSAI SRC is HSE + VCO_Input := HSE_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + end if; + + if Input_Selector = 0 then + -- PLLSAI is the clock source + + -- VCO out = VCO in & PLLSAIN + -- SAI firstlevel = VCO out / PLLSAIQ + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIN) / + UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIQ); + + -- SAI frequency is SAI First level / PLLSAIDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DCKCFGR.PLLSAIDIVQ); + + else + -- PLLI2S as clock source + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SN) / + UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SQ); + -- SAI frequency is SAI First level / PLLI2SDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DCKCFGR.PLLIS2DIVQ + 1); + end if; + end Get_Input_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDIO_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2ENR.SDIOEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDIO_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2RSTR.SDIORST := True; + RCC_Periph.APB2RSTR.SDIORST := False; + end Reset; + + ---------------------- + -- Set_Clock_Source -- + ---------------------- + + procedure Set_Clock_Source + (This : in out SDMMC_Controller; + Src : SDIO_Clock_Source) + is + Src_Val : constant Boolean := Src = Src_Sysclk; + begin + if This.Periph.all'Address /= SDIO_Base then + raise Unknown_Device; + end if; + + RCC_Periph.DCKCFGR.SDMMCSEL := Src_Val; + + case Src is + when Src_Sysclk => + STM32.SDMMC.Set_Clk_Src_Speed + (This, System_Clock_Frequencies.SYSCLK); + when Src_48Mhz => + STM32.SDMMC.Set_Clk_Src_Speed + (This, 48_000_000); + end case; + end Set_Clock_Source; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + +-- procedure Enable_Clock (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2ENR.USART1EN := True; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1ENR.USART2EN := True; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1ENR.USART3EN := True; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1ENR.UART4EN := True; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1ENR.UART5EN := True; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2ENR.USART6EN := True; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1ENR.UART7ENR := True; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1ENR.UART8ENR := True; +-- else +-- raise Unknown_Device; +-- end if; +-- end Enable_Clock; + + ----------- + -- Reset -- + ----------- + +-- procedure Reset (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2RSTR.USART1RST := True; +-- RCC_Periph.APB2RSTR.USART1RST := False; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1RSTR.UART2RST := True; +-- RCC_Periph.APB1RSTR.UART2RST := False; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1RSTR.UART3RST := True; +-- RCC_Periph.APB1RSTR.UART3RST := False; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1RSTR.UART4RST := True; +-- RCC_Periph.APB1RSTR.UART4RST := False; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1RSTR.UART5RST := True; +-- RCC_Periph.APB1RSTR.UART5RST := False; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2RSTR.USART6RST := True; +-- RCC_Periph.APB2RSTR.USART6RST := False; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1RSTR.UART7RST := True; +-- RCC_Periph.APB1RSTR.UART7RST := False; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1RSTR.UART8RST := True; +-- RCC_Periph.APB1RSTR.UART8RST := False; +-- else +-- raise Unknown_Device; +-- end if; +-- end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + elsif Port.Periph.all'Address = I2C4_Base then + return I2C_Id_4; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + when I2C_Id_4 => + RCC_Periph.APB1ENR.I2C4EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + when I2C_Id_4 => + RCC_Periph.APB1RSTR.I2C4RST := True; + RCC_Periph.APB1RSTR.I2C4RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2ENR.SAI1EN := True; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2ENR.SAI2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2RSTR.SAI1RST := True; + RCC_Periph.APB2RSTR.SAI1RST := False; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2RSTR.SAI2RST := True; + RCC_Periph.APB2RSTR.SAI2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + --------------------- + -- Get_Input_Clock -- + --------------------- + + function Get_Input_Clock (Periph : SAI_Port) return UInt32 + is + Input_Selector : UInt2; + VCO_Input : UInt32; + SAI_First_Level : UInt32; + begin + if Periph'Address = SAI1_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI1SEL; + elsif Periph'Address = SAI2_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI2SEL; + else + raise Unknown_Device; + end if; + + + -- This driver doesn't support external source clock + if Input_Selector > 1 then + raise Constraint_Error + with ""External PLL SAI source clock unsupported""; + end if; + + if not RCC_Periph.PLLCFGR.PLLSRC then + -- PLLSAI SRC is HSI + VCO_Input := HSI_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + else + -- PLLSAI SRC is HSE + VCO_Input := HSE_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + end if; + + if Input_Selector = 0 then + -- PLLSAI is the clock source + + -- VCO out = VCO in & PLLSAIN + -- SAI firstlevel = VCO out / PLLSAIQ + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIN) / + UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIQ); + + -- SAI frequency is SAI First level / PLLSAIDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLSAIDIVQ); + + else + -- PLLI2S as clock source + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SN) / + UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SQ); + -- SAI frequency is SAI First level / PLLI2SDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLI2SDIV + 1); + end if; + end Get_Input_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address = SDMMC1_Base then + RCC_Periph.APB2ENR.SDMMC1EN := True; + elsif This.Periph.all'Address = SDMMC2_Base then + RCC_Periph.APB2ENR.SDMMC2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address = SDMMC1_Base then + RCC_Periph.APB2RSTR.SDMMC1RST := True; + RCC_Periph.APB2RSTR.SDMMC1RST := False; + elsif This.Periph.all'Address = SDMMC2_Base then + RCC_Periph.APB2RSTR.SDMMC2RST := True; + RCC_Periph.APB2RSTR.SDMMC2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------------- + -- Set_Clock_Source -- + ---------------------- + + procedure Set_Clock_Source + (This : in out SDMMC_Controller; + Src : SDMMC_Clock_Source) + is + Sel_Value : constant Boolean := Src = Src_Sysclk; + begin + if This.Periph.all'Address = SDMMC1_Base then + RCC_Periph.DKCFGR2.SDMMC1SEL := Sel_Value; + elsif This.Periph.all'Address = SDMMC2_Base then + RCC_Periph.DKCFGR2.SDMMC2SEL := Sel_Value; + else + raise Unknown_Device; + end if; + + case Src is + when Src_Sysclk => + STM32.SDMMC.Set_Clk_Src_Speed + (This, System_Clock_Frequencies.SYSCLK); + when Src_48Mhz => + STM32.SDMMC.Set_Clk_Src_Speed + (This, 48_000_000); + end case; + end Set_Clock_Source; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2ENR.USART1EN := True; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1ENR.USART2EN := True; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1ENR.USART3EN := True; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2ENR.USART6EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2RSTR.USART1RST := True; + RCC_Periph.APB2RSTR.USART1RST := False; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1RSTR.UART2RST := True; + RCC_Periph.APB1RSTR.UART2RST := False; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1RSTR.UART3RST := True; + RCC_Periph.APB1RSTR.UART3RST := False; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2RSTR.USART6RST := True; + RCC_Periph.APB2RSTR.USART6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1ENR.SPI3EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant + UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant + UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2ENR.USART1EN := True; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1ENR.USART2EN := True; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1ENR.USART3EN := True; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1ENR.UART4EN := True; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1ENR.UART5EN := True; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2ENR.USART6EN := True; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1ENR.UART7ENR := True; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1ENR.UART8ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2RSTR.USART1RST := True; + RCC_Periph.APB2RSTR.USART1RST := False; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1RSTR.UART2RST := True; + RCC_Periph.APB1RSTR.UART2RST := False; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1RSTR.UART3RST := True; + RCC_Periph.APB1RSTR.UART3RST := False; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1RSTR.UART4RST := True; + RCC_Periph.APB1RSTR.UART4RST := False; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1RSTR.UART5RST := True; + RCC_Periph.APB1RSTR.UART5RST := False; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2RSTR.USART6RST := True; + RCC_Periph.APB2RSTR.USART6RST := False; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1RSTR.UART7RST := True; + RCC_Periph.APB1RSTR.UART7RST := False; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1RSTR.UART8RST := True; + RCC_Periph.APB1RSTR.UART8RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + +-- procedure Enable_Clock (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2ENR.USART1EN := True; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1ENR.USART2EN := True; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1ENR.USART3EN := True; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1ENR.UART4EN := True; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1ENR.UART5EN := True; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2ENR.USART6EN := True; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1ENR.UART7ENR := True; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1ENR.UART8ENR := True; +-- else +-- raise Unknown_Device; +-- end if; +-- end Enable_Clock; + + ----------- + -- Reset -- + ----------- + +-- procedure Reset (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2RSTR.USART1RST := True; +-- RCC_Periph.APB2RSTR.USART1RST := False; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1RSTR.UART2RST := True; +-- RCC_Periph.APB1RSTR.UART2RST := False; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1RSTR.UART3RST := True; +-- RCC_Periph.APB1RSTR.UART3RST := False; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1RSTR.UART4RST := True; +-- RCC_Periph.APB1RSTR.UART4RST := False; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1RSTR.UART5RST := True; +-- RCC_Periph.APB1RSTR.UART5RST := False; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2RSTR.USART6RST := True; +-- RCC_Periph.APB2RSTR.USART6RST := False; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1RSTR.UART7RST := True; +-- RCC_Periph.APB1RSTR.UART7RST := False; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1RSTR.UART8RST := True; +-- RCC_Periph.APB1RSTR.UART8RST := False; +-- else +-- raise Unknown_Device; +-- end if; +-- end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + elsif Port.Periph.all'Address = I2C4_Base then + return I2C_Id_4; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + when I2C_Id_4 => + RCC_Periph.APB1ENR.I2C4EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + when I2C_Id_4 => + RCC_Periph.APB1RSTR.I2C4RST := True; + RCC_Periph.APB1RSTR.I2C4RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2ENR.SAI1EN := True; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2ENR.SAI2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2RSTR.SAI1RST := True; + RCC_Periph.APB2RSTR.SAI1RST := False; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2RSTR.SAI2RST := True; + RCC_Periph.APB2RSTR.SAI2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + --------------------- + -- Get_Input_Clock -- + --------------------- + + function Get_Input_Clock (Periph : SAI_Port) return UInt32 + is + Input_Selector : UInt2; + VCO_Input : UInt32; + SAI_First_Level : UInt32; + begin + if Periph'Address = SAI1_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI1SEL; + elsif Periph'Address = SAI2_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI2SEL; + else + raise Unknown_Device; + end if; + + + -- This driver doesn't support external source clock + if Input_Selector > 1 then + raise Constraint_Error + with ""External PLL SAI source clock unsupported""; + end if; + + if not RCC_Periph.PLLCFGR.PLLSRC then + -- PLLSAI SRC is HSI + VCO_Input := HSI_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + else + -- PLLSAI SRC is HSE + VCO_Input := HSE_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + end if; + + if Input_Selector = 0 then + -- PLLSAI is the clock source + + -- VCO out = VCO in & PLLSAIN + -- SAI firstlevel = VCO out / PLLSAIQ + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIN) / + UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIQ); + + -- SAI frequency is SAI First level / PLLSAIDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLSAIDIVQ); + + else + -- PLLI2S as clock source + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SN) / + UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SQ); + -- SAI frequency is SAI First level / PLLI2SDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLI2SDIV + 1); + end if; + end Get_Input_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDMMC_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2ENR.SDMMC1EN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDMMC_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2RSTR.SDMMC1RST := True; + RCC_Periph.APB2RSTR.SDMMC1RST := False; + end Reset; + + ---------------------- + -- Set_Clock_Source -- + ---------------------- + + procedure Set_Clock_Source + (This : in out SDMMC_Controller; + Src : SDMMC_Clock_Source) + is + begin + if This.Periph.all'Address /= SDMMC_Base then + raise Unknown_Device; + end if; + + RCC_Periph.DKCFGR2.SDMMCSEL := Src = Src_Sysclk; + + case Src is + when Src_Sysclk => + STM32.SDMMC.Set_Clk_Src_Speed + (This, System_Clock_Frequencies.SYSCLK); + when Src_48Mhz => + STM32.SDMMC.Set_Clk_Src_Speed + (This, 48_000_000); + end case; + end Set_Clock_Source; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Disable,"(This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.EN1 := False; + when Channel_2 => + This.CR.EN2 := False; + end case; + end Disable; + + ------------- + -- Enabled -- + ------------- + + function Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean is + begin + case Channel is + when Channel_1 => + return This.CR.EN1; + when Channel_2 => + return This.CR.EN2; + end case; + end Enabled; + + ---------------- + -- Set_Output -- + ---------------- + + procedure Set_Output + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel; + Value : UInt32; + Resolution : DAC_Resolution; + Alignment : Data_Alignment) + is + begin + case Channel is + + when Channel_1 => + case Resolution is + when DAC_Resolution_12_Bits => + case Alignment is + when Left_Aligned => + This.DHR12L1.DACC1DHR := + UInt12 (Value and Max_12bit_Resolution); + when Right_Aligned => + This.DHR12R1.DACC1DHR := + UInt12 (Value and Max_12bit_Resolution); + end case; + when DAC_Resolution_8_Bits => + This.DHR8R1.DACC1DHR := UInt8 (Value and Max_8bit_Resolution); + end case; + + when Channel_2 => + case Resolution is + when DAC_Resolution_12_Bits => + case Alignment is + when Left_Aligned => + This.DHR12L2.DACC2DHR := + UInt12 (Value and Max_12bit_Resolution); + when Right_Aligned => + This.DHR12R2.DACC2DHR := + UInt12 (Value and Max_12bit_Resolution); + end case; + when DAC_Resolution_8_Bits => + This.DHR8R2.DACC2DHR := UInt8 (Value and Max_8bit_Resolution); + end case; + + end case; + end Set_Output; + + ------------------------------------ + -- Trigger_Conversion_By_Software -- + ------------------------------------ + + procedure Trigger_Conversion_By_Software + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.SWTRIGR.SWTRIG.Arr (1) := True; -- cleared by hardware + when Channel_2 => + This.SWTRIGR.SWTRIG.Arr (2) := True; -- cleared by hardware + end case; + end Trigger_Conversion_By_Software; + + ---------------------------- + -- Converted_Output_Value -- + ---------------------------- + + function Converted_Output_Value + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return UInt32 + is + begin + case Channel is + when Channel_1 => + return UInt32 (This.DOR1.DACC1DOR); + when Channel_2 => + return UInt32 (This.DOR2.DACC2DOR); + end case; + end Converted_Output_Value; + + ------------------------------ + -- Set_Dual_Output_Voltages -- + ------------------------------ + + procedure Set_Dual_Output_Voltages + (This : in out Digital_To_Analog_Converter; + Channel_1_Value : UInt32; + Channel_2_Value : UInt32; + Resolution : DAC_Resolution; + Alignment : Data_Alignment) + is + begin + case Resolution is + when DAC_Resolution_12_Bits => + case Alignment is + when Left_Aligned => + This.DHR12LD.DACC1DHR := + UInt12 (Channel_1_Value and Max_12bit_Resolution); + This.DHR12LD.DACC2DHR := + UInt12 (Channel_2_Value and Max_12bit_Resolution); + when Right_Aligned => + This.DHR12RD.DACC1DHR := + UInt12 (Channel_1_Value and Max_12bit_Resolution); + This.DHR12RD.DACC2DHR := + UInt12 (Channel_2_Value and Max_12bit_Resolution); + end case; + when DAC_Resolution_8_Bits => + This.DHR8RD.DACC1DHR := + UInt8 (Channel_1_Value and Max_8bit_Resolution); + This.DHR8RD.DACC2DHR := + UInt8 (Channel_2_Value and Max_8bit_Resolution); + end case; + end Set_Dual_Output_Voltages; + + --------------------------------- + -- Converted_Dual_Output_Value -- + --------------------------------- + + function Converted_Dual_Output_Value (This : Digital_To_Analog_Converter) + return Dual_Channel_Output + is + Result : Dual_Channel_Output; + begin + Result.Channel_1_Data := UInt16 (This.DOR1.DACC1DOR); + Result.Channel_2_Data := UInt16 (This.DOR2.DACC2DOR); + return Result; + end Converted_Dual_Output_Value; + + -------------------------- + -- Enable_Output_Buffer -- + -------------------------- + + procedure Enable_Output_Buffer + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.BOFF1 := True; + when Channel_2 => + This.CR.BOFF2 := True; + end case; + end Enable_Output_Buffer; + + --------------------------- + -- Disable_Output_Buffer -- + --------------------------- + + procedure Disable_Output_Buffer + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.BOFF1 := False; + when Channel_2 => + This.CR.BOFF2 := False; + end case; + end Disable_Output_Buffer; + + --------------------------- + -- Output_Buffer_Enabled -- + --------------------------- + + function Output_Buffer_Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean + is + begin + case Channel is + when Channel_1 => + return This.CR.BOFF1; + when Channel_2 => + return This.CR.BOFF2; + end case; + end Output_Buffer_Enabled; + + -------------------- + -- Select_Trigger -- + -------------------- + + procedure Select_Trigger + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel; + Trigger : External_Event_Trigger_Selection) + is + begin + case Channel is + when Channel_1 => + This.CR.TSEL1 := + External_Event_Trigger_Selection'Enum_Rep (Trigger); + when Channel_2 => + This.CR.TSEL2 := + External_Event_Trigger_Selection'Enum_Rep (Trigger); + end case; + end Select_Trigger; + + ----------------------- + -- Trigger_Selection -- + ----------------------- + + function Trigger_Selection + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return External_Event_Trigger_Selection + is + begin + case Channel is + when Channel_1 => + return External_Event_Trigger_Selection'Val (This.CR.TSEL1); + when Channel_2 => + return External_Event_Trigger_Selection'Val (This.CR.TSEL2); + end case; + end Trigger_Selection; + + -------------------- + -- Enable_Trigger -- + -------------------- + + procedure Enable_Trigger + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.TEN1 := True; + when Channel_2 => + This.CR.TEN2 := True; + end case; + end Enable_Trigger; + + --------------------- + -- Disable_Trigger -- + --------------------- + + procedure Disable_Trigger + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.TEN1 := False; + when Channel_2 => + This.CR.TEN2 := False; + end case; + end Disable_Trigger; + + --------------------- + -- Trigger_Enabled -- + --------------------- + + function Trigger_Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean + is + begin + case Channel is + when Channel_1 => + return This.CR.TEN1; + when Channel_2 => + return This.CR.TEN2; + end case; + end Trigger_Enabled; + + ---------------- + -- Enable_DMA -- + ---------------- + + procedure Enable_DMA + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.DMAEN1 := True; + when Channel_2 => + This.CR.DMAEN2 := True; + end case; + end Enable_DMA; + + ----------------- + -- Disable_DMA -- + ----------------- + + procedure Disable_DMA + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.DMAEN1 := False; + when Channel_2 => + This.CR.DMAEN2 := False; + end case; + end Disable_DMA; + + ----------------- + -- DMA_Enabled -- + ----------------- + + function DMA_Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean + is + begin + case Channel is + when Channel_1 => + return This.CR.DMAEN1; + when Channel_2 => + return This.CR.DMAEN2; + end case; + end DMA_Enabled; + + ------------ + -- Status -- + ------------ + + function Status + (This : Digital_To_Analog_Converter; + Flag : DAC_Status_Flag) + return Boolean + is + begin + case Flag is + when DMA_Underrun_Channel_1 => + return This.SR.DMAUDR1; + when DMA_Underrun_Channel_2 => + return This.SR.DMAUDR2; + end case; + end Status; + + ------------------ + -- Clear_Status -- + ------------------ + + procedure Clear_Status + (This : in out Digital_To_Analog_Converter; + Flag : DAC_Status_Flag) + is + begin + case Flag is + when DMA_Underrun_Channel_1 => + This.SR.DMAUDR1 := True; -- set to 1 to clear + when DMA_Underrun_Channel_2 => + This.SR.DMAUDR2 := True; -- set to 1 to clear + end case; + end Clear_Status; + + ----------------------- + -- Enable_Interrupts -- + ----------------------- + + procedure Enable_Interrupts + (This : in out Digital_To_Analog_Converter; + Source : DAC_Interrupts) + is + begin + case Source is + when DMA_Underrun_Channel_1 => + This.CR.DMAUDRIE1 := True; + when DMA_Underrun_Channel_2 => + This.CR.DMAUDRIE2 := True; + end case; + end Enable_Interrupts; + + ------------------------ + -- Disable_Interrupts -- + ------------------------ + + procedure Disable_Interrupts + (This : in out Digital_To_Analog_Converter; + Source : DAC_Interrupts) + is + begin + case Source is + when DMA_Underrun_Channel_1 => + This.CR.DMAUDRIE1 := False; + when DMA_Underrun_Channel_2 => + This.CR.DMAUDRIE2 := False; + end case; + end Disable_Interrupts; + + ----------------------- + -- Interrupt_Enabled -- + ----------------------- + + function Interrupt_Enabled + (This : Digital_To_Analog_Converter; + Source : DAC_Interrupts) + return Boolean + is + begin + case Source is + when DMA_Underrun_Channel_1 => + return This.CR.DMAUDRIE1; + when DMA_Underrun_Channel_2 => + return This.CR.DMAUDRIE2; + end case; + end Interrupt_Enabled; + + ---------------------- + -- Interrupt_Source -- + ---------------------- + + function Interrupt_Source + (This : Digital_To_Analog_Converter) + return DAC_Interrupts + is + begin + if This.CR.DMAUDRIE1 then + return DMA_Underrun_Channel_1; + else + return DMA_Underrun_Channel_2; + end if; + end Interrupt_Source; + + ----------------------------- + -- Clear_Interrupt_Pending -- + ----------------------------- + + procedure Clear_Interrupt_Pending + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.SR.DMAUDR1 := False; + when Channel_2 => + This.SR.DMAUDR2 := False; + end case; + end Clear_Interrupt_Pending; + + ---------------------------- + -- Select_Wave_Generation -- + ---------------------------- + + procedure Select_Wave_Generation + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel; + Selection : Wave_Generation) + is + + function As_UInt4 is new Ada.Unchecked_Conversion + (Source => Noise_Wave_Mask_Selection, Target => UInt4); + + function As_UInt4 is new Ada.Unchecked_Conversion + (Source => Triangle_Wave_Amplitude_Selection, Target => UInt4); + + begin + case Channel is + when Channel_1 => + This.CR.WAVE1 := + Wave_Generation_Selection'Enum_Rep (Selection.Kind); + when Channel_2 => + This.CR.WAVE2 := + Wave_Generation_Selection'Enum_Rep (Selection.Kind); + end case; + + case Selection.Kind is + + when No_Wave_Generation => + null; + + when Noise_Wave => + case Channel is + when Channel_1 => + This.CR.MAMP1 := As_UInt4 (Selection.Mask); + when Channel_2 => + This.CR.MAMP2 := As_UInt4 (Selection.Mask); + end case; + + when Triangle_Wave => + case Channel is + when Channel_1 => + This.CR.MAMP1 := As_UInt4 (Selection.Amplitude); + when Channel_2 => + This.CR.MAMP2 := As_UInt4 (Selection.Amplitude); + end case; + + end case; + end Select_Wave_Generation; + + ------------------------------ + -- Selected_Wave_Generation -- + ------------------------------ + + function Selected_Wave_Generation + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Wave_Generation + is + Kind : Wave_Generation_Selection; + + function As_Mask is new Ada.Unchecked_Conversion + (Target => Noise_Wave_Mask_Selection, Source => UInt4); + + function As_Amplitude is new Ada.Unchecked_Conversion + (Target => Triangle_Wave_Amplitude_Selection, Source => UInt4); + + begin + case Channel is + when Channel_1 => + Kind := Wave_Generation_Selection'Val (This.CR.WAVE1); + when Channel_2 => + Kind := Wave_Generation_Selection'Val (This.CR.WAVE2); + end case; + declare + Result : Wave_Generation (Kind); + begin + case Kind is + when No_Wave_Generation => + null; + + when Noise_Wave => + case Channel is + when Channel_1 => + Result.Mask := As_Mask (This.CR.MAMP1); + when Channel_2 => + Result.Mask := As_Mask (This.CR.MAMP2); + end case; + + when Triangle_Wave => + case Channel is + when Channel_1 => + Result.Amplitude := As_Amplitude (This.CR.MAMP1); + when Channel_2 => + Result.Amplitude := As_Amplitude (This.CR.MAMP2); + end case; + end case; + + return Result;" +procedure Disable (This : in out Analog_To_Digital_Converter) is,"begin + This.CR2.ADON := False; + end Disable; + + ------------- + -- Enabled -- + ------------- + + function Enabled (This : Analog_To_Digital_Converter) return Boolean is + (This.CR2.ADON); + + ---------------------- + -- Conversion_Value -- + ---------------------- + + function Conversion_Value + (This : Analog_To_Digital_Converter) + return UInt16 + is + begin + return This.DR.DATA; + end Conversion_Value; + + --------------------------- + -- Data_Register_Address -- + --------------------------- + + function Data_Register_Address + (This : Analog_To_Digital_Converter) + return System.Address + is + (This.DR'Address); + + ------------------------------- + -- Injected_Conversion_Value -- + ------------------------------- + + function Injected_Conversion_Value + (This : Analog_To_Digital_Converter; + Rank : Injected_Channel_Rank) + return UInt16 + is + begin + case Rank is + when 1 => + return This.JDR1.JDATA; + when 2 => + return This.JDR2.JDATA; + when 3 => + return This.JDR3.JDATA; + when 4 => + return This.JDR4.JDATA; + end case; + end Injected_Conversion_Value; + + -------------------------------- + -- Multimode_Conversion_Value -- + -------------------------------- + + function Multimode_Conversion_Value return UInt32 is + (C_ADC_Periph.CDR.Val); + + -------------------- + -- Configure_Unit -- + -------------------- + + procedure Configure_Unit + (This : in out Analog_To_Digital_Converter; + Resolution : ADC_Resolution; + Alignment : Data_Alignment) + is + begin + This.CR1.RES := ADC_Resolution'Enum_Rep (Resolution); + This.CR2.ALIGN := Alignment = Left_Aligned; + end Configure_Unit; + + ------------------------ + -- Current_Resolution -- + ------------------------ + + function Current_Resolution + (This : Analog_To_Digital_Converter) + return ADC_Resolution + is (ADC_Resolution'Val (This.CR1.RES)); + + ----------------------- + -- Current_Alignment -- + ----------------------- + + function Current_Alignment + (This : Analog_To_Digital_Converter) + return Data_Alignment + is ((if This.CR2.ALIGN then Left_Aligned else Right_Aligned)); + + --------------------------------- + -- Configure_Common_Properties -- + --------------------------------- + + procedure Configure_Common_Properties + (Mode : Multi_ADC_Mode_Selections; + Prescalar : ADC_Prescalars; + DMA_Mode : Multi_ADC_DMA_Modes; + Sampling_Delay : Sampling_Delay_Selections) + is + begin + C_ADC_Periph.CCR.MULT := Multi_ADC_Mode_Selections'Enum_Rep (Mode); + C_ADC_Periph.CCR.DELAY_k := + Sampling_Delay_Selections'Enum_Rep (Sampling_Delay); + C_ADC_Periph.CCR.DMA := Multi_ADC_DMA_Modes'Enum_Rep (DMA_Mode); + C_ADC_Periph.CCR.ADCPRE := ADC_Prescalars'Enum_Rep (Prescalar); + end Configure_Common_Properties; + + ----------------------------------- + -- Configure_Regular_Conversions -- + ----------------------------------- + + procedure Configure_Regular_Conversions + (This : in out Analog_To_Digital_Converter; + Continuous : Boolean; + Trigger : Regular_Channel_Conversion_Trigger; + Enable_EOC : Boolean; + Conversions : Regular_Channel_Conversions) + is + begin + This.CR2.EOCS := Enable_EOC; + This.CR2.CONT := Continuous; + + This.CR1.SCAN := Conversions'Length > 1; + + if Trigger.Enabler /= Trigger_Disabled then + This.CR2.EXTSEL := External_Events_Regular_Group'Enum_Rep (Trigger.Event); + This.CR2.EXTEN := External_Trigger'Enum_Rep (Trigger.Enabler); + else + This.CR2.EXTSEL := 0; + This.CR2.EXTEN := 0; + end if; + + for Rank in Conversions'Range loop + declare + Conversion : Regular_Channel_Conversion renames Conversions (Rank); + begin + Configure_Regular_Channel + (This, Conversion.Channel, Rank, Conversion.Sample_Time); + + -- We check the VBat first because that channel is also used for + -- the temperature sensor channel on some MCUs, in which case the + -- VBat conversion is the only one done. This order reflects that + -- hardware behavior. + if VBat_Conversion (This, Conversion.Channel) then + Enable_VBat_Connection; + elsif VRef_TemperatureSensor_Conversion (This, Conversion.Channel) + then + Enable_VRef_TemperatureSensor_Connection; + end if;" +procedure Disable_Interrupt,"(This : in out SDMMC_Controller; + Interrupt : SDMMC_Interrupts) + is + begin + case Interrupt is + when Data_End_Interrupt => + This.Periph.MASK.DATAENDIE := False; + when Data_CRC_Fail_Interrupt => + This.Periph.MASK.DCRCFAILIE := False; + when Data_Timeout_Interrupt => + This.Periph.MASK.DTIMEOUTIE := False; + when TX_FIFO_Empty_Interrupt => + This.Periph.MASK.TXFIFOEIE := False; + when RX_FIFO_Full_Interrupt => + This.Periph.MASK.RXFIFOFIE := False; + when TX_Underrun_Interrupt => + This.Periph.MASK.TXUNDERRIE := False; + when RX_Overrun_Interrupt => + This.Periph.MASK.RXOVERRIE := False; + end case; + end Disable_Interrupt; + + ------------------------ + -- Delay_Milliseconds -- + ------------------------ + + overriding procedure Delay_Milliseconds + (This : SDMMC_Controller; + Amount : Natural) + is + pragma Unreferenced (This); + begin + delay until Clock + Milliseconds (Amount); + end Delay_Milliseconds; + + ----------- + -- Reset -- + ----------- + + overriding procedure Reset + (This : in out SDMMC_Controller; + Status : out SD_Error) + is + begin + -- Make sure the POWER register is writable by waiting a bit after + -- the Power_Off command + DCTRL_Write_Delay; + + This.Periph.POWER.PWRCTRL := Power_Off; + + -- Use the Default SDMMC peripheral configuration for SD card init + This.Periph.CLKCR := (others => <>); + This.Set_Clock (400_000); + This.Periph.DTIMER := SD_DATATIMEOUT; + + This.Periph.CLKCR.CLKEN := False; + DCTRL_Write_Delay; + This.Periph.POWER.PWRCTRL := Power_On; + + -- Wait for the clock to stabilize. + DCTRL_Write_Delay; + + This.Periph.CLKCR.CLKEN := True; + + delay until Clock + Milliseconds (20); + + Status := OK; + end Reset; + + --------------- + -- Set_Clock -- + --------------- + + overriding procedure Set_Clock + (This : in out SDMMC_Controller; + Freq : Natural) + is + Div : UInt32; + CLKCR : CLKCR_Register; + begin + Div := (This.CLK_In + UInt32 (Freq) - 1) / UInt32 (Freq); + + -- Make sure the POWER register is writable by waiting a bit after + -- the Power_Off command + DCTRL_Write_Delay; + + if Div <= 1 then + This.Periph.CLKCR.BYPASS := True; + else + Div := Div - 2; + CLKCR := This.Periph.CLKCR; + CLKCR.BYPASS := False; + + if Div > UInt32 (CLKCR_CLKDIV_Field'Last) then + CLKCR.CLKDIV := CLKCR_CLKDIV_Field'Last; + else + CLKCR.CLKDIV := CLKCR_CLKDIV_Field (Div); + end if; + + This.Periph.CLKCR := CLKCR; + end if; + end Set_Clock; + + ------------------ + -- Set_Bus_Size -- + ------------------ + + overriding procedure Set_Bus_Size + (This : in out SDMMC_Controller; + Mode : Wide_Bus_Mode) + is + function To_WIDBUS_Field is new Ada.Unchecked_Conversion + (Wide_Bus_Mode, CLKCR_WIDBUS_Field); + begin + This.Periph.CLKCR.WIDBUS := To_WIDBUS_Field (Mode); + end Set_Bus_Size; + + ------------------ + -- Send_Command -- + ------------------ + + overriding procedure Send_Cmd + (This : in out SDMMC_Controller; + Cmd : Cmd_Desc_Type; + Arg : UInt32; + Status : out SD_Error) + is + CMD_Reg : CMD_Register := This.Periph.CMD; + begin + if Cmd.Rsp = Rsp_Invalid or else Cmd.Tfr = Tfr_Invalid then + raise Program_Error with ""Not implemented""; + end if; + + This.Periph.ARG := Arg; + CMD_Reg.CMDINDEX := CMD_CMDINDEX_Field (Cmd.Cmd); + CMD_Reg.WAITRESP := (case Cmd.Rsp is + when Rsp_No => No_Response, + when Rsp_R2 => Long_Response, + when others => Short_Response); + CMD_Reg.WAITINT := False; + CMD_Reg.CPSMEN := True; + This.Periph.CMD := CMD_Reg; + + case Cmd.Rsp is + when Rsp_No => + Status := This.Command_Error; + + when Rsp_R1 | Rsp_R1B => + Status := This.Response_R1_Error (Cmd.Cmd); + + when Rsp_R2 => + Status := This.Response_R2_Error; + + when Rsp_R3 => + Status := This.Response_R3_Error; + + when Rsp_R6 => + declare + RCA : UInt32; + begin + Status := This.Response_R6_Error (Cmd.Cmd, RCA); + This.RCA := UInt16 (Shift_Right (RCA, 16));" +procedure Disable_Data,"(This : in out SDMMC_Controller) + is + begin + This.Periph.DCTRL := (others => <>); + end Disable_Data; + + -------------------------- + -- Enable_DMA_Transfers -- + -------------------------- + + procedure Enable_DMA_Transfers + (This : in out SDMMC_Controller; + RX_Int : not null STM32.DMA.Interrupts.DMA_Interrupt_Controller_Access; + TX_Int : not null STM32.DMA.Interrupts.DMA_Interrupt_Controller_Access; + SD_Int : not null STM32.SDMMC_Interrupt.SDMMC_Interrupt_Handler_Access) + is + begin + This.TX_DMA_Int := TX_Int; + This.RX_DMA_Int := RX_Int; + This.SD_Int := SD_Int; + end Enable_DMA_Transfers; + + -------------------------- + -- Has_Card_Information -- + -------------------------- + + function Has_Card_Information + (This : SDMMC_Controller) + return Boolean + is (This.Has_Info); + + ---------------------- + -- Card_Information -- + ---------------------- + + function Card_Information + (This : SDMMC_Controller) + return HAL.SDMMC.Card_Information + is + begin + return This.Info; + end Card_Information; + + ---------------------------- + -- Clear_Card_Information -- + ---------------------------- + + procedure Clear_Card_Information + (This : in out SDMMC_Controller) + is + begin + This.Has_Info := False; + end Clear_Card_Information; + + --------------- + -- Read_FIFO -- + --------------- + + function Read_FIFO + (Controller : in out SDMMC_Controller) return UInt32 + is + begin + return Controller.Periph.FIFO; + end Read_FIFO; + + ------------------- + -- Command_Error -- + ------------------- + + function Command_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + Start : constant Time := Clock; + begin + while not Controller.Periph.STA.CMDSENT loop + if Clock - Start > Milliseconds (1000) then + return Timeout_Error; + end if; + end loop; + + Clear_Static_Flags (Controller); + + return OK; + end Command_Error; + + ----------------------- + -- Response_R1_Error -- + ----------------------- + + function Response_R1_Error + (Controller : in out SDMMC_Controller; + Command_Index : SD_Command) return SD_Error + is + Start : constant Time := Clock; + Timeout : Boolean := False; + R1 : UInt32; + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + if Clock - Start > Milliseconds (1000) then + Timeout := True; + + exit; + end if; + end loop; + + if Timeout or else Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + end if; + + if SD_Command (Controller.Periph.RESPCMD.RESPCMD) /= + Command_Index + then + return Illegal_Cmd; + end if; + + Clear_Static_Flags (Controller); + + R1 := Controller.Periph.RESP1; + + if (R1 and SD_OCR_ERRORMASK) = 0 then + return OK; + end if; + + if (R1 and SD_OCR_ADDR_OUT_OF_RANGE) /= 0 then + return Address_Out_Of_Range; + elsif (R1 and SD_OCR_ADDR_MISALIGNED) /= 0 then + return Address_Missaligned; + elsif (R1 and SD_OCR_BLOCK_LEN_ERR) /= 0 then + return Block_Length_Error; + elsif (R1 and SD_OCR_ERASE_SEQ_ERR) /= 0 then + return Erase_Seq_Error; + elsif (R1 and SD_OCR_BAD_ERASE_PARAM) /= 0 then + return Bad_Erase_Parameter; + elsif (R1 and SD_OCR_WRITE_PROT_VIOLATION) /= 0 then + return Write_Protection_Violation; + elsif (R1 and SD_OCR_LOCK_UNLOCK_FAILED) /= 0 then + return Lock_Unlock_Failed; + elsif (R1 and SD_OCR_COM_CRC_FAILED) /= 0 then + return CRC_Check_Fail; + elsif (R1 and SD_OCR_ILLEGAL_CMD) /= 0 then + return Illegal_Cmd; + elsif (R1 and SD_OCR_CARD_ECC_FAILED) /= 0 then + return Card_ECC_Failed; + elsif (R1 and SD_OCR_CC_ERROR) /= 0 then + return CC_Error; + elsif (R1 and SD_OCR_GENERAL_UNKNOWN_ERROR) /= 0 then + return General_Unknown_Error; + elsif (R1 and SD_OCR_STREAM_READ_UNDERRUN) /= 0 then + return Stream_Read_Underrun; + elsif (R1 and SD_OCR_STREAM_WRITE_UNDERRUN) /= 0 then + return Stream_Write_Underrun; + elsif (R1 and SD_OCR_CID_CSD_OVERWRITE) /= 0 then + return CID_CSD_Overwrite; + elsif (R1 and SD_OCR_WP_ERASE_SKIP) /= 0 then + return WP_Erase_Skip; + elsif (R1 and SD_OCR_CARD_ECC_DISABLED) /= 0 then + return Card_ECC_Disabled; + elsif (R1 and SD_OCR_ERASE_RESET) /= 0 then + return Erase_Reset; + elsif (R1 and SD_OCR_AKE_SEQ_ERROR) /= 0 then + return AKE_SEQ_Error; + else + return General_Unknown_Error; + end if; + end Response_R1_Error; + + ----------------------- + -- Response_R2_Error -- + ----------------------- + + function Response_R2_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + null; + end loop; + + if Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + end if; + + Clear_Static_Flags (Controller); + + return OK; + end Response_R2_Error; + + ----------------------- + -- Response_R3_Error -- + ----------------------- + + function Response_R3_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + null; + end loop; + + if Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + end if; + + Clear_Static_Flags (Controller); + + return OK; + end Response_R3_Error; + + ----------------------- + -- Response_R6_Error -- + ----------------------- + + function Response_R6_Error + (Controller : in out SDMMC_Controller; + Command_Index : SD_Command; + RCA : out UInt32) return SD_Error + is + Response : UInt32; + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + null; + end loop; + + if Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + end if; + + if SD_Command (Controller.Periph.RESPCMD.RESPCMD) /= + Command_Index + then + return Illegal_Cmd; + end if; + + Clear_Static_Flags (Controller); + + Response := Controller.Periph.RESP1; + + if (Response and SD_R6_Illegal_Cmd) = SD_R6_Illegal_Cmd then + return Illegal_Cmd; + + elsif (Response and SD_R6_General_Unknown_Error) = + SD_R6_General_Unknown_Error + then + return General_Unknown_Error; + + elsif (Response and SD_R6_Com_CRC_Failed) = SD_R6_Com_CRC_Failed then + return CRC_Check_Fail; + end if; + + RCA := Response and 16#FFFF_0000#; + + return OK; + end Response_R6_Error; + + ----------------------- + -- Response_R7_Error -- + ----------------------- + + function Response_R7_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + Start : constant Time := Clock; + Timeout : Boolean := False; + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + if Clock - Start > Milliseconds (1000) then + Timeout := True; + + exit; + end if; + end loop; + + if Timeout or else Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + + elsif Controller.Periph.STA.CMDREND then + Controller.Periph.ICR.CMDRENDC := True; + + return OK; + + else + return Error; + end if; + end Response_R7_Error; + + ------------------- + -- Stop_Transfer -- + ------------------- + + function Stop_Transfer + (This : in out SDMMC_Controller) return SD_Error + is + Ret : SD_Error; + begin + Send_Cmd (This, Cmd_Desc (Stop_Transmission), 0, Ret); + + return Ret; + end Stop_Transfer; + + ----------------------- + -- Set_Clk_Src_Speed -- + ----------------------- + + procedure Set_Clk_Src_Speed + (This : in out SDMMC_Controller; + CLK : UInt32) + is + begin + This.CLK_In := CLK; + end Set_Clk_Src_Speed; + + ---------------- + -- Initialize -- + ---------------- + + function Initialize + (This : in out SDMMC_Controller) return SD_Error + is + Ret : SD_Error; + begin + SDMMC_Init.Card_Identification_Process (This, This.Info, Ret); + This.Card_Type := This.Info.Card_Type; + This.RCA := This.Info.RCA; + + return Ret; + end Initialize; + + ---------- + -- Read -- + ---------- + + overriding + function Read + (This : in out SDMMC_Controller; + Block_Number : UInt64; + Data : out HAL.Block_Drivers.Block) return Boolean + is + Ret : Boolean; + SD_Err : SD_Error; + DMA_Err : DMA_Error_Code; + begin + + Ensure_Card_Informations (This); + + if This.RX_DMA_Int = null or else This.SD_Int = null then + SD_Err := Read_Blocks + (This, + Block_Number * 512, + Data); + return SD_Err = OK; + end if; + + This.SD_Int.Set_Transfer_State (This); + + SD_Err := Read_Blocks_DMA + (This, + Block_Number * 512, + Data); + + if SD_Err /= OK then + This.RX_DMA_Int.Clear_Transfer_State; + This.SD_Int.Clear_Transfer_State; + This.RX_DMA_Int.Abort_Transfer (DMA_Err); + + return False; + end if; + + This.SD_Int.Wait_Transfer (SD_Err); + + if SD_Err /= OK then + This.RX_DMA_Int.Clear_Transfer_State; + else + This.RX_DMA_Int.Wait_For_Completion (DMA_Err); + + loop + exit when not Get_Flag (This, RX_Active); + end loop; + end if; + + Ret := SD_Err = OK and then DMA_Err = DMA_No_Error; + + if Last_Operation (This) = + Read_Multiple_Blocks_Operation + then + SD_Err := Stop_Transfer (This); + Ret := Ret and then SD_Err = OK; + end if; + + Clear_All_Status (This.RX_DMA_Int.Controller.all, This.RX_DMA_Int.Stream); + Disable (This.RX_DMA_Int.Controller.all, This.RX_DMA_Int.Stream); + Disable_Data (This); + Clear_Static_Flags (This); + + Cortex_M.Cache.Invalidate_DCache + (Start => Data'Address, + Len => Data'Length); + + return Ret; + end Read; + + ----------- + -- Write -- + ----------- + + overriding + function Write + (This : in out SDMMC_Controller; + Block_Number : UInt64; + Data : HAL.Block_Drivers.Block) return Boolean + is + Ret : SD_Error; + DMA_Err : DMA_Error_Code; + begin + if This.TX_DMA_Int = null then + raise Program_Error with ""No TX DMA controller""; + end if; + + if This.SD_Int = null then + raise Program_Error with ""No SD interrupt controller""; + end if; + + Ensure_Card_Informations (This); + + -- Flush the data cache + Cortex_M.Cache.Clean_DCache + (Start => Data (Data'First)'Address, + Len => Data'Length); + + This.SD_Int.Set_Transfer_State (This); + + Ret := Write_Blocks_DMA + (This, + Block_Number * 512, + Data); + -- this always leaves the last 12 byte standing. Why? + -- also...NDTR is not what it should be. + + if Ret /= OK then + This.TX_DMA_Int.Clear_Transfer_State; + This.SD_Int.Clear_Transfer_State; + This.TX_DMA_Int.Abort_Transfer (DMA_Err); + + return False; + end if; + + This.TX_DMA_Int.Wait_For_Completion (DMA_Err); -- this unblocks + This.SD_Int.Wait_Transfer (Ret); -- TX underrun! + + -- this seems slow. Do we have to wait? + loop + -- FIXME: some people claim, that this goes wrong with multiblock, see + -- http://blog.frankvh.com/2011/09/04/stm32f2xx-sdio-sd-card-interface/ + exit when not Get_Flag (This, TX_Active); + end loop; + + if Last_Operation (This) = + Write_Multiple_Blocks_Operation + then + Ret := Stop_Transfer (This); + end if; + + Clear_All_Status (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream); + Disable (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream); + + declare + Data_Incomplete : constant Boolean := + This.TX_DMA_Int.Buffer_Error and then + Items_Transferred (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream) + /= Data'Length / 4; + begin + return Ret = OK + and then DMA_Err = DMA_No_Error + and then not Data_Incomplete;" +"function To_Word is new Ada.Unchecked_Conversion (System.Address, UInt32);","function Offset (Buffer : DMA2D_Buffer; + X, Y : Integer) return UInt32 with Inline_Always; + + DMA2D_Init_Transfer_Int : DMA2D_Sync_Procedure := null; + DMA2D_Wait_Transfer_Int : DMA2D_Sync_Procedure := null; + + ------------------ + -- DMA2D_DeInit -- + ------------------ + + procedure DMA2D_DeInit is + begin + RCC_Periph.AHB1ENR.DMA2DEN := False; + DMA2D_Init_Transfer_Int := null; + DMA2D_Wait_Transfer_Int := null; + end DMA2D_DeInit; + + ---------------- + -- DMA2D_Init -- + ---------------- + + procedure DMA2D_Init + (Init : DMA2D_Sync_Procedure; + Wait : DMA2D_Sync_Procedure) + is + begin + if DMA2D_Init_Transfer_Int = Init then + return; + end if; + + DMA2D_DeInit; + + DMA2D_Init_Transfer_Int := Init; + DMA2D_Wait_Transfer_Int := Wait; + + RCC_Periph.AHB1ENR.DMA2DEN := True; + RCC_Periph.AHB1RSTR.DMA2DRST := True; + RCC_Periph.AHB1RSTR.DMA2DRST := False; + end DMA2D_Init; + + ------------ + -- Offset -- + ------------ + + function Offset (Buffer : DMA2D_Buffer; + X, Y : Integer) return UInt32 + is + Off : constant UInt32 := UInt32 (X + Buffer.Width * Y); + begin + case Buffer.Color_Mode is + when ARGB8888 => + return 4 * Off; + when RGB888 => + return 3 * Off; + when ARGB1555 | ARGB4444 | RGB565 | AL88 => + return 2 * Off; + when L8 | AL44 | A8 => + return Off; + when L4 | A4 => + return Off / 2; + end case; + end Offset; + + ---------------- + -- DMA2D_Fill -- + ---------------- + + procedure DMA2D_Fill + (Buffer : DMA2D_Buffer; + Color : UInt32; + Synchronous : Boolean := False) + is + function Conv is new Ada.Unchecked_Conversion (UInt32, OCOLR_Register); + begin + DMA2D_Wait_Transfer_Int.all; + + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (R2M); + DMA2D_Periph.OPFCCR.CM := As_UInt3 (Buffer.Color_Mode); + DMA2D_Periph.OCOLR := Conv (Color); + DMA2D_Periph.OMAR := To_Word (Buffer.Addr); + DMA2D_Periph.OOR := (LO => 0, others => <>); + DMA2D_Periph.NLR := (NL => UInt16 (Buffer.Height), + PL => UInt14 (Buffer.Width), + others => <>); + + DMA2D_Init_Transfer_Int.all; + + if Synchronous then + DMA2D_Wait_Transfer_Int.all; + end if; + end DMA2D_Fill; + + --------------------- + -- DMA2D_Fill_Rect -- + --------------------- + + procedure DMA2D_Fill_Rect + (Buffer : DMA2D_Buffer; + Color : UInt32; + X : Integer; + Y : Integer; + Width : Integer; + Height : Integer; + Synchronous : Boolean := False) + is + function Conv is new Ada.Unchecked_Conversion (UInt32, OCOLR_Register); + Off : constant UInt32 := Offset (Buffer, X, Y); + + begin + DMA2D_Wait_Transfer_Int.all; + + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (R2M); + DMA2D_Periph.OPFCCR := + (CM => DMA2D_Color_Mode'Enum_Rep (Buffer.Color_Mode), + others => <>); + DMA2D_Periph.OCOLR := Conv (Color); + DMA2D_Periph.OMAR := To_Word (Buffer.Addr) + Off; + DMA2D_Periph.OOR.LO := UInt14 (Buffer.Width - Width); + DMA2D_Periph.NLR := + (NL => UInt16 (Height), PL => UInt14 (Width), others => <>); + + DMA2D_Init_Transfer_Int.all; + if Synchronous then + DMA2D_Wait_Transfer_Int.all; + end if; + end DMA2D_Fill_Rect; + + --------------------- + -- DMA2D_Draw_Rect -- + --------------------- + + procedure DMA2D_Draw_Rect + (Buffer : DMA2D_Buffer; + Color : UInt32; + X : Integer; + Y : Integer; + Width : Integer; + Height : Integer) + is + begin + DMA2D_Draw_Horizontal_Line (Buffer, Color, X, Y, Width); + DMA2D_Draw_Horizontal_Line (Buffer, Color, X, Y + Height - 1, Width); + DMA2D_Draw_Vertical_Line (Buffer, Color, X, Y, Height); + DMA2D_Draw_Vertical_Line (Buffer, Color, X + Width - 1, Y, Height, True); + end DMA2D_Draw_Rect; + + --------------------- + -- DMA2D_Copy_Rect -- + --------------------- + + procedure DMA2D_Copy_Rect + (Src_Buffer : DMA2D_Buffer; + X_Src : Natural; + Y_Src : Natural; + Dst_Buffer : DMA2D_Buffer; + X_Dst : Natural; + Y_Dst : Natural; + Bg_Buffer : DMA2D_Buffer; + X_Bg : Natural; + Y_Bg : Natural; + Width : Natural; + Height : Natural; + Synchronous : Boolean := False) + is + Src_Off : constant UInt32 := Offset (Src_Buffer, X_Src, Y_Src); + Dst_Off : constant UInt32 := Offset (Dst_Buffer, X_Dst, Y_Dst); + begin + DMA2D_Wait_Transfer_Int.all; + + if Bg_Buffer /= Null_Buffer then + -- PFC and blending + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (M2M_BLEND); + + elsif Src_Buffer.Color_Mode = Dst_Buffer.Color_Mode then + -- Direct memory transfer + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (M2M); + else + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (M2M_PFC); + end if; + + -- SOURCE CONFIGURATION + DMA2D_Periph.FGPFCCR := + (CM => DMA2D_Color_Mode'Enum_Rep (Src_Buffer.Color_Mode), + AM => DMA2D_AM'Enum_Rep (NO_MODIF), + ALPHA => 255, + others => <>); + + if Src_Buffer.Color_Mode = L8 or else Src_Buffer.Color_Mode = L4 then + + if Src_Buffer.CLUT_Addr = System.Null_Address then + raise Program_Error with ""Source CLUT address required""; + end if; + + DMA2D_Periph.FGCMAR := To_Word (Src_Buffer.CLUT_Addr); + + DMA2D_Periph.FGCMAR := To_Word (Src_Buffer.CLUT_Addr); + DMA2D_Periph.FGPFCCR.CS := (case Src_Buffer.Color_Mode is + when L8 => 2**8 - 1, + when L4 => 2**4 - 1, + when others => 0); + -- Set CLUT mode to RGB888 + DMA2D_Periph.FGPFCCR.CCM := Src_Buffer.CLUT_Color_Mode = RGB888; + + -- Start loading the CLUT + DMA2D_Periph.FGPFCCR.START := True; + + while DMA2D_Periph.FGPFCCR.START loop + -- Wait for CLUT loading... + null; + end loop; + end if; + + DMA2D_Periph.FGOR := (LO => UInt14 (Src_Buffer.Width - Width), + others => <>); + DMA2D_Periph.FGMAR := To_Word (Src_Buffer.Addr) + Src_Off; + + if Bg_Buffer /= Null_Buffer then + declare + Bg_Off : constant UInt32 := Offset (Bg_Buffer, X_Bg, Y_Bg); + begin + DMA2D_Periph.BGPFCCR.CM := + DMA2D_Color_Mode'Enum_Rep (Bg_Buffer.Color_Mode); + DMA2D_Periph.BGMAR := To_Word (Bg_Buffer.Addr) + Bg_Off; + DMA2D_Periph.BGPFCCR.CS := 0; + DMA2D_Periph.BGPFCCR.START := False; + DMA2D_Periph.BGOR := + (LO => UInt14 (Bg_Buffer.Width - Width), others => <>); + + if Bg_Buffer.Color_Mode = L8 or else Bg_Buffer.Color_Mode = L4 then + + if Bg_Buffer.CLUT_Addr = System.Null_Address then + raise Program_Error with ""Background CLUT address required""; + end if; + + DMA2D_Periph.BGCMAR := To_Word (Bg_Buffer.CLUT_Addr); + DMA2D_Periph.BGPFCCR.CS := (case Bg_Buffer.Color_Mode is + when L8 => 2**8 - 1, + when L4 => 2**4 - 1, + when others => 0); + -- Set CLUT mode to RGB888 + DMA2D_Periph.BGPFCCR.CCM := Bg_Buffer.CLUT_Color_Mode = RGB888; + + -- Start loading the CLUT + DMA2D_Periph.BGPFCCR.START := True; + + while DMA2D_Periph.BGPFCCR.START loop + -- Wait for CLUT loading... + null; + end loop; + end if;" +procedure Demo_Timer_PWM is -- low-level demo of the PWM capabilities,"Period : constant := 1000; + + Output_Channel : constant Timer_Channel := Channel_2; + -- The LED driven by this example is determined by the channel selected. + -- That is so because each channel of Timer_4 is connected to a specific + -- LED in the alternate function configuration on this board. We will + -- initialize all of the LEDs to be in the AF mode for Timer_4. The + -- particular channel selected is completely arbitrary, as long as the + -- selected GPIO port/pin for the LED matches the selected channel. + -- + -- Channel_1 is connected to the green LED. + -- Channel_2 is connected to the orange LED. + -- Channel_3 is connected to the red LED. + -- Channel_4 is connected to the blue LED. + + -------------------- + -- Configure_LEDs -- + -------------------- + + procedure Configure_LEDs; + + procedure Configure_LEDs is + begin + Enable_Clock (GPIO_D); + + Configure_IO + (All_LEDs, + (Mode_AF, + AF => GPIO_AF_TIM4_2, + AF_Speed => Speed_50MHz, + AF_Output_Type => Push_Pull, + Resistors => Floating)); + end Configure_LEDs; + + -- The SFP run-time library for these boards is intended for certified + -- environments and so does not contain the full set of facilities defined + -- by the Ada language. The elementary functions are not included, for + -- example. In contrast, the Ravenscar ""full"" run-times do have these + -- functions. + + function Sine (Input : Long_Float) return Long_Float; + + -- Therefore there are four choices: 1) use the ""ravescar-full-stm32f4"" + -- runtime library, 2) pull the sources for the language-defined elementary + -- function package into the board's run-time library and rebuild the + -- run-time, 3) pull the sources for those packages into the source + -- directory of your application and rebuild your application, or 4) roll + -- your own approximation to the functions required by your application. + + -- In this demonstration we roll our own approximation to the sine function + -- so that it doesn't matter which runtime library is used. + + function Sine (Input : Long_Float) return Long_Float is + Pi : constant Long_Float := 3.14159_26535_89793_23846; + X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0); + B : constant Long_Float := 4.0 / Pi; + C : constant Long_Float := (-4.0) / (Pi * Pi); + Y : constant Long_Float := B * X + C * X * abs (X); + P : constant Long_Float := 0.225; + begin + return P * (Y * abs (Y) - Y) + Y; + end Sine; + + -- We use the sine function to drive the power applied to the LED, thereby + -- making the LED increase and decrease in brightness. We attach the timer + -- to the LED and then control how much power is supplied by changing the + -- value of the timer's output compare register. The sine function drives + -- that value, thus the waxing/waning effect. + +begin + Configure_LEDs; + + Enable_Clock (Timer_4); + + Reset (Timer_4); + + Configure + (Timer_4, + Prescaler => 1, + Period => Period, + Clock_Divisor => Div1, + Counter_Mode => Up); + + Configure_Channel_Output + (Timer_4, + Channel => Output_Channel, + Mode => PWM1, + State => Enable, + Pulse => 0, + Polarity => High); + + Set_Autoreload_Preload (Timer_4, True); + + Enable_Channel (Timer_4, Output_Channel); + + Enable (Timer_4); + + declare + Arg : Long_Float := 0.0; + Pulse : UInt16; + Increment : constant Long_Float := 0.00003; + -- The Increment value controls the rate at which the brightness + -- increases and decreases. The value is more or less arbitrary, but + -- note that the effect of optimization is observable. + begin + loop + Pulse := UInt16 (Long_Float (Period / 2) * (1.0 + Sine (Arg))); + Set_Compare_Value (Timer_4, Output_Channel, Pulse); + Arg := Arg + Increment; + end loop;" +procedure Demo_PWM_ADT is -- demo the higher-level PWM abstract data type,"Selected_Timer : STM32.Timers.Timer renames Timer_4; + -- NOT arbitrary! We drive the on-board LEDs that are tied to the channels + -- of Timer_4 on some boards. Not all boards have this association. If you + -- use a different board, select a GPIO point connected to your selected + -- timer and drive that instead. + + Timer_AF : constant STM32.GPIO_Alternate_Function := GPIO_AF_TIM4_2; + -- Note that this value MUST match the corresponding timer selected! + + Output_Channel : constant Timer_Channel := Channel_2; -- arbitrary + -- The LED driven by this example is determined by the channel selected. + -- That is so because each channel of Timer_4 is connected to a specific + -- LED in the alternate function configuration on this board. We will + -- initialize all of the LEDs to be in the AF mode. The + -- particular channel selected is completely arbitrary, as long as the + -- selected GPIO port/pin for the LED matches the selected channel. + -- + -- Channel_1 is connected to the green LED. + -- Channel_2 is connected to the orange LED. + -- Channel_3 is connected to the red LED. + -- Channel_4 is connected to the blue LED. + LED_For : constant array (Timer_Channel) of User_LED := + (Channel_1 => Green_LED, + Channel_2 => Orange_LED, + Channel_3 => Red_LED, + Channel_4 => Blue_LED); + + Requested_Frequency : constant Hertz := 30_000; -- arbitrary + + Power_Control : PWM_Modulator; + + -- The SFP run-time library for these boards is intended for certified + -- environments and so does not contain the full set of facilities defined + -- by the Ada language. The elementary functions are not included, for + -- example. In contrast, the Ravenscar ""full"" run-times do have these + -- functions. + function Sine (Input : Long_Float) return Long_Float; + + -- Therefore there are four choices: 1) use the ""ravescar-full-stm32f4"" + -- runtime library, 2) pull the sources for the language-defined elementary + -- function package into the board's run-time library and rebuild the + -- run-time, 3) pull the sources for those packages into the source + -- directory of your application and rebuild your application, or 4) roll + -- your own approximation to the functions required by your application. + + -- In this demonstration we roll our own approximation to the sine function + -- so that it doesn't matter which runtime library is used. + + function Sine (Input : Long_Float) return Long_Float is + Pi : constant Long_Float := 3.14159_26535_89793_23846; + X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0); + B : constant Long_Float := 4.0 / Pi; + C : constant Long_Float := (-4.0) / (Pi * Pi); + Y : constant Long_Float := B * X + C * X * abs (X); + P : constant Long_Float := 0.225; + begin + return P * (Y * abs (Y) - Y) + Y; + end Sine; + + -- We use the sine function to drive the power applied to the LED, thereby + -- making the LED increase and decrease in brightness. We attach the timer + -- to the LED and then control how much power is supplied by changing the + -- value of the timer's output compare register. The sine function drives + -- that value, thus the waxing/waning effect. + +begin + Configure_PWM_Timer (Selected_Timer'Access, Requested_Frequency); + + Power_Control.Attach_PWM_Channel + (Selected_Timer'Access, + Output_Channel, + LED_For (Output_Channel), + Timer_AF); + + Power_Control.Enable_Output; + + declare + Arg : Long_Float := 0.0; + Value : Percentage; + Increment : constant Long_Float := 0.00003; + -- The Increment value controls the rate at which the brightness + -- increases and decreases. The value is more or less arbitrary, but + -- note that the effect of compiler optimization is observable. + begin + loop + Value := Percentage (50.0 * (1.0 + Sine (Arg))); + Power_Control.Set_Duty_Cycle (Value); + Arg := Arg + Increment; + end loop;" +procedure Demo_DAC_Basic is,"Output_Channel : constant DAC_Channel := Channel_1; -- arbitrary + + procedure Configure_DAC_GPIO (Output_Channel : DAC_Channel); + -- Once the channel is enabled, the corresponding GPIO pin is automatically + -- connected to the analog converter output. However, in order to avoid + -- parasitic consumption, the PA4 pin (Channel_1) or PA5 pin (Channel_2) + -- should first be configured to analog mode. See the note in the RM, page + -- 431. + + procedure Print (Value : UInt32); + -- Prints the image of the arg at a fixed location + + procedure Await_Button; + -- Wait for the user to press and then release the blue user button + + ----------- + -- Print -- + ----------- + + procedure Print (Value : UInt32) is + Value_Image : constant String := Value'Img; + begin + LCD_Std_Out.Put (170, 52, Value_Image (2 .. Value_Image'Last) & "" ""); + end Print; + + ------------------ + -- Await_Button -- + ------------------ + + procedure Await_Button is + begin + Await_Pressed : loop + exit Await_Pressed when Set (User_Button_Point); + end loop Await_Pressed; + + Await_Released : loop + exit Await_Released when not Set (User_Button_Point); + end loop Await_Released; + end Await_Button; + + ------------------------ + -- Configure_DAC_GPIO -- + ------------------------ + + procedure Configure_DAC_GPIO (Output_Channel : DAC_Channel) is + Output : constant GPIO_Point := (if Output_Channel = Channel_1 + then DAC_Channel_1_IO + else DAC_Channel_2_IO); + begin + Enable_Clock (Output); + Configure_IO (Output, (Mode => Mode_Analog, Resistors => Floating)); + end Configure_DAC_GPIO; + +begin + Initialize_LEDs; + All_LEDs_Off; + + LCD_Std_Out.Clear_Screen; + + Configure_User_Button_GPIO; + + Configure_DAC_GPIO (Output_Channel); + + Enable_Clock (DAC_1); + + Reset (DAC_1); + + Select_Trigger (DAC_1, Output_Channel, Software_Trigger); + + Enable_Trigger (DAC_1, Output_Channel); + + Enable (DAC_1, Output_Channel); + + declare + Value : UInt32 := 0; + Percent : UInt32; + + Resolution : constant DAC_Resolution := DAC_Resolution_12_Bits; + -- Arbitrary, change as desired. Counts will automatically adjust. + + Max_Counts : constant UInt32 := (if Resolution = DAC_Resolution_12_Bits + then Max_12bit_Resolution + else Max_8bit_Resolution); + begin + Put (0, 0, ""VRef+ is 2.95V""); -- measured + Put (0, 25, ""Button advances""); + Put (0, 52, ""Current %:""); + loop + for K in UInt32 range 0 .. 10 loop + Percent := K * 10; + Print (Percent); + + Value := (Percent * Max_Counts) / 100; + + Set_Output + (DAC_1, + Output_Channel, + Value, + Resolution, + Right_Aligned); + + Trigger_Conversion_By_Software (DAC_1, Output_Channel); + + Await_Button; + end loop; + end loop;" +procedure Demo_CRC is,"Checksum_CPU : UInt32 := 0; + -- the checksum obtained by calling a routine that uses the CPU to transfer + -- the memory block to the CRC processor + + Checksum_DMA : UInt32 := 0; + -- the checksum obtained by calling a routine that uses DMA to transfer the + -- memory block to the CRC processor + + -- see the STM32Cube_FW_F4_V1.6.0\Projects\ CRC example for data and + -- expected CRC checksum value + + Section1 : constant Block_32 := + (16#00001021#, 16#20423063#, 16#408450A5#, 16#60C670E7#, 16#9129A14A#, 16#B16BC18C#, + 16#D1ADE1CE#, 16#F1EF1231#, 16#32732252#, 16#52B54294#, 16#72F762D6#, 16#93398318#, + 16#A35AD3BD#, 16#C39CF3FF#, 16#E3DE2462#, 16#34430420#, 16#64E674C7#, 16#44A45485#, + 16#A56AB54B#, 16#85289509#, 16#F5CFC5AC#, 16#D58D3653#, 16#26721611#, 16#063076D7#, + 16#569546B4#, 16#B75BA77A#, 16#97198738#, 16#F7DFE7FE#, 16#C7BC48C4#, 16#58E56886#, + 16#78A70840#, 16#18612802#, 16#C9CCD9ED#, 16#E98EF9AF#, 16#89489969#, 16#A90AB92B#, + 16#4AD47AB7#, 16#6A961A71#, 16#0A503A33#, 16#2A12DBFD#, 16#FBBFEB9E#, 16#9B798B58#, + 16#BB3BAB1A#, 16#6CA67C87#, 16#5CC52C22#, 16#3C030C60#, 16#1C41EDAE#, 16#FD8FCDEC#, + 16#AD2ABD0B#, 16#8D689D49#, 16#7E976EB6#, 16#5ED54EF4#, 16#2E321E51#, 16#0E70FF9F#); + + Section2 : constant Block_32 := + (16#EFBEDFDD#, 16#CFFCBF1B#, 16#9F598F78#, 16#918881A9#, 16#B1CAA1EB#, 16#D10CC12D#, + 16#E16F1080#, 16#00A130C2#, 16#20E35004#, 16#40257046#, 16#83B99398#, 16#A3FBB3DA#, + 16#C33DD31C#, 16#E37FF35E#, 16#129022F3#, 16#32D24235#, 16#52146277#, 16#7256B5EA#, + 16#95A88589#, 16#F56EE54F#, 16#D52CC50D#, 16#34E224C3#, 16#04817466#, 16#64475424#, + 16#4405A7DB#, 16#B7FA8799#, 16#E75FF77E#, 16#C71DD73C#, 16#26D336F2#, 16#069116B0#, + 16#76764615#, 16#5634D94C#, 16#C96DF90E#, 16#E92F99C8#, 16#B98AA9AB#, 16#58444865#, + 16#78066827#, 16#18C008E1#, 16#28A3CB7D#, 16#DB5CEB3F#, 16#FB1E8BF9#, 16#9BD8ABBB#, + 16#4A755A54#, 16#6A377A16#, 16#0AF11AD0#, 16#2AB33A92#, 16#ED0FDD6C#, 16#CD4DBDAA#, + 16#AD8B9DE8#, 16#8DC97C26#, 16#5C644C45#, 16#3CA22C83#, 16#1CE00CC1#, 16#EF1FFF3E#, + 16#DF7CAF9B#, 16#BFBA8FD9#, 16#9FF86E17#, 16#7E364E55#, 16#2E933EB2#, 16#0ED11EF0#); + + -- expected CRC value for the data above is 379E9F06 hex, or 933142278 dec + Expected_Checksum : constant UInt32 := 933142278; + + Next_DMA_Interrupt : DMA_Interrupt; + + procedure Panic with No_Return; + -- flash the on-board LEDs, indefinitely, to indicate a failure + + procedure Panic is + begin + loop + Toggle_LEDs (All_LEDs); + delay until Clock + Milliseconds (100); + end loop; + end Panic; + +begin + Clear_Screen; + Initialize_LEDs; + + Enable_Clock (CRC_Unit); + + -- get the checksum using the CPU to transfer memory to the CRC processor; + -- verify it is the expected value + + Update_CRC (CRC_Unit, Input => Section1, Output => Checksum_CPU); + Update_CRC (CRC_Unit, Input => Section2, Output => Checksum_CPU); + + Put_Line (""CRC:"" & Checksum_CPU'Img); + + if Checksum_CPU /= Expected_Checksum then + Panic; + end if; + + -- get the checksum using DMA to transfer memory to the CRC processor + + Enable_Clock (Controller); + + Reset (Controller); + + Reset_Calculator (CRC_Unit); + + Update_CRC (CRC_Unit, Controller'Access, Stream, Input => Section1); + + DMA_IRQ_Handler.Await_Event (Next_DMA_Interrupt); + + if Next_DMA_Interrupt /= Transfer_Complete_Interrupt then + Panic; + end if; + + -- In this code fragment we use the approach suited for the case in which + -- we are calculating the CRC for a section of system memory rather than a + -- block of application data. We pretend that Section2 is a memory section. + -- All we need is a known starting address and a known length. Given that, + -- we can create a view of it as if it is an object of type Block_32 (or + -- whichever block type is appropriate). + declare + subtype Memory_Section is Block_32 (1 .. Section2'Length); + type Section_Pointer is access all Memory_Section with Storage_Size => 0; + function As_Memory_Section_Reference is new Ada.Unchecked_Conversion + (Source => System.Address, Target => Section_Pointer); + begin + Update_CRC + (CRC_Unit, + Controller'Access, + Stream, + Input => As_Memory_Section_Reference (Section2'Address).all);" +procedure DSB is,"begin + Asm (""dsb"", Volatile => True); + end DSB; + + --------- + -- ISB -- + --------- + + procedure ISB is + begin + Asm (""isb"", Volatile => True); + end ISB; + + ----------------------- + -- Cache_Maintenance -- + ----------------------- + + procedure Cache_Maintenance + (Start : System.Address; + Len : Natural) + is + begin + if not D_Cache_Enabled then + return; + end if; + + declare + function To_U32 is new Ada.Unchecked_Conversion + (System.Address, UInt32); + + Op_Size : Integer_32 := Integer_32 (Len); + Op_Addr : UInt32 := To_U32 (Start); + Reg : UInt32 with Volatile, Address => Reg_Address; + + begin + DSB; + + while Op_Size > 0 loop + Reg := Op_Addr; + Op_Addr := Op_Addr + Data_Cache_Line_Size; + Op_Size := Op_Size - Integer_32 (Data_Cache_Line_Size); + end loop; + + DSB; + ISB;" +"function To_Char is new Ada.Unchecked_Conversion (Source => UInt8,","Target => Character); + function To_UInt8 is new Ada.Unchecked_Conversion (Source => Character, + Target => UInt8); + + procedure Write (This : in out TP_Device; Cmd : String); + procedure Read (This : in out TP_Device; Str : out String); + + ----------- + -- Write -- + ----------- + + procedure Write (This : in out TP_Device; Cmd : String) is + Status : UART_Status; + Data : UART_Data_8b (Cmd'Range); + begin + + for Index in Cmd'Range loop + Data (Index) := To_UInt8 (Cmd (Index)); + end loop; + + This.Port.Transmit (Data, Status); + + if Status /= Ok then + -- No error handling... + raise Program_Error; + end if; + -- This.Time.Delay_Microseconds ((11 * 1000000 / 19_2000) + Cmd'Length); + end Write; + + ---------- + -- Read -- + ---------- + + procedure Read (This : in out TP_Device; Str : out String) is + Status : UART_Status; + Data : UART_Data_8b (Str'Range); + begin + This.Port.Receive (Data, Status); + if Status /= Ok then + -- No error handling... + raise Program_Error; + end if; + + for Index in Str'Range loop + Str (Index) := To_Char (Data (Index)); + end loop; + end Read; + + ---------------------- + -- Set_Line_Spacing -- + ---------------------- + + procedure Set_Line_Spacing (This : in out TP_Device; Spacing : UInt8) is + begin + Write (This, ASCII.ESC & '3' & To_Char (Spacing)); + end Set_Line_Spacing; + + --------------- + -- Set_Align -- + --------------- + + procedure Set_Align (This : in out TP_Device; Align : Text_Align) is + Mode : Character; + begin + case Align is + when Left => Mode := '0'; + when Center => Mode := '1'; + when Right => Mode := '2'; + end case; + Write (This, ASCII.ESC & 'a' & Mode); + end Set_Align; + + ---------------------- + -- Set_Font_Enlarge -- + ---------------------- + + procedure Set_Font_Enlarge (This : in out TP_Device; Height, Width : Boolean) is + Data : UInt8 := 0; + begin + if Height then + Data := Data or 16#01#; + end if; + if Width then + Data := Data or 16#10#; + end if; + Write (This, ASCII.GS & '!' & To_Char (Data)); + end Set_Font_Enlarge; + + -------------- + -- Set_Bold -- + -------------- + + procedure Set_Bold (This : in out TP_Device; Bold : Boolean) is + begin + Write (This, ASCII.ESC & 'E' & To_Char (if Bold then 1 else 0)); + end Set_Bold; + + ---------------------- + -- Set_Double_Width -- + ---------------------- + + procedure Set_Double_Width (This : in out TP_Device; Double : Boolean) is + begin + if Double then + Write (This, ASCII.ESC & ASCII.SO); + else + Write (This, ASCII.ESC & ASCII.DC4); + end if; + end Set_Double_Width; + + ---------------- + -- Set_UpDown -- + ---------------- + + procedure Set_UpDown (This : in out TP_Device; UpDown : Boolean) is + begin + Write (This, ASCII.ESC & '{' & To_Char (if UpDown then 1 else 0)); + end Set_UpDown; + + ------------------ + -- Set_Reversed -- + ------------------ + + procedure Set_Reversed (This : in out TP_Device; Reversed : Boolean) is + begin + Write (This, ASCII.GS & 'B' & To_Char (if Reversed then 1 else 0)); + end Set_Reversed; + + -------------------------- + -- Set_Underline_Height -- + -------------------------- + + procedure Set_Underline_Height (This : in out TP_Device; Height : Underline_Height) is + begin + Write (This, ASCII.ESC & '-' & To_Char (Height)); + end Set_Underline_Height; + + ----------------------- + -- Set_Character_Set -- + ----------------------- + + procedure Set_Character_Set (This : in out TP_Device; Set : Character_Set) is + begin + Write (This, ASCII.ESC & 't' & To_Char (Character_Set'Pos (Set))); + end Set_Character_Set; + + ---------- + -- Feed -- + ---------- + + procedure Feed (This : in out TP_Device; Rows : UInt8) is + begin + Write (This, ASCII.ESC & 'd' & To_Char (Rows)); + end Feed; + + ------------------ + -- Print_Bitmap -- + ------------------ + + procedure Print_Bitmap (This : in out TP_Device; + BM : Thermal_Printer_Bitmap) + is + Nbr_Of_Rows : constant Natural := BM'Length (2); + Nbr_Of_Columns : constant Natural := BM'Length (1); + Str : String (1 .. Nbr_Of_Columns / 8); + begin + + Write (This, ASCII.DC2 & 'v' & + To_Char (UInt8 (Nbr_Of_Rows rem 256)) & + To_Char (UInt8 (Nbr_Of_Rows / 256))); + + for Row in 0 .. Nbr_Of_Rows - 1 loop + for Colum in 0 .. (Nbr_Of_Columns / 8) - 1 loop + declare + BM_Index : constant Natural := BM'First (1) + Colum * 8; + Str_Index : constant Natural := Str'First + Colum; + B : UInt8 := 0; + begin + for X in 0 .. 7 loop + B := B or (if BM (BM_Index + X, + BM'First (2) + Row) + then 2**X else 0); + end loop; + Str (Str_Index) := To_Char (B);" +function As_UInt8 is new Ada.Unchecked_Conversion,"(Source => High_Pass_Filter_Mode, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => High_Pass_Cutoff_Frequency, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Power_Mode_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Output_Data_Rate_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Axes_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Bandwidth_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Block_Data_Update_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Endian_Data_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Full_Scale_Selection, Target => UInt8); + + type Angle_Rate_Pointer is access all Angle_Rate with Storage_Size => 0; + + function As_Angle_Rate_Pointer is new Ada.Unchecked_Conversion + (Source => System.Address, Target => Angle_Rate_Pointer); + -- So that we can treat the address of a UInt8 as a pointer to a two-UInt8 + -- sequence representing a signed integer quantity. + + procedure Swap2 (Location : System.Address) with Inline; + -- Swaps the two UInt8s at Location and Location+1 + + procedure SPI_Mode (This : Three_Axis_Gyroscope; Enabled : Boolean); + -- Enable or disable SPI mode communication with the device. This is named + -- ""chip select"" in other demos/examples. + + ---------------- + -- Initialize -- + ---------------- + + procedure Initialize + (This : in out Three_Axis_Gyroscope; + Port : Any_SPI_Port; + Chip_Select : Any_GPIO_Point) + is + begin + This.Port := Port; + This.CS := Chip_Select; + + SPI_Mode (This, Enabled => False); + end Initialize; + + ----------------- + -- SPI_Mode -- + ----------------- + + procedure SPI_Mode (This : Three_Axis_Gyroscope; Enabled : Boolean) is + -- When the pin is low (cleared), the device is in SPI mode. + -- When the pin is high (set), the device is in I2C mode. + -- We want SPI mode communication, so Enabled, when True, + -- means we must drive the pin low. + begin + if Enabled then + This.CS.Clear; + else + This.CS.Set; + end if; + end SPI_Mode; + + ----------- + -- Write -- + ----------- + + procedure Write (This : Three_Axis_Gyroscope; Addr : Register; Data : UInt8) + is + Status : SPI_Status; + begin + SPI_Mode (This, Enabled => True); + + This.Port.Transmit (SPI_Data_8b'(1 => UInt8 (Addr)), Status); + if Status /= Ok then + raise Program_Error; + end if; + + This.Port.Transmit (SPI_Data_8b'(1 => Data), Status); + if Status /= Ok then + raise Program_Error; + end if; + + SPI_Mode (This, Enabled => False); + end Write; + + ---------- + -- Read -- + ---------- + + procedure Read + (This : Three_Axis_Gyroscope; + Addr : Register; + Data : out UInt8) + is + Status : SPI_Status; + Tmp_Data : SPI_Data_8b (1 .. 1); + begin + SPI_Mode (This, Enabled => True); + + This.Port.Transmit (SPI_Data_8b'(1 => UInt8 (Addr) or ReadWrite_CMD), + Status); + if Status /= Ok then + raise Program_Error; + end if; + + This.Port.Receive (Tmp_Data, Status); + if Status /= Ok then + raise Program_Error; + end if; + Data := Tmp_Data (Tmp_Data'First); + + SPI_Mode (This, Enabled => False); + end Read; + + ---------------- + -- Read_UInt8s -- + ---------------- + + procedure Read_UInt8s + (This : Three_Axis_Gyroscope; + Addr : Register; + Buffer : out SPI_Data_8b; + Count : Natural) + is + Index : Natural := Buffer'First; + Status : SPI_Status; + Tmp_Data : SPI_Data_8b (1 .. 1); + begin + SPI_Mode (This, Enabled => True); + + This.Port.Transmit + (SPI_Data_8b'(1 => UInt8 (Addr) or ReadWrite_CMD or MultiUInt8_CMD), + Status); + + if Status /= Ok then + raise Program_Error; + end if; + + for K in 1 .. Count loop + This.Port.Receive (Tmp_Data, Status); + if Status /= Ok then + raise Program_Error; + end if; + Buffer (Index) := Tmp_Data (Tmp_Data'First); + Index := Index + 1; + end loop; + + SPI_Mode (This, Enabled => False); + end Read_UInt8s; + + --------------- + -- Configure -- + --------------- + + procedure Configure + (This : in out Three_Axis_Gyroscope; + Power_Mode : Power_Mode_Selection; + Output_Data_Rate : Output_Data_Rate_Selection; + Axes_Enable : Axes_Selection; + Bandwidth : Bandwidth_Selection; + BlockData_Update : Block_Data_Update_Selection; + Endianness : Endian_Data_Selection; + Full_Scale : Full_Scale_Selection) + is + Ctrl1 : UInt8; + Ctrl4 : UInt8; + begin + Ctrl1 := As_UInt8 (Power_Mode) or + As_UInt8 (Output_Data_Rate) or + As_UInt8 (Axes_Enable) or + As_UInt8 (Bandwidth); + + Ctrl4 := As_UInt8 (BlockData_Update) or + As_UInt8 (Endianness) or + As_UInt8 (Full_Scale); + + Write (This, CTRL_REG1, Ctrl1); + Write (This, CTRL_REG4, Ctrl4); + end Configure; + + ----------- + -- Sleep -- + ----------- + + procedure Sleep (This : in out Three_Axis_Gyroscope) is + Ctrl1 : UInt8; + Sleep_Mode : constant := 2#1000#; -- per the Datasheet, Table 22, pg 32 + begin + Read (This, CTRL_REG1, Ctrl1); + Ctrl1 := Ctrl1 or Sleep_Mode; + Write (This, CTRL_REG1, Ctrl1); + end Sleep; + + -------------------------------- + -- Configure_High_Pass_Filter -- + -------------------------------- + + procedure Configure_High_Pass_Filter + (This : in out Three_Axis_Gyroscope; + Mode_Selection : High_Pass_Filter_Mode; + Cutoff_Frequency : High_Pass_Cutoff_Frequency) + is + Ctrl2 : UInt8; + begin + -- note that the two high-order bits must remain zero, per the datasheet + Ctrl2 := As_UInt8 (Mode_Selection) or As_UInt8 (Cutoff_Frequency); + Write (This, CTRL_REG2, Ctrl2); + end Configure_High_Pass_Filter; + + ----------------------------- + -- Enable_High_Pass_Filter -- + ----------------------------- + + procedure Enable_High_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- set HPen bit + Ctrl5 := Ctrl5 or HighPass_Filter_Enable; + Write (This, CTRL_REG5, Ctrl5); + end Enable_High_Pass_Filter; + + ------------------------------ + -- Disable_High_Pass_Filter -- + ------------------------------ + + procedure Disable_High_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- clear HPen bit + Ctrl5 := Ctrl5 and (not HighPass_Filter_Enable); + Write (This, CTRL_REG5, Ctrl5); + end Disable_High_Pass_Filter; + + ---------------------------- + -- Enable_Low_Pass_Filter -- + ---------------------------- + + procedure Enable_Low_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + Ctrl5 := Ctrl5 or LowPass_Filter_Enable; + Write (This, CTRL_REG5, Ctrl5); + end Enable_Low_Pass_Filter; + + ----------------------------- + -- Disable_Low_Pass_Filter -- + ----------------------------- + + procedure Disable_Low_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- clear HPen bit + Ctrl5 := Ctrl5 and (not LowPass_Filter_Enable); + Write (This, CTRL_REG5, Ctrl5); + end Disable_Low_Pass_Filter; + + --------------------- + -- Reference_Value -- + --------------------- + + function Reference_Value (This : Three_Axis_Gyroscope) return UInt8 is + Result : UInt8; + begin + Read (This, Reference, Result); + return Result; + end Reference_Value; + + ------------------- + -- Set_Reference -- + ------------------- + + procedure Set_Reference (This : in out Three_Axis_Gyroscope; Value : UInt8) is + begin + Write (This, Reference, Value); + end Set_Reference; + + ----------------- + -- Data_Status -- + ----------------- + + function Data_Status (This : Three_Axis_Gyroscope) return Gyro_Data_Status is + Result : UInt8; + function As_Gyro_Data_Status is + new Ada.Unchecked_Conversion (Source => UInt8, + Target => Gyro_Data_Status); + begin + Read (This, Status, Result); + return As_Gyro_Data_Status (Result); + end Data_Status; + + --------------- + -- Device_Id -- + --------------- + + function Device_Id (This : Three_Axis_Gyroscope) return UInt8 is + Result : UInt8; + begin + Read (This, Who_Am_I, Result); + return Result; + end Device_Id; + + ----------------- + -- Temperature -- + ----------------- + + function Temperature (This : Three_Axis_Gyroscope) return UInt8 is + Result : UInt8; + begin + Read (This, OUT_Temp, Result); + return Result; + end Temperature; + + ------------ + -- Reboot -- + ------------ + + procedure Reboot (This : Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- set the boot bit + Ctrl5 := Ctrl5 or Boot_Bit; + Write (This, CTRL_REG5, Ctrl5); + end Reboot; + + ---------------------------- + -- Full_Scale_Sensitivity -- + ---------------------------- + + function Full_Scale_Sensitivity (This : Three_Axis_Gyroscope) return Float is + Ctrl4 : UInt8; + Result : Float; + Fullscale_Selection : UInt8; + begin + Read (This, CTRL_REG4, Ctrl4); + + Fullscale_Selection := Ctrl4 and Fullscale_Selection_Bits; + + if Fullscale_Selection = L3GD20_Fullscale_250'Enum_Rep then + Result := Sensitivity_250dps; + elsif Fullscale_Selection = L3GD20_Fullscale_500'Enum_Rep then + Result := Sensitivity_500dps; + else + Result := Sensitivity_2000dps; + end if; + + return Result; + end Full_Scale_Sensitivity; + + ------------------------- + -- Get_Raw_Angle_Rates -- + ------------------------- + + procedure Get_Raw_Angle_Rates + (This : Three_Axis_Gyroscope; + Rates : out Angle_Rates) + is + + Ctrl4 : UInt8; + + UInt8s_To_Read : constant Integer := 6; -- ie, three 2-UInt8 integers + -- the number of UInt8s in an Angle_Rates record object + + Received : SPI_Data_8b (1 .. UInt8s_To_Read); + + begin + Read (This, CTRL_REG4, Ctrl4); + + Read_UInt8s (This, OUT_X_L, Received, UInt8s_To_Read); + -- The above has the effect of separate reads, as follows: + -- Read (This, OUT_X_L, Received (1)); + -- Read (This, OUT_X_H, Received (2)); + -- Read (This, OUT_Y_L, Received (3)); + -- Read (This, OUT_Y_H, Received (4)); + -- Read (This, OUT_Z_L, Received (5)); + -- Read (This, OUT_Z_H, Received (6)); + + if (Ctrl4 and Endian_Selection_Mask) = L3GD20_Big_Endian'Enum_Rep then + Swap2 (Received (1)'Address); + Swap2 (Received (3)'Address); + Swap2 (Received (5)'Address); + end if; + + Rates.X := As_Angle_Rate_Pointer (Received (1)'Address).all; + Rates.Y := As_Angle_Rate_Pointer (Received (3)'Address).all; + Rates.Z := As_Angle_Rate_Pointer (Received (5)'Address).all; + end Get_Raw_Angle_Rates; + + -------------------------- + -- Configure_Interrupt1 -- + -------------------------- + + procedure Configure_Interrupt1 + (This : in out Three_Axis_Gyroscope; + Triggers : Threshold_Event_List; + Latched : Boolean := False; + Active_Edge : Interrupt1_Active_Edge := L3GD20_Interrupt1_High_Edge; + Combine_Events : Boolean := False; + Sample_Count : Sample_Counter := 0) + is + Config : UInt8; + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 and 16#DF#; + Ctrl3 := Ctrl3 or Active_Edge'Enum_Rep; + Ctrl3 := Ctrl3 or INT1_Interrupt_Enable; + Write (This, CTRL_REG3, Ctrl3); + + if Sample_Count > 0 then + Set_Duration_Counter (This, Sample_Count); + end if; + + Config := 0; + + if Latched then + Config := Config or Int1_Latch_Enable_Bit; + end if; + + if Combine_Events then + Config := Config or Logically_And_Or_Events_Bit; + end if; + + for Event of Triggers loop + Config := Config or Axes_Interrupt_Enablers (Event.Axis); + end loop; + + Write (This, INT1_CFG, Config); + + for Event of Triggers loop + Set_Threshold (This, Event.Axis, Event.Threshold); + end loop; + end Configure_Interrupt1; + + ---------------------------- + -- Set_Interrupt_Pin_Mode -- + ---------------------------- + + procedure Set_Interrupt_Pin_Mode + (This : in out Three_Axis_Gyroscope; + Mode : Pin_Modes) + is + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 and (not Interrupt_Pin_Mode_Bit); + Ctrl3 := Ctrl3 or Mode'Enum_Rep; + Write (This, CTRL_REG3, Ctrl3); + end Set_Interrupt_Pin_Mode; + + ----------------------- + -- Enable_Interrupt1 -- + ----------------------- + + procedure Enable_Interrupt1 (This : in out Three_Axis_Gyroscope) is + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 or INT1_Interrupt_Enable; + Write (This, CTRL_REG3, Ctrl3); + end Enable_Interrupt1; + + ------------------------ + -- Disable_Interrupt1 -- + ------------------------ + + procedure Disable_Interrupt1 (This : in out Three_Axis_Gyroscope) is + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 and (not INT1_Interrupt_Enable); + Write (This, CTRL_REG3, Ctrl3); + end Disable_Interrupt1; + + ----------------------- + -- Interrupt1_Status -- + ----------------------- + + function Interrupt1_Source (This : Three_Axis_Gyroscope) return Interrupt1_Sources is + Result : UInt8; + function As_Interrupt_Source is new Ada.Unchecked_Conversion + (Source => UInt8, Target => Interrupt1_Sources); + begin + Read (This, INT1_SRC, Result); + return As_Interrupt_Source (Result); + end Interrupt1_Source; + + -------------------------- + -- Set_Duration_Counter -- + -------------------------- + + procedure Set_Duration_Counter + (This : in out Three_Axis_Gyroscope; + Value : Sample_Counter) + is + Wait_Bit : constant := 2#1000_0000#; + begin + Write (This, INT1_Duration, UInt8 (Value) or Wait_Bit); + end Set_Duration_Counter; + + ------------------ + -- Enable_Event -- + ------------------ + + procedure Enable_Event + (This : in out Three_Axis_Gyroscope; + Event : Axes_Interrupts) + is + Config : UInt8; + begin + Read (This, INT1_CFG, Config); + Config := Config or Axes_Interrupt_Enablers (Event); + Write (This, INT1_CFG, Config); + end Enable_Event; + + ------------------- + -- Disable_Event -- + ------------------- + + procedure Disable_Event + (This : in out Three_Axis_Gyroscope; + Event : Axes_Interrupts) + is + Config : UInt8; + begin + Read (This, INT1_CFG, Config); + Config := Config and (not Axes_Interrupt_Enablers (Event)); + Write (This, INT1_CFG, Config); + end Disable_Event; + + ------------------- + -- Set_Threshold -- + ------------------- + + procedure Set_Threshold + (This : in out Three_Axis_Gyroscope; + Event : Axes_Interrupts; + Value : Axis_Sample_Threshold) + is + begin + case Event is + when Z_High_Interrupt | Z_Low_Interrupt => + Write (This, INT1_TSH_ZL, UInt8 (Value)); + Write (This, INT1_TSH_ZH, UInt8 (Shift_Right (Value, 8))); + + when Y_High_Interrupt | Y_Low_Interrupt => + Write (This, INT1_TSH_YL, UInt8 (Value)); + Write (This, INT1_TSH_YH, UInt8 (Shift_Right (Value, 8))); + + when X_High_Interrupt | X_Low_Interrupt => + Write (This, INT1_TSH_XL, UInt8 (Value)); + Write (This, INT1_TSH_XH, UInt8 (Shift_Right (Value, 8))); + end case; + end Set_Threshold; + + ------------------- + -- Set_FIFO_Mode -- + ------------------- + + procedure Set_FIFO_Mode + (This : in out Three_Axis_Gyroscope; + Mode : FIFO_Modes) + is + FIFO : UInt8; + begin + Read (This, FIFO_CTRL, FIFO); + FIFO := FIFO and (not FIFO_Mode_Bits); -- clear the current bits + FIFO := FIFO or Mode'Enum_Rep; + Write (This, FIFO_CTRL, FIFO); + end Set_FIFO_Mode; + + ----------------- + -- Enable_FIFO -- + ----------------- + + procedure Enable_FIFO (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + Ctrl5 := Ctrl5 or FIFO_Enable_Bit; + Write (This, CTRL_REG5, Ctrl5); + end Enable_FIFO; + + ------------------ + -- Disable_FIFO -- + ------------------ + + procedure Disable_FIFO (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + Ctrl5 := Ctrl5 and (not FIFO_Enable_Bit); + Write (This, CTRL_REG5, Ctrl5); + end Disable_FIFO; + + ------------------------ + -- Set_FIFO_Watermark -- + ------------------------ + + procedure Set_FIFO_Watermark + (This : in out Three_Axis_Gyroscope; + Level : FIFO_Level) + is + Value : UInt8; + begin + Read (This, FIFO_CTRL, Value); + Value := Value and (not Watermark_Threshold_Bits); -- clear the bits + Value := Value or UInt8 (Level); + Write (This, FIFO_CTRL, Value); + end Set_FIFO_Watermark; + + ------------------------------ + -- Get_Raw_Angle_Rates_FIFO -- + ------------------------------ + + procedure Get_Raw_Angle_Rates_FIFO + (This : in out Three_Axis_Gyroscope; + Buffer : out Angle_Rates_FIFO_Buffer) + is + Ctrl4 : UInt8; + + Angle_Rate_Size : constant Integer := 6; -- UInt8s + UInt8s_To_Read : constant Integer := Buffer'Length * Angle_Rate_Size; + Received : SPI_Data_8b (0 .. UInt8s_To_Read - 1) + with Alignment => 2; + begin + Read (This, CTRL_REG4, Ctrl4); + + Read_UInt8s (This, OUT_X_L, Received, UInt8s_To_Read); + + if (Ctrl4 and Endian_Selection_Mask) = L3GD20_Big_Endian'Enum_Rep then + declare + J : Integer := 0; + begin + for K in Received'First .. Received'Last / 2 loop + Swap2 (Received (J)'Address); + J := J + 2; + end loop;" +function To_Map is new Ada.Unchecked_Conversion,"(SPAD_Map_Bytes, SPAD_Map); + function To_Bytes is new Ada.Unchecked_Conversion + (SPAD_Map, SPAD_Map_Bytes); + + SPAD_Count : UInt8; + SPAD_Is_Aperture : Boolean; + Ref_SPAD_Map_Bytes : SPAD_Map_Bytes; + Ref_SPAD_Map : SPAD_Map; + First_SPAD : UInt8; + SPADS_Enabled : UInt8; + Timing_Budget : UInt32; + + begin + Status := SPAD_Info (This, SPAD_Count, SPAD_Is_Aperture); + + if not Status then + return; + end if; + + Read + (This, REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_0, + Ref_SPAD_Map_Bytes, Status); + Ref_SPAD_Map := To_Map (Ref_SPAD_Map_Bytes); + + -- Set reference spads + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, REG_DYNAMIC_SPAD_REF_EN_START_OFFSET, + UInt8'(16#00#), Status); + end if; + if Status then + Write (This, REG_DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, + UInt8'(16#2C#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, REG_GLOBAL_CONFIG_REF_EN_START_SELECT, + UInt8'(16#B4#), Status); + end if; + + if Status then + if SPAD_Is_Aperture then + First_SPAD := 13; + else + First_SPAD := 1; + end if; + + SPADS_Enabled := 0; + + for J in UInt8 range 1 .. 48 loop + + if J < First_SPAD or else SPADS_Enabled = SPAD_Count then + -- This bit is lower than the first one that should be enabled, + -- or SPAD_Count bits have already been enabled, so zero this + -- bit + Ref_SPAD_Map (J) := False; + + elsif Ref_SPAD_Map (J) then + SPADS_Enabled := SPADS_Enabled + 1; + end if; + end loop; + end if; + + if Status then + Ref_SPAD_Map_Bytes := To_Bytes (Ref_SPAD_Map); + Write (This, REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_0, + Ref_SPAD_Map_Bytes, Status); + end if; + + -- Load tuning Settings + -- default tuning settings from vl53l0x_tuning.h + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#00#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#09#, UInt8'(16#00#), Status); + Write (This, 16#10#, UInt8'(16#00#), Status); + Write (This, 16#11#, UInt8'(16#00#), Status); + + Write (This, 16#24#, UInt8'(16#01#), Status); + Write (This, 16#25#, UInt8'(16#FF#), Status); + Write (This, 16#75#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#4E#, UInt8'(16#2C#), Status); + Write (This, 16#48#, UInt8'(16#00#), Status); + Write (This, 16#30#, UInt8'(16#20#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#30#, UInt8'(16#09#), Status); + Write (This, 16#54#, UInt8'(16#00#), Status); + Write (This, 16#31#, UInt8'(16#04#), Status); + Write (This, 16#32#, UInt8'(16#03#), Status); + Write (This, 16#40#, UInt8'(16#83#), Status); + Write (This, 16#46#, UInt8'(16#25#), Status); + Write (This, 16#60#, UInt8'(16#00#), Status); + Write (This, 16#27#, UInt8'(16#00#), Status); + Write (This, 16#50#, UInt8'(16#06#), Status); + Write (This, 16#51#, UInt8'(16#00#), Status); + Write (This, 16#52#, UInt8'(16#96#), Status); + Write (This, 16#56#, UInt8'(16#08#), Status); + Write (This, 16#57#, UInt8'(16#30#), Status); + Write (This, 16#61#, UInt8'(16#00#), Status); + Write (This, 16#62#, UInt8'(16#00#), Status); + Write (This, 16#64#, UInt8'(16#00#), Status); + Write (This, 16#65#, UInt8'(16#00#), Status); + Write (This, 16#66#, UInt8'(16#A0#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#22#, UInt8'(16#32#), Status); + Write (This, 16#47#, UInt8'(16#14#), Status); + Write (This, 16#49#, UInt8'(16#FF#), Status); + Write (This, 16#4A#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#7A#, UInt8'(16#0A#), Status); + Write (This, 16#7B#, UInt8'(16#00#), Status); + Write (This, 16#78#, UInt8'(16#21#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#23#, UInt8'(16#34#), Status); + Write (This, 16#42#, UInt8'(16#00#), Status); + Write (This, 16#44#, UInt8'(16#FF#), Status); + Write (This, 16#45#, UInt8'(16#26#), Status); + Write (This, 16#46#, UInt8'(16#05#), Status); + Write (This, 16#40#, UInt8'(16#40#), Status); + Write (This, 16#0E#, UInt8'(16#06#), Status); + Write (This, 16#20#, UInt8'(16#1A#), Status); + Write (This, 16#43#, UInt8'(16#40#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#34#, UInt8'(16#03#), Status); + Write (This, 16#35#, UInt8'(16#44#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#31#, UInt8'(16#04#), Status); + Write (This, 16#4B#, UInt8'(16#09#), Status); + Write (This, 16#4C#, UInt8'(16#05#), Status); + Write (This, 16#4D#, UInt8'(16#04#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#44#, UInt8'(16#00#), Status); + Write (This, 16#45#, UInt8'(16#20#), Status); + Write (This, 16#47#, UInt8'(16#08#), Status); + Write (This, 16#48#, UInt8'(16#28#), Status); + Write (This, 16#67#, UInt8'(16#00#), Status); + Write (This, 16#70#, UInt8'(16#04#), Status); + Write (This, 16#71#, UInt8'(16#01#), Status); + Write (This, 16#72#, UInt8'(16#FE#), Status); + Write (This, 16#76#, UInt8'(16#00#), Status); + Write (This, 16#77#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#0D#, UInt8'(16#01#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#80#, UInt8'(16#01#), Status); + Write (This, 16#01#, UInt8'(16#F8#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#8E#, UInt8'(16#01#), Status); + Write (This, 16#00#, UInt8'(16#01#), Status); + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + Set_GPIO_Config (This, GPIO_Function, Polarity_High, Status); + + if Status then + Timing_Budget := Measurement_Timing_Budget (This); + + -- Disable MSRC and TCC by default + -- MSRC = Minimum Signal Rate Check + -- TCC = Target CenterCheck + + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#E8#), Status); + end if; + + -- Recalculate the timing Budget + if Status then + Set_Measurement_Timing_Budget (This, Timing_Budget, Status); + end if; + end Static_Init; + + ------------------------------------ + -- Perform_Single_Ref_Calibration -- + ------------------------------------ + + procedure Perform_Single_Ref_Calibration + (This : VL53L0X_Ranging_Sensor; + VHV_Init : UInt8; + Status : out Boolean) + is + Val : UInt8; + + begin + Write (This, REG_SYSRANGE_START, VHV_Init or 16#01#, Status); + + if not Status then + return; + end if; + + loop + Read (This, REG_RESULT_INTERRUPT_STATUS, Val, Status); + exit when not Status; + exit when (Val and 16#07#) /= 0; + end loop; + + if not Status then + return; + end if; + + Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); + if not Status then + return; + end if; + + Write (This, REG_SYSRANGE_START, UInt8'(16#00#), Status); + end Perform_Single_Ref_Calibration; + + ----------------------------- + -- Perform_Ref_Calibration -- + ----------------------------- + + procedure Perform_Ref_Calibration + (This : in out VL53L0X_Ranging_Sensor; + Status : out Boolean) + is + begin + -- VHV calibration + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#01#), Status); + + if Status then + Perform_Single_Ref_Calibration (This, 16#40#, Status); + end if; + + -- Phase calibration + if Status then + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#02#), Status); + end if; + + if Status then + Perform_Single_Ref_Calibration (This, 16#00#, Status); + end if; + + -- Restore the sequence config + if Status then + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#E8#), Status); + end if; + end Perform_Ref_Calibration; + + ------------------------------------ + -- Start_Range_Single_Millimeters -- + ------------------------------------ + + procedure Start_Range_Single_Millimeters + (This : VL53L0X_Ranging_Sensor; + Status : out Boolean) + is + Val : UInt8; + begin + Write (This, 16#80#, UInt8'(16#01#), Status); + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#91#, This.Stop_Variable, Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + if Status then + Write (This, REG_SYSRANGE_START, UInt8'(16#01#), Status); + end if; + + if not Status then + return; + end if; + + loop + Read (This, REG_SYSRANGE_START, Val, Status); + exit when not Status; + exit when (Val and 16#01#) = 0; + end loop; + end Start_Range_Single_Millimeters; + + --------------------------- + -- Range_Value_Available -- + --------------------------- + + function Range_Value_Available + (This : VL53L0X_Ranging_Sensor) return Boolean + is + Status : Boolean with Unreferenced; + Val : UInt8; + begin + Read (This, REG_RESULT_INTERRUPT_STATUS, Val, Status); + return (Val and 16#07#) /= 0; + end Range_Value_Available; + + ---------------------------- + -- Read_Range_Millimeters -- + ---------------------------- + + function Read_Range_Millimeters + (This : VL53L0X_Ranging_Sensor) return HAL.UInt16 + is + Status : Boolean with Unreferenced; + Ret : HAL.UInt16; + begin + Read (This, REG_RESULT_RANGE_STATUS + 10, Ret, Status); + Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); + + return Ret; + end Read_Range_Millimeters; + + ----------------------------------- + -- Read_Range_Single_Millimeters -- + ----------------------------------- + + function Read_Range_Single_Millimeters + (This : VL53L0X_Ranging_Sensor) return HAL.UInt16 + is + Status : Boolean; + begin + Start_Range_Single_Millimeters (This, Status); + if not Status then + return 4000; + end if; + + while not Range_Value_Available (This) loop + null; + end loop; + + return Read_Range_Millimeters (This); + end Read_Range_Single_Millimeters; + + --------------------- + -- Set_GPIO_Config -- + --------------------- + + procedure Set_GPIO_Config + (This : in out VL53L0X_Ranging_Sensor; + Functionality : VL53L0X_GPIO_Functionality; + Polarity : VL53L0X_Interrupt_Polarity; + Status : out Boolean) + is + Data : UInt8; + Tmp : UInt8; + begin + case Functionality is + when No_Interrupt => + Data := 0; + when Level_Low => + Data := 1; + when Level_High => + Data := 2; + when Out_Of_Window => + Data := 3; + when New_Sample_Ready => + Data := 4; + end case; + + -- 16#04#: interrupt on new measure ready + Write (This, REG_SYSTEM_INTERRUPT_CONFIG_GPIO, Data, Status); + + -- Interrupt polarity + if Status then + case Polarity is + when Polarity_Low => + Data := 16#10#; + when Polarity_High => + Data := 16#00#; + end case; + + Read (This, REG_GPIO_HV_MUX_ACTIVE_HIGH, Tmp, Status); + Tmp := (Tmp and 16#EF#) or Data; + Write (This, REG_GPIO_HV_MUX_ACTIVE_HIGH, Tmp, Status); + end if; + + if Status then + Clear_Interrupt_Mask (This); + end if; + end Set_GPIO_Config; + + -------------------------- + -- Clear_Interrupt_Mask -- + -------------------------- + + procedure Clear_Interrupt_Mask + (This : VL53L0X_Ranging_Sensor) + is + Status : Boolean with Unreferenced; +-- Tmp : UInt8; + begin +-- for J in 1 .. 3 loop + Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); +-- exit when not Status; +-- Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#00#), Status); +-- exit when not Status; +-- Read (This, REG_RESULT_INTERRUPT_STATUS, Tmp, Status); +-- exit when not Status; +-- exit when (Tmp and 16#07#) /= 0; +-- end loop; + end Clear_Interrupt_Mask; + + --------------------------- + -- Sequence_Step_Enabled -- + --------------------------- + + function Sequence_Step_Enabled + (This : VL53L0X_Ranging_Sensor) return VL53L0x_Sequence_Step_Enabled + is + Sequence_Steps : VL53L0x_Sequence_Step_Enabled; + Sequence_Config : UInt8 := 0; + Status : Boolean; + + function Sequence_Step_Enabled + (Step : VL53L0x_Sequence_Step; + Sequence_Config : UInt8) return Boolean; + + --------------------------- + -- Sequence_Step_Enabled -- + --------------------------- + + function Sequence_Step_Enabled + (Step : VL53L0x_Sequence_Step; + Sequence_Config : UInt8) return Boolean + is + begin + case Step is + when TCC => + return (Sequence_Config and 16#10#) /= 0; + when DSS => + return (Sequence_Config and 16#08#) /= 0; + when MSRC => + return (Sequence_Config and 16#04#) /= 0; + when Pre_Range => + return (Sequence_Config and 16#40#) /= 0; + when Final_Range => + return (Sequence_Config and 16#80#) /= 0; + end case; + end Sequence_Step_Enabled; + + begin + Read (This, REG_SYSTEM_SEQUENCE_CONFIG, Sequence_Config, Status); + + if not Status then + return (others => False); + end if; + + for Step in Sequence_Steps'Range loop + Sequence_Steps (Step) := + Sequence_Step_Enabled (Step, Sequence_Config); + end loop; + + return Sequence_Steps; + end Sequence_Step_Enabled; + + --------------------------- + -- Sequence_Step_Timeout -- + --------------------------- + + function Sequence_Step_Timeout + (This : VL53L0X_Ranging_Sensor; + Step : VL53L0x_Sequence_Step; + As_Mclks : Boolean := False) return UInt32 + is + VCSel_Pulse_Period_Pclk : UInt8; + Encoded_UInt8 : UInt8; + Encoded_UInt16 : UInt16; + Status : Boolean; + Timeout_Mclks : UInt32; + Sequence_Steps : VL53L0x_Sequence_Step_Enabled; + + begin + case Step is + when TCC | DSS | MSRC => + Read (This, REG_MSRC_CONFIG_TIMEOUT_MACROP, + Encoded_UInt8, Status); + if Status then + Timeout_Mclks := Decode_Timeout (UInt16 (Encoded_UInt8)); + end if; + + if As_Mclks then + return Timeout_Mclks; + else + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Pre_Range); + + return To_Timeout_Microseconds + (Timeout_Mclks, VCSel_Pulse_Period_Pclk); + end if; + + when Pre_Range => + Read (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encoded_UInt16, Status); + + if Status then + Timeout_Mclks := Decode_Timeout (Encoded_UInt16); + end if; + + if As_Mclks then + return Timeout_Mclks; + else + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Pre_Range); + + return To_Timeout_Microseconds + (Timeout_Mclks, VCSel_Pulse_Period_Pclk); + end if; + + when Final_Range => + Sequence_Steps := Sequence_Step_Enabled (This); + + if Sequence_Steps (Pre_Range) then + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Pre_Range); + + Read (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encoded_UInt16, Status); + + if Status then + Timeout_Mclks := Decode_Timeout (Encoded_UInt16); + end if; + else + Timeout_Mclks := 0; + end if; + + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Final_Range); + + Read (This, REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encoded_UInt16, Status); + + Timeout_Mclks := + Decode_Timeout (Encoded_UInt16) - Timeout_Mclks; + + if As_Mclks then + return Timeout_Mclks; + else + return To_Timeout_Microseconds + (Timeout_Mclks, VCSel_Pulse_Period_Pclk); + end if; + end case; + end Sequence_Step_Timeout; + + ------------------------------- + -- Measurement_Timing_Budget -- + ------------------------------- + + function Measurement_Timing_Budget + (This : VL53L0X_Ranging_Sensor) return HAL.UInt32 + is + Ret : UInt32; + Pre_Range_Timeout : UInt32; + Final_Range_Timeout : UInt32; + Sequence_Steps : VL53L0x_Sequence_Step_Enabled; + Msrc_Dcc_Tcc_Timeout : UInt32; + + begin + Ret := Start_Overhead + End_Overhead; + + Sequence_Steps := Sequence_Step_Enabled (This); + + if Sequence_Steps (TCC) + or else Sequence_Steps (MSRC) + or else Sequence_Steps (DSS) + then + Msrc_Dcc_Tcc_Timeout := Sequence_Step_Timeout (This, MSRC); + if Sequence_Steps (TCC) then + Ret := Ret + Msrc_Dcc_Tcc_Timeout + Tcc_Overhead; + end if; + if Sequence_Steps (DSS) then + Ret := Ret + 2 * (Msrc_Dcc_Tcc_Timeout + Dss_Overhead); + elsif Sequence_Steps (MSRC) then + Ret := Ret + Msrc_Dcc_Tcc_Timeout + Msrc_Overhead; + end if; + end if; + + if Sequence_Steps (Pre_Range) then + Pre_Range_Timeout := Sequence_Step_Timeout (This, Pre_Range); + Ret := Ret + Pre_Range_Timeout + Pre_Range_Overhead; + end if; + + if Sequence_Steps (Final_Range) then + Final_Range_Timeout := Sequence_Step_Timeout (This, Final_Range); + Ret := Ret + Final_Range_Timeout + Final_Range_Overhead; + end if; + + return Ret; + end Measurement_Timing_Budget; + + ----------------------------------- + -- Set_Measurement_Timing_Budget -- + ----------------------------------- + + procedure Set_Measurement_Timing_Budget + (This : VL53L0X_Ranging_Sensor; + Budget_Micro_Seconds : HAL.UInt32; + Status : out Boolean) + is + Final_Range_Timing_Budget_us : UInt32; + Sequence_Steps : VL53L0x_Sequence_Step_Enabled; + Pre_Range_Timeout_us : UInt32 := 0; + Sub_Timeout : UInt32 := 0; + Msrc_Dcc_Tcc_Timeout : UInt32; + + begin + Status := True; + + Final_Range_Timing_Budget_us := + Budget_Micro_Seconds - Start_Overhead - End_Overhead + - Final_Range_Overhead; + + Sequence_Steps := Sequence_Step_Enabled (This); + + if not Sequence_Steps (Final_Range) then + return; + end if; + + if Sequence_Steps (TCC) + or else Sequence_Steps (MSRC) + or else Sequence_Steps (DSS) + then + Msrc_Dcc_Tcc_Timeout := Sequence_Step_Timeout (This, MSRC); + + if Sequence_Steps (TCC) then + Sub_Timeout := Msrc_Dcc_Tcc_Timeout + Tcc_Overhead; + end if; + + if Sequence_Steps (DSS) then + Sub_Timeout := + Sub_Timeout + 2 * (Msrc_Dcc_Tcc_Timeout + Dss_Overhead); + + elsif Sequence_Steps (MSRC) then + Sub_Timeout := Sub_Timeout + Msrc_Dcc_Tcc_Timeout + Msrc_Overhead; + end if; + end if; + + if Sequence_Steps (Pre_Range) then + Pre_Range_Timeout_us := Sequence_Step_Timeout (This, Pre_Range); + + Sub_Timeout := + Sub_Timeout + Pre_Range_Timeout_us + Pre_Range_Overhead; + end if; + + if Sub_Timeout < Final_Range_Timing_Budget_us then + Final_Range_Timing_Budget_us := + Final_Range_Timing_Budget_us - Sub_Timeout; + + else + -- Requested timeout too big + Status := False; + + return; + end if; + + declare + VCSel_Pulse_Period_Pclk : UInt8; + Encoded_UInt16 : UInt16; + Timeout_Mclks : UInt32; + begin + if Sequence_Steps (Pre_Range) then + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Pre_Range); + + Read (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encoded_UInt16, Status); + + if Status then + Timeout_Mclks := Decode_Timeout (Encoded_UInt16); + end if; + else + Timeout_Mclks := 0; + end if; + + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Final_Range); + + Timeout_Mclks := Timeout_Mclks + To_Timeout_Mclks + (Final_Range_Timing_Budget_us, + VCSel_Pulse_Period_Pclk); + + Write (This, REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encode_Timeout (Timeout_Mclks), Status);" +function To_U32 is new Ada.Unchecked_Conversion,"(Fix_Point_16_16, UInt32); + Val : UInt16; + Status : Boolean; + begin + -- Expecting Fixed Point 9.7 + Val := UInt16 (Shift_Right (To_U32 (Limit_Mcps), 9) and 16#FF_FF#); + Write (This, + REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, + Val, + Status); + return Status; + end Set_Signal_Rate_Limit; + + --------------- + -- SPAD_Info -- + --------------- + + function SPAD_Info + (This : VL53L0X_Ranging_Sensor; + SPAD_Count : out HAL.UInt8; + Is_Aperture : out Boolean) return Boolean + is + Status : Boolean; + Tmp : UInt8; + begin + Write (This, 16#80#, UInt8'(16#01#), Status); + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#00#), Status); + end if; + + if Status then + Write (This, 16#FF#, UInt8'(16#06#), Status); + end if; + if Status then + Read (This, 16#83#, Tmp, Status); + end if; + if Status then + Write (This, 16#83#, Tmp or 16#04#, Status); + end if; + + if Status then + Write (This, 16#FF#, UInt8'(16#07#), Status); + end if; + if Status then + Write (This, 16#81#, UInt8'(16#01#), Status); + end if; + + if Status then + Write (This, 16#80#, UInt8'(16#01#), Status); + end if; + + if Status then + Write (This, 16#94#, UInt8'(16#6B#), Status); + end if; + if Status then + Write (This, 16#83#, UInt8'(16#00#), Status); + end if; + + loop + exit when not Status; + Read (This, 16#83#, Tmp, Status); + exit when Tmp /= 0; + end loop; + + if Status then + Write (This, 16#83#, UInt8'(16#01#), Status); + end if; + if Status then + Read (This, 16#92#, Tmp, Status); + end if; + + if Status then + SPAD_Count := Tmp and 16#7F#; + Is_Aperture := (Tmp and 16#80#) /= 0; + + Write (This, 16#81#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#06#), Status); + end if; + if Status then + Read (This, 16#83#, Tmp, Status); + end if; + if Status then + Write (This, 16#83#, Tmp and not 16#04#, Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#01#), Status); + end if; + + if Status then + Write (This, 16#FF#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + return Status; + end SPAD_Info; + + --------------------------- + -- Set_Signal_Rate_Limit -- + --------------------------- + + procedure Set_Signal_Rate_Limit + (This : VL53L0X_Ranging_Sensor; + Rate_Limit : Fix_Point_16_16) + is + function To_U32 is new Ada.Unchecked_Conversion + (Fix_Point_16_16, UInt32); + Reg : UInt16; + Status : Boolean with Unreferenced; + begin + -- Encoded as Fixed Point 9.7. Let's translate. + Reg := UInt16 (Shift_Right (To_U32 (Rate_Limit), 9) and 16#FFFF#); + Write (This, REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, + Reg, Status); + end Set_Signal_Rate_Limit; + + -------------------------------------- + -- Set_Vcsel_Pulse_Period_Pre_Range -- + -------------------------------------- + + procedure Set_VCSEL_Pulse_Period_Pre_Range + (This : VL53L0X_Ranging_Sensor; + Period : UInt8; + Status : out Boolean) + is + begin + Set_VCSel_Pulse_Period (This, Period, Pre_Range, Status); + end Set_VCSEL_Pulse_Period_Pre_Range; + + ---------------------------------------- + -- Set_Vcsel_Pulse_Period_Final_Range -- + ---------------------------------------- + + procedure Set_VCSEL_Pulse_Period_Final_Range + (This : VL53L0X_Ranging_Sensor; + Period : UInt8; + Status : out Boolean) + is + begin + Set_VCSel_Pulse_Period (This, Period, Final_Range, Status); + end Set_VCSEL_Pulse_Period_Final_Range; + + ---------------------------- + -- Set_VCSel_Pulse_Period -- + ---------------------------- + + procedure Set_VCSel_Pulse_Period + (This : VL53L0X_Ranging_Sensor; + Period : UInt8; + Sequence : VL53L0x_Sequence_Step; + Status : out Boolean) + is + Encoded : constant UInt8 := Shift_Right (Period, 1) - 1; + Phase_High : UInt8; + Pre_Timeout : UInt32; + Final_Timeout : UInt32; + Msrc_Timeout : UInt32; + Timeout_Mclks : UInt32; + Steps_Enabled : constant VL53L0x_Sequence_Step_Enabled := + Sequence_Step_Enabled (This); + Budget : UInt32; + Sequence_Cfg : UInt8; + + begin + -- Save the measurement timing budget + Budget := Measurement_Timing_Budget (This); + + case Sequence is + when Pre_Range => + Pre_Timeout := Sequence_Step_Timeout (This, Pre_Range); + Msrc_Timeout := Sequence_Step_Timeout (This, MSRC); + + case Period is + when 12 => + Phase_High := 16#18#; + when 14 => + Phase_High := 16#30#; + when 16 => + Phase_High := 16#40#; + when 18 => + Phase_High := 16#50#; + when others => + Status := False; + + return; + end case; + + Write (This, REG_PRE_RANGE_CONFIG_VALID_PHASE_HIGH, + Phase_High, Status); + if not Status then + return; + end if; + + Write (This, REG_PRE_RANGE_CONFIG_VALID_PHASE_LOW, + UInt8'(16#08#), Status); + if not Status then + return; + end if; + + Write (This, REG_PRE_RANGE_CONFIG_VCSEL_PERIOD, + Encoded, Status); + if not Status then + return; + end if; + + -- Update the timeouts + Timeout_Mclks := To_Timeout_Mclks (Pre_Timeout, Period); + Write (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, + UInt16 (Timeout_Mclks), Status); + + Timeout_Mclks := To_Timeout_Mclks (Msrc_Timeout, Period); + if Timeout_Mclks > 256 then + Timeout_Mclks := 255; + else + Timeout_Mclks := Timeout_Mclks - 1; + end if; + + Write (This, REG_MSRC_CONFIG_TIMEOUT_MACROP, + UInt8 (Timeout_Mclks), Status); + + when Final_Range => + Pre_Timeout := Sequence_Step_Timeout + (This, Pre_Range, As_Mclks => True); + Final_Timeout := Sequence_Step_Timeout (This, Final_Range); + + declare + Phase_High : UInt8; + Width : UInt8; + Cal_Timeout : UInt8; + Cal_Lim : UInt8; + begin + case Period is + when 8 => + Phase_High := 16#10#; + Width := 16#02#; + Cal_Timeout := 16#0C#; + Cal_Lim := 16#30#; + when 10 => + Phase_High := 16#28#; + Width := 16#03#; + Cal_Timeout := 16#09#; + Cal_Lim := 16#20#; + when 12 => + Phase_High := 16#38#; + Width := 16#03#; + Cal_Timeout := 16#08#; + Cal_Lim := 16#20#; + when 14 => + Phase_High := 16#48#; + Width := 16#03#; + Cal_Timeout := 16#07#; + Cal_Lim := 16#20#; + when others => + return; + end case; + + Write (This, REG_FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, + Phase_High, Status); + if not Status then + return; + end if; + + Write (This, REG_FINAL_RANGE_CONFIG_VALID_PHASE_LOW, + UInt8'(16#08#), Status); + if not Status then + return; + end if; + + Write (This, REG_GLOBAL_CONFIG_VCSEL_WIDTH, + Width, Status); + if not Status then + return; + end if; + + Write (This, REG_ALGO_PHASECAL_CONFIG_TIMEOUT, + Cal_Timeout, Status); + if not Status then + return; + end if; + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, REG_ALGO_PHASECAL_LIM, + Cal_Lim, Status); + Write (This, 16#FF#, UInt8'(16#00#), Status); + if not Status then + return; + end if;" +function To_UInt16 is,"new Ada.Unchecked_Conversion (UInt16_HL_Type, UInt16); + + Ret : TP_Touch_State; + Regs : FT6206_Pressure_Registers; + Tmp : UInt16_HL_Type; + Status : Boolean; + begin + if Touch_Id not in FT6206_Px_Regs'Range then + return (0, 0, 0); + end if; + + if Touch_Id > This.Active_Touch_Points then + return (0, 0, 0); + end if; + + -- X/Y are swaped from the screen coordinates + + Regs := FT6206_Px_Regs (Touch_Id); + + Tmp.Low := This.I2C_Read (Regs.XL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.XH_Reg, Status) and + FT6206_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.Y := Natural (To_UInt16 (Tmp)); + + Tmp.Low := This.I2C_Read (Regs.YL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.YH_Reg, Status) and + FT6206_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.X := Natural (To_UInt16 (Tmp)); + + Ret.Weight := Natural (This.I2C_Read (Regs.Weight_Reg, Status)); + + if not Status then + Ret.Weight := 0; + end if; + + if Ret.Weight = 0 then + Ret.Weight := 50; + end if; + + Ret.X := Natural'Max (0, Ret.X); + Ret.Y := Natural'Max (0, Ret.Y); + Ret.X := Natural'Min (This.LCD_Natural_Width - 1, Ret.X); + Ret.Y := Natural'Min (This.LCD_Natural_Height - 1, Ret.Y); + + if (This.Swap and Invert_X) /= 0 then + Ret.X := This.LCD_Natural_Width - Ret.X - 1; + end if; + if (This.Swap and Invert_Y) /= 0 then + Ret.Y := This.LCD_Natural_Height - Ret.Y - 1; + end if; + if (This.Swap and Swap_XY) /= 0 then + declare + Tmp_X : constant Integer := Ret.X; + begin + Ret.X := Ret.Y; + Ret.Y := Tmp_X;" +function Read_Register (This : STMPE811_Device;,"Reg_Addr : UInt8) return UInt8 + is + Data : TSC_Data (1 .. 1); + Status : I2C_Status; + + begin + This.Port.Mem_Read (This.I2C_Addr, + UInt16 (Reg_Addr), + Memory_Size_8b, + Data, + Status); + + if Status /= Ok then + raise Program_Error with ""Timeout while reading TC data""; + end if; + + return Data (1); + end Read_Register; + + -------------------- + -- Write_Register -- + -------------------- + + procedure Write_Register (This : in out STMPE811_Device; + Reg_Addr : UInt8; + Data : UInt8) is + Status : I2C_Status; + + begin + This.Port.Mem_Write (This.I2C_Addr, + UInt16 (Reg_Addr), + Memory_Size_8b, + (1 => Data), + Status); + + if Status /= Ok then + raise Program_Error with ""Timeout while reading TC data""; + end if; + end Write_Register; + + --------------- + -- IOE_Reset -- + --------------- + + procedure IOE_Reset (This : in out STMPE811_Device) is + begin + This.Write_Register (IOE_REG_SYS_CTRL1, 16#02#); + + -- Give some time for the reset + This.Time.Delay_Milliseconds (2); + + This.Write_Register (IOE_REG_SYS_CTRL1, 16#00#); + end IOE_Reset; + + -------------------------- + -- IOE_Function_Command -- + -------------------------- + + procedure IOE_Function_Command (This : in out STMPE811_Device; + Func : UInt8; + Enabled : Boolean) + is + Reg : UInt8 := This.Read_Register (IOE_REG_SYS_CTRL2); + begin + -- CTRL2 functions are disabled when corresponding bit is set + + if Enabled then + Reg := Reg and (not Func); + else + Reg := Reg or Func; + end if; + + This.Write_Register (IOE_REG_SYS_CTRL2, Reg); + end IOE_Function_Command; + + ------------------- + -- IOE_AF_Config -- + ------------------- + + procedure IOE_AF_Config (This : in out STMPE811_Device; + Pin : UInt8; + Enabled : Boolean) is + Reg : UInt8 := This.Read_Register (IOE_REG_GPIO_AF); + begin + if Enabled then + Reg := Reg or Pin; + else + Reg := Reg and (not Pin); + end if; + + This.Write_Register (IOE_REG_GPIO_AF, Reg); + end IOE_AF_Config; + + ---------------- + -- Get_IOE_ID -- + ---------------- + + function Get_IOE_ID (This : in out STMPE811_Device) return UInt16 is + begin + return (UInt16 (This.Read_Register (0)) * (2**8)) + or UInt16 (This.Read_Register (1)); + end Get_IOE_ID; + + ---------------- + -- Initialize -- + ---------------- + + function Initialize (This : in out STMPE811_Device) return Boolean + is + begin + + This.Time.Delay_Milliseconds (100); + + if This.Get_IOE_ID /= 16#0811# then + return False; + end if; + + This.IOE_Reset; + + This.IOE_Function_Command (IOE_ADC_FCT, True); + This.IOE_Function_Command (IOE_TSC_FCT, True); + + This.Write_Register (IOE_REG_ADC_CTRL1, 16#49#); + + This.Time.Delay_Milliseconds (2); + + This.Write_Register (IOE_REG_ADC_CTRL2, 16#01#); + + This.IOE_AF_Config (TOUCH_IO_ALL, False); + + This.Write_Register (IOE_REG_TSC_CFG, 16#9A#); + + This.Write_Register (IOE_REG_FIFO_TH, 16#01#); + + This.Write_Register (IOE_REG_FIFO_STA, 16#01#); + + This.Write_Register (IOE_REG_FIFO_TH, 16#00#); + + This.Write_Register (IOE_REG_TSC_FRACT_Z, 16#00#); + + This.Write_Register (IOE_REG_TSC_I_DRIVE, 16#01#); + + This.Write_Register (IOE_REG_TSC_CTRL, 16#01#); + + This.Write_Register (IOE_REG_INT_STA, 16#FF#); + + return True; + end Initialize; + + ---------------- + -- Set_Bounds -- + ---------------- + + overriding + procedure Set_Bounds (This : in out STMPE811_Device; + Width : Natural; + Height : Natural; + Swap : HAL.Touch_Panel.Swap_State) + is + begin + This.LCD_Natural_Width := Width; + This.LCD_Natural_Height := Height; + This.Swap := Swap; + end Set_Bounds; + + ------------------------- + -- Active_Touch_Points -- + ------------------------- + + overriding + function Active_Touch_Points (This : in out STMPE811_Device) + return Touch_Identifier + is + Val : constant UInt8 := This.Read_Register (IOE_REG_TSC_CTRL) and 16#80#; + begin + if Val = 0 then + This.Write_Register (IOE_REG_FIFO_STA, 16#01#); + This.Write_Register (IOE_REG_FIFO_STA, 16#00#); + + return 0; + else + return 1; + end if; + end Active_Touch_Points; + + --------------------- + -- Get_Touch_Point -- + --------------------- + + overriding + function Get_Touch_Point (This : in out STMPE811_Device; + Touch_Id : Touch_Identifier) + return TP_Touch_State + is + State : TP_Touch_State; + Raw_X : UInt32; + Raw_Y : UInt32; + Raw_Z : UInt32; + X : Integer; + Y : Integer; + Tmp : Integer; + + begin + + -- Check Touch detected bit in CTRL register + if Touch_Id /= 1 or else This.Active_Touch_Points = 0 then + return (0, 0, 0); + end if; + + declare + Data_X : constant TSC_Data := This.Read_Data (IOE_REG_TSC_DATA_X, 2); + Data_Y : constant TSC_Data := This.Read_Data (IOE_REG_TSC_DATA_Y, 2); + Data_Z : constant TSC_Data := This.Read_Data (IOE_REG_TSC_DATA_Z, 1); + Z_Frac : constant TSC_Data := This.Read_Data (IOE_REG_TSC_FRACT_Z, 1); + + begin + Raw_X := 2 ** 12 - + (Shift_Left (UInt32 (Data_X (1)) and 16#0F#, 8) or UInt32 (Data_X (2))); + Raw_Y := + Shift_Left (UInt32 (Data_Y (1)) and 16#0F#, 8) or UInt32 (Data_Y (2)); + Raw_Z := + Shift_Right (UInt32 (Data_Z (1)), Natural (Z_Frac (1) and 2#111#));" +function To_UInt16 is,"new Ada.Unchecked_Conversion (UInt16_HL_Type, UInt16); + + Ret : TP_Touch_State; + Regs : FT5336_Pressure_Registers; + Tmp : UInt16_HL_Type; + Status : Boolean; + + begin + -- X/Y are swaped from the screen coordinates + + if Touch_Id not in FT5336_Px_Regs'Range + or else Touch_Id > This.Active_Touch_Points + then + return (0, 0, 0); + end if; + + Regs := FT5336_Px_Regs (Touch_Id); + + Tmp.Low := This.I2C_Read (Regs.XL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.XH_Reg, Status) and + FT5336_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.Y := Natural (To_UInt16 (Tmp)); + + Tmp.Low := This.I2C_Read (Regs.YL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.YH_Reg, Status) and + FT5336_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.X := Natural (To_UInt16 (Tmp)); + + Ret.Weight := Natural (This.I2C_Read (Regs.Weight_Reg, Status)); + + if not Status then + Ret.Weight := 0; + end if; + + Ret.X := + Natural'Min (Natural'Max (0, Ret.X), This.LCD_Natural_Width - 1); + Ret.Y := + Natural'Min (Natural'Max (0, Ret.Y), This.LCD_Natural_Height - 1); + + if (This.Swap and Invert_X) /= 0 then + Ret.X := This.LCD_Natural_Width - Ret.X - 1; + end if; + if (This.Swap and Invert_Y) /= 0 then + Ret.Y := This.LCD_Natural_Height - Ret.Y - 1; + end if; + if (This.Swap and Swap_XY) /= 0 then + declare + Tmp_X : constant Integer := Ret.X; + begin + Ret.X := Ret.Y; + Ret.Y := Tmp_X;" +procedure Destroy is new Ada.Unchecked_Deallocation,"(File_Handle, File_Handle_Access); + procedure Destroy is new Ada.Unchecked_Deallocation + (Directory_Handle, Directory_Handle_Access); + procedure Destroy is new Ada.Unchecked_Deallocation + (Node_Handle, Node_Handle_Access); + + function ""<"" (Left, Right : Node_Handle) return Boolean is + (Ada.Strings.Unbounded.""<"" (Left.Name, Right.Name)); + + package Node_Sorting is + new Node_Vectors.Generic_Sorting; + + -- Most of the time, standard operations give us no reliable way to + -- determine specifically what triggered a failure, so use the following + -- error code as a ""generic"" one. + + Generic_Error : constant Status_Code := Input_Output_Error; + + function Absolute_Path + (This : Native_FS_Driver; + Relative_Path : String) + return String + is (if Relative_Path = """" + then +This.Root_Dir + else Join (+This.Root_Dir, Relative_Path, True)); + + ---------------- + -- Get_Handle -- + ---------------- + + function Get_Handle + (FS : in out Native_FS_Driver) + return File_Handle_Access + is + Result : File_Handle_Access := FS.Free_File_Handles; + begin + if Result = null then + Result := new File_Handle' + (FS => FS'Unrestricted_Access, + others => <>); + else + FS.Free_File_Handles := Result.Next; + end if; + return Result; + end Get_Handle; + + ---------------- + -- Get_Handle -- + ---------------- + + function Get_Handle + (FS : in out Native_FS_Driver) + return Directory_Handle_Access + is + Result : Directory_Handle_Access := FS.Free_Dir_Handles; + begin + if Result = null then + Result := new Directory_Handle' + (FS => FS'Unrestricted_Access, + others => <>); + else + FS.Free_Dir_Handles := Result.Next; + end if; + return Result; + end Get_Handle; + + --------------------- + -- Add_Free_Handle -- + --------------------- + + procedure Add_Free_Handle + (FS : in out Native_FS_Driver; + Handle : in out File_Handle_Access) + is + begin + Handle.Next := FS.Free_File_Handles; + FS.Free_File_Handles := Handle; + Handle := null; + end Add_Free_Handle; + + --------------------- + -- Add_Free_Handle -- + --------------------- + + procedure Add_Free_Handle + (FS : in out Native_FS_Driver; + Handle : in out Directory_Handle_Access) + is + begin + Handle.Next := FS.Free_Dir_Handles; + FS.Free_Dir_Handles := Handle; + Handle := null; + end Add_Free_Handle; + + ------------- + -- Destroy -- + ------------- + + procedure Destroy (This : in out Native_FS_Driver_Access) is + procedure Destroy is new Ada.Unchecked_Deallocation + (Native_FS_Driver, Native_FS_Driver_Access); + begin + -- Free all handles + + while This.Free_File_Handles /= null loop + declare + H : constant File_Handle_Access := This.Free_File_Handles.Next; + begin + Destroy (This.Free_File_Handles); + This.Free_File_Handles := H;" +procedure update_Enn is,"begin + if Next_Ennmie = 0 then + for i in Ennmies'First .. Ennmies'Last loop + if Ennmies(i).State = DEAD then + Ennmie.appear_enn(Ennmies(i), RANDOM(G), MAX_HEIGHT -5 , MAX_HEIGHT, MAX_WIDTH); + exit; + end if; + end loop; + Next_Ennmie := 50; + else + Next_Ennmie := Next_Ennmie - 1; + end if; + if Next_Enemie_Move = 0 then + for i in Ennmies'First .. Ennmies'Last loop + if Ennmies(i).State = DMG_DEALT then + Ennmies(i).State := DEAD; + end if; + if Ennmies(i).State /= DEAD then + Ennmie.move_enn(Ennmies(i)); + end if; + end loop; + Next_Enemie_Move := 2; + else + Next_Enemie_Move := Next_Enemie_Move - 1; + end if; + end update_Enn; + + procedure update(X : Integer; Y : Integer) is + begin + if Next_missile = 0 then + for i in Missiles'First .. Missiles'Last loop + if Missiles(i).State = DEAD then + Missile.appear_mis(Missiles(i), space.X, space.Y, Height); + exit; + end if; + end loop; + Next_missile := 20; + else + Next_missile := Next_missile - 1; + end if; + for i in Missiles'First .. Missiles'Last loop + if Missiles(i).State /= DEAD then + Missile.move_mis(Missiles(i)); + end if; + if Missiles(i).State = TOUCHED then + Missiles(i).State := DEAD; + end if; + end loop; + update_Enn; + for i in Missiles'First .. Missiles'Last loop + if Missiles(i).State = ALIVE then + for j in Ennmies'First .. Ennmies'Last loop + if Ennmies(j).State = ALIVE then + ishit(Missiles(i), Ennmies(j)); + end if; + end loop; + end if; + end loop; + if X = 0 then + return; + end if; + space.X := X; + space.Y := Y; + end update; + + procedure draw_mis(s : in Missile.Missile) is + begin + if s.State = DEAD then + return; + end if; + + Bitmap_Buffer.Set_Source (HAL.Bitmap.Yellow); + Bitmap_Buffer.Fill_Rect ((Position => (s.X, s.Y), + Width => Width / 80, + Height => Height / 80)); + end draw_mis; + + procedure draw_space(s : in out Spaceship.Spaceship; X : Integer; Y : Integer) is + begin + s.X := X; + s.Y := Y; + if s.State = ALIVE then + Bitmap_Buffer.Set_Source (HAL.Bitmap.Blue); + else if s.State = DMG_DEALT then + Bitmap_Buffer.Set_Source (HAL.Bitmap.White); + end if; + end if; + Bitmap_Buffer.Fill_Rect ((Position => (X, Y), + Width => Width / 8, + Height => Height / 8)); + end draw_space; + + procedure draw_enn(e : in Ennmie.Ennmie) is + begin + if e.State = DEAD then + return; + end if; + if e.State = ALIVE then + Bitmap_Buffer.Set_Source (HAL.Bitmap.Red); + else if e.State = DMG_DEALT then + Bitmap_Buffer.Set_Source (HAL.Bitmap.White); + end if; + end if; + Bitmap_Buffer.Fill_Rect ((Position => (e.X, e.Y), + Width => Width / 12, + Height => Height / 12)); + end draw_enn; + + procedure draw(X : Integer; Y : Integer) is + begin + draw_space(space, X, Y); + for i in Missiles'First .. Missiles'Last loop + draw_mis(Missiles(i)); + end loop; + for i in Ennmies'First .. Ennmies'Last loop + draw_enn(Ennmies(i)); + end loop; + end draw; + +begin + Reset(G); + -- Initialize LCD + Display.Initialize; + Display.Initialize_Layer (1, HAL.Bitmap.ARGB_8888); + + Touch_Panel.Initialize; + + Width := Bitmap_Buffer.Width; + Height := Bitmap_Buffer.Height; + + space.Y := 20; + space.X := Width/2; + loop + declare + State : constant TP_State := Touch_Panel.Get_All_Touch_Points; + begin + if State'Length > 0 then + X_Coord := State (State'First).X; + Y_Coord := State (State'First).Y; + end if;" +procedure Clear;,"----------- + -- Clear -- + ----------- + + procedure Clear is + begin + Display.Hidden_Buffer (1).Set_Source (BG); + Display.Hidden_Buffer (1).Fill; + + LCD_Std_Out.Clear_Screen; + LCD_Std_Out.Put_Line (""Touch the screen to draw or""); + LCD_Std_Out.Put_Line (""press the blue button for""); + LCD_Std_Out.Put_Line (""a demo of drawing primitives.""); + + Display.Update_Layer (1, Copy_Back => True); + end Clear; + + Last_X : Integer := -1; + Last_Y : Integer := -1; + + type Mode is (Drawing_Mode, Bitmap_Showcase_Mode); + + Current_Mode : Mode := Drawing_Mode; + +begin + + -- Initialize LCD + Display.Initialize; + Display.Initialize_Layer (1, ARGB_8888); + + -- Initialize touch panel + Touch_Panel.Initialize; + + -- Initialize button + User_Button.Initialize; + + LCD_Std_Out.Set_Font (BMP_Fonts.Font8x8); + LCD_Std_Out.Current_Background_Color := BG; + + -- Clear LCD (set background) + Clear; + + -- The application: set pixel where the finger is (so that you + -- cannot see what you are drawing). + loop + if User_Button.Has_Been_Pressed then + case Current_Mode is + when Drawing_Mode => + Current_Mode := Bitmap_Showcase_Mode; + when Bitmap_Showcase_Mode => + Clear; + Current_Mode := Drawing_Mode; + end case; + end if; + + if Current_Mode = Drawing_Mode then + + Display.Hidden_Buffer (1).Set_Source (HAL.Bitmap.Green); + + declare + State : constant TP_State := Touch_Panel.Get_All_Touch_Points; + begin + if State'Length = 0 then + Last_X := -1; + Last_Y := -1; + + elsif State'Length = 1 then + -- Lines can be drawn between two consecutive points only when + -- one touch point is active: the order of the touch data is not + -- necessarily preserved by the hardware. + if Last_X > 0 then + Draw_Line + (Display.Hidden_Buffer (1).all, + Start => (Last_X, Last_Y), + Stop => (State (State'First).X, State (State'First).Y), + Thickness => State (State'First).Weight / 2, + Fast => False); + end if; + + Last_X := State (State'First).X; + Last_Y := State (State'First).Y; + + else + Last_X := -1; + Last_Y := -1; + end if; + + for Id in State'Range loop + Fill_Circle + (Display.Hidden_Buffer (1).all, + Center => (State (Id).X, State (Id).Y), + Radius => State (Id).Weight / 4); + end loop; + + if State'Length > 0 then + Display.Update_Layer (1, Copy_Back => True); + end if;" +procedure Free is,"new Ada.Unchecked_Deallocation (Object => T_Cellule, Name => T_Registre); + + + -- Trouver si une clé est déjà présente ou non, utilisée dans Creer_Cle + -- Paramètres : + -- Reg : in T_Registre Registre dans lequel on cherche + -- Cle : in Entier Clé provisoire en attente d'unicité + function Est_Present(Reg : in T_Registre; Cle : in Integer; X : in out Integer) return Integer is + begin + if Reg = Null then + return X; + elsif Reg.all.Cle < Cle then + return Est_Present (Reg.all.Sous_Arbre_Droit, Cle, X); + elsif Reg.all.Cle > Cle then + return Est_Present (Reg.all.Sous_Arbre_Gauche, Cle, X); + else -- { Reg.all.Cle = Cle } + X := X + 1; + -- On relance une recherche sur la clé Cle + 1 + return Est_Present(Reg, Cle+1, X); + end if; + end Est_Present; + + + procedure Creer_Cle (Reg : in T_Registre; Cle : out Integer; Donnee : in T_Donnee) is + X : Integer; + Cle_Provisoire : Integer; + begin + -- On cherche si d'autres individus sont nés le même jour + Cle_Provisoire := 100000000 * Donnee.Mois_N + 1000000 * Donnee.Jour_N + 100*Donnee.Annee_N; + X := 0; + + -- Si la clé est déjà présente on incrémente X et on cherche si la clé avec X+1 est présente etc... + X := Est_Present (Reg, Cle_Provisoire, X); + + -- Finalement on change la clé ! + Cle := Cle_Provisoire + X; + end Creer_Cle; + + + procedure Initialiser_Donnee ( Donnee : out T_Donnee; + Nom : in unbounded_string; + Prenom : in unbounded_string; + Jour_N : in Integer; + Mois_N : in Integer; + Annee_N : in Integer; + Sexe : in Character) is + begin + Donnee.Nom := Nom; + Donnee.Prenom := Prenom; + Donnee.Jour_N := Jour_N; + Donnee.Mois_N := Mois_N; + Donnee.Annee_N := Annee_N; + Donnee.Sexe := Sexe; + end Initialiser_Donnee; + + + procedure Initialiser_Reg(Reg: out T_Registre; Cle : in Integer; Donnee : in T_Donnee) is + Cellule : T_Registre; + begin + Cellule := new T_Cellule; + Cellule.all.Cle := Cle; + Cellule.all.Sous_Arbre_Droit := null; + Cellule.all.Sous_Arbre_Gauche := null; + Cellule.all.Donnee := Donnee; + Reg := Cellule; + end Initialiser_Reg; + + + function Est_Vide (Reg : T_Registre) return Boolean is + begin + return Reg = Null;" +procedure Free is new Ada.Unchecked_Deallocation,"(Object => Test_Event_Base'Class, + Name => Test_Event_Access); + + begin + + N_E.Event.Clean_Up; + Free (N_E.Event); + + end Clean_Up_Events; + + ----------------------------------------------------- + + begin + + Obj.Active_Node_Map.Clear; + + Obj.Event_Vector.Iterate (Clean_Up_Events'Access); + Obj.Event_Vector.Clear; + + Obj.Node_Data_Tree.Clear; + + end Reset; + + ---------------------------------------------------------------------------- + + overriding + function Is_Active (Obj : Test_Reporter_Data; + Node_Tag : Tag) return Boolean + is (Obj.Active_Node_Map.Contains (Node_Tag)); + + ---------------------------------------------------------------------------- + + overriding + procedure Include_Node (Obj : in out Test_Reporter_Data; + Node_Lineage : Tag_Array) is + + C : Cursor := Root (Obj.Node_Data_Tree); + + begin + + for T of Node_Lineage loop + + declare + + Insertion_Required : Boolean := Is_Leaf (C); + + begin + + for Child_C in Obj.Node_Data_Tree.Iterate_Children (C) loop + + if Element (Child_C).T = T then + C := Child_C; + exit; + end if; + + Insertion_Required := Child_C = Last_Child (C); + + end loop; + + if Insertion_Required then + + declare + Position : Cursor; + begin + Obj.Node_Data_Tree.Insert_Child + (Parent => C, + Before => No_Element, + New_Item => (T => T, + Event_Index_Vector => <>), + Position => Position); + C := Position;" +procedure Update_Map_With_Work_Data is,"C : constant Cursor := M.Find (T); + begin + if C = No_Element then + M.Insert (Key => T, + New_Item => S); + else + M.Replace_Element (Position => C, + New_Item => S); + end if; + end Update_Map_With_Work_Data; + + procedure Extract_Work_Data is + C : constant Cursor := M.Find (Node_Tag); + begin + T := Node_Tag; + S := (if C = No_Element then + Initial_Routine_State + else + Element (C)); + end Extract_Work_Data; + + begin + + if T /= Node_Tag then + + if T /= No_Tag then + Update_Map_With_Work_Data; + end if; + + Extract_Work_Data; + + end if; + + end Switch_Key_If_Needed; + + ----------------------------------------------------- + + procedure Reset_Routine_State (Node_Tag : Tag; + Routine_Index : Test_Routine_Index) is + + begin + + Switch_Key_If_Needed (Node_Tag); + S := Initial_Routine_State (Routine_Index); + + end Reset_Routine_State; + + ----------------------------------------------------- + + procedure Increment_Assert_Count (Node_Tag : Tag) is + + begin + + Switch_Key_If_Needed (Node_Tag); + Prot_Test_Assert_Count.Inc (S.Assert_Count); + + end Increment_Assert_Count; + + ----------------------------------------------------- + + procedure Set_Failed_Outcome (Node_Tag : Tag) is + + begin + + Switch_Key_If_Needed (Node_Tag); + S.Assert_Outcome := Failed; + + end Set_Failed_Outcome; + + ----------------------------------------------------- + + procedure Get_Assert_Count (Node_Tag : Tag; + Routine_Index : out Test_Routine_Index; + Count : out O_P_I_Test_Assert_Count) + is + + begin + + Switch_Key_If_Needed (Node_Tag); + Routine_Index := S.Routine_Index; + Count := S.Assert_Count; + + end Get_Assert_Count; + + ----------------------------------------------------- + + procedure Get_Assert_Outcome (Node_Tag : Tag; + Outcome : out Test_Outcome) is + + begin + + Switch_Key_If_Needed (Node_Tag); + Outcome := S.Assert_Outcome; + + end Get_Assert_Outcome; + + ----------------------------------------------------- + + procedure Delete (Node_Tag : Tag) is + + use Routine_State_Hashed_Maps; + + begin + + if M.Length = 0 then + T := No_Tag; + else + + declare + C : Cursor := M.Find (Node_Tag); + begin + + if C /= No_Element then + M.Delete (C); + end if; + + if T = Node_Tag and then M.Length > 0 then + declare + C_First : constant Cursor := M.First; + begin + T := Key (C_First); + S := Element (C_First);" +procedure Populate_Current is,"begin + if N /= 0 then + Ret(1).T := T; + Ret(1).S := S; + end if; + end Populate_Current; + + procedure Populate_Others is + K : Index_Type := 1; + procedure Process (C : Cursor) is + Key_C : constant Tag := Key (C); + begin + if Key_C /= T then + K := K + 1; + Ret(K).T := Key_C; + Ret(K).S := Element (C); + end if; + end Process; + begin + M.Iterate (Process'Access); + Ada.Assertions.Assert ((N = 0 and then K = 1) + or else + (N > 0 and then K = N)); + end Populate_Others; + + begin + + Populate_Current; + Populate_Others; + return Ret; + + end To_Array; + + ----------------------------------------------------- + + end Routine_State_Map_Handler; + + ---------------------------------------------------------------------------- + + procedure Run_Test_Routines (Obj : Test_Node_Interfa'Class; + Outcome : out Test_Outcome; + Kind : Run_Kind) is + + use Ada.Assertions, + Private_Test_Reporter; + + pragma Unreferenced (Kind); + + T : constant Tag := Obj'Tag; + + K : Test_Routine_Count := 0; + R : Test_Routine := Null_Test_Routine'Access; + Err : Boolean := False; -- ""Unexpected error"" flag. + + ----------------------------------------------------- + + function Done return Boolean is + + N : constant Test_Routine_Count := Obj.Routine_Count; + Ret : Boolean := K >= N; + + begin + + if Err and then not Ret then + Ret := True; + Outcome := Failed; + Test_Reporter.Report_Test_Routines_Cancellation (Obj'Tag, + K + 1, + N); + end if; + + return Ret; + + end Done; + + ----------------------------------------------------- + + begin + + Outcome := Passed; + + while not Done loop + + K := K + 1; + Err := True; + + Routine_State_Map_Handler.Reset_Routine_State (T, K); + Test_Reporter.Report_Test_Routine_Start (T, K); + + begin + + R := Obj.Routine (K); + + begin + + Obj.Setup_Routine; + + declare + Assert_Outcome : Test_Outcome; + begin + R.all; + Err := False; + Routine_State_Map_Handler.Get_Assert_Outcome + (T, Assert_Outcome); + case Assert_Outcome is + when Failed => + raise Assertion_Error; -- Causes a jump to + -- Assertion_Error handler + -- below. Happens when a test + -- assertion has failed but has + -- been handled in the test + -- routine. + when Passed => + null; + end case; + Test_Reporter.Report_Passed_Test_Routine (T, K); + exception + when Run_E : Assertion_Error => + Routine_State_Map_Handler.Get_Assert_Outcome + (T, Assert_Outcome); + Err := False; + Outcome := Failed; + case Assert_Outcome is + when Failed => -- Exception very likely originates in + -- a failed test assertion and not in + -- an ""unexpected error"". + Test_Reporter.Report_Failed_Test_Routine (T, K); + when Passed => -- Exception may originates in a failed + -- contract. + Test_Reporter.Report_Unexpected_Routine_Exception + (T, K, Run_E); + end case; + when Run_E : others => -- Exception originates in an + -- unexpected error. + Test_Reporter.Report_Unexpected_Routine_Exception + (T, K, Run_E);" +procedure Unl_CB is,"begin + + if Unlock_CB /= null then + Unlock_CB.all; + end if; + + if Deallocation_Needed then + + declare + + procedure Free is new Ada.Unchecked_Deallocation + (Object => Instance_Ancestor_Type'Class, + Name => Instance_Type_Access); + + begin + + Deallocation_Needed := False; + Free (Instance_Access);" +procedure SB_Lock_CB_procedure_Test is,"procedure P_Null is new SB_Lock_CB_procedure (null); + + procedure P_Increment_N is new SB_Lock_CB_procedure (Increment_N'Access); + + begin + + P_Null; + Assert (SBLF.N = 0); + + P_Increment_N; + Assert (SBLF.N = 1); + + end SB_Lock_CB_procedure_Test; + + ---------------------------------------------------------------------------- + + procedure Locked_Test is + + begin + + Assert (not Locked (SBLF.Lock)); + + declare + Locker : SB_L_Locker (SBLF.Lock'Access); + pragma Unreferenced (Locker); + begin + Assert (Locked (SBLF.Lock));" +procedure Locked_With_CB_Test is,"begin + + Assert (not Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 0); + + declare + Locker : SB_L_Locker (SBLF.Lock_W_CB'Access); + pragma Unreferenced (Locker); + begin + Assert (Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 1);" +procedure Has_Actually_Locked_Test is,"begin + + declare + Outer_Locker : SB_L_Locker (SBLF.Lock'Access); + begin + Assert (Outer_Locker.Has_Actually_Locked); + + declare + Inner_Locker : SB_L_Locker (SBLF.Lock'Access); + begin + Assert (not Inner_Locker.Has_Actually_Locked);" +procedure Has_Actually_Locked_With_CB_Test is,"begin + + declare + Outer_Locker : SB_L_Locker (SBLF.Lock_W_CB'Access); + begin + Assert (Outer_Locker.Has_Actually_Locked); + Assert (SBLF.N = 1); + + declare + Inner_Locker : SB_L_Locker (SBLF.Lock_W_CB'Access); + begin + Assert (not Inner_Locker.Has_Actually_Locked); + Assert (SBLF.N = 1);" +procedure Allocator_Test is,"type SB_L_Locker_Access is access SB_L_Locker; + + procedure Free + is new Ada.Unchecked_Deallocation (SB_L_Locker, SB_L_Locker_Access); + + Locker_Access_1, Locker_Access_2 : SB_L_Locker_Access; + + begin + + Assert (not Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 0); + + Locker_Access_1 := new SB_L_Locker (SBLF.Lock_W_CB'Access); + Assert (Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 1); + Assert (Locker_Access_1.Has_Actually_Locked); + + Locker_Access_2 := new SB_L_Locker (SBLF.Lock_W_CB'Access); + Assert (Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 1); + Assert (not Locker_Access_2.Has_Actually_Locked); + + Assert (Locker_Access_1.Has_Actually_Locked); + Free (Locker_Access_1); + Assert (Locker_Access_1 = null); + Assert (not Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 0); + + Assert (not Locker_Access_2.Has_Actually_Locked); + Free (Locker_Access_2); + Assert (Locker_Access_2 = null); + Assert (not Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 0); + + Locker_Access_1 := new SB_L_Locker (SBLF.Lock_W_CB'Access); + Assert (Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 1); + Assert (Locker_Access_1.Has_Actually_Locked); + + Locker_Access_2 := new SB_L_Locker (SBLF.Lock_W_CB'Access); + Assert (Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 1); + + Assert (not Locker_Access_2.Has_Actually_Locked); + Free (Locker_Access_2); + Assert (Locker_Access_2 = null); + Assert (Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 1); + + Assert (Locker_Access_1.Has_Actually_Locked); + Free (Locker_Access_1); + Assert (Locker_Access_1 = null); + Assert (not Locked (SBLF.Lock_W_CB)); + Assert (SBLF.N = 0);" +procedure Scope_Debug_Create_Test is,"begin + + Assert (SDF.Scope_Entry_Count = 0); + Assert (SDF.Scope_Exit_Count = 0); + + declare + C_D_T : Controlled_Debug_Tracer := Create (""Scope_Debug_Create_Test""); + pragma Unreferenced (C_D_T); + begin + Assert (SDF.Scope_Entry_Count = 1); + Assert (SDF.Scope_Exit_Count = 0);" +procedure Scope_Debug_Create_A_Test is,"begin + + Assert (SDF.Scope_Entry_Count = 0); + Assert (SDF.Scope_Exit_Count = 0); + + declare + C_D_T : Controlled_Debug_Tracer + := Create_A (""Scope_Debug_Create_A_Test""); + pragma Unreferenced (C_D_T); + begin + Assert (SDF.Scope_Entry_Count = 1); + Assert (SDF.Scope_Exit_Count = 0);" +procedure Scope_Debug_Create_A_E_Test is,"begin + + Assert (SDF.Scope_Entry_Count = 0); + Assert (SDF.Scope_Exit_Count = 0); + + begin + + declare + C_D_T : Controlled_Debug_Tracer + := Create_A (""Scope_Debug_Create_A_Test""); + pragma Unreferenced (C_D_T); + begin + Assert (SDF.Scope_Entry_Count = 1); + Assert (SDF.Scope_Exit_Count = 0); + raise Program_Error;" +procedure Scope_Debug_Create_I_Test is,"begin + + Assert (SDF.Scope_Entry_Count = 0); + Assert (SDF.Scope_Exit_Count = 0); + + declare + C_D_T : Controlled_Debug_Tracer + := Create_I (""Scope_Debug_Create_I_Test""); + pragma Unreferenced (C_D_T); + begin + Assert (SDF.Scope_Entry_Count = 1); + Assert (SDF.Scope_Exit_Count = 0);" +procedure Scope_Debug_Create_F_Test is,"begin + + Assert (SDF.Scope_Entry_Count = 0); + Assert (SDF.Scope_Exit_Count = 0); + + declare + C_D_T : Controlled_Debug_Tracer + := Create_F (""Scope_Debug_Create_F_Test""); + pragma Unreferenced (C_D_T); + begin + Assert (SDF.Scope_Entry_Count = 0); + Assert (SDF.Scope_Exit_Count = 0);" +procedure Scope_Debug_Create_N_Test is,"begin + + Assert (SDF.Scope_Entry_Count = 0); + Assert (SDF.Scope_Exit_Count = 0); + + declare + C_D_T : Controlled_Debug_Tracer + := Create_N (""Scope_Debug_Create_N_Test""); + pragma Unreferenced (C_D_T); + begin + Assert (SDF.Scope_Entry_Count = 0); + Assert (SDF.Scope_Exit_Count = 0);" +procedure Shared_Instance_Access_Setter_L_Null_CB_Test is,"use Ada.Tags; + use SIFLI_Shared_Instance_L; + + begin + + Assert (not SIFLI_Shared_Instance_L.Locked); + Assert (not SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance = null); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + + declare + package Outer_A_S is new SIFLI_Shared_Instance_L.Access_Setter + (Inst_Access => SIFLI_Concrete_1_Instance'Access); + begin + Assert (SIFLI_Shared_Instance_L.Locked); + Assert (SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance + = + SIFLI_Concrete_1_Instance'Access); + Assert (SIFLI_Shared_Instance_L.Instance'Tag = SIFLI_Concrete_1'Tag); + Assert (SIFLI_Shared_Instance_L.Instance.Primitive = '1'); + Assert (SIF.Lock_Count = 1); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_A_S.Has_Actually_Set); + + declare + package Inner_A_S is new SIFLI_Shared_Instance_L.Access_Setter + (Inst_Access => SIFLI_Concrete_2_Instance'Access); + begin + Assert (SIFLI_Shared_Instance_L.Locked); + Assert (SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance + = + SIFLI_Concrete_1_Instance'Access); + Assert (SIFLI_Shared_Instance_L.Instance'Tag + = + SIFLI_Concrete_1'Tag); + Assert (SIFLI_Shared_Instance_L.Instance.Primitive = '1'); + Assert (SIF.Lock_Count = 1); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_A_S.Has_Actually_Set); + Assert (not Inner_A_S.Has_Actually_Set);" +procedure Shared_Instance_Access_Setter_L_Null_CB_E_Test is,"use Ada.Tags; + use SIFLI_Shared_Instance_L; + + begin + + Assert (not SIFLI_Shared_Instance_L.Locked); + Assert (not SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance = null); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + + begin + + declare + package Outer_A_S is new SIFLI_Shared_Instance_L.Access_Setter + (Inst_Access => SIFLI_Concrete_1_Instance'Access); + begin + Assert (SIFLI_Shared_Instance_L.Locked); + Assert (SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance + = + SIFLI_Concrete_1_Instance'Access); + Assert (SIFLI_Shared_Instance_L.Instance'Tag + = + SIFLI_Concrete_1'Tag); + Assert (SIFLI_Shared_Instance_L.Instance.Primitive = '1'); + Assert (SIF.Lock_Count = 1); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_A_S.Has_Actually_Set); + raise Program_Error;" +procedure Shared_Instance_Access_Setter_U_Null_CB_Test is,"use Ada.Tags; + use SIFLI_Shared_Instance_U; + + begin + + Assert (not SIFLI_Shared_Instance_U.Locked); + Assert (not SIFLI_Shared_Instance_U.Instantiated); + Assert (SIFLI_Shared_Instance_U.Instance = null); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + + declare + package Outer_A_S is new SIFLI_Shared_Instance_U.Access_Setter + (Inst_Access => SIFLI_Concrete_2_Instance'Access); + begin + Assert (SIFLI_Shared_Instance_U.Locked); + Assert (SIFLI_Shared_Instance_U.Instantiated); + Assert (SIFLI_Shared_Instance_U.Instance + = + SIFLI_Concrete_2_Instance'Access); + Assert (SIFLI_Shared_Instance_U.Instance'Tag = SIFLI_Concrete_2'Tag); + Assert (SIFLI_Shared_Instance_U.Instance.Primitive = '2'); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_A_S.Has_Actually_Set); + + declare + package Inner_A_S is new SIFLI_Shared_Instance_U.Access_Setter + (Inst_Access => SIFLI_Concrete_2_Instance'Access); + begin + Assert (SIFLI_Shared_Instance_U.Locked); + Assert (SIFLI_Shared_Instance_U.Instantiated); + Assert (SIFLI_Shared_Instance_U.Instance + = + SIFLI_Concrete_2_Instance'Access); + Assert (SIFLI_Shared_Instance_U.Instance'Tag + = + SIFLI_Concrete_2'Tag); + Assert (SIFLI_Shared_Instance_U.Instance.Primitive = '2'); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_A_S.Has_Actually_Set); + Assert (not Inner_A_S.Has_Actually_Set);" +procedure Shared_Instance_Access_Setter_CB_Test is,"begin + + Assert (SIF.CB_Calls_Count = 0); + + declare + package A_S is new SIFLI_Shared_Instance_L.Access_Setter + (Inst_Access => SIFLI_Concrete_1_Instance'Access, + CB => CB); + pragma Unreferenced (A_S); + begin + Assert (SIF.CB_Calls_Count = 1);" +procedure Shared_Instance_Creator_L_Null_CB_Test is,"use Ada.Tags; + use SIFLI_Shared_Instance_L; + + begin + + Assert (not SIFLI_Shared_Instance_L.Locked); + Assert (not SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance = null); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + + declare + package Outer_C is new SIFLI_Shared_Instance_L.Creator + (Allocate => Allocate_SIFLI_Concrete_1_L); + begin + Assert (SIFLI_Shared_Instance_L.Locked); + Assert (SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance'Tag = SIFLI_Concrete_1'Tag); + Assert (SIFLI_Shared_Instance_L.Instance.Primitive = '1'); + Assert (SIF.Lock_Count = 1); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_C.Has_Actually_Created); + + declare + package Inner_C is new SIFLI_Shared_Instance_L.Creator + (Allocate => Allocate_SIFLI_Concrete_2_L); + begin + Assert (SIFLI_Shared_Instance_L.Locked); + Assert (SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance'Tag + = + SIFLI_Concrete_1'Tag); + Assert (SIFLI_Shared_Instance_L.Instance.Primitive = '1'); + Assert (SIF.Lock_Count = 1); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_C.Has_Actually_Created); + Assert (not Inner_C.Has_Actually_Created);" +procedure Shared_Instance_Creator_L_Null_CB_J_P_Test is,"use SIFLI_Shared_Instance_L; + + begin + + Assert (not SIFLI_Shared_Instance_L.Locked); + Assert (not SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance = null); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + + declare + package Outer_C is new SIFLI_Shared_Instance_L.Creator + (Allocate => Allocate_SIFLI_Concrete_1_L, + Just_Pretend => True); + begin + Assert (SIFLI_Shared_Instance_L.Locked); + Assert (not SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance = null); + Assert (SIF.Lock_Count = 1); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_C.Has_Actually_Created); + + declare + package Inner_C is new SIFLI_Shared_Instance_L.Creator + (Allocate => Allocate_SIFLI_Concrete_2_L); + begin + Assert (SIFLI_Shared_Instance_L.Locked); + Assert (not SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance = null); + Assert (SIF.Lock_Count = 1); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_C.Has_Actually_Created); + Assert (not Inner_C.Has_Actually_Created);" +procedure Shared_Instance_Creator_U_Null_CB_Test is,"use Ada.Tags; + use SIFLI_Shared_Instance_U; + + begin + + Assert (not SIFLI_Shared_Instance_U.Locked); + Assert (not SIFLI_Shared_Instance_U.Instantiated); + Assert (SIFLI_Shared_Instance_U.Instance = null); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + + declare + package Outer_C is new SIFLI_Shared_Instance_U.Creator + (Allocate => Allocate_SIFLI_Concrete_2_U); + begin + Assert (SIFLI_Shared_Instance_U.Locked); + Assert (SIFLI_Shared_Instance_U.Instantiated); + Assert (SIFLI_Shared_Instance_U.Instance'Tag = SIFLI_Concrete_2'Tag); + Assert (SIFLI_Shared_Instance_U.Instance.Primitive = '2'); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_C.Has_Actually_Created); + + declare + package Inner_C is new SIFLI_Shared_Instance_U.Creator + (Allocate => Allocate_SIFLI_Concrete_2_U); + begin + Assert (SIFLI_Shared_Instance_U.Locked); + Assert (SIFLI_Shared_Instance_U.Instantiated); + Assert (SIFLI_Shared_Instance_U.Instance'Tag + = + SIFLI_Concrete_2'Tag); + Assert (SIFLI_Shared_Instance_U.Instance.Primitive = '2'); + Assert (SIF.Lock_Count = 0); + Assert (SIF.Unlock_Count = 0); + Assert (Outer_C.Has_Actually_Created); + Assert (not Inner_C.Has_Actually_Created);" +procedure Shared_Instance_Creator_CB_Test is,"begin + + Assert (SIF.CB_Calls_Count = 0); + + declare + package C is new SIFLI_Shared_Instance_L.Creator + (Allocate => Allocate_SIFLI_Concrete_1_L, + CB => CB); + pragma Unreferenced (C); + begin + Assert (SIF.CB_Calls_Count = 1);" +procedure Shared_Instance_Fallback_Switch_Test is,"use Ada.Tags; + use SIFLI_Shared_Instance_L; + + package F_S is new SIFLI_Shared_Instance_L.Fallback_Switch + (Fallback_Instance => SIFLI_Concrete_2_Instance'Access); + + begin + + Assert (not SIFLI_Shared_Instance_L.Locked); + Assert (not SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance = null); + Assert (F_S.Instance_FS'Tag = SIFLI_Concrete_2'Tag); + Assert (F_S.Instance_FS.Primitive = '2'); + + declare + package A_S is new SIFLI_Shared_Instance_L.Access_Setter + (Inst_Access => SIFLI_Concrete_1_Instance'Access); + begin + + Assert (SIFLI_Shared_Instance_L.Locked); + Assert (SIFLI_Shared_Instance_L.Instantiated); + Assert (SIFLI_Shared_Instance_L.Instance'Tag = SIFLI_Concrete_1'Tag); + Assert (SIFLI_Shared_Instance_L.Instance.Primitive = '1'); + Assert (A_S.Has_Actually_Set); + Assert (F_S.Instance_FS'Tag = SIFLI_Concrete_1'Tag); + Assert (F_S.Instance_FS.Primitive = '1');" +procedure Free is new Ada.Unchecked_Deallocation,"(Object => Exception_Occurrence, + Name => Exception_Occurrence_Access); + + begin + + Inc (Crossing_Count); + + if not Permanently_Opened then + + if Sat (Crossing_Count) then + Permanent_Opening_Cause + := Saturation; -- Causes Permanently_Opened to be True from + -- from now on. + C_D_T.Trace (""Test node barrier saturated""); + elsif Val (Crossing_Count) > Expected_Tag'Length then + Permanent_Opening_Cause := Overflow; -- Ditto. + Crossing_Count_On_Overflow := Val (Crossing_Count) - 1; + C_D_T.Trace (""Test node barrier overflowed""); + end if; + + end if; + + if not Permanently_Opened then + declare + Excep : Exception_Occurrence_Access := Event_Data.E; + begin + Validate (Val (Crossing_Count), + Event_Kind, + Event_Data, + Char, + Char_To_Tag, + Msg_Pref); + Free (Excep); -- Free the exception allocated by Save_Occurrence + -- in the Report_ primitives of + -- Test_Reporter_W_Barrier. + exception + when E : others => -- Probably + -- Ada.Assertions.Assertion_Error. + C_D_T.Trace (Msg_Pref & Exception_Message (E)); + Failed_Validation_Flag := True; + Failed_Val := True;" +procedure Assert_Node_Tags is,"Not_All_Desc : constant String + := "" elements are not all descendant of ""; + + Dup_Tag : constant String := ""Duplicate tag in array ""; + + begin + + Ada.Assertions.Assert + ((for all E of Simu_Case => + Is_Descendant_At_Same_Level (E'Tag, Simu_Test_Case'Tag)), + ""Simu_Case"" & Not_All_Desc & ""Simu_Test_Case""); + + Ada.Assertions.Assert + ((for all K_1 in Simu_Case'Range => + (for all K_2 in Simu_Case'Range => + K_1 = K_2 + or else + Simu_Case(K_1)'Tag /= Simu_Case(K_2)'Tag)), + Dup_Tag & ""Simu_Case""); + + Ada.Assertions.Assert + ((for all E of Slave_Runner_Arr => + Is_Descendant_At_Same_Level (E'Tag, Test_Runner_Sequential'Tag)), + ""Slave_Runner_Arr"" & Not_All_Desc & ""Test_Runner_Sequential""); + + Ada.Assertions.Assert + (not (for some E of Slave_Runner_Arr => + E'Tag = Test_Runner_Sequential_W_Slave_Tasks'Tag), + ""No element in Slave_Runner_Arr should have the tag of "" + & ""Test_Runner_Sequential_W_Slave_Tasks""); + + Ada.Assertions.Assert + ((for all K_1 in Slave_Runner_Arr'Range => + (for all K_2 in Slave_Runner_Arr'Range => + K_1 = K_2 + or else + Slave_Runner_Arr(K_1)'Tag /= Slave_Runner_Arr(K_2)'Tag)), + Dup_Tag & ""Slave_Runner_Arr""); + + end Assert_Node_Tags; + + ---------------------------------------------------------------------------- + + procedure Assert_Barrier_Status + (Barrier : not null Test_Node_Barrier_Access; + Expected_Tag_Length : Natural) is + + F : constant Boolean := Barrier.Timed_Out; + N : constant Natural := Barrier.Cross_Count_On_Time_Out; + M : constant String := (if F then + (if N = 0 then + "", no crossing happened"" + else + "" after crossing "") + else + """"); + Image_N : String := (if F and then N > 0 then + Positive'Image (N) + else + """"); + + begin + + if Image_N'Length > 0 then + Image_N(Image_N'First) := '#'; + end if; + Ada.Assertions.Assert (not Barrier.Timed_Out, + ""Barrier timed out"" & M & Image_N); + + Ada.Assertions.Assert (not Barrier.Saturated, + ""Barrier saturated (quite an exploit)""); + + Ada.Assertions.Assert (not Barrier.Overflowed, ""Barrier overflowed, "" + & ""looks like Expected_Tag.all'Length should be greater (than"" + & Integer'Image (Barrier.Cross_Count_On_Overflow) & "")""); + + Ada.Assertions.Assert (Barrier.Completed, + ""Expected_Tag'Length is"" & Integer'Image (Expected_Tag_Length) + & (if Barrier.Cross_Count = 0 then + "", O crossing done"" + else + "", only"" & Natural'Image (Barrier.Cross_Count) + & "" crossing(s) done"")); + + Ada.Assertions.Assert (not Barrier.Failed_Validation, + ""Failed validation, please analyse trace for details""); + + end Assert_Barrier_Status; + + ---------------------------------------------------------------------------- + + function Ind (A : Test_Node_Char_Array) return Test_Node_Array is + + Ret : Test_Node_Array (1 .. A'Length) := (others => A(A'First)); + K : Test_Node_Count := 0; + + begin + + for E of A loop + K := K + 1; + Ret(K) := E; + end loop; + + return Ret;" +procedure Process is,"begin + K := K + 1; + if Node_Tag_Tree(K).Node_Tag = Parent_Tag then + A.Parent_Index := K; + end if; + end Process; + + begin + + A.Parent_Index := 0; + + while A.Parent_Index = 0 and then K < Node_Tag_Tree'Last loop + Process; + end loop; + K := 0; + while A.Parent_Index = 0 and then K < K_Node_Tag_Tree loop + Process; + end loop; + Ada.Assertions.Assert + (A.Parent_Index /= 0, + ""Unable to build Node_Tag_Tree array"");" +procedure Free is new Ada.Unchecked_Deallocation,"(Object => Test_Node_Array, + Name => Test_Node_Array_Access); + + begin + + Free (Obj.A); + + end Finalize; + + ---------------------------------------------------------------------------- + + overriding + procedure Run + (Obj : in out Test_Runner_Sequential_W_Slave_Tasks; + Outcome : out Test_Outcome; + Kind : Run_Kind := Assert_Cond_And_Run_Test) + is + + use Private_Test_Reporter; + + R_A : constant Shared_Instance.Instance_Type_Access + := Shared_Instance.Instance_Type_Access (Obj.Reporter_Access); + + procedure CB is new SB_Lock_CB_procedure (SBLCB_Access => Obj.R_A_S_CB); + + package Test_Reporter_Access_Setter is new Shared_Instance.Access_Setter + (Inst_Access => R_A, + CB => CB); + + pragma Unreferenced (Test_Reporter_Access_Setter); + + ----------------------------------------------------- + + procedure Run_Test is + + Node_Task : Slave_Node_Task_Array (Obj.Slaves.A'Range); + Ex : Exception_Occurrence_Access; + + procedure Free is new Ada.Unchecked_Deallocation + (Object => Exception_Occurrence, + Name => Exception_Occurrence_Access); + + begin + + for K in Node_Task'Range loop + Node_Task(K).Start_Run (Obj.Slaves.A(K)); + end loop; + + Test_Runner_Sequential (Obj).Run (Outcome); + -- Inherited procedure call. + + for Ta of Node_Task loop + declare + Outc : Test_Outcome; + E : Exception_Occurrence_Access; + begin + Ta.Get_Outcome_And_E (Outc, E); + if Ex /= null and then E /= null then + Free (E); + elsif E /= null then + Ex := E; -- Ex will be freed later. + end if; + case Outc is + when Failed => Outcome := Failed; + when Passed => null; + end case;" +procedure Cursor_Left is,"begin + Platform.Put (CSI & ""1D""); + end Cursor_Left; + + procedure Cursor_Right is + begin + Platform.Put (CSI & ""1C""); + end Cursor_Right; + + procedure Cursor_Down is + begin + Platform.Put (CSI & ""B""); + end Cursor_Down; + + procedure Cursor_Up is + begin + Platform.Put (CSI & ""A""); + end Cursor_Up; + + procedure Hide_Cursor is + begin + Platform.Put (CSI & ""?25l""); + end Hide_Cursor; + + procedure Show_Cursor is + begin + Platform.Put (CSI & ""?25h""); + end Show_Cursor; + + procedure Scroll_Down is + begin + Platform.Put (CSI & ""T""); + end Scroll_Down; + + procedure Scroll_Up is + begin + Platform.Put (CSI & ""S""); + end Scroll_Up; + + procedure Cursor_Next_Line is + begin + Platform.Put (CSI & ""E""); + end Cursor_Next_Line; + + procedure Erase is + begin + Platform.Put (CSI & 'X'); + end Erase; + + procedure Beginning_Of_Line is + begin + Platform.Put (CSI & ""1G""); + end Beginning_Of_Line; + + procedure Clear_Line is + begin + Platform.Put (CSI & 'K'); + end Clear_Line; + + procedure Report_Cursor_Position is + begin + Platform.Put (CSI & ""6n""); + end Report_Cursor_Position; + + procedure Set_Cursor_Position (C : Cursor_Position) is + use Ada.Strings; + use Ada.Strings.Fixed; + begin + Platform.Put (CSI & Trim (C.Row'Image, Left) & "";"" & Trim (C.Col'Image, Left) & ""H""); + end Set_Cursor_Position; + + function Get_Cursor_Position return VT100.Cursor_Position is + begin + loop + VT100.Report_Cursor_Position; + declare + Result : constant String := Platform.Get_Input; + Semicolon_Index : constant Natural := Ada.Strings.Fixed.Index(Result, "";"", 1); + Row : Integer := 1; + Col : Integer := 1; + begin + -- The cursor position is reported as + -- ESC [ ROW ; COL R + + -- May throw on bad parse. + Row := Integer'Value(Result(3 .. Semicolon_Index - 1)); + Col := Integer'Value(Result(Semicolon_Index + 1 .. Result'Length - 1)); + + return VT100.Cursor_Position'(Row => Row, Col => Col); + exception + -- Bad parse due to existing input on the line. + when Constraint_Error => + null;" +procedure Run_Print_Input is,"subtype Key_Enter is Integer with + Static_Predicate => Key_Enter in 10 | 13; + begin + loop + declare + Input : constant ASU.Unbounded_String := ASU.To_Unbounded_String (TT.Platform.Get_Input); + begin + AIO.New_Line; + if Trendy_Terminal.Maps.Is_Key (ASU.To_String (Input)) then + AIO.Put_Line (TT.Maps.Key'Image (Trendy_Terminal.Maps.Key_For (ASU.To_String (Input)))); + end if; + + for X in 1 .. ASU.Length (Input) loop + if Character'Pos (ASU.Element (Input, X)) in Key_Enter then + return; + end if; + AIO.Put_Line (Character'Pos (ASU.Element (Input, X))'Image); + end loop;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (Ada, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := 1; + Time_Slice_Value := 0; + WC_Encoding := 'b'; + Locking_Policy := 'C'; + Queuing_Policy := ' '; + Task_Dispatching_Policy := 'F'; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 1; + Default_Stack_Size := -1; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Ada.Strings.Text_Buffers'Elab_Spec; + E096 := E096 + 1; + System.Bb.Timing_Events'Elab_Spec; + E094 := E094 + 1; + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + Ada.Tags'Elab_Body; + E105 := E105 + 1; + System.Exception_Table'Elab_Body; + E045 := E045 + 1; + E047 := E047 + 1; + E022 := E022 + 1; + Ada.Streams'Elab_Spec; + E130 := E130 + 1; + System.Finalization_Root'Elab_Spec; + E136 := E136 + 1; + Ada.Finalization'Elab_Spec; + E134 := E134 + 1; + System.Storage_Pools'Elab_Spec; + E138 := E138 + 1; + System.Finalization_Masters'Elab_Spec; + System.Finalization_Masters'Elab_Body; + E133 := E133 + 1; + Ada.Real_Time'Elab_Body; + E006 := E006 + 1; + Ada.Real_Time.Timing_Events'Elab_Spec; + E235 := E235 + 1; + Ada.Strings.Maps'Elab_Spec; + E241 := E241 + 1; + Ada.Strings.Unbounded'Elab_Spec; + E237 := E237 + 1; + System.Pool_Global'Elab_Spec; + E140 := E140 + 1; + System.Tasking.Protected_Objects'Elab_Body; + E219 := E219 + 1; + System.Tasking.Restricted.Stages'Elab_Body; + E226 := E226 + 1; + E253 := E253 + 1; + HAL.GPIO'ELAB_SPEC; + E161 := E161 + 1; + HAL.I2C'ELAB_SPEC; + E128 := E128 + 1; + HAL.SPI'ELAB_SPEC; + E175 := E175 + 1; + HAL.UART'ELAB_SPEC; + E185 := E185 + 1; + LSM303AGR'ELAB_SPEC; + LSM303AGR'ELAB_BODY; + E127 := E127 + 1; + E217 := E217 + 1; + E215 := E215 + 1; + E210 := E210 + 1; + Nrf.Gpio'Elab_Spec; + Nrf.Gpio'Elab_Body; + E155 := E155 + 1; + E212 := E212 + 1; + E170 := E170 + 1; + Nrf.Spi_Master'Elab_Spec; + Nrf.Spi_Master'Elab_Body; + E173 := E173 + 1; + E197 := E197 + 1; + E195 := E195 + 1; + E260 := E260 + 1; + Nrf.Timers'Elab_Spec; + Nrf.Timers'Elab_Body; + E177 := E177 + 1; + Nrf.Twi'Elab_Spec; + Nrf.Twi'Elab_Body; + E180 := E180 + 1; + Nrf.Uart'Elab_Spec; + Nrf.Uart'Elab_Body; + E183 := E183 + 1; + Nrf.Device'Elab_Spec; + Nrf.Device'Elab_Body; + E146 := E146 + 1; + Microbit.Console'Elab_Body; + E231 := E231 + 1; + Microbit.Displayrt'Elab_Body; + E233 := E233 + 1; + E255 := E255 + 1; + E189 := E189 + 1; + Microbit.Accelerometer'Elab_Body; + E187 := E187 + 1; + Microbit.Radio'Elab_Spec; + E257 := E257 + 1; + Microbit.Timewithrtc1'Elab_Spec; + Microbit.Timewithrtc1'Elab_Body; + E193 := E193 + 1; + Microbit.Buttons'Elab_Body; + E191 := E191 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + procedure main is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (Ada, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := 0; + Time_Slice_Value := 0; + WC_Encoding := 'b'; + Locking_Policy := 'C'; + Queuing_Policy := ' '; + Task_Dispatching_Policy := 'F'; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 1; + Default_Stack_Size := -1; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 4; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Ada.Strings.Text_Buffers'Elab_Spec; + E005 := E005 + 1; + System.Bb.Timing_Events'Elab_Spec; + E059 := E059 + 1; + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + Ada.Tags'Elab_Body; + E061 := E061 + 1; + System.Exception_Table'Elab_Body; + E096 := E096 + 1; + E098 := E098 + 1; + E012 := E012 + 1; + Ada.Streams'Elab_Spec; + E148 := E148 + 1; + System.Finalization_Root'Elab_Spec; + E155 := E155 + 1; + Ada.Finalization'Elab_Spec; + E153 := E153 + 1; + System.Storage_Pools'Elab_Spec; + E157 := E157 + 1; + System.Finalization_Masters'Elab_Spec; + System.Finalization_Masters'Elab_Body; + E152 := E152 + 1; + Ada.Real_Time'Elab_Body; + E125 := E125 + 1; + System.Pool_Global'Elab_Spec; + E159 := E159 + 1; + System.Tasking.Protected_Objects'Elab_Body; + E222 := E222 + 1; + System.Tasking.Restricted.Stages'Elab_Body; + E229 := E229 + 1; + HAL.GPIO'ELAB_SPEC; + E150 := E150 + 1; + HAL.I2C'ELAB_SPEC; + E182 := E182 + 1; + HAL.SPI'ELAB_SPEC; + E175 := E175 + 1; + HAL.UART'ELAB_SPEC; + E186 := E186 + 1; + LSM303AGR'ELAB_SPEC; + LSM303AGR'ELAB_BODY; + E253 := E253 + 1; + E195 := E195 + 1; + E193 := E193 + 1; + E212 := E212 + 1; + Nrf.Gpio'Elab_Spec; + Nrf.Gpio'Elab_Body; + E141 := E141 + 1; + E214 := E214 + 1; + E216 := E216 + 1; + E170 := E170 + 1; + Nrf.Spi_Master'Elab_Spec; + Nrf.Spi_Master'Elab_Body; + E173 := E173 + 1; + E199 := E199 + 1; + E197 := E197 + 1; + E243 := E243 + 1; + E218 := E218 + 1; + E241 := E241 + 1; + Nrf.Timers'Elab_Spec; + Nrf.Timers'Elab_Body; + E177 := E177 + 1; + Nrf.Twi'Elab_Spec; + Nrf.Twi'Elab_Body; + E180 := E180 + 1; + Nrf.Uart'Elab_Spec; + Nrf.Uart'Elab_Body; + E184 := E184 + 1; + Nrf.Device'Elab_Spec; + Nrf.Device'Elab_Body; + E131 := E131 + 1; + Microbit.Console'Elab_Body; + E188 := E188 + 1; + E257 := E257 + 1; + Microbit.Accelerometer'Elab_Body; + E255 := E255 + 1; + Microbit.Iosfortasking'Elab_Spec; + Microbit.Iosfortasking'Elab_Body; + E190 := E190 + 1; + Microbit.Radio'Elab_Spec; + E238 := E238 + 1; + Microbit.Timehighspeed'Elab_Body; + E245 := E245 + 1; + Mybrain'Elab_Spec; + E247 := E247 + 1; + Mymotordriver'Elab_Spec; + E234 := E234 + 1; + Taskact'Elab_Spec; + Taskact'Elab_Body; + E123 := E123 + 1; + Drivingstatesfsm'Elab_Spec; + E263 := E263 + 1; + E261 := E261 + 1; + Taskthink'Elab_Spec; + Taskthink'Elab_Body; + E259 := E259 + 1; + E249 := E249 + 1; + E251 := E251 + 1; + Tasksense'Elab_Spec; + Tasksense'Elab_Body; + E236 := E236 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + procedure main is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize;" +procedure SetupMotors is,"Pins : MotorControllerPins; + + begin + Pins.LeftFrontSpeedEnA := 0; + Pins.LeftFrontPin1In1 := 6; + Pins.LeftFrontPin2In2 := 7; + Pins.LeftBackSpeedEnB := 0; + Pins.LeftBackPin1In3 := 2; + Pins.LeftBackPin2In4 := 3; + + Pins.RightFrontSpeedEnA := 1; + Pins.RightFrontPin1In1 := 12; + Pins.RightFrontPin2In2 := 13; + Pins.RightBackSpeedEnB := 1; + Pins.RightBackPin1In3 := 14; + Pins.RightBackPin2In4 := 15; + + MotorDriver.SetMotorPins(Pins); + + Set_Analog_Period_Us (20_000); + + null;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (Ada, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := 0; + Time_Slice_Value := 0; + WC_Encoding := 'b'; + Locking_Policy := 'C'; + Queuing_Policy := ' '; + Task_Dispatching_Policy := 'F'; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 1; + Default_Stack_Size := -1; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 4; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Ada.Text_Io'Elab_Body; + E249 := E249 + 1; + Ada.Strings.Text_Buffers'Elab_Spec; + E005 := E005 + 1; + System.Bb.Timing_Events'Elab_Spec; + E059 := E059 + 1; + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + Ada.Tags'Elab_Body; + E061 := E061 + 1; + System.Exception_Table'Elab_Body; + E096 := E096 + 1; + E098 := E098 + 1; + E012 := E012 + 1; + Ada.Streams'Elab_Spec; + E157 := E157 + 1; + System.Finalization_Root'Elab_Spec; + E164 := E164 + 1; + Ada.Finalization'Elab_Spec; + E162 := E162 + 1; + System.Storage_Pools'Elab_Spec; + E166 := E166 + 1; + System.Finalization_Masters'Elab_Spec; + System.Finalization_Masters'Elab_Body; + E161 := E161 + 1; + Ada.Real_Time'Elab_Body; + E134 := E134 + 1; + System.Bb.Execution_Time'Elab_Body; + E132 := E132 + 1; + System.Pool_Global'Elab_Spec; + E168 := E168 + 1; + System.Tasking.Protected_Objects'Elab_Body; + E231 := E231 + 1; + System.Tasking.Restricted.Stages'Elab_Body; + E130 := E130 + 1; + HAL.GPIO'ELAB_SPEC; + E159 := E159 + 1; + HAL.I2C'ELAB_SPEC; + E191 := E191 + 1; + HAL.SPI'ELAB_SPEC; + E184 := E184 + 1; + HAL.UART'ELAB_SPEC; + E195 := E195 + 1; + LSM303AGR'ELAB_SPEC; + LSM303AGR'ELAB_BODY; + E266 := E266 + 1; + E204 := E204 + 1; + E202 := E202 + 1; + E221 := E221 + 1; + Nrf.Gpio'Elab_Spec; + Nrf.Gpio'Elab_Body; + E150 := E150 + 1; + E223 := E223 + 1; + E225 := E225 + 1; + E179 := E179 + 1; + Nrf.Spi_Master'Elab_Spec; + Nrf.Spi_Master'Elab_Body; + E182 := E182 + 1; + E208 := E208 + 1; + E206 := E206 + 1; + E256 := E256 + 1; + E227 := E227 + 1; + E254 := E254 + 1; + Nrf.Timers'Elab_Spec; + Nrf.Timers'Elab_Body; + E186 := E186 + 1; + Nrf.Twi'Elab_Spec; + Nrf.Twi'Elab_Body; + E189 := E189 + 1; + Nrf.Uart'Elab_Spec; + Nrf.Uart'Elab_Body; + E193 := E193 + 1; + Nrf.Device'Elab_Spec; + Nrf.Device'Elab_Body; + E140 := E140 + 1; + Microbit.Console'Elab_Body; + E197 := E197 + 1; + E270 := E270 + 1; + Microbit.Accelerometer'Elab_Body; + E268 := E268 + 1; + Microbit.Iosfortasking'Elab_Spec; + Microbit.Iosfortasking'Elab_Body; + E199 := E199 + 1; + Microbit.Radio'Elab_Spec; + E251 := E251 + 1; + Microbit.Timehighspeed'Elab_Body; + E258 := E258 + 1; + Mybrain'Elab_Spec; + E260 := E260 + 1; + Mymotordriver'Elab_Spec; + E238 := E238 + 1; + Drivingstatesfsm'Elab_Spec; + E276 := E276 + 1; + E274 := E274 + 1; + Taskact'Elab_Spec; + Taskact'Elab_Body; + E123 := E123 + 1; + Taskthink'Elab_Spec; + Taskthink'Elab_Body; + E272 := E272 + 1; + E262 := E262 + 1; + E264 := E264 + 1; + Tasksense'Elab_Spec; + Tasksense'Elab_Body; + E247 := E247 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + procedure main is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize;" +procedure SetupMotors is,"Pins : MotorControllerPins; + + begin + Pins.LeftFrontSpeedEnA := 0; -- set you MB pins here. Note that some pins overlap with other M:B functions! See the Microbit package to inspect which function lives on which pin. + Pins.LeftFrontPin1In1 := 6; + Pins.LeftFrontPin2In2 := 7; + Pins.LeftBackSpeedEnB := 0; + Pins.LeftBackPin1In3 := 2; + Pins.LeftBackPin2In4 := 3; + + Pins.RightFrontSpeedEnA := 1; + Pins.RightFrontPin1In1 := 12; + Pins.RightFrontPin2In2 := 13; + Pins.RightBackSpeedEnB := 1; + Pins.RightBackPin1In3 := 14; + Pins.RightBackPin2In4 := 15; + + MotorDriver.SetMotorPins(Pins); + + --For example set the PWM period, as you only need to do this once + Set_Analog_Period_Us (20_000); --20 ms = 50 Hz, typical for many actuators. You can change this, check the motor behavior with an oscilloscope. + + null;" +procedure Test is,"function ""+"" + (Text : Wide_Wide_String) return League.Strings.Universal_String + renames League.Strings.To_Universal_String; + + function Headless return League.JSON.Values.JSON_Value; + + -------------- + -- Headless -- + -------------- + + function Headless return League.JSON.Values.JSON_Value is + Cap : League.JSON.Objects.JSON_Object; + Options : League.JSON.Objects.JSON_Object; + Args : League.JSON.Arrays.JSON_Array; + begin + return Cap.To_JSON_Value; + pragma Warnings (Off); + Args.Append (League.JSON.Values.To_JSON_Value (+""--headless"")); + Args.Append (League.JSON.Values.To_JSON_Value (+""--disable-extensions"")); + Args.Append (League.JSON.Values.To_JSON_Value (+""--no-sandbox"")); + Options.Insert (+""args"", Args.To_JSON_Value); + Options.Insert + (+""binary"", + League.JSON.Values.To_JSON_Value + (+""/usr/lib64/chromium-browser/headless_shell"")); + Cap.Insert (+""chromeOptions"", Options.To_JSON_Value); + return Cap.To_JSON_Value; + end Headless; + + Web_Driver : aliased WebDriver.Drivers.Driver'Class + := WebDriver.Remote.Create (+""http://127.0.0.1:9515""); + Session : constant WebDriver.Sessions.Session_Access := + Web_Driver.New_Session (Headless); +begin + Session.Go (+""http://www.ada-ru.org/""); + + Ada.Wide_Wide_Text_IO.Put_Line + (Session.Get_Current_URL.To_Wide_Wide_String); + + declare + Body_Element : constant WebDriver.Elements.Element_Access := + Session.Find_Element + (Strategy => WebDriver.Tag_Name, + Selector => +""body""); + begin + Ada.Wide_Wide_Text_IO.Put_Line + (""Selected="" & Boolean'Wide_Wide_Image (Body_Element.Is_Selected)); + Ada.Wide_Wide_Text_IO.Put_Line + (""itemtype="" & + Body_Element.Get_Attribute (+""itemtype"").To_Wide_Wide_String); + Ada.Wide_Wide_Text_IO.Put_Line + (""height="" & + Body_Element.Get_CSS_Value (+""height"").To_Wide_Wide_String); + Ada.Wide_Wide_Text_IO.Put_Line + (""tag="" & Body_Element.Get_Tag_Name.To_Wide_Wide_String);" +procedure Example is,"Addr : constant League.Strings.Universal_String := + League.Application.Arguments.Element (1); + Error : League.Strings.Universal_String; + Manager : Network.Managers.Manager; + Promise : Network.Connection_Promises.Promise; +begin + Manager.Initialize; + Network.Managers.TCP_V4.Register (Manager); + + Manager.Connect + (Address => Network.Addresses.To_Address (Addr), + Error => Error, + Promise => Promise); + + if not Error.Is_Empty then + Ada.Wide_Wide_Text_IO.Put_Line + (""Connect fails: "" & Error.To_Wide_Wide_String); + return; + end if; + + declare + Listener : aliased Listeners.Listener := + (Promise => Promise, others => <>); + begin + Promise.Add_Listener (Listener'Unchecked_Access); + + for J in 1 .. 100 loop + Manager.Wait (1.0); + exit when Listener.Done; + end loop;" +procedure Free is new Ada.Unchecked_Deallocation,"(List_Node, List_Node_Access); + + function Has_Listener + (Self : Promise'Class; + Value : not null Listener_Access) return Boolean; + + ------------------ + -- Add_Listener -- + ------------------ + + not overriding procedure Add_Listener + (Self : in out Promise'Class; + Value : not null Listener_Access) + is + Parent : constant Controller_Access := Self.Parent; + begin + case Parent.Data.State is + when Pending => + if not Self.Has_Listener (Value) then + Parent.Data.Listeners := new List_Node' + (Item => Value, + Next => Parent.Data.Listeners); + end if; + when Resolved => + Value.On_Resolve (Parent.Data.Resolve_Value); + when Rejected => + Value.On_Reject (Parent.Data.Reject_Value); + end case; + end Add_Listener; + + -------------- + -- Finalize -- + -------------- + + overriding procedure Finalize (Self : in out Controller) is + begin + if Self.Data.State = Pending then + declare + Next : List_Node_Access := Self.Data.Listeners; + begin + while Next /= null loop + declare + Item : List_Node_Access := Next; + begin + Next := Item.Next; + Free (Item);" +function Has_Listener,"(Self : Promise'Class; + Value : not null Listener_Access) return Boolean + is + Next : List_Node_Access := Self.Parent.Data.Listeners; + begin + while Next /= null loop + if Next.Item = Value then + return True; + end if; + + Next := Next.Next; + end loop; + + return False; + end Has_Listener; + + ----------------- + -- Is_Attached -- + ----------------- + + function Is_Attached (Self : Promise'Class) return Boolean is + begin + return Self.Parent /= null; + end Is_Attached; + + ---------------- + -- Is_Pending -- + ---------------- + + function Is_Pending (Self : Promise'Class) return Boolean is + begin + return Self.Parent.Is_Pending; + end Is_Pending; + + function Is_Pending (Self : Controller'Class) return Boolean is + begin + return Self.Data.State = Pending; + end Is_Pending; + + ----------------- + -- Is_Rejected -- + ----------------- + + function Is_Rejected (Self : Promise'Class) return Boolean is + begin + return Self.Parent.Is_Rejected; + end Is_Rejected; + + function Is_Rejected (Self : Controller'Class) return Boolean is + begin + return Self.Data.State = Rejected; + end Is_Rejected; + + ----------------- + -- Is_Resolved -- + ----------------- + + function Is_Resolved (Self : Promise'Class) return Boolean is + begin + return Self.Parent.Is_Resolved; + end Is_Resolved; + + function Is_Resolved (Self : Controller'Class) return Boolean is + begin + return Self.Data.State = Resolved; + end Is_Resolved; + + ------------ + -- Reject -- + ------------ + + procedure Reject (Self : in out Controller'Class; + Value : Reject_Element) is + Next : List_Node_Access := Self.Data.Listeners; + begin + Self.Data := (Rejected, Value); + + while Next /= null loop + declare + Item : List_Node_Access := Next; + begin + Item.Item.On_Reject (Self.Data.Reject_Value); + Next := Item.Next; + Free (Item);" +procedure Remove_Listener,"(Self : in out Promise'Class; + Value : not null Listener_Access) + is + Next : List_Node_Access := Self.Parent.Data.Listeners; + begin + if Next.Item = Value then + Self.Parent.Data.Listeners := Next.Next; + Free (Next); + end if; + + while Next /= null loop + if Next.Next /= null + and then Next.Next.Item = Value + then + Next.Next := Next.Next.Next; + Free (Next); + + exit; + end if; + end loop; + end Remove_Listener; + + ------------- + -- Resolve -- + ------------- + + procedure Resolve (Self : in out Controller'Class; + Value : Resolve_Element) is + Next : List_Node_Access := Self.Data.Listeners; + begin + Self.Data := (Resolved, Value); + + while Next /= null loop + declare + Item : List_Node_Access := Next; + begin + Item.Item.On_Resolve (Self.Data.Resolve_Value); + Next := Item.Next; + Free (Item);" +overriding function Has_Listener (Self : Out_Socket) return Boolean is,"begin + return Self.Listener.Assigned; + end Has_Listener; + + --------------- + -- Is_Closed -- + --------------- + + overriding function Is_Closed (Self : Out_Socket) return Boolean is + begin + return Self.Is_Closed; + end Is_Closed; + + -------------- + -- On_Event -- + -------------- + + overriding procedure On_Event + (Self : in out Out_Socket; + Events : Network.Polls.Event_Set) + is + use type Network.Connections.Listener_Access; + + function Get_Error return League.Strings.Universal_String; + procedure Disconnect (Error : League.Strings.Universal_String); + + ---------------- + -- Disconnect -- + ---------------- + + procedure Disconnect (Error : League.Strings.Universal_String) is + begin + Self.Change_Watch ((others => False)); + GNAT.Sockets.Close_Socket (Self.Internal); + Self.Is_Closed := True; + + if Self.Listener.Assigned then + Self.Listener.Closed (Error); + end if; + end Disconnect; + + --------------- + -- Get_Error -- + --------------- + + function Get_Error return League.Strings.Universal_String is + use type GNAT.Sockets.Error_Type; + + Option : constant GNAT.Sockets.Option_Type := + GNAT.Sockets.Get_Socket_Option + (Self.Internal, + GNAT.Sockets.Socket_Level, + GNAT.Sockets.Error); + begin + if Option.Error = GNAT.Sockets.Success then + return League.Strings.Empty_Universal_String; + else + return League.Strings.To_Universal_String + (GNAT.Sockets.Error_Type'Wide_Wide_Image (Option.Error)); + end if; + end Get_Error; + + Prev : constant Network.Polls.Event_Set := Self.Events; + -- Active poll events + + Input : constant Network.Polls.Event := Network.Polls.Input; + Output : constant Network.Polls.Event := Network.Polls.Output; + Listener : array (Input .. Output) of Network.Connections.Listener_Access + := (others => Self.Listener); + + Again : Boolean := True; + + begin + Self.In_Event := True; + + if Self.Promise.Is_Pending then + Self.Error := Get_Error; + + if Self.Error.Is_Empty then + Self.Events := (others => False); -- no events before listener + Self.Promise.Resolve (Self'Unchecked_Access); + -- Usually it changes Listener + + if Self.Listener.Assigned then + if not Self.Events (Polls.Output) then + Self.Events := not Write_Event; -- We can write now + Self.Listener.Can_Write; + else + Self.Events := (others => True); + end if; + end if; + + if Self.Events /= Prev then + Self.Change_Watch (Self.Events); + end if; + else + Disconnect (Self.Error); + Self.Promise.Reject (Self.Error); + end if; + elsif Self.Is_Closed then + -- Connection has been closed, but some events arrive after that. + null; + else + pragma Assert (Self.Listener.Assigned); + pragma Assert (Self.Error.Is_Empty); + + Self.Events := Self.Events and not Events; + + -- Report read event to current listener + if Events (Input) then -- Have something to read + Self.Listener.Can_Read; + -- This can change Self.Events, Self.Listener or close + end if; + + -- Report write event to current listener + if Events (Output) + and not Self.Events (Output) -- Have space to write + and Self.Listener = Listener (Output) + and not Self.Is_Closed + then + Self.Listener.Can_Write; + -- This can change Self.Events, Self.Listener or close + end if; + + -- Now report to changed listener if any + while Again loop + Again := False; + + if not Self.Events (Input) -- Can read + and Self.Listener /= Listener (Input) + and not Self.Is_Closed + then + Listener (Input) := Self.Listener; + Self.Listener.Can_Read; + Again := True; + end if; + + if not Self.Events (Output) -- Can write + and Self.Listener /= Listener (Output) + and not Self.Is_Closed + then + Listener (Output) := Self.Listener; + Self.Listener.Can_Write; + Again := True; + end if; + end loop; + + if Self.Is_Closed then + Disconnect (League.Strings.Empty_Universal_String); + elsif not Self.Error.Is_Empty then + Disconnect (Self.Error); + elsif Events (Network.Polls.Error) then + Disconnect (Get_Error); + elsif Events (Network.Polls.Close) then + Disconnect (League.Strings.Empty_Universal_String); + elsif Self.Events /= Prev then + Self.Change_Watch (Self.Events); + end if; + end if; + + Self.In_Event := False; + end On_Event; + + ---------- + -- Read -- + ---------- + + overriding procedure Read + (Self : in out Out_Socket; + Data : out Ada.Streams.Stream_Element_Array; + Last : out Ada.Streams.Stream_Element_Offset) + is + use type Ada.Streams.Stream_Element_Offset; + use type GNAT.Sockets.Error_Type; + + Kind : GNAT.Sockets.Error_Type; + begin + GNAT.Sockets.Receive_Socket (Self.Internal, Data, Last); + + if Last < Data'First then -- End of stream + Self.Is_Closed := True; + + if not Self.In_Event then + raise Program_Error with ""Unimplemented""; + end if; + end if; + + exception + when E : GNAT.Sockets.Socket_Error => + Last := Data'First - 1; + Kind := GNAT.Sockets.Resolve_Exception (E); + + if Kind /= GNAT.Sockets.Resource_Temporarily_Unavailable then + Self.Is_Closed := True; + Self.Error := League.Strings.From_UTF_8_String + (Ada.Exceptions.Exception_Message (E)); + + if not Self.In_Event then + raise Program_Error with ""Unimplemented""; + end if; + + elsif Self.In_Event then + Self.Events := Self.Events or Read_Event; + + else + Self.Change_Watch (Self.Events or Read_Event); + end if; + end Read; + + ------------ + -- Remote -- + ------------ + + overriding function Remote (Self : Out_Socket) + return Network.Addresses.Address + is + Result : League.Strings.Universal_String; + Value : GNAT.Sockets.Sock_Addr_Type; + begin + Value := GNAT.Sockets.Get_Peer_Name (Self.Internal); + Result.Append (""/ip4/""); + Result.Append + (League.Strings.From_UTF_8_String (GNAT.Sockets.Image (Value.Addr))); + Result.Append (""/tcp/""); + + declare + Port : constant Wide_Wide_String := Value.Port'Wide_Wide_Image; + begin + Result.Append (Port (2 .. Port'Last)); + + return Network.Addresses.To_Address (Result);" +overriding function Can_Listen,"(Self : Protocol; Address : Network.Addresses.Address) return Boolean + renames Can_Connect; + + ------------- + -- Connect -- + ------------- + + overriding procedure Connect + (Self : in out Protocol; + Address : Network.Addresses.Address; + Poll : in out Network.Polls.Poll; + Error : out League.Strings.Universal_String; + Promise : out Network.Connection_Promises.Promise; + Options : League.String_Vectors.Universal_String_Vector := + League.String_Vectors.Empty_Universal_String_Vector) + is + pragma Unreferenced (Options, Self); + + Req : GNAT.Sockets.Request_Type := + (GNAT.Sockets.Non_Blocking_IO, Enabled => True); + + List : constant League.String_Vectors.Universal_String_Vector := + Network.Addresses.To_String (Address).Split ('/'); + + Internal : GNAT.Sockets.Socket_Type; + Addr : GNAT.Sockets.Sock_Addr_Type; + Socket : Out_Socket_Access; + begin + Addr.Addr := GNAT.Sockets.Inet_Addr (List (3).To_UTF_8_String); + Addr.Port := GNAT.Sockets.Port_Type'Wide_Wide_Value + (List (5).To_Wide_Wide_String); + + GNAT.Sockets.Create_Socket (Internal); + GNAT.Sockets.Control_Socket (Internal, Req); + + begin + GNAT.Sockets.Connect_Socket (Internal, Addr); + exception -- Ignore Operation_Now_In_Progress + when E : GNAT.Sockets.Socket_Error => + declare + Kind : constant GNAT.Sockets.Error_Type := + GNAT.Sockets.Resolve_Exception (E); + begin + if Kind not in GNAT.Sockets.Operation_Now_In_Progress then + Error := League.Strings.From_UTF_8_String + (Ada.Exceptions.Exception_Message (E)); + return; + end if;" +procedure Listen,"(Self : in out Manager'Class; + List : Network.Addresses.Address_Array; + Listener : Connection_Listener_Access; + Error : out League.Strings.Universal_String; + Options : League.String_Vectors.Universal_String_Vector := + League.String_Vectors.Empty_Universal_String_Vector) + is + Done : array (List'Range) of Boolean := (List'Range => False); + begin + for Proto of Self.Proto (1 .. Self.Last) loop + declare + Ok : League.Strings.Universal_String; + Slice : Network.Addresses.Address_Array (List'Range); + Last : Natural := Slice'First - 1; + begin + for J in List'Range loop + if not Done (J) and then Proto.Can_Listen (List (J)) then + Done (J) := True; + Last := Last + 1; + Slice (Last) := List (J); + end if; + end loop; + + if Last >= Slice'First then + Proto.Listen + (Slice (Slice'First .. Last), + Listener, + Self.Poll, + Ok, + Options); + + Error.Append (Ok); + end if;" +function Convert is new Ada.Unchecked_Conversion,"(Raw_Protocol_Name, Protocol_Name); + + Raw : Ada.Streams.Stream_Element_Count; + begin + Read (Stream, Raw); + Value := Convert (Raw_Protocol_Name (Raw)); + end Read_Protocol_Name; + + ---------------- + -- To_Address -- + ---------------- + + function To_Address + (Value : League.Strings.Universal_String) return Address is + begin + return (Value => Value); + end To_Address; + + ---------------- + -- To_Address -- + ---------------- + + function To_Address + (Value : Ada.Streams.Stream_Element_Array) return Address + is + use type Ada.Streams.Stream_Element_Count; + + UTF : constant League.Text_Codecs.Text_Codec := + League.Text_Codecs.Codec (+""utf-8""); + + S : aliased Simple_Stream := + (Ada.Streams.Root_Stream_Type with + Size => Value'Length, + Last => 0, + Data => Value); + Result : League.Strings.Universal_String; + Proto : Protocol_Name; + Length : Ada.Streams.Stream_Element_Count; + begin + while S.Last < S.Size loop + Protocol_Name'Read (S'Access, Proto); + Result.Append ('/'); + Result.Append (Image (Proto)); + + case Proto is + when ip4 => + declare + Addr : IP4_Raw; + begin + Result.Append ('/'); + IP4_Raw'Read (S'Access, Addr); + Result.Append (Image (Addr (1))); + + for X in 2 .. 4 loop + Result.Append ('.'); + Result.Append (Image (Addr (X))); + end loop;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Strings.Unbounded, + Ada.Text_IO; + use Utils; + + subtype Big_Cave_Character is Character range 'A' .. 'Z'; + subtype Small_Cave_Character is Character range 'a' .. 'z'; + + package Cave_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, + Element_Type => String, + ""="" => ""=""); + use Cave_Vectors; + + type Cave_Kind is (K_Start, K_Big, K_Small, K_End); + Start_Name : constant String := ""start""; + End_Name : constant String := ""end""; + + -- Given the name of a node, it retreive the corresponding kind + function Get_Kind (Name : String) return Cave_Kind; + + -------------- + -- Get_Kind -- + -------------- + + function Get_Kind (Name : String) return Cave_Kind is + begin + if Name = Start_Name then + return K_Start; + elsif Name = End_Name then + return K_End; + elsif Name (Name'First) in Big_Cave_Character then + return K_Big; + elsif Name (Name'First) in Small_Cave_Character then + return K_Small; + end if; + raise Constraint_Error with ""Unexpected cave name: "" & Name; + end Get_Kind; + + type Cave_Info (Length : Positive) is record + Name : String (1 .. Length); + Kind : Cave_Kind; + Adjacent : Vector; + end record; + + package Cave_Maps is new Ada.Containers.Indefinite_Hashed_Maps + (Key_Type => String, + Element_Type => Cave_Info, + Hash => Ada.Strings.Hash, + Equivalent_Keys => ""=""); + + package String_Sets is new Ada.Containers.Indefinite_Hashed_Sets (Element_Type => String, + Hash => Ada.Strings.Hash, + Equivalent_Elements => ""="", + ""="" => ""=""); + + type Cave_Explorer is record + Name : Unbounded_String; + Already_Visited_Small_Cave_Name : Unbounded_String; + Already_Visited_Small_Cave : String_Sets.Set; + end record; + + package Explored_Cave_Interfaces is + new Ada.Containers.Synchronized_Queue_Interfaces + (Element_Type => Cave_Explorer); + + package Explored_Cave_Queue is new Ada.Containers.Unbounded_Synchronized_Queues + (Queue_Interfaces => Explored_Cave_Interfaces); + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Result : Natural := Natural'First; + Nodes : Cave_Maps.Map := Cave_Maps.Empty_Map; +begin + Get_File (File); + + -- Get all values + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Separator_Index : constant Integer := + Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => ""-""); + Node_1 : constant String := Str (1 .. Separator_Index - 1); + Node_2 : constant String := Str (Separator_Index + 1 .. Str'Last); + begin + declare + Cave_Node_1 : Cave_Info := (Length => Node_1'Length, + Name => Node_1, + Kind => Get_Kind (Node_1), + Adjacent => Empty_Vector); + + Cave_Node_2 : Cave_Info := (Length => Node_2'Length, + Name => Node_2, + Kind => Get_Kind (Node_2), + Adjacent => Empty_Vector); + begin + if Nodes.Contains (Node_1) then + Cave_Node_1 := Nodes.Element (Node_1); + end if; + if Nodes.Contains (Node_2) then + Cave_Node_2 := Nodes.Element (Node_2); + end if; + + Cave_Node_1.Adjacent.Append (Node_2); + Cave_Node_2.Adjacent.Append (Node_1); + + Nodes.Include (Node_1, Cave_Node_1); + Nodes.Include (Node_2, Cave_Node_2);" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Strings.Unbounded, + Ada.Text_IO; + use Utils; + + subtype Big_Cave_Character is Character range 'A' .. 'Z'; + subtype Small_Cave_Character is Character range 'a' .. 'z'; + + package Cave_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, + Element_Type => String, + ""="" => ""=""); + use Cave_Vectors; + + type Cave_Kind is (K_Start, K_Big, K_Small, K_End); + Start_Name : constant String := ""start""; + End_Name : constant String := ""end""; + + -- Given the name of a node, it retreive the corresponding kind + function Get_Kind (Name : String) return Cave_Kind; + + -------------- + -- Get_Kind -- + -------------- + + function Get_Kind (Name : String) return Cave_Kind is + begin + if Name = Start_Name then + return K_Start; + elsif Name = End_Name then + return K_End; + elsif Name (Name'First) in Big_Cave_Character then + return K_Big; + elsif Name (Name'First) in Small_Cave_Character then + return K_Small; + end if; + raise Constraint_Error with ""Unexpected cave name: "" & Name; + end Get_Kind; + + type Cave_Info (Length : Positive) is record + Name : String (1 .. Length); + Kind : Cave_Kind; + Adjacent : Vector; + end record; + + package Cave_Maps is new Ada.Containers.Indefinite_Hashed_Maps + (Key_Type => String, + Element_Type => Cave_Info, + Hash => Ada.Strings.Hash, + Equivalent_Keys => ""=""); + + package String_Sets is new Ada.Containers.Indefinite_Hashed_Sets (Element_Type => String, + Hash => Ada.Strings.Hash, + Equivalent_Elements => ""="", + ""="" => ""=""); + + type Cave_Explorer is record + Name : Unbounded_String; + Already_Visited_Small_Cave_Name : Unbounded_String; + Already_Visited_Small_Cave : String_Sets.Set; + end record; + + package Explored_Cave_Interfaces is + new Ada.Containers.Synchronized_Queue_Interfaces + (Element_Type => Cave_Explorer); + + package Explored_Cave_Queue is new Ada.Containers.Unbounded_Synchronized_Queues + (Queue_Interfaces => Explored_Cave_Interfaces); + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Result : Natural := Natural'First; + Nodes : Cave_Maps.Map := Cave_Maps.Empty_Map; +begin + Get_File (File); + + -- Get all values + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Separator_Index : constant Integer := + Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => ""-""); + Node_1 : constant String := Str (1 .. Separator_Index - 1); + Node_2 : constant String := Str (Separator_Index + 1 .. Str'Last); + begin + declare + Cave_Node_1 : Cave_Info := (Length => Node_1'Length, + Name => Node_1, + Kind => Get_Kind (Node_1), + Adjacent => Empty_Vector); + + Cave_Node_2 : Cave_Info := (Length => Node_2'Length, + Name => Node_2, + Kind => Get_Kind (Node_2), + Adjacent => Empty_Vector); + begin + if Nodes.Contains (Node_1) then + Cave_Node_1 := Nodes.Element (Node_1); + end if; + if Nodes.Contains (Node_2) then + Cave_Node_2 := Nodes.Element (Node_2); + end if; + + Cave_Node_1.Adjacent.Append (Node_2); + Cave_Node_2.Adjacent.Append (Node_1); + + Nodes.Include (Node_1, Cave_Node_1); + Nodes.Include (Node_2, Cave_Node_2);" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Strings.Fixed, + Ada.Strings.Unbounded, + Ada.Text_IO; + use Utils; + + package Character_Queue_Interfaces is + new Ada.Containers.Synchronized_Queue_Interfaces (Element_Type => Character); + + package Character_Queues is new Ada.Containers.Unbounded_Synchronized_Queues + (Queue_Interfaces => Character_Queue_Interfaces); + use Character_Queues; + + function Pop (Q : in out Queue; N : Positive; Nb_Delete : in out Natural) return String; + + function Pop (Q : in out Queue; N : Positive; Nb_Delete : in out Natural) return String is + Result : String (1 .. N); + begin + for Index in 1 .. N loop + Q.Dequeue (Result (Index)); + end loop; + Nb_Delete := Nb_Delete + N; + return Result; + end Pop; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Result : Natural := Natural'First; + Packet : Queue; +begin + Get_File (File); + + -- Get all values + declare + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Value : Natural; + Temp : String (1 .. 8); + begin + for Char of Str loop + Value := Natural'Value (""16#"" & Char & ""#""); + Ada.Integer_Text_IO.Put (Temp, + Value, + Base => 2); + File_Is_Empty := False; + + declare + Trimmed : constant String := Trim (Temp, Ada.Strings.Both); + Formatted_Bin_Str : constant String := + Tail (Trimmed (Trimmed'First + 2 .. Trimmed'Last - 1), 4, '0'); + begin + for Elt of Formatted_Bin_Str loop + Packet.Enqueue (Elt); + end loop;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Strings.Fixed, + Ada.Strings.Unbounded, + Ada.Text_IO; + use Utils; + + package Character_Queue_Interfaces is + new Ada.Containers.Synchronized_Queue_Interfaces (Element_Type => Character); + + package Character_Queues is new Ada.Containers.Unbounded_Synchronized_Queues + (Queue_Interfaces => Character_Queue_Interfaces); + use Character_Queues; + + function Pop (Q : in out Queue; N : Positive; Nb_Delete : in out Long_Long_Natural) return String; + + function Pop (Q : in out Queue; N : Positive; Nb_Delete : in out Long_Long_Natural) return String is + Result : String (1 .. N); + begin + for Index in 1 .. N loop + Q.Dequeue (Result (Index)); + end loop; + Nb_Delete := Nb_Delete + Long_Long_Natural (N); + return Result; + end Pop; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Result : Long_Long_Natural := Long_Long_Natural'First; + Packet : Queue; +begin + Get_File (File); + + -- Get all values + declare + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Value : Natural; + Temp : String (1 .. 8); + begin + for Char of Str loop + Value := Natural'Value (""16#"" & Char & ""#""); + Ada.Integer_Text_IO.Put (Temp, + Value, + Base => 2); + File_Is_Empty := False; + + declare + Trimmed : constant String := Trim (Temp, Ada.Strings.Both); + Formatted_Bin_Str : constant String := + Tail (Trimmed (Trimmed'First + 2 .. Trimmed'Last - 1), 4, '0'); + begin + for Elt of Formatted_Bin_Str loop + Packet.Enqueue (Elt); + end loop;" +procedure Main is,"use Ada.Text_IO; + use Utils; + + package L9 renames Ada.Characters.Latin_9; + + type Movements is (Forward, Down, Up); + + File : File_Type; + Horizontal_Position : Natural := 0; + Depth : Natural := 0; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + declare + Line : constant String := Get_Line (File); + begin + Split_Value : for Index in Line'Range loop + if Line (Index) = L9.Space then + Solve_Puzzle : declare + Movement : constant Movements := Movements'Value (Line (Line'First .. Index - 1)); + Value : constant Natural := Natural'Value (Line (Index + 1 .. Line'Last)); + begin + case Movement is + when Forward => + Horizontal_Position := Horizontal_Position + Value; + when Down => + Depth := Depth + Value; + when Up => + Depth := Depth - Value; + end case; + end Solve_Puzzle; + exit Split_Value; + end if; + + end loop Split_Value;" +procedure Main is,"use Ada.Text_IO; + use Utils; + + package L9 renames Ada.Characters.Latin_9; + + type Movements is (Forward, Down, Up); + + File : File_Type; + Horizontal_Position : Natural := 0; + Depth : Natural := 0; + Aim : Natural := 0; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + declare + Line : constant String := Get_Line (File); + begin + Split_Value : for Index in Line'Range loop + if Line (Index) = L9.Space then + Solve_Puzzle : declare + Movement : constant Movements := Movements'Value (Line (Line'First .. Index - 1)); + Value : constant Natural := Natural'Value (Line (Index + 1 .. Line'Last)); + begin + case Movement is + when Forward => + Horizontal_Position := Horizontal_Position + Value; + Depth := Depth + Aim * Value; + when Down => + Aim := Aim + Value; + when Up => + Aim := Aim - Value; + end case; + end Solve_Puzzle; + exit Split_Value; + end if; + + end loop Split_Value;" +procedure Main is,"use Ada.Text_IO; + use Utils; + + File : File_Type; + Result : Natural := Natural'First; +begin + Get_File (File); + + if End_Of_File (File) then + raise Program_Error with ""Empty file""; + end if; + + -- Resolve puzzle while exploring file + while not End_Of_File (File) loop + declare + use Ada.Integer_Text_IO; + Line : constant String := Get_Line (File); + First : Positive := Line'First; + Last : Positive := Line'First; + Last_Index : Positive := Line'First; + After_Pipe : Boolean := False; + Current_Size : Natural := Natural'First; + begin + while Last <= Line'Last loop + if After_Pipe then + -- Process data + if Line (Last) = ' ' then + Current_Size := Last - First; + First := Last + 1; + + if Current_Size in 2 .. 4 or Current_Size = 7 then + Result := Result + 1; + end if; + elsif Last = Line'Last then + Current_Size := Last - First + 1; + First := Last + 1; + + if Current_Size in 2 .. 4 or Current_Size = 7 then + Result := Result + 1; + end if; + end if; + + Last := Last + 1; + elsif Line (Last) = '|' then + After_Pipe := True; + + Last := Last + 2; + First := Last; + else + Last := Last + 1; + end if; + end loop;" +procedure Main is,"use Ada.Text_IO; + use Utils; + + package Digit_Str is new + Ada.Strings.Bounded.Generic_Bounded_Length (Max => 7); + use Digit_Str; + + subtype Segment is Character range 'a' .. 'g'; + subtype Digit is Bounded_String; + subtype Seven_Segments_Digits is Natural range 0 .. 9; + + -- Sort the characters in a String + procedure String_Sort is new Ada.Containers.Generic_Array_Sort (Positive, Character, String); + + function Digit_Hash is new Ada.Strings.Bounded.Hash (Digit_Str); + + package Segments_To_Digit_Maps is new Ada.Containers.Indefinite_Hashed_Maps + (Key_Type => Digit, + Element_Type => Seven_Segments_Digits, + Hash => Digit_Hash, + Equivalent_Keys => ""=""); + + function Segment_Hash (Elt : Segment) return Ada.Containers.Hash_Type is + (Ada.Containers.Hash_Type (Segment'Pos (Elt))); + + package Mapping_Table_Maps is new Ada.Containers.Indefinite_Hashed_Maps + (Key_Type => Segment, + Element_Type => Segment, + Hash => Segment_Hash, + Equivalent_Keys => ""=""); + + subtype Digits_Array_Index is Positive range 1 .. 10; + type Digits_Array is array (Digits_Array_Index) of Digit; + + function Is_Lower_Than (Left, Right : Digit) return Boolean is (Length (Left) < Length (Right)); + + procedure Digits_Sort is new Ada.Containers.Generic_Constrained_Array_Sort (Index_Type => Digits_Array_Index, + Element_Type => Digit, + Array_Type => Digits_Array, + ""<"" => Is_Lower_Than); + + -- Given a String that represent a segment (like ""be"", or ""fgaecd"", etc.) it retrieve the corresponding segment. + -- Note: when the word ""associated"" is used, it means that we cannot know exactly which segment corresponds + -- to which other segment. + -- When the word ""corresponding"" is used, it means that we know exactly which segment corresponds to which + -- other segment. + -- + -- @param Seg a String that represent a digit + -- @returns Retruns the corresponding mapping table between segments of digits + function Get_Corresponding_Segments (Digit_Array : Digits_Array) return Mapping_Table_Maps.Map; + + -------------------------------- + -- Get_Corresponding_Segments -- + -------------------------------- + + function Get_Corresponding_Segments (Digit_Array : Digits_Array) return Mapping_Table_Maps.Map is + use Mapping_Table_Maps; + + Mapping_Table : Mapping_Table_Maps.Map; + CF_Seg, + BD_Seg, + EG_Seg : Digit := Null_Bounded_String; + Can_Break_CF, + Can_Break_BD : Boolean := False; + begin + -- Get the number 1 to get associated segments ""c"" and ""f"" + CF_Seg := Digit_Array (1); + + -- Get the number 7 to find the corresponding segment of ""a"" + for Char of To_String (Digit_Array (2)) loop + if Index (CF_Seg, Char & """", 1) = 0 then + Mapping_Table.Include (Char, 'a'); + exit; + end if; + end loop; + + -- Get the number 4 to find associated to ""b"" and ""d"" + for Char of To_String (Digit_Array (3)) loop + if Index (CF_Seg, Char & """", 1) = 0 then + BD_Seg := BD_Seg & Char; + end if; + end loop; + + for Idx in 7 .. 9 loop + -- Find the number 6 to find corresponding segment of ""f"" and ""c"" + if (Index (Digit_Array (Idx), Element (CF_Seg, 1) & """") > 0) /= + (Index (Digit_Array (Idx), Element (CF_Seg, 2) & """") > 0) + then + if Index (Digit_Array (Idx), Element (CF_Seg, 1) & """") > 0 then + Mapping_Table.Include (Element (CF_Seg, 1), 'f'); + Mapping_Table.Include (Element (CF_Seg, 2), 'c'); + else + Mapping_Table.Include (Element (CF_Seg, 2), 'f'); + Mapping_Table.Include (Element (CF_Seg, 1), 'c'); + end if; + Can_Break_CF := True; + end if; + + -- Find the number 0 to find corresponding segment of ""b"" and ""d"" + if (Index (Digit_Array (Idx), Element (BD_Seg, 1) & """") > 0) /= + (Index (Digit_Array (Idx), Element (BD_Seg, 2) & """") > 0) + then + if Index (Digit_Array (Idx), Element (BD_Seg, 1) & """") > 0 then + Mapping_Table.Include (Element (BD_Seg, 1), 'b'); + Mapping_Table.Include (Element (BD_Seg, 2), 'd'); + else + Mapping_Table.Include (Element (BD_Seg, 2), 'b'); + Mapping_Table.Include (Element (BD_Seg, 1), 'd'); + end if; + Can_Break_BD := True; + end if; + + if Can_Break_CF and Can_Break_BD then + exit; + end if; + end loop; + + for Char in Character range 'a' .. 'g' loop + if not Mapping_Table.Contains (Char) then + EG_Seg := EG_Seg & Char; + end if; + end loop; + + -- Find the number 9 to find corresponding segment of ""e"" and ""g"" + for Idx in 7 .. 10 loop + if (Index (Digit_Array (Idx), Element (EG_Seg, 1) & """") > 0) /= + (Index (Digit_Array (Idx), Element (EG_Seg, 2) & """") > 0) + then + if Index (Digit_Array (Idx), Element (EG_Seg, 1) & """") > 0 then + Mapping_Table.Include (Element (EG_Seg, 1), 'g'); + Mapping_Table.Include (Element (EG_Seg, 2), 'e'); + else + Mapping_Table.Include (Element (EG_Seg, 2), 'g'); + Mapping_Table.Include (Element (EG_Seg, 1), 'e'); + end if; + exit; + end if; + end loop; + + return Mapping_Table; + end Get_Corresponding_Segments; + use Segments_To_Digit_Maps; + + -- Given a Value, it retrieve the original value according to Mapping_Table. + -- @param Mapping_Table The mapping table that correspond mixed segment signal with the good segment signal + -- @param Value The digit te retrieve + -- @returns Return the resolved digit + function Digit_Reconstruction (Mapping_Table : Mapping_Table_Maps.Map; Value : Digit) return Digit; + + -------------------------- + -- Digit_Reconstruction -- + -------------------------- + + function Digit_Reconstruction (Mapping_Table : Mapping_Table_Maps.Map; Value : Digit) return Digit is + Result : Digit := Null_Bounded_String; + begin + for Char of To_String (Value) loop + Result := Result & Mapping_Table.Element (Char); + end loop; + + declare + Str : String := To_String (Result); + begin + String_Sort (Str); + Result := To_Bounded_String (Str);" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + type Lanternfish_Life_Span is range -1 .. 8; + subtype Long_Long_Natural is Long_Long_Integer range 0 .. Long_Long_Integer'Last; + type Lanternfishes_School is array (Lanternfish_Life_Span) of Long_Long_Natural; + + package Lanternfish_Life_Span_IO is new Ada.Text_IO.Integer_IO (Lanternfish_Life_Span); + use Lanternfish_Life_Span_IO; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Lanternfishes : Lanternfishes_School := (others => Long_Long_Natural'First); + Nb_Lanternfishes : Long_Long_Natural := Long_Long_Natural'First; +begin + Get_File (File); + + if End_Of_File (File) then + raise Program_Error with ""Empty file""; + end if; + + -- Get all Lanternfishes + while not End_Of_File (File) loop + declare + Line : constant String := Get_Line (File); + First : Positive := Line'First; + Last : Positive := Line'First; + Last_Index : Positive := Line'First; + Value : Lanternfish_Life_Span; + begin + while Last <= Line'Last loop + if Line (Last) not in '0' .. '9' then + if Line (First .. Last - 1) /= """" then + Get (Line (First .. Last - 1), Value, Last_Index); + Lanternfishes (Value) := Lanternfishes (Value) + 1; + end if; + First := Last + 1; + Last := First; + elsif Last = Line'Last then + Get (Line (First .. Line'Last), Value, Last_Index); + Lanternfishes (Value) := Lanternfishes (Value) + 1; + Last := Last + 1; + else + Last := Last + 1; + end if; + end loop;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + type Lanternfish_Life_Span is range -1 .. 8; + subtype Long_Long_Natural is Long_Long_Integer range 0 .. Long_Long_Integer'Last; + type Lanternfishes_School is array (Lanternfish_Life_Span) of Long_Long_Natural; + + package Lanternfish_Life_Span_IO is new Ada.Text_IO.Integer_IO (Lanternfish_Life_Span); + use Lanternfish_Life_Span_IO; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Lanternfishes : Lanternfishes_School := (others => Long_Long_Natural'First); + Nb_Lanternfishes : Long_Long_Natural := Long_Long_Natural'First; +begin + Get_File (File); + + if End_Of_File (File) then + raise Program_Error with ""Empty file""; + end if; + + -- Get all Lanternfishes + while not End_Of_File (File) loop + declare + Line : constant String := Get_Line (File); + First : Positive := Line'First; + Last : Positive := Line'First; + Last_Index : Positive := Line'First; + Value : Lanternfish_Life_Span; + begin + while Last <= Line'Last loop + if Line (Last) not in '0' .. '9' then + if Line (First .. Last - 1) /= """" then + Get (Line (First .. Last - 1), Value, Last_Index); + Lanternfishes (Value) := Lanternfishes (Value) + 1; + end if; + First := Last + 1; + Last := First; + elsif Last = Line'Last then + Get (Line (First .. Line'Last), Value, Last_Index); + Lanternfishes (Value) := Lanternfishes (Value) + 1; + Last := Last + 1; + else + Last := Last + 1; + end if; + end loop;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + subtype Chunks is Character + with Static_Predicate => Chunks in + '(' .. '(' + | '{' .. '{' + | '[' .. '[' + | '<' .. '<' + | ')' .. ')' + | '}' .. '}' + | ']' .. ']' + | '>' .. '>'; + subtype Open_Chunks is Chunks + with Static_Predicate => Open_Chunks in + '(' .. '(' + | '{' .. '{' + | '[' .. '[' + | '<' .. '<'; + subtype Close_Chunks is Chunks + with Static_Predicate => Close_Chunks in + ')' .. ')' + | '}' .. '}' + | ']' .. ']' + | '>' .. '>'; + + function ID_Hashed (Id : Open_Chunks) return Ada.Containers.Hash_Type is + (Ada.Containers.Hash_Type (Open_Chunks'Pos (Id))); + + package Corresponding_Chunk_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Open_Chunks, + Element_Type => Close_Chunks, + Hash => ID_Hashed, + Equivalent_Keys => ""=""); + + package Chunks_Vectors is new Ada.Containers.Vectors (Natural, Chunks); + + package Chunks_Vectors_Vectors is new Ada.Containers.Vectors (Natural, Chunks_Vectors.Vector, Chunks_Vectors.""=""); + + Corresponding_Chunk : Corresponding_Chunk_Maps.Map; + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Values : Chunks_Vectors_Vectors.Vector := Chunks_Vectors_Vectors.Empty_Vector; + Result : Natural := Natural'First; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + declare + use Chunks_Vectors; + + Str : constant String := Get_Line (File); + Row : Vector := Empty_Vector; + begin + for Char of Str loop + Row.Append (Char); + end loop; + Values.Append (Row);" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + subtype Chunks is Character + with Static_Predicate => Chunks in + '(' .. '(' + | '{' .. '{' + | '[' .. '[' + | '<' .. '<' + | ')' .. ')' + | '}' .. '}' + | ']' .. ']' + | '>' .. '>'; + subtype Open_Chunks is Chunks + with Static_Predicate => Open_Chunks in + '(' .. '(' + | '{' .. '{' + | '[' .. '[' + | '<' .. '<'; + subtype Close_Chunks is Chunks + with Static_Predicate => Close_Chunks in + ')' .. ')' + | '}' .. '}' + | ']' .. ']' + | '>' .. '>'; + + function ID_Hashed (Id : Open_Chunks) return Ada.Containers.Hash_Type is + (Ada.Containers.Hash_Type (Open_Chunks'Pos (Id))); + + package Corresponding_Chunk_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Open_Chunks, + Element_Type => Close_Chunks, + Hash => ID_Hashed, + Equivalent_Keys => ""=""); + + package Chunks_Vectors is new Ada.Containers.Vectors (Natural, Chunks); + subtype Long_Long_Natural is Long_Long_Integer range 0 .. Long_Long_Integer'Last; + package Natural_Vectors is new Ada.Containers.Vectors (Natural, Long_Long_Natural); + package Natural_Vectors_Sorting is new Natural_Vectors.Generic_Sorting; + + package Chunks_Vectors_Vectors is new Ada.Containers.Vectors (Natural, Chunks_Vectors.Vector, Chunks_Vectors.""=""); + + Corresponding_Chunk : Corresponding_Chunk_Maps.Map; + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Values : Chunks_Vectors_Vectors.Vector := Chunks_Vectors_Vectors.Empty_Vector; + Result : Long_Long_Natural := 0; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + declare + use Chunks_Vectors; + + Str : constant String := Get_Line (File); + Row : Vector := Empty_Vector; + begin + for Char of Str loop + Row.Append (Char); + end loop; + Values.Append (Row);" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + package Natural_Vectors is new Ada.Containers.Vectors (Natural, Natural); + use Natural_Vectors; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Crabs : Vector; + Min_Dist : Natural := Natural'Last; +begin + Get_File (File); + + if End_Of_File (File) then + raise Program_Error with ""Empty file""; + end if; + + -- Get all Lanternfishes + while not End_Of_File (File) loop + declare + use Ada.Integer_Text_IO; + Line : constant String := Get_Line (File); + First : Positive := Line'First; + Last : Positive := Line'First; + Last_Index : Positive := Line'First; + Value : Natural; + begin + while Last <= Line'Last loop + if Line (Last) not in '0' .. '9' then + if Line (First .. Last - 1) /= """" then + Get (Line (First .. Last - 1), Value, Last_Index); + Crabs.Append (Value); + end if; + First := Last + 1; + Last := First; + elsif Last = Line'Last then + Get (Line (First .. Line'Last), Value, Last_Index); + Crabs.Append (Value); + Last := Last + 1; + else + Last := Last + 1; + end if; + end loop;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + package Natural_Vectors is new Ada.Containers.Vectors (Natural, Natural); + use Natural_Vectors; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Crabs : Vector; + Min_Dist, Min : Natural := Natural'Last; + Max : Natural := Natural'First; +begin + Get_File (File); + + if End_Of_File (File) then + raise Program_Error with ""Empty file""; + end if; + + -- Get all Lanternfishes + while not End_Of_File (File) loop + declare + use Ada.Integer_Text_IO; + Line : constant String := Get_Line (File); + First : Positive := Line'First; + Last : Positive := Line'First; + Last_Index : Positive := Line'First; + Value : Natural; + begin + while Last <= Line'Last loop + if Line (Last) not in '0' .. '9' then + if Line (First .. Last - 1) /= """" then + Get (Line (First .. Last - 1), Value, Last_Index); + Crabs.Append (Value); + + if Value < Min then + Min := Value; + end if; + + if Value > Max then + Max := Value; + end if; + end if; + First := Last + 1; + Last := First; + elsif Last = Line'Last then + Get (Line (First .. Line'Last), Value, Last_Index); + Crabs.Append (Value); + + if Value < Min then + Value := Min; + end if; + + if Value > Max then + Value := Max; + end if; + + Last := Last + 1; + else + Last := Last + 1; + end if; + end loop;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Strings.Unbounded, + Ada.Text_IO; + use Utils; + + Max_Steps : constant := 10; + + subtype Rule_Str is String (1 .. 2); + subtype Long_Long_Natural is Long_Long_Integer range 0 .. Long_Long_Integer'Last; + + package Rule_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Rule_Str, + Element_Type => Character, + Hash => Ada.Strings.Hash, + Equivalent_Keys => ""="", + ""="" => ""=""); + + package Rule_Counter_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Rule_Str, + Element_Type => Long_Long_Natural, + Hash => Ada.Strings.Hash, + Equivalent_Keys => ""="", + ""="" => ""=""); + use Rule_Maps; + use Rule_Counter_Maps; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Result : Long_Long_Natural := Long_Long_Natural'First; + Rules : Rule_Maps.Map := Rule_Maps.Empty_Map; + Counter : Rule_Counter_Maps.Map := Rule_Counter_Maps.Empty_Map; + Polymer_Template : Unbounded_String; +begin + Get_File (File); + + Polymer_Template := To_Unbounded_String (Get_Line (File)); + + -- Get all rules + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + begin + if Str'Length = 0 then + goto Continue_Next_Line; + end if; + + declare + Pattern : constant String := "" -> ""; + Separator_Index : constant Integer := + Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => Pattern); + Left_Str : constant String := Str (1 .. Separator_Index - 1); + Right_Str : constant String := Str (Separator_Index + Pattern'Length .. Str'Last); + begin + Rules.Include (Rule_Str (Left_Str), Right_Str (Right_Str'First));" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Strings.Unbounded, + Ada.Text_IO; + use Utils; + + Max_Steps : constant := 40; + + subtype Rule_Str is String (1 .. 2); + subtype Long_Long_Natural is Long_Long_Integer range 0 .. Long_Long_Integer'Last; + + package Rule_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Rule_Str, + Element_Type => Character, + Hash => Ada.Strings.Hash, + Equivalent_Keys => ""="", + ""="" => ""=""); + + package Rule_Counter_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Rule_Str, + Element_Type => Long_Long_Natural, + Hash => Ada.Strings.Hash, + Equivalent_Keys => ""="", + ""="" => ""=""); + use Rule_Maps; + use Rule_Counter_Maps; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Result : Long_Long_Natural := Long_Long_Natural'First; + Rules : Rule_Maps.Map := Rule_Maps.Empty_Map; + Counter : Rule_Counter_Maps.Map := Rule_Counter_Maps.Empty_Map; + Polymer_Template : Unbounded_String; +begin + Get_File (File); + + Polymer_Template := To_Unbounded_String (Get_Line (File)); + + -- Get all rules + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + begin + if Str'Length = 0 then + goto Continue_Next_Line; + end if; + + declare + Pattern : constant String := "" -> ""; + Separator_Index : constant Integer := + Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => Pattern); + Left_Str : constant String := Str (1 .. Separator_Index - 1); + Right_Str : constant String := Str (Separator_Index + Pattern'Length .. Str'Last); + begin + Rules.Include (Rule_Str (Left_Str), Right_Str (Right_Str'First));" +procedure Main is,"use Ada.Text_IO; + use Utils; + + package Integer_Vectors is new Ada.Containers.Vectors (Natural, Integer); + use Integer_Vectors; + + File : File_Type; + Values : Vector := Empty_Vector; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + declare + Value : Natural; + begin + Ada.Integer_Text_IO.Get (File, Value); + Values.Append (Value);" +procedure Main is,"use Ada.Text_IO; + use Utils; + use type Ada.Containers.Count_Type; + + package Integer_Vectors is new Ada.Containers.Vectors (Natural, Integer); + use Integer_Vectors; + + File : File_Type; + Values : Vector := Empty_Vector; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + declare + Value : Natural; + begin + Ada.Integer_Text_IO.Get (File, Value); + Values.Append (Value);" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + Opening_Bracket : constant := -2; + Closing_Bracket : constant := -1; + subtype Snailfish_Values is Integer range Opening_Bracket .. Integer'Last; + + package Snailfish_Math_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Snailfish_Values, + ""="" => ""=""); + use Snailfish_Math_List; + + function ""+"" (Left, Right : List) return List; + function ""+"" (Left, Right : List) return List is + Result : List := Copy (Left); + begin + Result.Prepend (New_Item => Opening_Bracket, + Count => 1); + + for Elt of Right loop + Result.Append (Elt); + end loop; + + Result.Append (Closing_Bracket); + + return Result; + end ""+""; + + function ""+"" (Left : Snailfish_Math_List.Cursor; Right : Positive) return Snailfish_Math_List.Cursor; + + function ""+"" (Left : Snailfish_Math_List.Cursor; Right : Positive) return Snailfish_Math_List.Cursor is + Result : Snailfish_Math_List.Cursor := Left; + begin + for Index in 1 .. Right loop + Result := Next (Result); + end loop; + return Result; + end ""+""; + + function ""-"" (Left : Snailfish_Math_List.Cursor; Right : Positive) return Snailfish_Math_List.Cursor; + + function ""-"" (Left : Snailfish_Math_List.Cursor; Right : Positive) return Snailfish_Math_List.Cursor is + Result : Snailfish_Math_List.Cursor := Left; + begin + for Index in 1 .. Right loop + Result := Previous (Result); + end loop; + return Result; + end ""-""; + + procedure Put (Snailfish_Number : List); + + procedure Put (Snailfish_Number : List) is + Curs : Snailfish_Math_List.Cursor := Snailfish_Number.First; + begin + while Has_Element (Curs) loop + case Element (Curs) is + when Opening_Bracket => + Put (""[""); + when Closing_Bracket => + Put (""]""); + if Has_Element (Curs + 1) and then Element (Curs + 1) = Opening_Bracket then + Put ("", ""); + end if; + when others => + if Element (Curs - 1) > Closing_Bracket then + Put ("", ""); + end if; + Ada.Integer_Text_IO.Put (Item => Element (Curs), Width => 0); + end case; + Curs := Curs + 1; + end loop; + end Put; + + package Snailfish_Math_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, + Element_Type => List, + ""="" => ""=""); + use Snailfish_Math_Vectors; + + function Pop (Vec : in out Vector) return List; + + function Pop (Vec : in out Vector) return List is + Result : List; + begin + if Vec.Is_Empty then + raise Constraint_Error with ""Container is empty""; + end if; + Result := Vec.First_Element; + Vec.Delete_First; + return Result; + end Pop; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Result : Natural := Natural'First; + Result_List : List; + Input : Vector; +begin + Get_File (File); + + -- Get all values + declare + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Last : Positive; + Value : Natural; + Snailfish_Number : List; + begin + for Char of Str loop + case Char is + when '[' => + Snailfish_Number.Append (Opening_Bracket); + when ']' => + Snailfish_Number.Append (Closing_Bracket); + when '0' .. '9' => + Ada.Integer_Text_IO.Get (Char & """", Value, Last); + Snailfish_Number.Append (Value); + when others => + null; + end case; + File_Is_Empty := False; + end loop; + Input.Append (Snailfish_Number);" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + Opening_Bracket : constant := -2; + Closing_Bracket : constant := -1; + subtype Snailfish_Values is Integer range Opening_Bracket .. Integer'Last; + + package Snailfish_Math_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Snailfish_Values, + ""="" => ""=""); + use Snailfish_Math_List; + + function ""+"" (Left, Right : List) return List; + function ""+"" (Left, Right : List) return List is + Result : List := Copy (Left); + begin + Result.Prepend (New_Item => Opening_Bracket, + Count => 1); + + for Elt of Right loop + Result.Append (Elt); + end loop; + + Result.Append (Closing_Bracket); + + return Result; + end ""+""; + + function ""+"" (Left : Snailfish_Math_List.Cursor; Right : Positive) return Snailfish_Math_List.Cursor; + + function ""+"" (Left : Snailfish_Math_List.Cursor; Right : Positive) return Snailfish_Math_List.Cursor is + Result : Snailfish_Math_List.Cursor := Left; + begin + for Index in 1 .. Right loop + Result := Next (Result); + end loop; + return Result; + end ""+""; + + function ""-"" (Left : Snailfish_Math_List.Cursor; Right : Positive) return Snailfish_Math_List.Cursor; + + function ""-"" (Left : Snailfish_Math_List.Cursor; Right : Positive) return Snailfish_Math_List.Cursor is + Result : Snailfish_Math_List.Cursor := Left; + begin + for Index in 1 .. Right loop + Result := Previous (Result); + end loop; + return Result; + end ""-""; + + procedure Put (Snailfish_Number : List); + + procedure Put (Snailfish_Number : List) is + Curs : Snailfish_Math_List.Cursor := Snailfish_Number.First; + begin + while Has_Element (Curs) loop + case Element (Curs) is + when Opening_Bracket => + Put (""[""); + when Closing_Bracket => + Put (""]""); + if Has_Element (Curs + 1) and then Element (Curs + 1) = Opening_Bracket then + Put ("", ""); + end if; + when others => + if Element (Curs - 1) > Closing_Bracket then + Put ("", ""); + end if; + Ada.Integer_Text_IO.Put (Item => Element (Curs), Width => 0); + end case; + Curs := Curs + 1; + end loop; + end Put; + + package Snailfish_Math_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, + Element_Type => List, + ""="" => ""=""); + use Snailfish_Math_Vectors; + + function Pop (Vec : in out Vector) return List; + + function Pop (Vec : in out Vector) return List is + Result : List; + begin + if Vec.Is_Empty then + raise Constraint_Error with ""Container is empty""; + end if; + Result := Vec.First_Element; + Vec.Delete_First; + return Result; + end Pop; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Result : Natural := Natural'First; + Result_List : List; + Input : Vector; + Output : Vector; +begin + Get_File (File); + + -- Get all values + declare + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Last : Positive; + Value : Natural; + Snailfish_Number : List; + begin + for Char of Str loop + case Char is + when '[' => + Snailfish_Number.Append (Opening_Bracket); + when ']' => + Snailfish_Number.Append (Closing_Bracket); + when '0' .. '9' => + Ada.Integer_Text_IO.Get (Char & """", Value, Last); + Snailfish_Number.Append (Value); + when others => + null; + end case; + File_Is_Empty := False; + end loop; + Input.Append (Snailfish_Number);" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + package My_Coordinates is new Coordinates_2D (Integer); + use My_Coordinates; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Result : Integer := Integer'First; + + X_Min, X_Max, + Y_Min, Y_Max : Integer; +begin + Get_File (File); + + -- Get all values + declare + procedure Split_Range (Str : String; Lower, Upper : out Integer); + + procedure Split_Range (Str : String; Lower, Upper : out Integer) is + use Ada.Integer_Text_IO; + + Pattern : constant String := ""..""; + Separator_Index : constant Natural := + Ada.Strings.Fixed.Index (Source => Str, Pattern => Pattern); + Left_Str : constant String := Str (Str'First .. Separator_Index - 1); + Right_Str : constant String := Str (Separator_Index + Pattern'Length .. Str'Last); + + Last : Positive; + begin + Get (Left_Str, Lower, Last); + Get (Right_Str, Upper, Last); + end Split_Range; + + Str : constant String := Get_Line (File); + Pattern : constant String := "",""; + Separator_Index : constant Natural := + Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => Pattern); + Left_Str : constant String := Str (16 .. Separator_Index - 1); + Right_Str : constant String := Str (Separator_Index + Pattern'Length + 3 .. Str'Last); + + begin + Split_Range (Left_Str, X_Min, X_Max); + Split_Range (Right_Str, Y_Min, Y_Max);" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + package My_Coordinates is new Coordinates_2D (Integer); + use My_Coordinates; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Result : Natural := Natural'First; + + X_Min, X_Max, + Y_Min, Y_Max : Integer; +begin + Get_File (File); + + -- Get all values + declare + procedure Split_Range (Str : String; Lower, Upper : out Integer); + + procedure Split_Range (Str : String; Lower, Upper : out Integer) is + use Ada.Integer_Text_IO; + + Pattern : constant String := ""..""; + Separator_Index : constant Natural := + Ada.Strings.Fixed.Index (Source => Str, Pattern => Pattern); + Left_Str : constant String := Str (Str'First .. Separator_Index - 1); + Right_Str : constant String := Str (Separator_Index + Pattern'Length .. Str'Last); + + Last : Positive; + begin + Get (Left_Str, Lower, Last); + Get (Right_Str, Upper, Last); + end Split_Range; + + Str : constant String := Get_Line (File); + Pattern : constant String := "",""; + Separator_Index : constant Natural := + Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => Pattern); + Left_Str : constant String := Str (16 .. Separator_Index - 1); + Right_Str : constant String := Str (Separator_Index + Pattern'Length + 3 .. Str'Last); + + begin + Split_Range (Left_Str, X_Min, X_Max); + Split_Range (Right_Str, Y_Min, Y_Max);" +procedure Main is,"use Ada.Containers, Ada.Text_IO; + use Utils; + + type Binary_Rate is record + Zero : Natural; + One : Natural; + end record; + + type Binary is mod 2; + + package Binary_Rate_Vectors is new Ada.Containers.Vectors (Natural, Binary_Rate); + use Binary_Rate_Vectors; + + File : File_Type; + Gamma : Vector := Empty_Vector; + Epsilon : Vector := Empty_Vector; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + declare + procedure Process (Vec : out Vector; Index : Natural; Bit : Binary); + + procedure Process (Vec : out Vector; Index : Natural; Bit : Binary) is + begin + if Count_Type (Index) > Vec.Length then + Vec.Append (New_Item => (Zero => (if Bit = 0 then 1 else 0), One => Natural (Bit))); + else + declare + Temp_Rate : Binary_Rate := Vec.Element (Index - 1); + begin + if Bit = 0 then + Temp_Rate.Zero := Temp_Rate.Zero + 1; + else + Temp_Rate.One := Temp_Rate.One + 1; + end if; + + Vec.Replace_Element (Index - 1, Temp_Rate);" +procedure Main is,"use Ada.Containers, Ada.Strings.Unbounded, Ada.Text_IO; + use Utils; + + subtype Binary_Values is Natural range 0 .. 1; + + package Unbounded_String_Vectors is new Ada.Containers.Vectors (Natural, Unbounded_String); + use Unbounded_String_Vectors; + + package Unbounded_String_Cursor_Vectors is new Ada.Containers.Vectors (Natural, Cursor); + + type Rate_Arrays is array (Binary_Values'Range) of Natural; + type Binary_Maps is array (Binary_Values'Range) of Unbounded_String_Cursor_Vectors.Vector; + type Strategies is (Most_Common, Least_Common); + + -- Given a String which represents a Natural in binary format, it returns the corresponding Natural. + -- @param Str A String which represents a Natural in binary format + -- @retuns Returns the corresponding Natural + function Binary_String_To_Number (Str : String) return Natural; + + function Binary_String_To_Number (Str : String) return Natural + is + Exponent : Natural := Natural'First; + Result : Natural := Natural'First; + begin + for Elt of reverse Str loop + if Elt = '1' then + Result := Result + 2 ** Exponent; + end if; + Exponent := Exponent + 1; + end loop; + + return Result; + end Binary_String_To_Number; + + -- Find the result in a set of String which represents a Natural in binary format according to criteria. + -- @param Values Contains all values (String which represents a Natural in binary format) extracted from a file. + -- @param Rate Indicate how many 0s and 1s there are at index ""Index"". + -- @param Map An array (Called Map because each index corresponds to a filter) that contains for each index (0 and + -- 1) each values of Values that contain a 0 (for index 0 of Map) or a 1 (for index 1 of Map) at index ""Index"" in + -- the the value in Values. + -- @param Index This index denote the position in the binary string representation of a Natural. + -- @param Strategy The strategy to apply (Most Common, Least Common). + -- @retuns Return the value that match the criteria (Strategy) + function Find_Value_According_To_Criteria (Values : Vector; + Rate : Rate_Arrays; + Map : Binary_Maps; + Index : in out Positive; + Strategy : Strategies) + return Natural; + + function Find_Value_According_To_Criteria (Values : Vector; + Rate : Rate_Arrays; + Map : Binary_Maps; + Index : in out Positive; + Strategy : Strategies) + return Natural + is + -- Filter the result for the next recursive call of Find_Value_According_To_Criteria. + -- @param Previous_Filtered_Values List of Cursor (pointing to value in Values) that match the previous + -- criteria. + -- @param Rate Indicate how many 0s and 1s there are at index ""Index"". + -- @param Map An array (Called Map because each index corresponds to a filter) that contains for each index (0 + -- and 1) each values of Values that contain a 0 (for index 0 of Map) or a 1 (for index 1 of Map) at index + -- ""Index"" in the the value in Values. + procedure Filter (Previous_Filtered_Values : Unbounded_String_Cursor_Vectors.Vector; + Rate : in out Rate_Arrays; + Map : in out Binary_Maps); + + procedure Filter (Previous_Filtered_Values : Unbounded_String_Cursor_Vectors.Vector; + Rate : in out Rate_Arrays; + Map : in out Binary_Maps) + is + Current_Value : Unbounded_String; + Binary_Value : Binary_Values; + + begin + for Curs : Cursor of Previous_Filtered_Values loop + Current_Value := Element (Curs); + + declare + Str : constant String := To_String (Current_Value); + begin + Binary_Value := Binary_Values'Value (Str (Index .. Index)); + + Map (Binary_Value).Append (Curs); + Rate (Binary_Value) := Rate (Binary_Value) + 1;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + Nb_Tiles : constant := 1; + + subtype Risk_Level is Natural range 1 .. 9; + + type Location is record + Line : Natural; + Column : Natural; + end record; + + subtype Adjacent_Index is Integer range -1 .. 1; + type Adjacent_Location is record + Line : Adjacent_Index; + Column : Adjacent_Index; + end record; + + type Adjacent is (Top, Right, Bottom, Left); + type Adjacent_Array is array (Adjacent) of Adjacent_Location; + + -- This Hash function transform a 2 dimensional location to an unique ID using Cantor pairing enumeration. + -- @param Loc A 2 dimensional location + -- @returns Return the corresponding hash + -- @link https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function + function Hash (Loc : Location) return Ada.Containers.Hash_Type is + (Ada.Containers.Hash_Type (((Loc.Line + Loc.Column) * (Loc.Line + Loc.Column + 1) / 2) + Loc.Column)); + + package Location_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Location, + Element_Type => Risk_Level, + Hash => Hash, + Equivalent_Keys => ""="", + ""="" => ""=""); + use Location_Maps; + + Adjacents : constant Adjacent_Array := (Top => (-1, 0), + Right => (0, 1), + Bottom => (1, 0), + Left => (0, -1)); + + function Equivalent_Keys (Left, Right : Location) return Boolean is + (Left.Line = Right.Line and Left.Column = Right.Column); + + -- Display the location + procedure Put (Loc : Location); + + --------- + -- Put -- + --------- + + procedure Put (Loc : Location) is + begin + Put (""(""); + Ada.Integer_Text_IO.Put (Item => Loc.Line, + Width => 0); + Put ("",""); + Ada.Integer_Text_IO.Put (Item => Loc.Column, + Width => 0); + Put ("")""); + end Put; + + package Chiton_Dijkstra is new Dijkstra (Node => Location, + Hash => Hash, + Equivalent_Keys => Equivalent_Keys, + Put => Put, + Is_Directed => True); + + -- This heuristic compute the Manhattan distance from Current to To + function Heuristic (Current, To : Location) return Long_Long_Natural; + + function Heuristic (Current, To : Location) return Long_Long_Natural is + begin + return Long_Long_Natural (abs (To.Line - Current.Line) + abs (To.Column - Current.Column)); + end Heuristic; + + use Chiton_Dijkstra; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Array_Width, + Array_Height : Natural := Natural'First; + Result : Long_Long_Natural := Long_Long_Natural'First; + Nodes : Map; + Edges : Edges_Lists.Vector := Edges_Lists.Empty_Vector; + Graph : Graph_Access; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Value : Risk_Level; + Last : Positive; + Current_Colum : Natural := Natural'First; + begin + if Array_Width = Natural'First then + Array_Width := Str'Length; + end if; + for Char of Str loop + Ada.Integer_Text_IO.Get (Char & """", Value, Last); + Nodes.Insert ((Array_Height, Current_Colum), Value); + Current_Colum := Current_Colum + 1; + end loop; + + Create_Horizontal_Tiles : for Column in Array_Width .. Array_Width * Nb_Tiles - 1 loop + Last := Nodes.Element ((Array_Height, Column - Array_Width)) + 1; + if Last > 9 then + Last := Last - 9; + end if; + Nodes.Insert ((Array_Height, Column), Last); + end loop Create_Horizontal_Tiles;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + Nb_Tiles : constant := 5; + + subtype Risk_Level is Natural range 1 .. 9; + + type Location is record + Line : Natural; + Column : Natural; + end record; + + subtype Adjacent_Index is Integer range -1 .. 1; + type Adjacent_Location is record + Line : Adjacent_Index; + Column : Adjacent_Index; + end record; + + type Adjacent is (Top, Right, Bottom, Left); + type Adjacent_Array is array (Adjacent) of Adjacent_Location; + + -- This Hash function transform a 2 dimensional location to an unique ID using Cantor pairing enumeration. + -- @param Loc A 2 dimensional location + -- @returns Return the corresponding hash + -- @link https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function + function Hash (Loc : Location) return Ada.Containers.Hash_Type is + (Ada.Containers.Hash_Type (((Loc.Line + Loc.Column) * (Loc.Line + Loc.Column + 1) / 2) + Loc.Column)); + + package Location_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Location, + Element_Type => Risk_Level, + Hash => Hash, + Equivalent_Keys => ""="", + ""="" => ""=""); + use Location_Maps; + + Adjacents : constant Adjacent_Array := (Top => (-1, 0), + Right => (0, 1), + Bottom => (1, 0), + Left => (0, -1)); + + function Equivalent_Keys (Left, Right : Location) return Boolean is + (Left.Line = Right.Line and Left.Column = Right.Column); + + -- Display the location + procedure Put (Loc : Location); + + --------- + -- Put -- + --------- + + procedure Put (Loc : Location) is + begin + Put (""(""); + Ada.Integer_Text_IO.Put (Item => Loc.Line, + Width => 0); + Put ("",""); + Ada.Integer_Text_IO.Put (Item => Loc.Column, + Width => 0); + Put ("")""); + end Put; + + package Chiton_Dijkstra is new Dijkstra (Node => Location, + Hash => Hash, + Equivalent_Keys => Equivalent_Keys, + Put => Put, + Is_Directed => True); + + -- This heuristic compute the Manhattan distance from Current to To + function Heuristic (Current, To : Location) return Long_Long_Natural; + + function Heuristic (Current, To : Location) return Long_Long_Natural is + begin + return Long_Long_Natural (abs (To.Line - Current.Line) + abs (To.Column - Current.Column)); + end Heuristic; + + use Chiton_Dijkstra; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Array_Width, + Array_Height : Natural := Natural'First; + Result : Long_Long_Natural := Long_Long_Natural'First; + Nodes : Map; + Edges : Edges_Lists.Vector := Edges_Lists.Empty_Vector; + Graph : Graph_Access; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Value : Risk_Level; + Last : Positive; + Current_Colum : Natural := Natural'First; + begin + if Array_Width = Natural'First then + Array_Width := Str'Length; + end if; + for Char of Str loop + Ada.Integer_Text_IO.Get (Char & """", Value, Last); + Nodes.Insert ((Array_Height, Current_Colum), Value); + Current_Colum := Current_Colum + 1; + end loop; + + Create_Horizontal_Tiles : for Column in Array_Width .. Array_Width * Nb_Tiles - 1 loop + Last := Nodes.Element ((Array_Height, Column - Array_Width)) + 1; + if Last > 9 then + Last := Last - 9; + end if; + Nodes.Insert ((Array_Height, Column), Last); + end loop Create_Horizontal_Tiles;" +procedure Main is,"use Ada.Text_IO; + use Utils; + + package Integer_Vectors is new Ada.Containers.Vectors (Natural, Integer); + use Integer_Vectors; + + subtype Hegihtmap_Values is Natural range 0 .. 10; + subtype Hegiht is Hegihtmap_Values range 0 .. 9; + + type Cave_Heightmap_Array is array (Natural range <>, Natural range <>) of Hegihtmap_Values; + + File : File_Type; + Values : Vector := Empty_Vector; + Array_Width, + Array_Height : Natural := Natural'First; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + Array_Height := Array_Height + 1; + declare + Str : constant String := Get_Line (File); + Value : Hegiht; + Last : Positive; + begin + if Array_Width = Natural'First then + Array_Width := Str'Length; + end if; + for Char of Str loop + Ada.Integer_Text_IO.Get (Char & """", Value, Last); + Values.Append (Value); + end loop;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + package Integer_Vectors is new Ada.Containers.Vectors (Natural, Natural); + use Integer_Vectors; + + subtype Hegihtmap_Values is Natural range 0 .. 10; + subtype Hegiht is Hegihtmap_Values range 0 .. 9; + + type Cave_Heightmap_Array is array (Natural range <>, Natural range <>) of Hegihtmap_Values; + + type Location is record + Line : Natural; + Column : Natural; + end record; + + subtype Adjacent_Index is Integer range -1 .. 1; + type Adjacent_Location is record + Line : Adjacent_Index; + Column : Adjacent_Index; + end record; + + type Adjacent is (Top, Right, Bottom, Left); + type Adjacent_Array is array (Adjacent) of Adjacent_Location; + + -- This Hash function transform a 2 dimensional location to an unique ID using Cantor pairing enumeration. + -- @param Loc A 2 dimensional location + -- @returns Return the corresponding hash + -- @link https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function + function Hash (Loc : Location) return Ada.Containers.Hash_Type is + (Ada.Containers.Hash_Type (((Loc.Line + Loc.Column) * (Loc.Line + Loc.Column + 1) / 2) + Loc.Column)); + + function Is_Equal (Loc_1, Loc_2 : Location) return Boolean is + (Loc_1.Line = Loc_2.Line and Loc_1.Column = Loc_2.Column); + + package Location_Sets is new Ada.Containers.Hashed_Sets (Element_Type => Location, + Hash => Hash, + Equivalent_Elements => Is_Equal, + ""="" => Is_Equal); + + Adjacents : constant Adjacent_Array := (Top => (-1, 0), + Right => (0, 1), + Bottom => (1, 0), + Left => (0, -1)); + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Values : Vector := Empty_Vector; + Array_Width, + Array_Height : Natural := Natural'First; +begin + Get_File (File); + + -- Get all values + while not End_Of_File (File) loop + Array_Height := Array_Height + 1; + declare + Str : constant String := Get_Line (File); + Value : Hegiht; + Last : Positive; + begin + if Array_Width = Natural'First then + Array_Width := Str'Length; + end if; + for Char of Str loop + Ada.Integer_Text_IO.Get (Char & """", Value, Last); + Values.Append (Value); + end loop;" +procedure Main is,"use Ada.Containers, + Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + type Bingo_Range is range 1 .. 5; + subtype Bingo_Values is Natural range 0 .. 99; + package Bingo_Values_IO is new Ada.Text_IO.Integer_IO (Bingo_Values); + use Bingo_Values_IO; + + type Grid_Element is record + Value : Bingo_Values; + Marked : Boolean; + end record; + + type Lookup_Item is record + Board_Id : Natural; + Line : Bingo_Range; + Column : Bingo_Range; + end record; + + package Lookup_Item_Vectors is new Ada.Containers.Vectors (Natural, Lookup_Item); + + function Bingo_Range_Hash (Elt : Bingo_Values) return Ada.Containers.Hash_Type is (Ada.Containers.Hash_Type (Elt)); + + package Lookup_Map is new Ada.Containers.Hashed_Maps (Key_Type => Bingo_Values, + Element_Type => Lookup_Item_Vectors.Vector, + Hash => Bingo_Range_Hash, + Equivalent_Keys => ""="", + ""="" => Lookup_Item_Vectors.""=""); + use Lookup_Map; + + -- Given a Lookup map, it add an element to the specified value. + -- @param Lookup Lookup map to update + -- @param Value Id in the map ""Lookup"" + -- @param Board_Id Property of the Lookup_Item that will be added to the vector at id ""Value"" + -- @param Line Property of the Lookup_Item that will be added to the vector at id ""Value"" + -- @param Column Property of the Lookup_Item that will be added to the vector at id ""Value"" + procedure Update_Lookup (Lookup : in out Map; Value : Bingo_Values; Board_Id : Natural; Line, Column : Bingo_Range); + + ------------------- + -- Update_Lookup -- + ------------------- + + procedure Update_Lookup (Lookup : in out Map; Value : Bingo_Values; Board_Id : Natural; Line, Column : Bingo_Range) + is + use Lookup_Item_Vectors; + + Item : constant Lookup_Item := (Board_Id, Line, Column); + Vec : Lookup_Item_Vectors.Vector := Lookup.Element (Value); + begin + Vec.Append (Item); + Lookup.Replace_Element (Lookup.Find (Value), Vec); + end Update_Lookup; + + type Grid is array (Bingo_Range, Bingo_Range) of Grid_Element; + + package Grid_Vectors is new Ada.Containers.Vectors (Natural, Grid); + use Grid_Vectors; + + package Bingo_Values_Queue_Interfaces is + new Ada.Containers.Synchronized_Queue_Interfaces + (Element_Type => Bingo_Values); + + package Bingo_Balls is new Ada.Containers.Unbounded_Synchronized_Queues + (Queue_Interfaces => Bingo_Values_Queue_Interfaces); + use Bingo_Balls; + + -- Tell if there is a bingo. + -- @param Board The board to check + -- @param Line The marked line + -- @param Column The marked column + -- @returns Return True if there is a bingo, False otherwise + function Is_Bingo (Board : Grid; Line, Column : Bingo_Range) return Boolean; + + -------------- + -- Is_Bingo -- + -------------- + + function Is_Bingo (Board : Grid; Line, Column : Bingo_Range) return Boolean is + Line_Bingo, Column_Bingo : Boolean := True; + begin + for Index in Bingo_Range loop + Line_Bingo := Line_Bingo and Board (Index, Column).Marked; + Column_Bingo := Column_Bingo and Board (Line, Index).Marked; + + if not Line_Bingo and not Column_Bingo then + return False; + end if; + end loop; + + return True; + end Is_Bingo; + + -- Compute the value of a board according to the exercice. + -- Formula: ""sum of all unmarked numbers"" x Current_Value + -- @param Board the winning board + -- @param Current_Value The last number called + -- @returns Returns the result of the calculation + function Compute_Board_Value (Board : Grid; Current_Value : Bingo_Values) return Natural; + + ------------------------- + -- Compute_Board_Value -- + ------------------------- + + function Compute_Board_Value (Board : Grid; Current_Value : Bingo_Values) return Natural is + Sum : Natural := Natural'First; + begin + for Line in Board'Range (1) loop + for Column in Board'Range (2) loop + if not Board (Line, Column).Marked then + Sum := Sum + Board (Line, Column).Value; + end if; + end loop; + end loop; + + return Sum * Current_Value; + end Compute_Board_Value; + + File : File_Type; + Ball_Box : Queue; + Boards : Vector := Empty_Vector; + Lookup : Map := Empty_Map; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; +begin + Get_File (File); + + if End_Of_File (File) then + raise Program_Error with ""Empty file""; + end if; + + Fill_Ball_Box : declare + Line : constant String := Get_Line (File); + First : Positive := Line'First; + Last : Positive := Line'First; + Last_Index : Positive := Line'First; + Value : Bingo_Values; + begin + while Last <= Line'Last loop + if Line (Last .. Last) = "","" then + Get (Line (First .. Last - 1), Value, Last_Index); + + Ball_Box.Enqueue (Value); + Lookup.Insert (Value, Lookup_Item_Vectors.Empty_Vector); + + First := Last + 1; + elsif Last = Line'Last then + Get (Line (First .. Line'Last), Value, Last_Index); + + Ball_Box.Enqueue (Value); + Lookup.Insert (Value, Lookup_Item_Vectors.Empty_Vector); + + First := Last + 1; + end if; + Last := Last + 1; + end loop; + end Fill_Ball_Box; + + -- Get all boards + Load_Boards : declare + Line_Index : Bingo_Range := Bingo_Range'First; + Column_Index : Bingo_Range := Bingo_Range'First; + Value : Bingo_Values; + Board : Grid; + begin + while not End_Of_File (File) loop + declare + Line : constant String := Get_Line (File); + Last : Positive := Line'First; + begin + while Last < Line'Last loop + Get (Line (Last .. Line'Last), Value, Last); + + Board (Line_Index, Column_Index) := (Value, False); + Update_Lookup (Lookup => Lookup, + Value => Value, + Board_Id => Natural (Boards.Length), + Line => Line_Index, + Column => Column_Index); + + if Column_Index = Bingo_Range'Last then + Column_Index := Bingo_Range'First; + + if Line_Index = Bingo_Range'Last then + Line_Index := Bingo_Range'First; + + Boards.Append (Board); + else + Line_Index := Line_Index + 1; + end if; + else + Column_Index := Column_Index + 1; + end if; + + Last := Last + 1; + end loop;" +procedure Main is,"use Ada.Containers, + Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + type Bingo_Range is range 1 .. 5; + subtype Bingo_Values is Natural range 0 .. 99; + package Bingo_Values_IO is new Ada.Text_IO.Integer_IO (Bingo_Values); + use Bingo_Values_IO; + + type Grid_Element is record + Value : Bingo_Values; + Marked : Boolean; + end record; + + type Lookup_Item is record + Board_Id : Natural; + Line : Bingo_Range; + Column : Bingo_Range; + end record; + + package Lookup_Item_Vectors is new Ada.Containers.Vectors (Natural, Lookup_Item); + + function Bingo_Range_Hash (Elt : Bingo_Values) return Ada.Containers.Hash_Type is (Ada.Containers.Hash_Type (Elt)); + + package Lookup_Map is new Ada.Containers.Hashed_Maps (Key_Type => Bingo_Values, + Element_Type => Lookup_Item_Vectors.Vector, + Hash => Bingo_Range_Hash, + Equivalent_Keys => ""="", + ""="" => Lookup_Item_Vectors.""=""); + use Lookup_Map; + + package Winner_Boards_Sets is new Ada.Containers.Ordered_Sets (Element_Type => Natural); + use Winner_Boards_Sets; + + -- Given a Lookup map, it add an element to the specified value. + -- @param Lookup Lookup map to update + -- @param Value Id in the map ""Lookup"" + -- @param Board_Id Property of the Lookup_Item that will be added to the vector at id ""Value"" + -- @param Line Property of the Lookup_Item that will be added to the vector at id ""Value"" + -- @param Column Property of the Lookup_Item that will be added to the vector at id ""Value"" + procedure Update_Lookup (Lookup : in out Map; Value : Bingo_Values; Board_Id : Natural; Line, Column : Bingo_Range); + + ------------------- + -- Update_Lookup -- + ------------------- + + procedure Update_Lookup (Lookup : in out Map; Value : Bingo_Values; Board_Id : Natural; Line, Column : Bingo_Range) + is + use Lookup_Item_Vectors; + + Item : constant Lookup_Item := (Board_Id, Line, Column); + Vec : Lookup_Item_Vectors.Vector := Lookup.Element (Value); + begin + Vec.Append (Item); + Lookup.Replace_Element (Lookup.Find (Value), Vec); + end Update_Lookup; + + type Grid is array (Bingo_Range, Bingo_Range) of Grid_Element; + + package Grid_Vectors is new Ada.Containers.Vectors (Natural, Grid); + use Grid_Vectors; + + package Bingo_Values_Queue_Interfaces is + new Ada.Containers.Synchronized_Queue_Interfaces + (Element_Type => Bingo_Values); + + package Bingo_Balls is new Ada.Containers.Unbounded_Synchronized_Queues + (Queue_Interfaces => Bingo_Values_Queue_Interfaces); + use Bingo_Balls; + + -- Tell if there is a bingo. + -- @param Board The board to check + -- @param Line The marked line + -- @param Column The marked column + -- @returns Return True if there is a bingo, False otherwise + function Is_Bingo (Board : Grid; Line, Column : Bingo_Range) return Boolean; + + -------------- + -- Is_Bingo -- + -------------- + + function Is_Bingo (Board : Grid; Line, Column : Bingo_Range) return Boolean is + Line_Bingo, Column_Bingo : Boolean := True; + begin + for Index in Bingo_Range loop + Line_Bingo := Line_Bingo and Board (Index, Column).Marked; + Column_Bingo := Column_Bingo and Board (Line, Index).Marked; + + if not Line_Bingo and not Column_Bingo then + return False; + end if; + end loop; + + return True; + end Is_Bingo; + + -- Compute the value of a board according to the exercice. + -- Formula: ""sum of all unmarked numbers"" x Current_Value + -- @param Board the winning board + -- @param Current_Value The last number called + -- @returns Returns the result of the calculation + function Compute_Board_Value (Board : Grid; Current_Value : Bingo_Values) return Natural; + + ------------------------- + -- Compute_Board_Value -- + ------------------------- + + function Compute_Board_Value (Board : Grid; Current_Value : Bingo_Values) return Natural is + Sum : Natural := Natural'First; + begin + for Line in Board'Range (1) loop + for Column in Board'Range (2) loop + if not Board (Line, Column).Marked then + Sum := Sum + Board (Line, Column).Value; + end if; + end loop; + end loop; + + return Sum * Current_Value; + end Compute_Board_Value; + + File : File_Type; + Ball_Box : Queue; + Boards : Vector := Empty_Vector; + Lookup : Map := Empty_Map; + Winner_Boards : Set := Empty_Set; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; +begin + Get_File (File); + + if End_Of_File (File) then + raise Program_Error with ""Empty file""; + end if; + + Fill_Ball_Box : declare + Line : constant String := Get_Line (File); + First : Positive := Line'First; + Last : Positive := Line'First; + Last_Index : Positive := Line'First; + Value : Bingo_Values; + begin + while Last <= Line'Last loop + if Line (Last .. Last) = "","" then + Get (Line (First .. Last - 1), Value, Last_Index); + + Ball_Box.Enqueue (Value); + Lookup.Insert (Value, Lookup_Item_Vectors.Empty_Vector); + + First := Last + 1; + elsif Last = Line'Last then + Get (Line (First .. Line'Last), Value, Last_Index); + + Ball_Box.Enqueue (Value); + Lookup.Insert (Value, Lookup_Item_Vectors.Empty_Vector); + + First := Last + 1; + end if; + Last := Last + 1; + end loop; + end Fill_Ball_Box; + + -- Get all boards + Load_Boards : declare + Line_Index : Bingo_Range := Bingo_Range'First; + Column_Index : Bingo_Range := Bingo_Range'First; + Value : Bingo_Values; + Board : Grid; + begin + while not End_Of_File (File) loop + declare + Line : constant String := Get_Line (File); + Last : Positive := Line'First; + begin + while Last < Line'Last loop + Get (Line (Last .. Line'Last), Value, Last); + + Board (Line_Index, Column_Index) := (Value, False); + Update_Lookup (Lookup => Lookup, + Value => Value, + Board_Id => Natural (Boards.Length), + Line => Line_Index, + Column => Column_Index); + + if Column_Index = Bingo_Range'Last then + Column_Index := Bingo_Range'First; + + if Line_Index = Bingo_Range'Last then + Line_Index := Bingo_Range'First; + + Boards.Append (Board); + else + Line_Index := Line_Index + 1; + end if; + else + Column_Index := Column_Index + 1; + end if; + + Last := Last + 1; + end loop;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + type Coordinate_2D is record + Line : Natural; + Column : Natural; + end record; + + type Folding_Kind is (K_Line, K_Column); + + type Folding_T is record + Kind : Folding_Kind; + Value : Natural; + end record; + + package Folding_Vectors is new Ada.Containers.Vectors (Natural, Folding_T); + + -- This Hash function transform a 2 dimensional location to an unique ID using Cantor pairing enumeration. + -- @param Coord A 2 dimensional location + -- @returns Return the corresponding hash + -- @link https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function + function Hash (Coord : Coordinate_2D) return Ada.Containers.Hash_Type is + (Ada.Containers.Hash_Type (((Coord.Line + Coord.Column) * (Coord.Line + Coord.Column + 1) / 2) + Coord.Column)); + + function Equivalent_Keys (Left, Right : Coordinate_2D) return Boolean is + (Left.Line = Right.Line and Left.Column = Right.Column); + + package Dots_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Coordinate_2D, + Element_Type => Boolean, + Hash => Hash, + Equivalent_Keys => Equivalent_Keys, + ""="" => ""=""); + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Max_Lines, Max_Columns : Positive := Positive'First; + Folding_Instructions : Folding_Vectors.Vector := Folding_Vectors.Empty_Vector; + Dots_Map : Dots_Maps.Map := Dots_Maps.Empty_Map; +begin + Get_File (File); + + -- Get all values + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + begin + if Str'Length = 0 then + goto Continue_Next_Line; + end if; + + if Str (Str'First) = 'f' then + -- ""fold along"" instruction + declare + use Ada.Integer_Text_IO; + + Separator_Index : constant Integer := + Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => ""=""); + Kind : constant String := Str (Separator_Index - 1 .. Separator_Index - 1); + Value_Str : constant String := Str (Separator_Index + 1 .. Str'Last); + Last_Index : Positive := Positive'First; + Value : Natural; + begin + Get (Value_Str, Value, Last_Index); + + Folding_Instructions.Append (((if Kind = ""x"" then K_Column else K_Line), Value));" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + type Coordinate_2D is record + Line : Natural; + Column : Natural; + end record; + + type Folding_Kind is (K_Line, K_Column); + + type Folding_T is record + Kind : Folding_Kind; + Value : Natural; + end record; + + package Folding_Vectors is new Ada.Containers.Vectors (Natural, Folding_T); + + -- This Hash function transform a 2 dimensional location to an unique ID using Cantor pairing enumeration. + -- @param Coord A 2 dimensional location + -- @returns Return the corresponding hash + -- @link https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function + function Hash (Coord : Coordinate_2D) return Ada.Containers.Hash_Type is + (Ada.Containers.Hash_Type (((Coord.Line + Coord.Column) * (Coord.Line + Coord.Column + 1) / 2) + Coord.Column)); + + function Equivalent_Keys (Left, Right : Coordinate_2D) return Boolean is + (Left.Line = Right.Line and Left.Column = Right.Column); + + package Dots_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Coordinate_2D, + Element_Type => Boolean, + Hash => Hash, + Equivalent_Keys => Equivalent_Keys, + ""="" => ""=""); + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + File_Is_Empty : Boolean := True; + Max_Lines, Max_Columns : Positive := Positive'First; + Folding_Instructions : Folding_Vectors.Vector := Folding_Vectors.Empty_Vector; + Dots_Map : Dots_Maps.Map := Dots_Maps.Empty_Map; +begin + Get_File (File); + + -- Get all values + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + begin + if Str'Length = 0 then + goto Continue_Next_Line; + end if; + + if Str (Str'First) = 'f' then + -- ""fold along"" instruction + declare + use Ada.Integer_Text_IO; + + Separator_Index : constant Integer := + Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => ""=""); + Kind : constant String := Str (Separator_Index - 1 .. Separator_Index - 1); + Value_Str : constant String := Str (Separator_Index + 1 .. Str'Last); + Last_Index : Positive := Positive'First; + Value : Natural; + begin + Get (Value_Str, Value, Last_Index); + + Folding_Instructions.Append (((if Kind = ""x"" then K_Column else K_Line), Value));" +procedure Main is,"use Ada.Containers, + Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + type Coordinate_2D is record + Line : Natural; + Column : Natural; + end record; + + type Segment is record + Start_Line : Coordinate_2D; + End_Line : Coordinate_2D; + end record; + + package Segment_Vectors is new Ada.Containers.Vectors (Natural, Segment); + use Segment_Vectors; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Segments : Vector := Empty_Vector; + Max_Lines, Max_Columns : Positive := Positive'First; + Nb_Dangerous_Cells : Natural := Natural'First; +begin + Get_File (File); + + if End_Of_File (File) then + raise Program_Error with ""Empty file""; + end if; + + -- Get all segments + while not End_Of_File (File) loop + declare + use Ada.Integer_Text_IO; + + Line : constant String := Get_Line (File); + First : Positive := Line'First; + Last : Positive := Line'First; + Last_Index : Positive := Line'First; + Values : array (1 .. 4) of Natural := (others => 0); + Current_Value_Index : Positive := Positive'First; + begin + while Last <= Line'Last loop + if Line (Last) not in '0' .. '9' then + if Line (First .. Last - 1) /= """" then + Get (Line (First .. Last - 1), Values (Current_Value_Index), Last_Index); + Current_Value_Index := Current_Value_Index + 1; + end if; + First := Last + 1; + Last := First; + elsif Last = Line'Last then + Get (Line (First .. Line'Last), Values (Current_Value_Index), Last_Index); + Last := Last + 1; + else + Last := Last + 1; + end if; + end loop; + + if Values (1) > Max_Lines then + Max_Lines := Values (1); + elsif Values (3) > Max_Lines then + Max_Lines := Values (3); + end if; + + if Values (2) > Max_Columns then + Max_Columns := Values (2); + elsif Values (4) > Max_Columns then + Max_Columns := Values (4); + end if; + + Segments.Append (( + Start_Line => (Line => Values (1), Column => Values (2)), + End_Line => (Line => Values (3), Column => Values (4)) + ));" +procedure Main is,"use Ada.Containers, + Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + type Coordinate_2D is record + Line : Natural; + Column : Natural; + end record; + + type Segment is record + Start_Line : Coordinate_2D; + End_Line : Coordinate_2D; + end record; + + package Segment_Vectors is new Ada.Containers.Vectors (Natural, Segment); + use Segment_Vectors; + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Segments : Vector := Empty_Vector; + Max_Lines, Max_Columns : Positive := Positive'First; + Nb_Dangerous_Cells : Natural := Natural'First; +begin + Get_File (File); + + if End_Of_File (File) then + raise Program_Error with ""Empty file""; + end if; + + -- Get all segments + while not End_Of_File (File) loop + declare + use Ada.Integer_Text_IO; + + Line : constant String := Get_Line (File); + First : Positive := Line'First; + Last : Positive := Line'First; + Last_Index : Positive := Line'First; + Values : array (1 .. 4) of Natural := (others => 0); + Current_Value_Index : Positive := Positive'First; + begin + while Last <= Line'Last loop + if Line (Last) not in '0' .. '9' then + if Line (First .. Last - 1) /= """" then + Get (Line (First .. Last - 1), Values (Current_Value_Index), Last_Index); + Current_Value_Index := Current_Value_Index + 1; + end if; + First := Last + 1; + Last := First; + elsif Last = Line'Last then + Get (Line (First .. Line'Last), Values (Current_Value_Index), Last_Index); + Last := Last + 1; + else + Last := Last + 1; + end if; + end loop; + + if Values (1) > Max_Lines then + Max_Lines := Values (1); + elsif Values (3) > Max_Lines then + Max_Lines := Values (3); + end if; + + if Values (2) > Max_Columns then + Max_Columns := Values (2); + elsif Values (4) > Max_Columns then + Max_Columns := Values (4); + end if; + + Segments.Append (( + Start_Line => (Line => Values (1), Column => Values (2)), + End_Line => (Line => Values (3), Column => Values (4)) + ));" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + subtype Adjacent_Index is Integer range -1 .. 1; + type Adjacent_Location is record + Line : Adjacent_Index; + Column : Adjacent_Index; + end record; + + Max_Steps : constant := 100; + + type Adjacent is (Top, Top_Right, Right, Bottom_Right, Bottom, Bottom_Left, Left, Top_Left); + type Adjacent_Array is array (Adjacent) of Adjacent_Location; + + type Octopuses_Energy_Level_Array is array (1 .. 10, 1 .. 10) of Integer; + + Adjacents : constant Adjacent_Array := (Top => (-1, 0), + Top_Right => (-1, 1), + Right => (0, 1), + Bottom_Right => (1, 1), + Bottom => (1, 0), + Bottom_Left => (1, -1), + Left => (0, -1), + Top_Left => (-1, -1)); + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Octopuses_Energy_Level : Octopuses_Energy_Level_Array; + File_Is_Empty : Boolean := True; + Result : Natural := Natural'First; +begin + Get_File (File); + + -- Get all values + declare + Current_Line, + Current_Column : Positive := Positive'First; + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Last : Positive; + begin + for Char of Str loop + Ada.Integer_Text_IO.Get (Char & """", Octopuses_Energy_Level (Current_Line, Current_Column), Last); + Current_Column := Current_Column + 1; + File_Is_Empty := False; + end loop;" +procedure Main is,"use Ada.Execution_Time, + Ada.Real_Time, + Ada.Text_IO; + use Utils; + + subtype Adjacent_Index is Integer range -1 .. 1; + type Adjacent_Location is record + Line : Adjacent_Index; + Column : Adjacent_Index; + end record; + + type Adjacent is (Top, Top_Right, Right, Bottom_Right, Bottom, Bottom_Left, Left, Top_Left); + type Adjacent_Array is array (Adjacent) of Adjacent_Location; + + type Octopuses_Energy_Level_Array is array (1 .. 10, 1 .. 10) of Integer; + + Adjacents : constant Adjacent_Array := (Top => (-1, 0), + Top_Right => (-1, 1), + Right => (0, 1), + Bottom_Right => (1, 1), + Bottom => (1, 0), + Bottom_Left => (1, -1), + Left => (0, -1), + Top_Left => (-1, -1)); + + File : File_Type; + Start_Time, End_Time : CPU_Time; + Execution_Duration : Time_Span; + Octopuses_Energy_Level : Octopuses_Energy_Level_Array; + File_Is_Empty : Boolean := True; + Result : Natural := Natural'First; +begin + Get_File (File); + + -- Get all values + declare + Current_Line, + Current_Column : Positive := Positive'First; + begin + while not End_Of_File (File) loop + declare + Str : constant String := Get_Line (File); + Last : Positive; + begin + for Char of Str loop + Ada.Integer_Text_IO.Get (Char & """", Octopuses_Energy_Level (Current_Line, Current_Column), Last); + Current_Column := Current_Column + 1; + File_Is_Empty := False; + end loop;" +procedure Parse_Register(parser : in out Parser_Type;,"result : out Memory_Pointer) is + + mem : Memory_Pointer := null; + +begin + + while Get_Type(parser) = Open loop + Match(parser, Open); + declare + name : constant String := Get_Value(parser); + begin + Match(parser, Literal); + if name = ""memory"" then + if mem /= null then + Destroy(mem); + Raise_Error(parser, + ""memory declared multiple times in register""); + end if; + Parse_Memory(parser, mem); + else + Raise_Error(parser, ""invalid register attribute: "" & name); + end if;" +procedure MemGen is,"mem : Memory_Pointer; + name : Unbounded_String := To_Unbounded_String(""mem""); + addr_width : Positive := 32 - 3; + mem_index : Integer := -1; + simplify : Boolean := True; + + procedure Show_Usage is + begin + Put_Line(""usage: "" & Command_Name & "" [options] ""); + Put_Line(""options:""); + Put_Line("" -width Address width (default"" & + Positive'Image(addr_width) & "")""); + Put_Line("" -nosimplify Disable memory simplification""); + end Show_Usage; + +begin + + -- Parse arguments. + declare + i : Positive := 1; + arg : Unbounded_String; + begin + while i <= Argument_Count loop + arg := To_Unbounded_String(Argument(i)); + if arg = ""-width"" and i + 1 <= Argument_Count then + i := i + 1; + addr_width := Positive'Value(Argument(i)); + elsif arg = ""-name"" and i + 1 <= Argument_Count then + i := i + 1; + name := To_Unbounded_String(Argument(i)); + elsif arg = ""-nosimplify"" then + simplify := False; + elsif mem_index < 0 then + mem_index := i; + else + Show_Usage; + return; + end if; + i := i + 1; + end loop;" +procedure Register_Benchmark(runner : in out Runner_Type;,"benchmark : in Benchmark_Pointer) is + begin + runner.benchmarks.Append(benchmark); + end Register_Benchmark; + + procedure Run(runner : in out Runner_Type; + mem : in Memory_Pointer) is + first : constant Natural := runner.benchmarks.First_Index; + last : constant Natural := runner.benchmarks.Last_Index; + bp : Benchmark_Pointer; + begin + for i in first .. last loop + bp := runner.benchmarks.Element(i); + Set_Memory(bp.all, mem); + end loop; + loop + for i in reverse first .. last loop + bp := runner.benchmarks.Element(i); + Reset(bp.all, i); + begin + Run(bp.all); + exception + when Prune_Error => + null;" +procedure MemSim is,"mem : Memory_Pointer := null; + runner : Runner_Type; + arg : Positive := 1; + + type Benchmark_Constructor_Type is + access function return Benchmark.Benchmark_Pointer; + + type Benchmark_Info_Type is record + name : Unbounded_String; + usage : Unbounded_String; + constructor : Benchmark_Constructor_Type; + end record; + + type Benchmark_Info_Array is array(Natural range <>) of Benchmark_Info_Type; + + function BM_Entry(name : String; + usage : String; + constructor : Benchmark_Constructor_Type) + return Benchmark_Info_Type is + begin + return Benchmark_Info_Type'(To_Unbounded_String(name), + To_Unbounded_String(usage), + constructor); + end BM_Entry; + + benchmark_map : constant Benchmark_Info_Array := ( + BM_Entry(""cholesky"", + ""[size=256][iterations=1][spacing=0]"", + Benchmark.Matrix.Cholesky.Create_Cholesky'Access), + BM_Entry(""hash"", + ""[size=1024][iterations=1000][spacing=0][seed=15]"", + Benchmark.Hash.Create_Hash'Access), + BM_Entry(""heap"", + ""[size=1024][spacing=0][seed=15]"", + Benchmark.Heap.Create_Heap'Access), + BM_Entry(""lu"", + ""[size=256][iterations=1][spacing=0]"", + Benchmark.Matrix.LU.Create_LU'Access), + BM_Entry(""mm"", + ""[size=256][iterations=1][spacing=0][seed=15]"", + Benchmark.Matrix.MM.Create_MM'Access), + BM_Entry(""qsort"", + ""[size=1024][iterations=1][spacing=0][seed=15]"", + Benchmark.QSort.Create_QSort'Access), + BM_Entry(""stride"", + ""[size=1024][iterations=1000][stride=1][spacing=0]"", + Benchmark.Stride.Create_Stride'Access), + BM_Entry(""trace"", + ""[file=trace.txt][spacing=0]"", + Benchmark.Trace.Create_Trace'Access), + BM_Entry(""tree"", + ""[size=1024][iterations=10000][spacing=0]"", + Benchmark.Tree.Create_Tree'Access) + ); + + procedure Show_Usage is + begin + Put_Line(""usage: "" & Command_Name & "" [options] "" & + "" { []}""); + Put_Line(""options:""); + Put_Line("" -addr_bits Number of address bits""); + Put_Line("" -device Device type (asic, virtex6, ...)""); + Put_Line(""benchmarks:""); + for i in benchmark_map'First .. benchmark_map'Last loop + Put_Line("" "" & To_String(benchmark_map(i).name & "" "" & + To_String(benchmark_map(i).usage))); + end loop; + Put_Line("" show""); + end Show_Usage; + +begin + + -- Run the tests if requested. + if Argument_Count = 1 and then Argument(1) = ""test"" then + Test.Run_Tests; + return; + end if; + + -- Parse options. + Parse_Options: while arg < Argument_Count loop + begin + if Argument(arg) = ""-addr_bits"" then + Device.Set_Address_Bits(Positive'Value(Argument(arg + 1))); + arg := arg + 2; + elsif Argument(arg) = ""-device"" then + Device.Set_Device(Argument(arg + 1)); + arg := arg + 2; + else + exit Parse_Options; + end if; + exception + when others => + Put_Line(""error: invalid option value""); + return;" +procedure Finish_Run(mem : in out Super_Type) is,"context : constant Context_Pointer := mem.context; + cost : constant Cost_Type := Get_Cost(mem); + value : Value_Type := Get_Value(mem'Access); + sum : Long_Float; + count : Long_Float; + total : Long_Integer; + var : LF_Variance.Variance_Type; + result : Result_Type; + begin + + -- Scale the result if necessary. + if mem.current_length > context.total_length then + context.total_length := mem.current_length; + end if; + if mem.current_length /= context.total_length then + Put_Line(""Prune""); + declare + mult : constant Long_Float := Long_Float(context.total_length) / + Long_Float(mem.current_length); + fval : constant Long_Float := Long_Float(value) * mult; + begin + if fval >= Long_Float(Value_Type'Last) then + value := Value_Type'Last; + else + value := Value_Type(fval); + end if;" +"procedure Destroy is new Ada.Unchecked_Deallocation(Distribution_Type,","Distribution_Pointer); + + procedure Destroy is new Ada.Unchecked_Deallocation(Context_Type, + Context_Pointer); + + procedure Finalize(mem : in out Super_Type) is + begin + for i in mem.contexts.First_Index .. mem.contexts.Last_Index loop + declare + cp : Context_Pointer := mem.contexts.Element(i); + begin + Destroy(cp);" +procedure Free is,"new Ada.Unchecked_Deallocation(Cache_Data, Cache_Data_Pointer); + + function Create_Cache(mem : access Memory_Type'Class; + line_count : Positive := 1; + line_size : Positive := 8; + associativity : Positive := 1; + latency : Time_Type := 1; + policy : Policy_Type := LRU; + write_back : Boolean := True) + return Cache_Pointer is + result : constant Cache_Pointer := new Cache_Type; + begin + Set_Memory(result.all, mem); + result.line_size := line_size; + result.line_count := line_count; + result.associativity := associativity; + result.latency := latency; + result.policy := policy; + result.write_back := write_back; + result.data.Set_Length(Count_Type(result.line_count)); + for i in 0 .. result.line_count - 1 loop + result.data.Replace_Element(i, new Cache_Data); + end loop; + return result; + end Create_Cache; + + function Random_Policy is new Random_Enum(Policy_Type); + + function Random_Boolean is new Random_Enum(Boolean); + + -- Set the latency based on associativity. + procedure Update_Latency(mem : in out Cache_Type'Class) is + begin + if Get_Device = ASIC then + mem.latency := CACTI.Get_Time(mem); + else + case mem.policy is + when PLRU => + mem.latency := 3 + Time_Type(mem.associativity) / 8; + when others => + mem.latency := 3 + Time_Type(mem.associativity) / 4; + end case; + end if; + end Update_Latency; + + function Random_Cache(next : access Memory_Type'Class; + generator : Distribution_Type; + max_cost : Cost_Type) + return Memory_Pointer is + result : Cache_Pointer := new Cache_Type; + begin + + -- Start with everything set to the minimum. + Set_Memory(result.all, next); + result.line_size := Get_Word_Size(next.all); + result.line_count := MIN_LINE_COUNT; + result.associativity := 1; + result.policy := LRU; + result.write_back := True; + + -- If even the minimum cache is too costly, return null. + if Get_Cost(result.all) > max_cost then + Set_Memory(result.all, null); + Destroy(Memory_Pointer(result)); + return Memory_Pointer(next); + end if; + + -- Randomly increase parameters, reverting them if we exceed the cost. + loop + + -- Line size. + declare + line_size : constant Positive := result.line_size; + begin + if Random_Boolean(Random(generator)) then + result.line_size := line_size * 2; + if Get_Cost(result.all) > max_cost then + result.line_size := line_size; + exit; + end if; + end if;" +function Insert_Register(mem : Memory_Pointer) return Boolean is,"max_path : constant Natural := Device.Get_Max_Path; + begin + + if Get_Path_Length(mem.all) <= max_path then + return False; + end if; + + if mem.all in Split_Type'Class then + + declare + sp : constant Split_Pointer := Split_Pointer(mem); + np : constant Memory_Pointer := Get_Memory(sp.all); + b0 : constant Memory_Pointer := Get_Bank(sp.all, 0); + b1 : constant Memory_Pointer := Get_Bank(sp.all, 1); + begin + + if Insert_Register(np) then + return True; + end if; + + if Insert_Register(b0) then + return True; + end if; + + if Insert_Register(b1) then + return True; + end if; + + -- Insert two registers: one for each bank. + Set_Bank(sp.all, 0, Create_Register(b0)); + Set_Bank(sp.all, 1, Create_Register(b1)); + + return True;" +procedure Insert_Registers(mem : access Memory_Type'Class) is,"begin + + -- Continue inserting registers until we either no longer exceed + -- the max path length or we are unable to reduce the path length. + loop + exit when not Insert_Register(Memory_Pointer(mem)); + end loop; + + end Insert_Registers; + + function Remove_Registers(mem : Memory_Pointer) return Memory_Pointer is + begin + if mem = null then + return null; + elsif mem.all in Register_Type'Class then + declare + rp : Register_Pointer := Register_Pointer(mem); + np : constant Memory_Pointer := Get_Memory(rp.all); + begin + Set_Memory(rp.all, null); + Destroy(Memory_Pointer(rp)); + return Remove_Registers(np);" +procedure Parse_Register(parser : in out Parser_Type;,"result : out Memory_Pointer) is separate; + + procedure Parse_Shift(parser : in out Parser_Type; + result : out Memory_Pointer) is separate; + + procedure Parse_Split(parser : in out Parser_Type; + result : out Memory_Pointer) is separate; + + procedure Parse_SPM(parser : in out Parser_Type; + result : out Memory_Pointer) is separate; + + procedure Parse_Stats(parser : in out Parser_Type; + result : out Memory_Pointer) is separate; + + procedure Parse_Super(parser : in out Parser_Type; + result : out Memory_Pointer) is separate; + + procedure Parse_Trace(parser : in out Parser_Type; + result : out Memory_Pointer) is separate; + + type Memory_Parser_Type is record + name : Unbounded_String; + parser : access procedure(parser : in out Parser_Type; + result : out Memory_Pointer); + end record; + + type Memory_Parser_Array is array(Positive range <>) of Memory_Parser_Type; + + parser_map : constant Memory_Parser_Array := ( + (To_Unbounded_String(""arbiter""), Parse_Arbiter'Access), + (To_Unbounded_String(""cache""), Parse_Cache'Access), + (To_Unbounded_String(""dram""), Parse_DRAM'Access), + (To_Unbounded_String(""dup""), Parse_Dup'Access), + (To_Unbounded_String(""eor""), Parse_EOR'Access), + (To_Unbounded_String(""flash""), Parse_Flash'Access), + (To_Unbounded_String(""flip""), Parse_Flip'Access), + (To_Unbounded_String(""join""), Parse_Join'Access), + (To_Unbounded_String(""offset""), Parse_Offset'Access), + (To_Unbounded_String(""option""), Parse_Option'Access), + (To_Unbounded_String(""perfect_prefetch""), Parse_Perfect_Prefetch'Access), + (To_Unbounded_String(""prefetch""), Parse_Prefetch'Access), + (To_Unbounded_String(""ram""), Parse_RAM'Access), + (To_Unbounded_String(""register""), Parse_Register'Access), + (To_Unbounded_String(""shift""), Parse_Shift'Access), + (To_Unbounded_String(""split""), Parse_Split'Access), + (To_Unbounded_String(""spm""), Parse_SPM'Access), + (To_Unbounded_String(""stats""), Parse_Stats'Access), + (To_Unbounded_String(""super""), Parse_Super'Access), + (To_Unbounded_String(""trace""), Parse_Trace'Access) + ); + + function Parse_Boolean(value : String) return Boolean is + begin + if value = ""true"" then + return True; + elsif value = ""false"" then + return False; + else + raise Data_Error; + end if; + end Parse_Boolean; + + procedure Parse_Memory(parser : in out Parser_Type; + result : out Memory_Pointer) is + begin + Match(parser, Open); + declare + name : constant String := Get_Value(parser.lexer); + begin + Next(parser.lexer); + for i in parser_map'First .. parser_map'Last loop + if parser_map(i).name = name then + parser_map(i).parser(parser, result); + Match(parser, Close); + return; + end if; + end loop; + Raise_Error(parser, ""invalid memory type: "" & name);" +procedure Raise_Error(parser : in Parser_Type;,"msg : in String) is + name : constant String := Get_File_Name(parser.lexer); + line : constant String := Positive'Image(Get_Line(parser.lexer)); + begin + Put_Line(name & ""["" & line(2 .. line'Last) & ""]: error: "" & msg); + raise Parse_Error; + end Raise_Error; + + function Get_Type(parser : Parser_Type) return Token_Type is + begin + return Get_Type(parser.lexer); + end Get_Type; + + function Get_Value(parser : Parser_Type) return String is + begin + return Get_Value(parser.lexer); + end Get_Value; + + procedure Match(parser : in out Parser_Type; + token : in Token_Type) is + begin + if Get_Type(parser) /= token then + Raise_Error(parser, ""got '"" & Get_Value(parser) & + ""' expected '"" & Token_Type'Image(token) & ""'""); + end if; + Next(parser.lexer); + end Match; + + procedure Push_Wrapper(parser : in out Parser_Type; + wrapper : in Wrapper_Pointer; + count : in Positive := 1) is + last : constant Natural := Natural(count); + begin + parser.wrappers.Append(Wrapper_Node'(wrapper, 0, last)); + end Push_Wrapper; + + procedure Pop_Wrapper(parser : in out Parser_Type; + wrapper : out Wrapper_Pointer; + index : out Natural) is + begin + if parser.wrappers.Is_Empty then + Raise_Error(parser, ""unexpected join""); + end if; + declare + node : Wrapper_Node := parser.wrappers.Last_Element; + begin + wrapper := node.wrapper; + index := node.current; + node.current := node.current + 1; + if node.current = node.last then + Delete_Wrapper(parser); + else + parser.wrappers.Replace_Element(parser.wrappers.Last, node); + end if;" +function Create_From_Status is,"new AWA.Helpers.Selectors.Create_From_Enum (Jason.Tickets.Models.Status_Type, + ""ticket_status""); + + function Create_From_Ticket_Type is + new AWA.Helpers.Selectors.Create_From_Enum (Jason.Tickets.Models.Ticket_Type, + ""ticket_type""); + + procedure Append (Into : in out Ada.Strings.Unbounded.Unbounded_String; + Value : in Jason.Tickets.Models.Status_Type); + function To_Priority (Value : in Util.Beans.Objects.Object) return Integer; + + -- ------------------------------ + -- Get a select item list which contains a list of ticket status. + -- ------------------------------ + function Create_Status_List (Module : in Jason.Tickets.Modules.Ticket_Module_Access) + return Util.Beans.Basic.Readonly_Bean_Access is + pragma Unreferenced (Module); + use AWA.Helpers; + begin + return Selectors.Create_Selector_Bean (Bundle => ""tickets"", + Context => null, + Create => Create_From_Status'Access).all'Access; + end Create_Status_List; + + -- ------------------------------ + -- Get a select item list which contains a list of ticket types. + -- ------------------------------ + function Create_Type_List (Module : in Jason.Tickets.Modules.Ticket_Module_Access) + return Util.Beans.Basic.Readonly_Bean_Access is + pragma Unreferenced (Module); + use AWA.Helpers; + begin + return Selectors.Create_Selector_Bean (Bundle => ""tickets"", + Context => null, + Create => Create_From_Ticket_Type'Access).all'Access; + end Create_Type_List; + + -- ------------------------------ + -- Create ticket action. + -- ------------------------------ + overriding + procedure Create (Bean : in out Ticket_Bean; + Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + pragma Unreferenced (Outcome); + begin + Bean.Module.Create (Bean, Bean.Project.Get_Id); + Bean.Tags.Update_Tags (Bean.Get_Id); + end Create; + + -- Save ticket action. + overriding + procedure Save (Bean : in out Ticket_Bean; + Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + pragma Unreferenced (Outcome); + begin + Bean.Module.Save (Bean, Ada.Strings.Unbounded.To_String (Bean.Comment)); + Bean.Tags.Update_Tags (Bean.Get_Id); + end Save; + + -- Save ticket action. + overriding + procedure Save_Status (Bean : in out Ticket_Bean; + Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + pragma Unreferenced (Outcome); + begin + Bean.Module.Save (Bean, Ada.Strings.Unbounded.To_String (Bean.Comment)); + end Save_Status; + + -- Load ticket action. + overriding + procedure Load (Bean : in out Ticket_Bean; + Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + use type AWA.Comments.Beans.Comment_List_Bean_Access; + + Comment_List : AWA.Comments.Beans.Comment_List_Bean_Access; + begin + Bean.Module.Load_Ticket (Bean, Bean.Project.all, Bean.Tags, Bean.Ticket_Id); + Comment_List := AWA.Comments.Beans.Get_Comment_List_Bean (""ticketComments""); + if Comment_List /= null then + Comment_List.Load_Comments (Bean.Get_Id); + end if; + Outcome := Ada.Strings.Unbounded.To_Unbounded_String (""loaded""); + end Load; + + -- ------------------------------ + -- Get the value identified by the name. + -- ------------------------------ + overriding + function Get_Value (From : in Ticket_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if Name = ""project_id"" then + if From.Project.Is_Inserted then + return ADO.Utils.To_Object (From.Project.Get_Id); + else + return ADO.Utils.To_Object (From.Project.Get_Id); + end if; + elsif Name = ""ticket_id"" or Name = ""id"" then + if From.Is_Inserted or From.Is_Loaded then + return ADO.Utils.To_Object (From.Get_Id); + else + return ADO.Utils.To_Object (From.Ticket_Id); + end if; + elsif Name = ""tags"" then + return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); + else + return Jason.Tickets.Models.Ticket_Bean (From).Get_Value (Name); + end if; + end Get_Value; + + -- ------------------------------ + -- Set the value identified by the name. + -- ------------------------------ + overriding + procedure Set_Value (From : in out Ticket_Bean; + Name : in String; + Value : in Util.Beans.Objects.Object) is + begin + if Name = ""project_id"" and not Util.Beans.Objects.Is_Empty (Value) then + From.Project.Set_Id (ADO.Utils.To_Identifier (Value)); + elsif Name = ""ticket_id"" and not Util.Beans.Objects.Is_Empty (Value) then + From.Ticket_Id := ADO.Utils.To_Identifier (Value); + elsif Name = ""id"" and not Util.Beans.Objects.Is_Empty (Value) then + From.Ticket_Id := ADO.Utils.To_Identifier (Value); + From.Module.Load_Ticket (From, From.Project.all, From.Tags, From.Ticket_Id); + else + Jason.Tickets.Models.Ticket_Bean (From).Set_Value (Name, Value); + end if; + end Set_Value; + + -- ------------------------------ + -- Create the Ticket_Bean bean instance. + -- ------------------------------ + function Create_Ticket_Bean (Module : in Jason.Tickets.Modules.Ticket_Module_Access) + return Util.Beans.Basic.Readonly_Bean_Access is + Object : constant Ticket_Bean_Access := new Ticket_Bean; + begin + Object.Module := Module; + Object.Tags_Bean := Object.Tags'Access; + Object.Tags.Set_Entity_Type (Jason.Tickets.Models.TICKET_TABLE); + Object.Tags.Set_Permission (""ticket-update""); + Object.Project := Jason.Projects.Beans.Get_Project_Bean (""project""); + return Object.all'Access; + end Create_Ticket_Bean; + + -- Get the value identified by the name. + overriding + function Get_Value (From : in Ticket_List_Bean; + Name : in String) return Util.Beans.Objects.Object is + Pos : Natural; + begin + if Name = ""tags"" then + Pos := From.Tickets.Get_Row_Index; + if Pos = 0 then + return Util.Beans.Objects.Null_Object; + end if; + declare + Item : constant Models.List_Info := From.Tickets.List.Element (Pos - 1); + begin + return From.Tags.Get_Tags (Item.Id);" +function Create_Ticket_List_Bean (Module : in Jason.Tickets.Modules.Ticket_Module_Access),"return Util.Beans.Basic.Readonly_Bean_Access is + Object : constant Ticket_List_Bean_Access := new Ticket_List_Bean; + begin + Object.Module := Module; + Object.Page_Size := 20; + Object.Count := 0; + Object.Page := 1; + Object.Priority := 0; + Object.Project_Id := ADO.NO_IDENTIFIER; + Object.Status := Jason.Tickets.Models.OPEN; + Object.Status_Filter := Ada.Strings.Unbounded.To_Unbounded_String (""pending""); + Object.Tickets_Bean := Object.Tickets'Access; + Object.Project := Jason.Projects.Beans.Get_Project_Bean (""project""); + return Object.all'Access; + end Create_Ticket_List_Bean; + + procedure Initialize (Object : in out Ticket_Raw_Stat_Bean) is + begin + Object.Low_Bean := Util.Beans.Objects.To_Object (Object.Low'Unchecked_Access, + Util.Beans.Objects.STATIC); + Object.High_Bean := Util.Beans.Objects.To_Object (Object.High'Unchecked_Access, + Util.Beans.Objects.STATIC); + Object.Medium_Bean := Util.Beans.Objects.To_Object (Object.Medium'Unchecked_Access, + Util.Beans.Objects.STATIC); + Object.Closed_Bean := Util.Beans.Objects.To_Object (Object.Closed'Unchecked_Access, + Util.Beans.Objects.STATIC); + end Initialize; + + -- ------------------------------ + -- Get the value identified by the name. + -- ------------------------------ + overriding + function Get_Value (From : in Ticket_Raw_Stat_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if Name = ""low"" then + return From.Low_Bean; + elsif Name = ""medium"" then + return From.Medium_Bean; + elsif Name = ""high"" then + return From.High_Bean; + elsif Name = ""closed"" then + return From.Closed_Bean; + elsif Name = ""progress"" then + return Util.Beans.Objects.To_Object (From.Progress); + else + return Jason.Tickets.Models.Stat_Bean (From).Get_Value (Name); + end if; + end Get_Value; + + -- ------------------------------ + -- Get the value identified by the name. + -- ------------------------------ + overriding + function Get_Value (From : in Ticket_Report_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if name = ""count"" then + return Util.Beans.Objects.To_Object (Natural (From.Report.Length)); + elsif name = ""total"" then + return From.Total_Bean; + end if; + return Util.Beans.Objects.Null_Object; + end Get_Value; + + -- ------------------------------ + -- Set the value identified by the name. + -- ------------------------------ + overriding + procedure Set_Value (From : in out Ticket_Report_Bean; + Name : in String; + Value : in Util.Beans.Objects.Object) is + begin + null; + end Set_Value; + + -- ------------------------------ + -- Get the number of elements in the list. + -- ------------------------------ + function Get_Count (From : Ticket_Report_Bean) return Natural is + begin + return Natural (From.Report.Length); + end Get_Count; + + -- ------------------------------ + -- Set the current row index. Valid row indexes start at 1. + -- ------------------------------ + overriding + procedure Set_Row_Index (From : in out Ticket_Report_Bean; + Index : in Natural) is + begin + if Index = 1 then + From.Current := From.Report.First; + From.Current_Pos := Index; + elsif Index = Natural (From.Report.Length) then + From.Current := From.Report.Last; + From.Current_Pos := Index; + else + while Index > From.Current_Pos and Ticket_Stat_Vectors.Has_Element (From.Current) loop + Ticket_Stat_Vectors.Next (From.Current); + From.Current_Pos := From.Current_Pos + 1; + end loop; + end if; + Ticket_Stat_Bean (From.Element) := Ticket_Stat_Vectors.Element (From.Report, + From.Current_Pos); + end Set_Row_Index; + + -- ------------------------------ + -- Get the element at the current row index. + -- ------------------------------ + overriding + function Get_Row (From : in Ticket_Report_Bean) return Util.Beans.Objects.Object is + begin + return From.Row; + end Get_Row; + + -- ------------------------------ + -- Load the information for the tickets. + -- ------------------------------ + overriding + procedure Load (Bean : in out Ticket_Report_Bean; + Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + pragma Unreferenced (Outcome); + + Session : constant ADO.Sessions.Session := Bean.Module.Get_Session; + Query : ADO.Queries.Context; + Empty : constant Jason.Tickets.Models.Stat_Bean := (Kind => Models.WORK, + others => 0); + Ctx : constant ASC.Service_Context_Access := ASC.Current; + User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; + begin + Query.Set_Query (Jason.Tickets.Models.Query_Stats); + Query.Bind_Param (""project_id"", Bean.Project.Get_Id); + Query.Bind_Param (""user_id"", User.Get_Id); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""project_table"", + Table => Jason.Projects.Models.PROJECT_TABLE, + Session => Session); + declare + Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); + begin + Stmt.Execute; + while Stmt.Has_Elements loop + declare + use Models; + + Status : constant Models.Status_Type := Status_Type'Val (Stmt.Get_Integer (0)); + Kind : constant Models.Ticket_Type := Ticket_Type'Val (Stmt.Get_Integer (1)); + Priority : constant Natural := Stmt.Get_Integer (2); + Count : constant Natural := Stmt.Get_Integer (3); + Time : constant Natural := Stmt.Get_Integer (4); + Done : constant Natural := Stmt.Get_Integer (5); + Remain : constant Natural := Stmt.Get_Integer (6); + + procedure Update (Key : in Models.Ticket_Type; + Item : in out Ticket_Stat_Bean); + + procedure Update (Key : in Models.Ticket_Type; + Item : in out Ticket_Stat_Bean) is + pragma Unreferenced (Key); + begin + if Status = Models.CLOSED or Status = Models.REJECTED then + Item.Closed.Count := Item.Closed.Count + Count; + Item.Closed.Time := Item.Closed.Time + Time; + Item.Closed.Done := Item.Closed.Done + Done; + Item.Closed.Remain := Item.Closed.Remain + Remain; + elsif Priority <= 3 then + Item.High.Count := Item.High.Count + Count; + Item.High.Time := Item.High.Time + Time; + Item.High.Done := Item.High.Done + Done; + Item.High.Remain := Item.High.Remain + Remain; + elsif Priority > 4 then + Item.Low.Count := Item.Low.Count + Count; + Item.Low.Time := Item.Low.Time + Time; + Item.Low.Done := Item.Low.Done + Done; + Item.Low.Remain := Item.Low.Remain + Remain; + else + Item.Medium.Count := Item.Medium.Count + Count; + Item.Medium.Time := Item.Medium.Time + Time; + Item.Medium.Done := Item.Medium.Done + Done; + Item.Medium.Remain := Item.Medium.Remain + Remain; + end if; + end Update; + + Pos : constant Ticket_Stat_Map.Cursor := Bean.List.Find (Kind); + begin + if Ticket_Stat_Map.Has_Element (Pos) then + Bean.List.Update_Element (Pos, Update'Access); + else + declare + T : Ticket_Stat_Bean; + begin + T.Kind := Kind; + T.Count := 0; + T.Time := 0; + T.Remain := 0; + T.High := Empty; + T.Low := Empty; + T.Medium := Empty; + T.Closed := Empty; + Update (Kind, T); + Bean.List.Insert (Kind, T);" +procedure Set_Field_Discrete is,"new ADO.Objects.Set_Field_Operation + (Status_Type); + Impl : Ticket_Access; + begin + Set_Field (Object, Impl); + Set_Field_Discrete (Impl.all, 7, Impl.Status, Value); + end Set_Status; + + function Get_Status (Object : in Ticket_Ref) + return Status_Type is + Impl : constant Ticket_Access + := Ticket_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Status; + end Get_Status; + + + procedure Set_Description (Object : in out Ticket_Ref; + Value : in String) is + Impl : Ticket_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 8, Impl.Description, Value); + end Set_Description; + + procedure Set_Description (Object : in out Ticket_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Ticket_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 8, Impl.Description, Value); + end Set_Description; + + function Get_Description (Object : in Ticket_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Description); + end Get_Description; + function Get_Description (Object : in Ticket_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Ticket_Access + := Ticket_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Description; + end Get_Description; + + + procedure Set_Update_Date (Object : in out Ticket_Ref; + Value : in Ada.Calendar.Time) is + Impl : Ticket_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 9, Impl.Update_Date, Value); + end Set_Update_Date; + + function Get_Update_Date (Object : in Ticket_Ref) + return Ada.Calendar.Time is + Impl : constant Ticket_Access + := Ticket_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Update_Date; + end Get_Update_Date; + + + procedure Set_Kind (Object : in out Ticket_Ref; + Value : in Ticket_Type) is + procedure Set_Field_Discrete is + new ADO.Objects.Set_Field_Operation + (Ticket_Type); + Impl : Ticket_Access; + begin + Set_Field (Object, Impl); + Set_Field_Discrete (Impl.all, 10, Impl.Kind, Value); + end Set_Kind; + + function Get_Kind (Object : in Ticket_Ref) + return Ticket_Type is + Impl : constant Ticket_Access + := Ticket_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Kind; + end Get_Kind; + + + procedure Set_Duration (Object : in out Ticket_Ref; + Value : in Integer) is + Impl : Ticket_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 11, Impl.Duration, Value); + end Set_Duration; + + function Get_Duration (Object : in Ticket_Ref) + return Integer is + Impl : constant Ticket_Access + := Ticket_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Duration; + end Get_Duration; + + + procedure Set_Progress (Object : in out Ticket_Ref; + Value : in Integer) is + Impl : Ticket_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 12, Impl.Progress, Value); + end Set_Progress; + + function Get_Progress (Object : in Ticket_Ref) + return Integer is + Impl : constant Ticket_Access + := Ticket_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Progress; + end Get_Progress; + + + procedure Set_Project (Object : in out Ticket_Ref; + Value : in Jason.Projects.Models.Project_Ref'Class) is + Impl : Ticket_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 13, Impl.Project, Value); + end Set_Project; + + function Get_Project (Object : in Ticket_Ref) + return Jason.Projects.Models.Project_Ref'Class is + Impl : constant Ticket_Access + := Ticket_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Project; + end Get_Project; + + + procedure Set_Creator (Object : in out Ticket_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Ticket_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 14, Impl.Creator, Value); + end Set_Creator; + + function Get_Creator (Object : in Ticket_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Ticket_Access + := Ticket_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Creator; + end Get_Creator; + + -- Copy of the object. + procedure Copy (Object : in Ticket_Ref; + Into : in out Ticket_Ref) is + Result : Ticket_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Ticket_Access + := Ticket_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Ticket_Access + := new Ticket_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Version := Impl.Version; + Copy.Summary := Impl.Summary; + Copy.Ident := Impl.Ident; + Copy.Create_Date := Impl.Create_Date; + Copy.Priority := Impl.Priority; + Copy.Status := Impl.Status; + Copy.Description := Impl.Description; + Copy.Update_Date := Impl.Update_Date; + Copy.Kind := Impl.Kind; + Copy.Duration := Impl.Duration; + Copy.Progress := Impl.Progress; + Copy.Project := Impl.Project; + Copy.Creator := Impl.Creator;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Ticket_Impl, Ticket_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Ticket_Impl_Ptr := Ticket_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + overriding + procedure Find (Object : in out Ticket_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, TICKET_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Ticket_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + overriding + procedure Save (Object : in out Ticket_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (TICKET_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- summary + Value => Object.Summary); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- ident + Value => Object.Ident); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- priority + Value => Object.Priority); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- status + Value => Integer (Status_Type'Enum_Rep (Object.Status))); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_1_NAME, -- description + Value => Object.Description); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_1_NAME, -- update_date + Value => Object.Update_Date); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_1_NAME, -- kind + Value => Integer (Ticket_Type'Enum_Rep (Object.Kind))); + Object.Clear_Modified (10); + end if; + if Object.Is_Modified (11) then + Stmt.Save_Field (Name => COL_10_1_NAME, -- duration + Value => Object.Duration); + Object.Clear_Modified (11); + end if; + if Object.Is_Modified (12) then + Stmt.Save_Field (Name => COL_11_1_NAME, -- progress + Value => Object.Progress); + Object.Clear_Modified (12); + end if; + if Object.Is_Modified (13) then + Stmt.Save_Field (Name => COL_12_1_NAME, -- project_id + Value => Object.Project); + Object.Clear_Modified (13); + end if; + if Object.Is_Modified (14) then + Stmt.Save_Field (Name => COL_13_1_NAME, -- creator_id + Value => Object.Creator); + Object.Clear_Modified (14); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Ticket_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, TICKET_DEF'Access); + begin + Stmt.Execute; + Ticket_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Ticket_Ref; + Impl : constant Ticket_Access := new Ticket_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Attribute_Impl, Attribute_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Attribute_Impl_Ptr := Attribute_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + overriding + procedure Find (Object : in out Attribute_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, ATTRIBUTE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Attribute_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + overriding + procedure Save (Object : in out Attribute_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (ATTRIBUTE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- value + Value => Object.Value); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- definition_id + Value => Object.Definition); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- ticket_id + Value => Object.Ticket); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Attribute_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, ATTRIBUTE_DEF'Access); + begin + Stmt.Execute; + Attribute_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Attribute_Ref; + Impl : constant Attribute_Access := new Attribute_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Set_Field_Discrete is,"new ADO.Objects.Set_Field_Operation + (Status_Type); + Impl : Project_Access; + begin + Set_Field (Object, Impl); + Set_Field_Discrete (Impl.all, 5, Impl.Status, Value); + end Set_Status; + + function Get_Status (Object : in Project_Ref) + return Status_Type is + Impl : constant Project_Access + := Project_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Status; + end Get_Status; + + + procedure Set_Last_Ticket (Object : in out Project_Ref; + Value : in Integer) is + Impl : Project_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 6, Impl.Last_Ticket, Value); + end Set_Last_Ticket; + + function Get_Last_Ticket (Object : in Project_Ref) + return Integer is + Impl : constant Project_Access + := Project_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Last_Ticket; + end Get_Last_Ticket; + + + procedure Set_Update_Date (Object : in out Project_Ref; + Value : in Ada.Calendar.Time) is + Impl : Project_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 7, Impl.Update_Date, Value); + end Set_Update_Date; + + function Get_Update_Date (Object : in Project_Ref) + return Ada.Calendar.Time is + Impl : constant Project_Access + := Project_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Update_Date; + end Get_Update_Date; + + + procedure Set_Description (Object : in out Project_Ref; + Value : in String) is + Impl : Project_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 8, Impl.Description, Value); + end Set_Description; + + procedure Set_Description (Object : in out Project_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Project_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 8, Impl.Description, Value); + end Set_Description; + + function Get_Description (Object : in Project_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Description); + end Get_Description; + function Get_Description (Object : in Project_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Project_Access + := Project_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Description; + end Get_Description; + + + procedure Set_Wiki (Object : in out Project_Ref; + Value : in AWA.Wikis.Models.Wiki_Space_Ref'Class) is + Impl : Project_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 9, Impl.Wiki, Value); + end Set_Wiki; + + function Get_Wiki (Object : in Project_Ref) + return AWA.Wikis.Models.Wiki_Space_Ref'Class is + Impl : constant Project_Access + := Project_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Wiki; + end Get_Wiki; + + + procedure Set_Owner (Object : in out Project_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Project_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 10, Impl.Owner, Value); + end Set_Owner; + + function Get_Owner (Object : in Project_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Project_Access + := Project_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Owner; + end Get_Owner; + + -- Copy of the object. + procedure Copy (Object : in Project_Ref; + Into : in out Project_Ref) is + Result : Project_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Project_Access + := Project_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Project_Access + := new Project_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Version := Impl.Version; + Copy.Name := Impl.Name; + Copy.Create_Date := Impl.Create_Date; + Copy.Status := Impl.Status; + Copy.Last_Ticket := Impl.Last_Ticket; + Copy.Update_Date := Impl.Update_Date; + Copy.Description := Impl.Description; + Copy.Wiki := Impl.Wiki; + Copy.Owner := Impl.Owner;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Project_Impl, Project_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Project_Impl_Ptr := Project_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + overriding + procedure Find (Object : in out Project_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, PROJECT_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Project_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + overriding + procedure Save (Object : in out Project_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (PROJECT_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- status + Value => Integer (Status_Type'Enum_Rep (Object.Status))); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- last_ticket + Value => Object.Last_Ticket); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- update_date + Value => Object.Update_Date); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_1_NAME, -- description + Value => Object.Description); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_1_NAME, -- wiki_id + Value => Object.Wiki); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_1_NAME, -- owner_id + Value => Object.Owner); + Object.Clear_Modified (10); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Project_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, PROJECT_DEF'Access); + begin + Stmt.Execute; + Project_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Project_Ref; + Impl : constant Project_Access := new Project_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Attribute_Definition_Impl, Attribute_Definition_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Attribute_Definition_Impl_Ptr := Attribute_Definition_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + overriding + procedure Find (Object : in out Attribute_Definition_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, ATTRIBUTE_DEFINITION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Attribute_Definition_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + overriding + procedure Save (Object : in out Attribute_Definition_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (ATTRIBUTE_DEFINITION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- default_value + Value => Object.Default_Value); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- project_id + Value => Object.Project); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Attribute_Definition_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, ATTRIBUTE_DEFINITION_DEF'Access); + begin + Stmt.Execute; + Attribute_Definition_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Attribute_Definition_Ref; + Impl : constant Attribute_Definition_Access := new Attribute_Definition_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +function Unchecked_To_Unsigned_16 is,"new Ada.Unchecked_Conversion (Octets_2, Unsigned_16); + + function Unchecked_To_Unsigned_32 is + new Ada.Unchecked_Conversion (Octets_4, Unsigned_32); + + function Unchecked_To_Octets_2 is + new Ada.Unchecked_Conversion (Unsigned_16, Octets_2); + + function Unchecked_To_Octets_4 is + new Ada.Unchecked_Conversion (Unsigned_32, Octets_4); + + function Swap_Bus (X : Unsigned_16) return Unsigned_16 + is + O : Octets_2 with + Address => X'Address, Alignment => Unsigned_16'Alignment; + begin + if System.Default_Bit_Order = System.Low_Order_First then + return X; + else + return Unchecked_To_Unsigned_16 ((O (1), O (0))); + end if; + end Swap_Bus; + + function Swap_Bus (X : Unsigned_32) return Unsigned_32 + is + O : Octets_4 with + Address => X'Address, Alignment => Unsigned_32'Alignment; + begin + if System.Default_Bit_Order = System.Low_Order_First then + return X; + else + return Unchecked_To_Unsigned_32 ((O (3), O (2), O (1), O (0))); + end if; + end Swap_Bus; + + function Swap_Bus (X : Octets_2) return Unsigned_16 + is + begin + if System.Default_Bit_Order = System.Low_Order_First then + return Unchecked_To_Unsigned_16 (X); + else + return Unchecked_To_Unsigned_16 ((X (1), X (0))); + end if; + end Swap_Bus; + + function Swap_Bus (X : Octets_4) return Unsigned_32 + is + begin + if System.Default_Bit_Order = System.Low_Order_First then + return Unchecked_To_Unsigned_32 (X); + else + return Unchecked_To_Unsigned_32 ((X (3), X (2), X (1), X (0))); + end if; + end Swap_Bus; + + function Swap_Bus (X : Unsigned_16) return Octets_2 + is + begin + if System.Default_Bit_Order = System.Low_Order_First then + return Unchecked_To_Octets_2 (X); + else + declare + O : constant Octets_2 := Unchecked_To_Octets_2 (X); + begin + return (O (1), O (0));" +function Object_Exist,"(This : Object_Dictionary'Class; + Index : Object_Index) return Boolean + is (This.Index_Map (Index) /= No_Index); + + function Entry_Exist + (This : Object_Dictionary'Class; + Index : Object_Index; + Subindex : Object_Subindex) return Boolean + is + Arr_Idx : constant Index_Type := This.Index_Map (Index); + begin + return Arr_Idx /= No_Index and then + Subindex in This.Objects (Arr_Idx).Entries'Range; + end Entry_Exist; + + function Maximum_Nof_Entries + (This : Object_Dictionary; + Index : Object_Index) + return Natural + is (This.Object (Index).Entries'Length); + + function Is_Entry_Compatible + (This : Object_Dictionary; + An_Entry : Entry_Base'Class; + Index : Object_Index; + Subindex : Object_Subindex) + return Boolean + is + use type Ada.Tags.Tag; + + OD_Entry : constant Entry_Ref := This.Object (Index).Entries (Subindex); + begin + return OD_Entry'Tag = An_Entry'Tag; + end Is_Entry_Compatible; + + function Is_Entry_Writable + (This : Object_Dictionary; + Index : Entry_Index) + return Boolean + is + begin + if This.Entry_Exist (Index.Object, Index.Sub) then + return This.Object (Index.Object).Entries (Index.Sub).Is_Writable; + else + return False; + end if; + end Is_Entry_Writable; + + function Is_Entry_Readable + (This : Object_Dictionary; + Index : Entry_Index) + return Boolean + is + begin + if This.Entry_Exist (Index.Object, Index.Sub) then + return This.Object (Index.Object).Entries (Index.Sub).Is_Readable; + else + return False; + end if; + end Is_Entry_Readable; + + function Get_Entry + (This : Object_Dictionary; + Index : Object_Index; + Subindex : Object_Subindex) return Entry_Base'Class + is + (This.Object (Index).Entries (Subindex).all); + + procedure Set_Entry + (This : in out Object_Dictionary; + New_Entry : in Entry_Base'Class; + Index : in Object_Index; + Subindex : in Object_Subindex; + Silently : in Boolean := False) + is + begin + This.Object (Index).Entries (Subindex).all := New_Entry; + if not Silently then + This.Events.Node_Events.Put + ((Event => ACO.Events.OD_Entry_Update, + Index => (Index, Subindex))); + end if; + end Set_Entry; + + procedure Set_Node_State + (This : in out Object_Dictionary; + Node_State : in ACO.States.State) + is + Prev : ACO.States.State; + begin + Prev := This.Node_State; + This.Node_State := Node_State; + This.Events.Node_Events.Put + ((Event => ACO.Events.State_Transition, + State => (Previous => Prev, Current => Node_State))); + end Set_Node_State; + + function Get_Node_State (This : Object_Dictionary) return ACO.States.State is + (This.Node_State); + + function Get_Hbt_Node_Id (Reg : U32) return ACO.Messages.Node_Nr is + (ACO.Messages.Node_Nr (Shift_Right (Reg, 16) and 16#FF#)); + + function Get_Hbt_Slave_Subindex + (This : Object_Dictionary; + Node_Id : ACO.Messages.Node_Nr) + return Object_Subindex + is + Object : constant Object_Ref := This.Object (Heartbeat_Consumer_Index); + begin + for I in 1 .. Object.Entries'Last loop + declare + E_Ref : constant Entry_Ref := Object.Entries (I); + Reg : constant U32 := Entry_U32 (E_Ref.all).Read; + use type ACO.Messages.Node_Nr; + begin + if Get_Hbt_Node_Id (Reg) = Node_Id then + return Object_Subindex (I); + end if;" +"function To_Data_Array is new Ada.Unchecked_Conversion (From, To);","begin + return To_Data_Array (D); + end Convert; + + function Convert (D : ACO.Messages.Data_Array) + return STM32.CAN.Message_Data + is + subtype From is ACO.Messages.Data_Array (D'Range); + subtype To is STM32.CAN.Message_Data (D'Range); + function To_Message_Data is new Ada.Unchecked_Conversion (From, To); + begin + return To_Message_Data (D); + end Convert; + + overriding + procedure Receive_Message_Blocking + (This : in out CAN_Driver; + Msg : out ACO.Messages.Message) + is + Rx_Msg : CAN_Message; + begin + -- Suspend until new CAN message is received + This.Controller.Receive_Message (Rx_Msg); + + Msg := ACO.Messages.Create + (CAN_Id => ACO.Messages.Id_Type (Rx_Msg.Std_ID), + RTR => Rx_Msg.Rtr, + DLC => ACO.Messages.Data_Length (Rx_Msg.Dlc), + Data => Convert (Rx_Msg.Data)); + end Receive_Message_Blocking; + + overriding + procedure Send_Message + (This : in out CAN_Driver; + Msg : in ACO.Messages.Message) + is + Success : Boolean; + Tx_Msg : constant CAN_Message := + (Std_ID => Standard_Id (ACO.Messages.CAN_Id (Msg)), + Ext_ID => 0, + Ide => False, + Rtr => Msg.RTR, + Dlc => Data_Length_Type (Msg.Length), + Data => Convert (Msg.Data)); + begin + This.Controller.Transmit_Message + (Message => Tx_Msg, + Success => Success); + end Send_Message; + + overriding + procedure Initialize (This : in out CAN_Driver) + is + use STM32.GPIO; + use STM32.Device; + + Tx_Pin : GPIO_Point renames PD1; + Rx_Pin : GPIO_Point renames PD0; + + Fifo_X : constant Fifo_Nr := FIFO_0; + + -- For now, set to 125 kbit/s + -- see http://www.bittiming.can-wiki.info/#bxCAN + Bit_Timing : constant Bit_Timing_Config := + (Resynch_Jump_Width => 1, + Time_Segment_1 => 13, + Time_Segment_2 => 2, + Quanta_Prescaler => 21); + + Mask_Allow_All : constant Filter_32 := + (Std_ID => 0, + Ext_ID => 0, + Ide => False, + Rtr => False); + + Bank_Config : constant CAN_Filter_Bank := + (Bank_Nr => 0, + Activated => True, + Fifo_Assignment => Fifo_X, + Filters => (Mask32, (Mask_Allow_All, Mask_Allow_All))); + begin + Enable_Clock (Points => (Tx_Pin, Rx_Pin)); + Configure_IO (Rx_Pin, (Mode_AF, Pull_Up, Push_Pull, Speed_50MHz, GPIO_AF_CAN1_9)); + Configure_IO (Tx_Pin, (Mode_AF, Floating, Push_Pull, Speed_50MHz, GPIO_AF_CAN1_9)); + + Enable_Clock (This.Device.all); + + Reset (This.Device.all); + + Configure + (This => This.Device.all, + Mode => Normal, + Time_Triggered => False, + Auto_Bus_Off => False, + Auto_Wakeup => False, + Auto_Retransmission => False, + Rx_FIFO_Locked => False, + Tx_FIFO_Prio => False, + Timing_Config => Bit_Timing); + + Set_Slave_Start_Bank (14); + + Configure_Filter + (This => This.Device.all, + Bank_Config => Bank_Config); + + This.Controller.Enable_Receiver (Fifo_X); + end Initialize; + + overriding + function Is_Message_Pending + (This : CAN_Driver) + return Boolean + is + begin + return This.Controller.Is_Message_Pending; + end Is_Message_Pending; + + + overriding + function Current_Time + (This : CAN_Driver) + return Ada.Real_Time.Time + is + pragma Unreferenced (This); + begin + return Ada.Real_Time.Clock; + end Current_Time; + + package body CAN_ISR is + function Tx_Interrupt_Id + (Device : not null access CAN_Controller) + return Ada.Interrupts.Interrupt_ID + is + begin + if Device = STM32.Device.CAN_1'Access then + return Ada.Interrupts.Names.CAN1_TX_Interrupt; + elsif Device = STM32.Device.CAN_2'Access then + return Ada.Interrupts.Names.CAN2_TX_Interrupt; + else + raise Constraint_Error; + end if; + end Tx_Interrupt_Id; + + function Rx0_Interrupt_Id + (Device : not null access CAN_Controller) + return Ada.Interrupts.Interrupt_ID + is + begin + if Device = STM32.Device.CAN_1'Access then + return Ada.Interrupts.Names.CAN1_RX0_Interrupt; + elsif Device = STM32.Device.CAN_2'Access then + return Ada.Interrupts.Names.CAN2_RX0_Interrupt; + else + raise Constraint_Error; + end if; + end Rx0_Interrupt_Id; + + function Rx1_Interrupt_Id + (Device : not null access CAN_Controller) + return Ada.Interrupts.Interrupt_ID + is + begin + if Device = STM32.Device.CAN_1'Access then + return Ada.Interrupts.Names.CAN1_RX1_Interrupt; + elsif Device = STM32.Device.CAN_2'Access then + return Ada.Interrupts.Names.CAN2_RX1_Interrupt; + else + raise Constraint_Error; + end if; + end Rx1_Interrupt_Id; + + function SCE_Interrupt_Id + (Device : not null access CAN_Controller) + return Ada.Interrupts.Interrupt_ID + is + begin + if Device = STM32.Device.CAN_1'Access then + return Ada.Interrupts.Names.CAN1_SCE_Interrupt; + elsif Device = STM32.Device.CAN_2'Access then + return Ada.Interrupts.Names.CAN2_SCE_Interrupt; + else + raise Constraint_Error; + end if; + end SCE_Interrupt_Id; + + function Nof_Messages (This : Message_Buffer) return Natural + is + begin + if This.Idx_New >= This.Idx_Old then + return This.Idx_New - This.Idx_Old; + else + return Index'Last - This.Idx_Old + 1 + This.Idx_New - Index'First; + end if; + end Nof_Messages; + + procedure Get_Next_Message + (This : in out Message_Buffer; + Message : out CAN_Message) + is + begin + Message := This.Buffer (This.Idx_Old); + This.Idx_Old := (This.Idx_Old + 1) mod (Index'Last + 1); + end Get_Next_Message; + + procedure Put_Message + (This : in out Message_Buffer; + Message : in CAN_Message) + is + Idx_Next : constant Index := (This.Idx_New + 1) mod (Index'Last + 1); + begin + This.Buffer (This.Idx_New) := Message; + This.Idx_New := Idx_Next; + end Put_Message; + + protected body Controller is + + procedure Transmit_Message + (Message : in CAN_Message; + Success : out Boolean) + is + begin + Success := Nof_Messages (Tx_Buffer) < Max_Nof_Messages; + if Success then + Put_Message (Tx_Buffer, Message); + Send; + end if; + end Transmit_Message; + + entry Receive_Message + (Message : out CAN_Message) when Is_Rx_Pending + is + begin + Get_Next_Message (Rx_Buffer, Message); + + Is_Rx_Pending := (Nof_Messages (Rx_Buffer) > 0); + end Receive_Message; + + procedure Enable_Receiver + (Fifo : in Fifo_Nr) + is + CAN : CAN_Controller renames Device.all; + begin + case Fifo is + when FIFO_0 => + Enable_Interrupts (CAN, FIFO_0_Message_Pending); + when FIFO_1 => + Enable_Interrupts (CAN, FIFO_1_Message_Pending); + end case; + end Enable_Receiver; + + procedure Send is + CAN : CAN_Controller renames Device.all; + begin + while Nof_Messages (Tx_Buffer) > 0 loop + declare + Message : CAN_Message; + Empty_Found : Boolean; + Mailbox : Mailbox_Type; + begin + Get_Empty_Mailbox (CAN, Mailbox, Empty_Found); + + exit when not Empty_Found; + + Get_Next_Message (Tx_Buffer, Message); + Write_Tx_Message (CAN, Message, Mailbox); + Enable_Interrupts (CAN, Transmit_Mailbox_Empty); + Transmission_Request (CAN, Mailbox);" +function Read_U16 is new ACO.Nodes.Remotes.Generic_Read,"(Entry_T => Entry_U16); + To_Entry : constant Entry_U16 := + Read_U16 (Node, ACO.OD.Heartbeat_Producer_Index, 0); + begin + Ada.Text_IO.Put_Line + (""Generic function read value = "" & U16' (To_Entry.Read)'Img);" +procedure InitExit is,"Ctx: aliased USB.LibUSB1.Context_Access; + R: USB.LibUSB1.Status; +begin + R := USB.LibUSB1.Init_Lib(Ctx'Access); + Put(USB.LibUSB1.Status'Image(R)); + Put_Line(""""); + USB.LibUSB1.Exit_Lib(Ctx);" +procedure List_Devices_C is,"Ctx: aliased Context_Access; + R: Status; + Ri: Integer; + Cnt: ssize_t; + Devs: aliased Device_Access_Lists.Pointer; +begin + R := Init_Lib(Ctx'Access); + if R /= Success then + Put(Status'Image(R)); + Put_Line(""""); + return; + end if; + + Cnt := Get_Device_List(Ctx, Devs'Access); + if Cnt < 0 then + --R := Status(Cnt); + --Put(Status'Image(R)); + Put_Line(""""); + --Exit_Lib(Ctx); + --return; + else + declare + Dev_Array: Device_Access_Array := + Device_Access_Lists.Value(Devs, Interfaces.C.ptrdiff_t(Cnt)); + Desc: aliased USB.Protocol.Device_Descriptor; + Path: Port_Number_Array(0..7); + begin + Put(Integer(Cnt)); + Put_Line("" devices listed""); + for I in Dev_Array'Range loop + Put(Integer(I-Dev_Array'First), 3); + Put(Integer(Get_Bus_Number(Dev_Array(I))), 4); + Put(Integer(Get_Device_Address(Dev_Array(I))), 4); + R := Get_Device_Descriptor(Dev_Array(I), Desc); + if R /= Success then + Put(""Failed to get device descriptor: "" & Status'Image(R)); + else + Put(Integer(Desc.idVendor), 10, 16); + Put(Integer(Desc.idProduct), 10, 16); + Ri := Integer(Get_Port_Numbers(Dev_Array(I), + Path(0)'Unrestricted_Access, -- do not know how to do right + Path'Length)); + if Ri > 0 then + Put("" path: ""); + for I in 0 .. Ri-1 loop + Put(Integer(Path(I)), 4); + end loop; + end if; + end if; + New_Line; + end loop;" +procedure Greet2 is,"begin + loop + Put_Line (""Please enter your name: ""); + + declare + Name : String := Get_Line; + -- ^ Call to the Get_Line function + begin + exit when Name = """"; + Put_line (""Hi "" & Name & ""!"");" +procedure Check_Positive2 is,"N : Integer; +begin + Put (""Enter an integer value: ""); -- Put a String + Get (N); -- Reads in an integer value + Put (N); -- Put an Integer + declare + S : String := + (if N > 0 then "" is a positive number"" + else "" is not a positive number""); + begin + Put_Line (S);" +procedure finalize_library is,"begin + E006 := E006 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__text_io__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""system__file_io__finalize_body""); + begin + E109 := E109 - 1; + F2;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (Ada, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + pragma Favor_Top_Level (No_Param_Proc); + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 0; + Default_Stack_Size := -1; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E025 := E025 + 1; + Ada.Containers'Elab_Spec; + E040 := E040 + 1; + Ada.Io_Exceptions'Elab_Spec; + E068 := E068 + 1; + Ada.Strings'Elab_Spec; + E052 := E052 + 1; + Ada.Strings.Maps'Elab_Spec; + E054 := E054 + 1; + Ada.Strings.Maps.Constants'Elab_Spec; + E058 := E058 + 1; + Interfaces.C'Elab_Spec; + E078 := E078 + 1; + System.Exceptions'Elab_Spec; + E027 := E027 + 1; + System.Object_Reader'Elab_Spec; + E080 := E080 + 1; + System.Dwarf_Lines'Elab_Spec; + E047 := E047 + 1; + System.Os_Lib'Elab_Body; + E072 := E072 + 1; + System.Soft_Links.Initialize'Elab_Body; + E021 := E021 + 1; + E013 := E013 + 1; + System.Traceback.Symbolic'Elab_Body; + E039 := E039 + 1; + E008 := E008 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E101 := E101 + 1; + Ada.Streams'Elab_Spec; + E099 := E099 + 1; + System.File_Control_Block'Elab_Spec; + E113 := E113 + 1; + System.Finalization_Root'Elab_Spec; + E112 := E112 + 1; + Ada.Finalization'Elab_Spec; + E110 := E110 + 1; + System.File_Io'Elab_Body; + E109 := E109 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E006 := E006 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_greet""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + if gnat_argc = 0 then + gnat_argc := argc; + gnat_argv := argv; + end if; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure Down is,"begin + Indent_Level := Indent_Level + Indent_Step; + Indent := Indent_String (Indent_Level); + end Down; + + -------- + -- Up -- + -------- + + procedure Up is + begin + Indent_Level := Indent_Level - Indent_Step; + Indent := Indent_String (Indent_Level); + end Up; + + -------------- + -- End_Line -- + -------------- + + procedure End_Line is + begin + Put ("""" & ASCII.LF); + end End_Line; + + -------------- + -- Dump_Rec -- + -------------- + + procedure Dump_Rec (N : Node) is + begin + case N.Kind is + when Map => + for Ent of N.Iterate_On_Table loop + Put (Indent); + + Put (Format_String (Ent.Key)); + Put (Key_Separator); + + if Ent.Value.Kind in Composite_Node_Kind then + End_Line; + Down; + Dump_Rec (Ent.Value); + Up; + else + Dump_Rec (Ent.Value); + End_Line; + end if; + end loop; + + when Vector => + for Index in 1 .. N.Length loop + declare + Value : constant Node := N.Item (Index); + begin + Put (Indent); + Put (""- ""); + + if Value.Kind in Composite_Node_Kind then + End_Line; + Down; + Dump_Rec (Value); + Up; + else + Dump_Rec (Value); + End_Line; + end if;" +procedure Down is,"begin + Indent_Level := Indent_Level + Indent_Step; + Indent := Indent_String (Indent_Level); + -- Put (""#down ("" & Indent_Level'Img & "")#""); + end Down; + + -------- + -- Up -- + -------- + + procedure Up is + begin + Indent_Level := Indent_Level - Indent_Step; + Indent := Indent_String (Indent_Level); + -- Put (""#up ("" & Indent_Level'Img & "")#""); + end Up; + + -------------- + -- End_Line -- + -------------- + + procedure End_Line is + begin + if Indent_Step /= 0 then + Put ("""" & ASCII.LF); + end if; + end End_Line; + + -------------- + -- Dump_Rec -- + -------------- + + procedure Dump_Rec (N : Node) is + begin + case N.Kind is + when Map => + for Ent of N.Iterate_On_Table loop + declare + Name : constant Unbounded_UTF8_String := + Element_Name (Ent.Key); + begin + Put (Indent); + Put (""<""); + Put (Name); + Put ("">""); + + if Ent.Value.Kind in Composite_Node_Kind then + End_Line; + Down; + Dump_Rec (Ent.Value); + Up; + Put (Indent); + else + Dump_Rec (Ent.Value); + end if; + Put (""""); + End_Line;" +procedure Sort_Keys is new Ada.Containers.Generic_Array_Sort,"(Index_Type => Positive, + Element_Type => Unbounded_UTF8_String, + Array_Type => Key_Array); + + package TOML_Maps is new Ada.Containers.Hashed_Maps + (Key_Type => Unbounded_String, + Element_Type => Node, + Hash => Hash, + Equivalent_Keys => ""=""); + + package TOML_Vectors is new Ada.Containers.Vectors (Positive, Node); + + type Node_Record (Kind : Any_Node_Kind) is limited record + Ref_Count : Natural; + + case Kind is + when Map => + Map_Value : TOML_Maps.Map; + + when Vector => + Array_Value : TOML_Vectors.Vector; + -- List of values for all items + + Array_Implicitly_Created : Boolean; + -- Same as Table_Implicitly_Created + + when Value => + String_Value : Unbounded_String; + + end case; + end record; + + procedure Free is new Ada.Unchecked_Deallocation + (Node_Record, Node_Record_Access); + + function Create_Node (Rec : Node_Record_Access) return Node; + -- Wrap a value record in a value. This resets its ref-count to 1. + + ----------------- + -- Create_Node -- + ----------------- + + function Create_Node (Rec : Node_Record_Access) return Node is + begin + return Result : Node do + Rec.Ref_Count := 1; + Result.Value := Rec; + end return; + end Create_Node; + + ------------- + -- Is_Null -- + ------------- + + function Is_Null (This : Node) return Boolean is + begin + return This.Value = null; + end Is_Null; + + ---------- + -- Kind -- + ---------- + + function Kind (This : Node) return Any_Node_Kind is + begin + return This.Value.Kind; + end Kind; + + ------------ + -- Equals -- + ------------ + + function Equals (Left, Right : Node) return Boolean is + begin + -- If Left and Right refer to the same document, they are obviously + -- equivalent (X is equivalent to X). If they don't have the same kind, + -- they are obviously not equivalent. + + if Left = Right then + return True; + elsif Left.Kind /= Right.Kind then + return False; + end if; + + case Left.Kind is + when Map => + declare + Left_Keys : constant Key_Array := Left.Keys; + Right_Keys : constant Key_Array := Right.Keys; + begin + if Left_Keys /= Right_Keys then + return False; + end if; + + for K of Left_Keys loop + if not Equals (Left.Get (K), Right.Get (K)) then + return False; + end if; + end loop;" +procedure Comp_Stats_Unit_test is,"Values: CompStats_Statistics.Values_Array(1..20); + Values2 : CompStats_Statistics.Values_Array(1..10); + + + procedure Test_Get_Count (Values : CompStats_Statistics.Values_Array) is + + Result : INTEGER; + + begin + Put(""Get_Count : ""); + Result := Get_Count(Values); + if Result = 20 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Count; + + + procedure Test_Get_Minimum (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Minimum : ""); + Result := Get_Minimum(Values); + if Result = -1.405158 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Minimum; + + + procedure Test_Get_Maximum (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Maximum : ""); + Result := Get_Maximum(Values); + if Result = 2.614303 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Maximum; + + + procedure Test_Get_Range (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Range : ""); + Result := Get_Range(Values); + if Result = 4.019462 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Range; + + + procedure Test_Get_Sum (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Sum : ""); + Result := Get_Sum(Values); + if Result = 4.070304 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Sum; + + + procedure Test_Get_Mean (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Mean : ""); + Result := Get_Mean (Values); + if Result = 0.2035152 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Mean; + + + procedure Test_Get_Sum_Of_Squares (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Sum_Of_Squares : ""); + Result := Get_Sum_Of_Squares (Values); + if Result = 24.19856 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Sum_Of_Squares; + + + procedure Test_Get_Population_Variance (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Population_Variance : ""); + Result := Get_Population_Variance (Values); + if Result = 1.209928 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Population_Variance; + + + procedure Test_Get_Sample_Variance (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Sample_Variance : ""); + Result := Get_Sample_Variance (Values); + if Result = 1.273608 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Sample_Variance; + + + procedure Test_Get_Population_Standard_Deviation (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Population_Standard_Deviation : ""); + Result := Get_Population_Standard_Deviation (Values); + if Result = 1.099967 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Population_Standard_Deviation; + + + procedure Test_Get_Sample_Standard_Deviation (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Sample_Standard_Deviation : ""); + Result := Get_Sample_Standard_Deviation (Values); + if Result = 1.128543 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Sample_Standard_Deviation; + + + procedure Test_Get_Standard_Error_of_Mean (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Standard_Error_of_Mean : ""); + Result := Get_Standard_Error_of_Mean (Values); + if Result = 0.2523498 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Standard_Error_of_Mean; + + + procedure Test_Get_Coefficient_Of_Variation (Values : CompStats_Statistics.Values_Array) is + + Result : FLOAT; + + begin + Put(""Get_Coefficient_Of_Variation : ""); + Result := Get_Coefficient_Of_Variation (Values); + if Result = 5.54525 then + Put(""True""); + else + Put("" False - ""); + Put(Result); + end if; + New_Line; + end Test_Get_Coefficient_Of_Variation; + + + procedure Test_Get_Unique_Values (Values : CompStats_Statistics.Values_Array) is + + begin + Put(""Get_Unique_Values : ""); + declare + Result : CompStats_Statistics.Values_Array := Get_Unique_Values (Values); + begin + for index in Integer range 1..Result'Length loop + put(Result(index)); + put("", ""); + end loop; + New_Line;" +procedure Execute is,"begin + Sub_Cmd.Parse_Global_Switches; + CLIC.TTY.Enable_Color (Force => False); + + begin + + Sub_Cmd.Execute; + exception + when Child_Failed | Command_Failed | Wrong_Command_Arguments => + GNAT.OS_Lib.OS_Exit (1); + when CLIC.User_Input.User_Interrupt => + GNAT.OS_Lib.OS_Exit (1);" +function Only_Objects is new Classes.Generic_Filter (Only_Object);,"function Is_Not_A_Token (P : Classes.Property) return Boolean is + (not Is_Token (P.Type_Name)); + + function Skip_Tokens is new Classes.Generic_Filter (Is_Not_A_Token); + + function Is_A_Token (P : Classes.Property) return Boolean is + (Is_Token (P.Type_Name)); + + function Is_Not_A_Text (P : Classes.Property) return Boolean is + (not Is_Text (P.Type_Name)); + + function Skip_Texts is new Classes.Generic_Filter (Is_Not_A_Text); + + function Only_Tokens is new Classes.Generic_Filter (Is_A_Token); + + function Is_A_Text (P : Classes.Property) return Boolean is + (Is_Text (P.Type_Name)); + + function Only_Texts is new Classes.Generic_Filter (Is_A_Text); + + function Is_A_Boolean (P : Classes.Property) return Boolean is + (Is_Boolean (P.Type_Name)); + + function Only_Booleans is new Classes.Generic_Filter (Is_A_Boolean); + + function Is_Not_A_Boolean (P : Classes.Property) return Boolean is + (not Is_Boolean (P.Type_Name)); + + function Skip_Booleans is new Classes.Generic_Filter (Is_Not_A_Boolean); + + function Visit_Spec + (F : aliased in out Ada_Pretty.Factory; + Name : Ada_Pretty.Node_Access; + Is_Abstract : Boolean := True) + return Ada_Pretty.Node_Access; + + generic + type T is limited private; + type T_Array is array (Positive range <>) of T; + + with function Convert + (F : aliased in out Ada_Pretty.Factory; + Item : T) return Ada_Pretty.Node_Access; + F : in out Ada_Pretty.Factory; + function Generic_List_Reduce (List : T_Array) return Ada_Pretty.Node_Access; + + ----------------- + -- All_Parents -- + ----------------- + + function All_Parents + (Item : Classes.Class; + Vector : Meta.Read.Class_Vectors.Vector) return String_Array + is + procedure Collect + (Result : in out League.String_Vectors.Universal_String_Vector; + Item : Meta.Classes.Class); + + procedure Collect + (Result : in out League.String_Vectors.Universal_String_Vector; + Item : Meta.Classes.Class) is + begin + if Is_Element (Item.Name) then + return; + end if; + + if Result.Index (Item.Name) = 0 then + Result.Append (Item.Name); + + for J in 1 .. Item.Parents.Length loop + declare + Parent : constant League.Strings.Universal_String := + Item.Parents.Element (J); + begin + for Next of Vector loop + if Next.Name = Parent then + Collect (Result, Next); + exit; + end if; + end loop;" +function Generic_List_Reduce,"(List : T_Array) return Ada_Pretty.Node_Access + is + Result : Ada_Pretty.Node_Access; + begin + for Item of List loop + Result := F.New_List (Result, Convert (F, Item)); + end loop; + + return Result; + end Generic_List_Reduce; + + Map : constant array (Boolean) of Ada_Pretty.Trilean := + (False => Ada_Pretty.False, True => Ada_Pretty.True); + + ---------------------- + -- Full_Record_Name -- + ---------------------- + + function Full_Record_Name + (Type_Name : League.Strings.Universal_String) + return League.Strings.Universal_String + is + Result : League.Strings.Universal_String := Get_Package_Name (Type_Name); + begin + if not Result.Is_Empty then + Result.Append ("".""); + end if; + + Result.Append (To_Element_Name (Type_Name)); + return Result; + end Full_Record_Name; + + ---------------------- + -- Full_Vector_Name -- + ---------------------- + + function Full_Vector_Name + (Type_Name : League.Strings.Universal_String) + return League.Strings.Universal_String + is + Result : League.Strings.Universal_String; + begin + if Is_Element (Type_Name) then + Result := Full_Record_Name (Element_Vector); + else + Result := Get_Package_Name (Type_Name); + Result.Append ("".""); + Result.Append (To_Element_Name (Type_Name)); + Result.Append (""_Vector""); + end if; + + return Result; + end Full_Vector_Name; + + ---------------------- + -- Full_Access_Name -- + ---------------------- + + function Full_Access_Name + (Type_Name : League.Strings.Universal_String) + return League.Strings.Universal_String + is + Result : League.Strings.Universal_String := Get_Package_Name (Type_Name); + begin + Result.Append ("".""); + Result.Append (Type_Name); + Result.Append (""_Access""); + return Result; + end Full_Access_Name; + + ---------------------- + -- Get_Parent_Props -- + ---------------------- + + function Get_Parent_Props + (Item : Classes.Class; + Vector : Meta.Read.Class_Vectors.Vector) + return Classes.Property_Array + is + Parent : constant League.Strings.Universal_String := + Item.Parents.Element (1); + begin + if Is_Element (Parent) then + return (1 .. 0 => <>); + end if; + + for Next of Vector loop + if Next.Name = Parent then + return Next.Properties; + end if; + end loop; + + raise Program_Error; + end Get_Parent_Props; + + ------------------- + -- Prop_Argument -- + ------------------- + + function Prop_Argument + (F : aliased in out Ada_Pretty.Factory; + Prop : Classes.Property) return Ada_Pretty.Node_Access + is + Name : constant Ada_Pretty.Node_Access := F.New_Name (Prop.Name); + begin + return F.New_Component_Association + (Choices => Name, + Value => Name); + end Prop_Argument; + + -------------------- + -- Prop_Parameter -- + -------------------- + + function Prop_Parameter + (F : aliased in out Ada_Pretty.Factory; + Prop : Classes.Property) return Ada_Pretty.Node_Access is + begin + if Is_Boolean (Prop.Type_Name) then + return F.New_Parameter + (Name => F.New_Name (Prop.Name), + Type_Definition => Property_Type (F, Prop), + Initialization => F.New_Name (+""False"")); + else + return F.New_Parameter + (Name => F.New_Name (Prop.Name), + Type_Definition => Property_Type (F, Prop)); + end if; + end Prop_Parameter; + + function Prop_Check_Spec + (F : aliased in out Ada_Pretty.Factory; + Name : League.Strings.Universal_String; + Base_Name : Ada_Pretty.Node_Access) return Ada_Pretty.Node_Access is + begin + return F.New_Subprogram_Specification + (Is_Overriding => Ada_Pretty.True, + Name => F.New_Name (""Is_"" & Name & ""_Element""), + Parameters => F.New_Parameter + (Name => F.New_Name (+""Self""), + Type_Definition => Base_Name), + Result => F.New_Name (+""Boolean"")); + end Prop_Check_Spec; + + + ------------------- + -- Property_Type -- + ------------------- + + function Property_Type + (F : aliased in out Ada_Pretty.Factory; + P : Meta.Classes.Property) return Ada_Pretty.Node_Access + is + use all type Meta.Classes.Capacity_Kind; + + R_Type : Ada_Pretty.Node_Access; + begin + if Is_Boolean (P.Type_Name) or Is_Text (P.Type_Name) then + R_Type := F.New_Name (P.Type_Name); + + elsif Is_Token (P.Type_Name) then + R_Type := F.New_Selected_Name (Full_Access_Name (Lexical_Element)); + + elsif P.Capacity in Just_One | Zero_Or_One then + R_Type := F.New_Selected_Name (Full_Access_Name (P.Type_Name)); + + elsif Is_Element (P.Type_Name) then + R_Type := F.New_Selected_Name + (+""Program.Element_Vectors.Element_Vector_Access""); + + else + R_Type := F.New_Selected_Name + (Full_Vector_Name (P.Type_Name) & ""_Access""); + + end if; + + if P.Capacity in Just_One | One_Or_More + and then not Is_Boolean (P.Type_Name) + and then not Is_Text (P.Type_Name) + then + R_Type := F.New_Null_Exclusion (R_Type); + end if; + + return R_Type; + end Property_Type; + + --------------- + -- Get_Props -- + --------------- + + function Get_Props + (F : aliased in out Ada_Pretty.Factory; + Name : Ada_Pretty.Node_Access; + Props : Meta.Classes.Property_Array; + Prefix : Ada_Pretty.Node_Access; + Is_Abstr : Boolean := True) return Ada_Pretty.Node_Access + is + Next : Ada_Pretty.Node_Access; + Result : Ada_Pretty.Node_Access := Prefix; + begin + for P of Props loop + Next := F.New_Subprogram_Declaration + (Specification => F.New_Subprogram_Specification + (Is_Overriding => Map (not Is_Abstr), + Name => F.New_Name (P.Name), + Parameters => F.New_Parameter + (Name => F.New_Name (+""Self""), + Type_Definition => Name), + Result => Property_Type (F, P)), + Is_Abstract => Is_Abstr); + + Result := F.New_List (Result, Next); + end loop; + + return Result; + end Get_Props; + + ---------------------- + -- Get_With_Clauses -- + ---------------------- + + function Get_With_Clauses + (F : access Ada_Pretty.Factory; + Vector : Meta.Read.Class_Vectors.Vector; + Is_Limited : Boolean; + With_Abstract : Boolean := True; + Skip : Natural := 1) return Ada_Pretty.Node_Access + is + Result : Ada_Pretty.Node_Access; + begin + for J in 1 + Skip .. Vector.Last_Index loop + declare + Item : constant Meta.Classes.Class := Vector (J); + Name : constant League.Strings.Universal_String := Item.Name; + Package_Name : constant League.Strings.Universal_String := + Get_Package_Name (Name); + Next : constant Ada_Pretty.Node_Access := + F.New_With (F.New_Name (Package_Name), Is_Limited); + begin + if With_Abstract or else not Item.Is_Abstract then + Result := F.New_List (Result, Next); + end if;" +function Visit_Spec,"(F : aliased in out Ada_Pretty.Factory; + Name : Ada_Pretty.Node_Access; + Is_Abstract : Boolean := True) + return Ada_Pretty.Node_Access + is + Visit : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Specification + (Is_Overriding => Map (not Is_Abstract), + Name => F.New_Name (+""Visit""), + Parameters => F.New_List + (F.New_Parameter + (Name => F.New_Name (+""Self""), + Type_Definition => F.New_Null_Exclusion + (F.New_Access + (Target => Name))), + F.New_Parameter + (Name => F.New_Name (+""Visitor""), + Type_Definition => F.New_Selected_Name + (Full_Record_Name (Element_Visitor) & ""'Class""), + Is_In => True, + Is_Out => True))); + begin + return Visit; + end Visit_Spec; + + -------------------- + -- Write_Elements -- + -------------------- + + procedure Write_Elements (Vector : Meta.Read.Class_Vectors.Vector) is + + F : aliased Ada_Pretty.Factory; + + function Element_Classifications return Ada_Pretty.Node_Access; + + function Element_Casts return Ada_Pretty.Node_Access; + + ------------------- + -- Element_Casts -- + ------------------- + + function Element_Casts return Ada_Pretty.Node_Access is + Result : Ada_Pretty.Node_Access; + begin + for J in 2 .. Vector.Last_Index loop + declare + Item : constant Meta.Classes.Class := Vector (J); + + Name : constant League.Strings.Universal_String := + ""To_"" & Item.Name; + + Type_Name : constant Ada_Pretty.Node_Access := + F.New_Selected_Name (Full_Access_Name (Item.Name)); + + Funct : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (F.New_Subprogram_Specification + (Name => F.New_Name (Name), + Parameters => F.New_Parameter + (Name => F.New_Name (+""Self""), + Type_Definition => F.New_Access + (Target => F.New_Name (+""Element'Class""))), + Result => Type_Name), + Aspects => F.New_Aspect + (Name => F.New_Name (+""Pre""), + Value => F.New_Name (""Self.Is_"" & Item.Name))); + begin + Result := F.New_List (Result, Funct);" +function Prop_Parameters is new Generic_List_Reduce,"(Classes.Property, Classes.Property_Array, Prop_Parameter, F); + + function Get_Params + (Item : Classes.Class) return Ada_Pretty.Node_Access; + + function Prop_List (Item : Classes.Class) return Classes.Property_Array; + + ---------------- + -- Get_Params -- + ---------------- + + function Get_Params + (Item : Classes.Class) return Ada_Pretty.Node_Access + is + List : constant Ada_Pretty.Node_Access := + Prop_Parameters (Prop_List (Item)); + Self : constant Ada_Pretty.Node_Access := F.New_Parameter + (Name => F.New_Name (+""Self""), + Type_Definition => Type_Name); + begin + if List in null then + return Self; + else + return F.New_List (Self, List); + end if; + end Get_Params; + + ------------- + -- Methods -- + ------------- + + function Methods return Ada_Pretty.Node_Access is + Result : Ada_Pretty.Node_Access; + begin + for Item of Vector loop + if not Item.Is_Abstract then + declare + Funct : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (F.New_Subprogram_Specification + (Is_Overriding => Ada_Pretty.False, + Name => F.New_Name (""Create_"" & Item.Name), + Parameters => Get_Params (Item), + Result => F.New_Null_Exclusion + (F.New_Selected_Name + (Full_Access_Name (Item.Name))))); + begin + Result := F.New_List (Result, Funct);" +function Prop_List,"(Item : Classes.Class) return Classes.Property_Array + is + use type Classes.Property_Array; + + Parent_Props : constant Classes.Property_Array := + Get_Parent_Props (Item, Vector); + + begin + if Implicit then + return Skip_Texts (Skip_Tokens (Item.Properties)) + & Only_Booleans + (Vector.First_Element.Properties & Parent_Props); + else + return Skip_Texts (Skip_Booleans (Item.Properties)) + & Only_Booleans (Parent_Props); + end if; + end Prop_List; + + Pure : constant Ada_Pretty.Node_Access := + F.New_Pragma (F.New_Name (+""Preelaborate"")); + + Public_Part : constant Ada_Pretty.Node_Access := + F.New_List ((Pure, Type_Decl, Methods)); + + Full_Type_Decl : constant Ada_Pretty.Node_Access := + F.New_Type + (Type_Name, + Discriminants => F.New_Parameter + (Name => Subpool, + Type_Definition => F.New_Null_Exclusion + (F.New_Selected_Name + (+""System.Storage_Pools.Subpools.Subpool_Handle""))), + Definition => F.New_Record + (Is_Limited => True, Is_Tagged => True)); + + Root : constant Ada_Pretty.Node_Access := + F.New_Package + (F.New_Selected_Name (Package_Name), Public_Part, Full_Type_Decl); + + With_Clauses : constant Ada_Pretty.Node_Access_Array := + (F.New_With (F.New_Selected_Name (+""System.Storage_Pools.Subpools"")), + Get_With_Clauses + (F'Access, Vector, Is_Limited => False), + F.New_With + (F.New_Selected_Name (Get_Package_Name (Lexical_Element))), + F.New_With + (F.New_Selected_Name (Get_Package_Name (Element_Vector)))); + + Unit : constant Ada_Pretty.Node_Access := + F.New_Compilation_Unit + (Root, + F.New_List (With_Clauses)); + + Output : Ada.Wide_Wide_Text_IO.File_Type; + begin + Open_File (Output, Package_Name, ""nodes/""); + + Ada.Wide_Wide_Text_IO.Put_Line + (Output, + F.To_Text (Unit).Join (Ada.Characters.Wide_Wide_Latin_1.LF) + .To_Wide_Wide_String); + + Ada.Wide_Wide_Text_IO.Close (Output); + end Write_Factories; + + -------------------------- + -- Write_Factories_Body -- + -------------------------- + + procedure Write_Factories_Body + (Vector : Meta.Read.Class_Vectors.Vector; + Implicit : Boolean := False) + is + function Methods return Ada_Pretty.Node_Access; + + Package_Name : constant League.Strings.Universal_String := + (if Implicit then +""Program.Implicit_Element_Factories"" + else +""Program.Element_Factories""); + + F : aliased Ada_Pretty.Factory; + + Type_Name : constant Ada_Pretty.Node_Access := + F.New_Name (+""Element_Factory""); + + function Prop_Parameters is new Generic_List_Reduce + (Classes.Property, Classes.Property_Array, Prop_Parameter, F); + + function Prop_Arguments is new Generic_List_Reduce + (Classes.Property, Classes.Property_Array, Prop_Argument, F); + + function Get_Params + (Item : Classes.Class) return Ada_Pretty.Node_Access; + + function Allocator_Args + (Item : Classes.Class) return Ada_Pretty.Node_Access; + + function Get_With_Clauses return Ada_Pretty.Node_Access; + function Access_Types return Ada_Pretty.Node_Access; + + function Prop_List + (Item : Classes.Class) return Classes.Property_Array; + + ------------------ + -- Access_Types -- + ------------------ + + function Access_Types return Ada_Pretty.Node_Access is + Result : Ada_Pretty.Node_Access; + begin + for Item of Vector loop + if not Item.Is_Abstract then + declare + Element_Name : constant League.Strings.Universal_String := + (if Implicit then ""Implicit_"" & Item.Name + else To_Element_Name (Item.Name)); + Def : constant Ada_Pretty.Node_Access := F.New_Access + (Target => F.New_Selected_Name + (F.New_Selected_Name (Node_Package_Name (Item.Name)), + F.New_Name (Element_Name))); + begin + Result := F.New_List + (Result, + F.New_Type + (F.New_Name (Item.Name & ""_Access""), + Definition => F.New_Null_Exclusion (Def), + Aspects => F.New_Aspect + (F.New_Name (+""Storage_Pool""), + F.New_Selected_Name + (+""Program.Storage_Pools.Pool""))));" +function Prop_List,"(Item : Classes.Class) return Classes.Property_Array + is + use type Classes.Property_Array; + + Parent_Props : constant Classes.Property_Array := + Get_Parent_Props (Item, Vector); + + begin + if Implicit then + return Skip_Texts (Skip_Tokens (Item.Properties)) + & Only_Booleans + (Vector.First_Element.Properties & Parent_Props); + else + return Skip_Texts (Skip_Booleans (Item.Properties)) + & Only_Booleans (Parent_Props); + end if; + end Prop_List; + + Root : constant Ada_Pretty.Node_Access := + F.New_Package_Body + (F.New_Selected_Name (Package_Name), + F.New_List (Access_Types, Methods)); + + Unit : constant Ada_Pretty.Node_Access := + F.New_Compilation_Unit + (Root, + Get_With_Clauses); + + Output : Ada.Wide_Wide_Text_IO.File_Type; + begin + Open_File (Output, Package_Name, ""nodes/"", Spec => False); + + Ada.Wide_Wide_Text_IO.Put_Line + (Output, + F.To_Text (Unit).Join (Ada.Characters.Wide_Wide_Latin_1.LF) + .To_Wide_Wide_String); + + Ada.Wide_Wide_Text_IO.Close (Output); + end Write_Factories_Body; + + ------------------ + -- Write_Header -- + ------------------ + + procedure Write_Header (Output : Ada.Wide_Wide_Text_IO.File_Type) is + begin + Ada.Wide_Wide_Text_IO.Put_Line + (Output, ""-- Copyright (c) 2019 Maxim Reznik ""); + + Ada.Wide_Wide_Text_IO.Put_Line (Output, ""--""); + + Ada.Wide_Wide_Text_IO.Put_Line + (Output, ""-- SPDX-License-Identifier: MIT""); + + Ada.Wide_Wide_Text_IO.Put_Line + (Output, ""-- License-Filename: LICENSE""); + + Ada.Wide_Wide_Text_IO.Put_Line + (Output, + ""-------------------------------------------------------------""); + Ada.Wide_Wide_Text_IO.New_Line (Output); + end Write_Header; + + --------------------- + -- Write_Iterators -- + --------------------- + + procedure Write_Iterators (Vector : Meta.Read.Class_Vectors.Vector) is + Package_Name : constant League.Strings.Universal_String := + +""Internal""; + + F : aliased Ada_Pretty.Factory; + + Visitor : constant Ada_Pretty.Node_Access := + F.New_Type + (Name => F.New_Name (+""Visitor""), + Definition => F.New_Record + (Parent => F.New_Selected_Name + (Full_Record_Name (Element_Visitor)), + Components => F.New_Variable + (Name => F.New_Name (+""Result""), + Type_Definition => F.New_Access + (Modifier => Access_Constant, + Target => F.New_Name (+""Getter_Array"")), + Initialization => F.New_Name (+""Empty'Access"")))); + + function Method_Bodies return Ada_Pretty.Node_Access; + + function Method_Spec + (Item : Classes.Class) return Ada_Pretty.Node_Access; + + function Child_Args + (Item : Classes.Class; + P : Classes.Property) return Ada_Pretty.Node_Access; + + function Vector_Args + (Item : Classes.Class; + P : Classes.Property) return Ada_Pretty.Node_Access; + + function Get_Inst + (Item : Classes.Class; + P : Classes.Property; + Index : Positive) return Ada_Pretty.Node_Access; + + function Is_Vector (P : Classes.Property) return Boolean is + (P.Capacity in Classes.Zero_Or_More | Classes.One_Or_More); + + function Get_Name (Index : Natural) return Wide_Wide_String; + + Count : Positive := 1; + + function Get_Name (Index : Natural) return Wide_Wide_String is + Count_Image : constant Wide_Wide_String := + Integer'Wide_Wide_Image (Count); + Index_Image : constant Wide_Wide_String := + Integer'Wide_Wide_Image (Index); + + Name : constant Wide_Wide_String := + ""F"" & Count_Image (2 .. Count_Image'Last); + + begin + if Index = 0 then + return Name; + else + return Name & ""_"" & Index_Image (2 .. Index_Image'Last); + end if; + end Get_Name; + + ---------------- + -- Child_Args -- + ---------------- + + function Child_Args + (Item : Classes.Class; + P : Classes.Property) return Ada_Pretty.Node_Access + is + Args : constant Ada_Pretty.Node_Access_Array := + (F.New_Argument_Association + (Choice => F.New_Name (+""Element""), + Value => F.New_Selected_Name + (Full_Record_Name (Item.Name)) + ), + F.New_Argument_Association + (Choice => F.New_Name (+""Child""), + Value => F.New_Selected_Name + (Full_Record_Name (P.Type_Name)) + ), + F.New_Argument_Association + (Choice => F.New_Name (+""Child_Access""), + Value => F.New_Selected_Name (Full_Access_Name (P.Type_Name)) + ), + F.New_Argument_Association + (Choice => F.New_Name (+""Get_Child""), + Value => F.New_Selected_Name + (Get_Package_Name (Item.Name) & ""."" & P.Name) + ) + ); + begin + return F.New_List (Args); + end Child_Args; + + ----------------- + -- Vector_Args -- + ----------------- + + function Vector_Args + (Item : Classes.Class; + P : Classes.Property) return Ada_Pretty.Node_Access + is + Args : constant Ada_Pretty.Node_Access_Array := + (F.New_Argument_Association + (Choice => F.New_Name (+""Parent""), + Value => F.New_Selected_Name + (Full_Record_Name (Item.Name)) + ), + F.New_Argument_Association + (Choice => F.New_Name (+""Vector""), + Value => F.New_Selected_Name + (Full_Vector_Name (P.Type_Name)) + ), + F.New_Argument_Association + (Choice => F.New_Name (+""Vector_Access""), + Value => F.New_Selected_Name + (Full_Vector_Name (P.Type_Name) & ""_Access"") + ), + F.New_Argument_Association + (Choice => F.New_Name (+""Get_Vector""), + Value => F.New_Selected_Name + (Get_Package_Name (Item.Name) & ""."" & P.Name) + ) + ); + begin + return F.New_List (Args); + end Vector_Args; + + -------------- + -- Get_Inst -- + -------------- + + function Get_Inst + (Item : Classes.Class; + P : Classes.Property; + Index : Positive) return Ada_Pretty.Node_Access + is + Template : constant Wide_Wide_String := + (if Is_Vector (P) + then ""Vector"" + else ""Child""); + + Result : constant Ada_Pretty.Node_Access := + (F.New_Apply + (Prefix => F.New_Name + (+""function "" & Get_Name (Index) & + "" is new Generic_"" & Template), + Arguments => + (if Is_Vector (P) then Vector_Args (Item, P) + else Child_Args (Item, P)))); + begin + return Result; + end Get_Inst; + + ----------------- + -- Method_Spec -- + ----------------- + + function Method_Spec + (Item : Classes.Class) return Ada_Pretty.Node_Access + is + Element_Name : constant League.Strings.Universal_String := + To_Element_Name (Item.Name); + + Funct : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Specification + (Is_Overriding => Ada_Pretty.True, + Name => F.New_Name (Element_Name), + Parameters => F.New_List + (F.New_Parameter + (Name => F.New_Name (+""Self""), + Is_In => True, + Is_Out => True, + Type_Definition => F.New_Name (+""Visitor"")), + F.New_Parameter + (Name => F.New_Name (Element), + Type_Definition => F.New_Null_Exclusion + (F.New_Selected_Name + (Full_Access_Name (Item.Name)))))); + begin + return Funct; + end Method_Spec; + + ------------------- + -- Method_Bodies -- + ------------------- + + function Method_Bodies return Ada_Pretty.Node_Access is + Result : Ada_Pretty.Node_Access; + Bodies : Ada_Pretty.Node_Access; + Map : constant array (Boolean) of Ada_Pretty.Node_Access := + (False => F.New_Name (+""False""), + True => F.New_Name (+""True"")); + begin + for Item of Vector loop + if not Item.Is_Abstract then + declare + Props : constant Meta.Classes.Property_Array := + Only_Objects (Item.Properties); + + Funct : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Body + (Specification => Method_Spec (Item), + Declarations => F.New_Pragma + (Name => F.New_Name (+""Unreferenced""), + Arguments => F.New_Name (+""Element"")), + Statements => F.New_Assignment + (Left => F.New_Selected_Name (+""Self.Result""), + Right => F.New_Name (+Get_Name (0) & ""'Access""))); + + Index : Positive := 1; + + List : Ada_Pretty.Node_Access; + begin + for P of Props loop + declare + Inst : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (Get_Inst (Item, P, Index)); + Data : constant Ada_Pretty.Node_Access_Array := + (Map (Is_Vector (P)), + F.New_Name (P.Name), + F.New_Name (+Get_Name (Index) & ""'Access"")); + begin + Bodies := F.New_List (Bodies, Inst); + + List := F.New_List + (List, F.New_Component_Association + (Choices => F.New_Literal (Index), + Value => F.New_Parentheses + (F.New_List (Data)) + )); + + Index := Index + 1;" +function Prop_Parameters is new Generic_List_Reduce,"(Classes.Property, Classes.Property_Array, Prop_Parameter, F); + + function Prop_Check + (F : aliased in out Ada_Pretty.Factory; + Name : League.Strings.Universal_String) return Ada_Pretty.Node_Access; + + function Prop_Checks is new Generic_List_Reduce + (League.Strings.Universal_String, String_Array, Prop_Check, F); + + ------------------- + -- Prop_Variable -- + ------------------- + + function Prop_Variable + (F : aliased in out Ada_Pretty.Factory; + Prop : Classes.Property) return Ada_Pretty.Node_Access + is + begin + return F.New_Variable + (Name => F.New_Name (Prop.Name), + Type_Definition => Property_Type (F, Prop)); + end Prop_Variable; + + function Prop_Variables is new Generic_List_Reduce + (Classes.Property, Classes.Property_Array, Prop_Variable, F); + + Text_Name : constant League.Strings.Universal_String := + Get_Package_Name (Item.Name) & ""."" & Item.Name & ""_Text""; + + Elem : constant Classes.Class := Vector.First_Element; + + Bool_Props : constant Classes.Property_Array := + Only_Booleans (Elem.Properties & Item.Properties); + + Parent_Props : constant Classes.Property_Array := + Get_Parent_Props (Item, Vector); + + Bool_Vars : constant Ada_Pretty.Node_Access := + Prop_Variables (Bool_Props); + + Package_Name : constant League.Strings.Universal_String := + Node_Package_Name (Item.Name); + + Element_Package_Name : constant League.Strings.Universal_String := + Get_Package_Name (Item.Name); + + Pure : constant Ada_Pretty.Node_Access := + F.New_Pragma (F.New_Name (+""Preelaborate"")); + + Base_Name : constant Ada_Pretty.Node_Access := + F.New_Name (""Base_"" & Item.Name); + + ---------------- + -- Prop_Check -- + ---------------- + + function Prop_Check + (F : aliased in out Ada_Pretty.Factory; + Name : League.Strings.Universal_String) return Ada_Pretty.Node_Access + is + begin + return F.New_Subprogram_Declaration + (Specification => Prop_Check_Spec (F, Name, Base_Name)); + end Prop_Check; + + Base_Props : constant Ada_Pretty.Node_Access := Prop_Variables + (Only_Objects (Item.Properties) & Only_Booleans (Parent_Props)); + + Base : constant Ada_Pretty.Node_Access := + F.New_Type + (Name => Base_Name, + Definition => F.New_Record + (Parent => F.New_List + (F.New_Selected_Name (+""Program.Nodes.Node""), + F.New_Infix + (Operator => +""and"", + Left => F.New_Selected_Name + (Full_Record_Name (Item.Name)))), + Components => Base_Props, + Is_Abstract => True)); + + Base_Init : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (Specification => F.New_Subprogram_Specification + (Name => F.New_Name (+""Initialize""), + Parameters => F.New_Parameter + (Name => F.New_Name (+""Self""), + Type_Definition => F.New_Name + (""Base_"" & Item.Name & ""'Class""), + Is_Aliased => True, + Is_In => True, + Is_Out => True))); + + Visit : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (Visit_Spec (F, Base_Name, False)); + + Base_List : constant Ada_Pretty.Node_Access := F.New_List + (Get_Props + (F, + Base_Name, + Only_Objects (Item.Properties) & Only_Booleans (Parent_Props), + F.New_List ((Base, Base_Init, Visit)), + Is_Abstr => False), + Prop_Checks (All_Parents (Item, Vector))); + + Node_Name : constant Ada_Pretty.Node_Access := + F.New_Name (To_Element_Name (Item.Name)); + + Node_Props : constant Ada_Pretty.Node_Access := + Prop_Variables (Only_Tokens (Item.Properties)); + + Node : constant Ada_Pretty.Node_Access := + F.New_Type + (Name => Node_Name, + Definition => F.New_Record + (Parent => F.New_List + (Base_Name, + F.New_Infix (+""and"", + F.New_Selected_Name (Text_Name))), + Components => Node_Props)); + + Public_Node : constant Ada_Pretty.Node_Access := + F.New_Type + (Name => Node_Name, + Definition => F.New_Private_Record + (Parents => F.New_List + ((F.New_Selected_Name (+""Program.Nodes.Node""), + F.New_Infix + (+""and"", + F.New_Selected_Name (Full_Record_Name (Item.Name))), + F.New_Infix (+""and"", + F.New_Selected_Name (Text_Name)))))); + + Create_Node : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (Specification => F.New_Subprogram_Specification + (Name => F.New_Name (+""Create""), + Parameters => Prop_Parameters + (Skip_Texts (Skip_Booleans (Item.Properties & Parent_Props)) + & Only_Booleans (Parent_Props)), + Result => Node_Name)); + + Node_To_Text : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (Specification => To_Text_Spec (F, Item, Node_Name)); + + Node_List : constant Ada_Pretty.Node_Access := + Get_Props + (F, + Name => Node_Name, + Props => Only_Tokens (Item.Properties) + & Only_Booleans (Item.Properties) + & Only_Texts (Item.Properties & Parent_Props), + Prefix => F.New_List (Node, Node_To_Text), + Is_Abstr => False); + + Implicit_Name : constant Ada_Pretty.Node_Access := + F.New_Name (""Implicit_"" & Item.Name); + + Implicit_Getters : constant Ada_Pretty.Node_Access := + Get_Props + (F, + Name => Implicit_Name, + Props => Bool_Props + & Only_Texts (Item.Properties & Parent_Props), + Prefix => null, + Is_Abstr => False); + + Implicit : constant Ada_Pretty.Node_Access := + F.New_Type + (Name => Implicit_Name, + Definition => F.New_Record + (Parent => Base_Name, + Components => Bool_Vars)); + + Implicit_To_Text : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (Specification => To_Text_Spec (F, Item, Implicit_Name)); + + Implicit_List : constant Ada_Pretty.Node_Access := + F.New_List ((Implicit, Implicit_To_Text, Implicit_Getters)); + + Public_Implicit : constant Ada_Pretty.Node_Access := + F.New_Type + (Name => Implicit_Name, + Definition => F.New_Private_Record + (Parents => F.New_List + (F.New_Selected_Name (+""Program.Nodes.Node""), + F.New_Infix + (+""and"", + F.New_Selected_Name (Full_Record_Name (Item.Name)))))); + + Aspec_List : constant Ada_Pretty.Node_Access_Array := + (F.New_Name (+""Is_Part_Of_Implicit""), + F.New_Infix (+""or"", F.New_Name (+""Is_Part_Of_Inherited"")), + F.New_Infix (+""or"", F.New_Name (+""Is_Part_Of_Instance""))); + + Create_Implicit : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (Specification => F.New_Subprogram_Specification + (Name => F.New_Name (+""Create""), + Parameters => Prop_Parameters + (Only_Objects (Item.Properties & Parent_Props) & + Bool_Props & Only_Booleans (Parent_Props)), + Result => Implicit_Name), + Aspects => F.New_Aspect + (Name => F.New_Name (+""Pre""), + Value => F.New_List (Aspec_List))); + + Public_Part : constant Ada_Pretty.Node_Access := F.New_List + ((Pure, Public_Node, Create_Node, Public_Implicit, Create_Implicit)); + + Private_Part : constant Ada_Pretty.Node_Access := + F.New_List ((Base_List, Node_List, Implicit_List)); + + Root : constant Ada_Pretty.Node_Access := + F.New_Package + (F.New_Selected_Name (Package_Name), Public_Part, Private_Part); + + With_Clauses_1 : constant Ada_Pretty.Node_Access := + Get_With_Clauses + (F'Access, Item, + With_List => False, + With_Parent => False); + + With_Clauses_2 : constant not null Ada_Pretty.Node_Access := + F.New_With (F.New_Selected_Name (Element_Package_Name)); + + With_Clauses_3 : constant not null Ada_Pretty.Node_Access := + F.New_With (F.New_Selected_Name (Get_Package_Name (Element_Visitor))); + + With_Clauses : constant Ada_Pretty.Node_Access := + F.New_List + (F.New_List (With_Clauses_1, With_Clauses_2), With_Clauses_3); + + Unit : constant Ada_Pretty.Node_Access := + F.New_Compilation_Unit (Root, With_Clauses); + + Output : Ada.Wide_Wide_Text_IO.File_Type; + begin + Open_File (Output, Package_Name, ""nodes/""); + + Ada.Wide_Wide_Text_IO.Put_Line + (Output, + F.To_Text (Unit).Join (Ada.Characters.Wide_Wide_Latin_1.LF) + .To_Wide_Wide_String); + + Ada.Wide_Wide_Text_IO.Close (Output); + end Write_One_Node; + + ------------------------- + -- Write_One_Node_Body -- + ------------------------- + + procedure Write_One_Node_Body + (Vector : Meta.Read.Class_Vectors.Vector; + Item : Meta.Classes.Class) + is + + use type Classes.Property_Array; + + F : aliased Ada_Pretty.Factory; + + function Prop_Parameters is new Generic_List_Reduce + (Classes.Property, Classes.Property_Array, Prop_Parameter, F); + + function Prop_Arguments is new Generic_List_Reduce + (Classes.Property, Classes.Property_Array, Prop_Argument, F); + + function Prop_Set_Enclosing + (F : aliased in out Ada_Pretty.Factory; + Prop : Classes.Property) return Ada_Pretty.Node_Access; + + function Prop_Check + (F : aliased in out Ada_Pretty.Factory; + Name : League.Strings.Universal_String) return Ada_Pretty.Node_Access; + + function Prop_Checks is new Generic_List_Reduce + (League.Strings.Universal_String, String_Array, Prop_Check, F); + + generic + Type_Name : Ada_Pretty.Node_Access; + Is_Node : Boolean; + function Prop_Getter + (F : aliased in out Ada_Pretty.Factory; + Prop : Classes.Property) return Ada_Pretty.Node_Access; + + Unreferenced : constant Ada_Pretty.Node_Access := F.New_Pragma + (Name => F.New_Name (+""Unreferenced""), + Arguments => F.New_Name (+""Self"")); + + ----------------- + -- Prop_Getter -- + ----------------- + + function Prop_Getter + (F : aliased in out Ada_Pretty.Factory; + Prop : Classes.Property) return Ada_Pretty.Node_Access + is + Pragmas : Ada_Pretty.Node_Access; + Return_Expr : Ada_Pretty.Node_Access; + Token : League.Strings.Universal_String; + begin + if Is_Node and then Prop.Name.Starts_With (""Has_"") then + if Prop.Name.Starts_With (""Has_Not_Null"") then + Token := Prop.Name.Tail_From (9); -- Null or Null_2 + else + Token := Prop.Name.Tail_From (5); + end if; + + Return_Expr := F.New_Selected_Name + (""Self."" & Token & ""_Token.Assigned""); + elsif Is_Text (Prop.Type_Name) then + if Is_Node then + Return_Expr := F.New_Selected_Name + (""Self."" & Only_Tokens (Item.Properties) (1).Name & "".Image""); + else + Return_Expr := F.New_Name (+""""""""""""); + Pragmas := Unreferenced; + end if; + else + Return_Expr := F.New_Selected_Name (""Self."" & Prop.Name); + end if; + + return F.New_Subprogram_Body + (Specification => F.New_Subprogram_Specification + (Is_Overriding => Ada_Pretty.True, + Name => F.New_Name (Prop.Name), + Parameters => F.New_Parameter + (Name => F.New_Name (+""Self""), + Type_Definition => Type_Name), + Result => Property_Type (F, Prop)), + Declarations => Pragmas, + Statements => F.New_Return (Return_Expr)); + end Prop_Getter; + + Set_Enclosing_Element : constant Ada_Pretty.Node_Access := + F.New_Name (+""Set_Enclosing_Element""); + + ------------------------ + -- Prop_Set_Enclosing -- + ------------------------ + + function Prop_Set_Enclosing + (F : aliased in out Ada_Pretty.Factory; + Prop : Classes.Property) return Ada_Pretty.Node_Access + is + Result : Ada_Pretty.Node_Access; + + Attr : constant Ada_Pretty.Node_Access := + F.New_Argument_Association + (Value => F.New_Name (+""Self."" & Prop.Name)); + + Self : constant Ada_Pretty.Node_Access := + F.New_Argument_Association + (Value => F.New_Name (+""Self'Unchecked_Access"")); + + Item : constant Ada_Pretty.Node_Access := + F.New_Argument_Association + (Value => F.New_Selected_Name (+""Item.Element"")); + + begin + case Prop.Capacity is + when Meta.Classes.Just_One => + Result := F.New_Statement + (F.New_Apply + (Set_Enclosing_Element, F.New_List (Attr, Self))); + + when Meta.Classes.Zero_Or_One => + Result := F.New_If + (Condition => F.New_Selected_Name + (Prefix => Attr, + Selector => F.New_Name (+""Assigned"")), + Then_Path => F.New_Statement + (F.New_Apply + (Set_Enclosing_Element, F.New_List (Attr, Self)))); + + when others => + Result := F.New_For + (Name => F.New_Name (+""Item""), + Iterator => F.New_Selected_Name + (Prefix => Attr, + Selector => F.New_Name (+""Each_Element"")), + Statements => F.New_Statement + (F.New_Apply + (Set_Enclosing_Element, + F.New_List (Item, Self)))); + end case; + + return Result; + end Prop_Set_Enclosing; + + function Prop_Set_Enclosings is new Generic_List_Reduce + (Classes.Property, Classes.Property_Array, Prop_Set_Enclosing, F); + + Base_Name : constant Ada_Pretty.Node_Access := + F.New_Name (""Base_"" & Item.Name); + + function Base_Getter is new Prop_Getter (Base_Name, False); + + ---------------- + -- Prop_Check -- + ---------------- + + function Prop_Check + (F : aliased in out Ada_Pretty.Factory; + Name : League.Strings.Universal_String) return Ada_Pretty.Node_Access + is + begin + return F.New_Subprogram_Body + (Specification => Prop_Check_Spec (F, Name, Base_Name), + Declarations => Unreferenced, + Statements => F.New_Return (F.New_Name (+""True""))); + end Prop_Check; + + Package_Name : constant League.Strings.Universal_String := + Node_Package_Name (Item.Name); + + Node_Name : constant Ada_Pretty.Node_Access := + F.New_Name (To_Element_Name (Item.Name)); + + function Node_Getter is new Prop_Getter (Node_Name, True); + + Implicit_Name : constant Ada_Pretty.Node_Access := + F.New_Name (""Implicit_"" & Item.Name); + + function Impl_Getter is new Prop_Getter (Implicit_Name, False); + + Elem : constant Classes.Class := Vector.First_Element; + + Bool_Props : constant Classes.Property_Array := + Only_Booleans (Elem.Properties & Item.Properties); + + Parent_Props : constant Classes.Property_Array := + Get_Parent_Props (Item, Vector); + + Result : constant Ada_Pretty.Node_Access := F.New_Name (+""Result""); + + Initialize : constant Ada_Pretty.Node_Access := + F.New_Name (+""Initialize""); + + Create_Node : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Body + (Specification => F.New_Subprogram_Specification + (Name => F.New_Name (+""Create""), + Parameters => Prop_Parameters + (Skip_Texts (Skip_Booleans (Item.Properties & Parent_Props)) + & Only_Booleans (Parent_Props)), + Result => Node_Name), + Statements => F.New_Extended_Return + (Name => Result, + Type_Definition => Node_Name, + Initialization => F.New_Parentheses + (F.New_List + (Prop_Arguments + (Skip_Texts (Skip_Booleans + (Item.Properties & Parent_Props)) + & Only_Booleans (Parent_Props)), + F.New_Component_Association + (Choices => F.New_Name (+""Enclosing_Element""), + Value => F.New_Name (+""null"")))), + Statements => F.New_Statement + (F.New_Apply + (Prefix => Initialize, + Arguments => Result)))); + + Create_Implicit : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Body + (Specification => F.New_Subprogram_Specification + (Name => F.New_Name (+""Create""), + Parameters => Prop_Parameters + (Only_Objects (Item.Properties & Parent_Props) & + Bool_Props & Only_Booleans (Parent_Props)), + Result => Implicit_Name), + Statements => F.New_Extended_Return + (Name => Result, + Type_Definition => Implicit_Name, + Initialization => F.New_Parentheses + (F.New_List + (Prop_Arguments + (Only_Objects (Item.Properties & Parent_Props) & + Bool_Props & Only_Booleans (Parent_Props)), + F.New_Component_Association + (Choices => F.New_Name (+""Enclosing_Element""), + Value => F.New_Name (+""null"")))), + Statements => F.New_Statement + (F.New_Apply + (Prefix => Initialize, + Arguments => Result)))); + + Base_Init : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Body + (Specification => F.New_Subprogram_Specification + (Name => F.New_Name (+""Initialize""), + Parameters => F.New_Parameter + (Name => F.New_Name (+""Self""), + Type_Definition => F.New_Name + (""Base_"" & Item.Name & ""'Class""), + Is_Aliased => True, + Is_In => True, + Is_Out => True)), + Statements => F.New_List + (Prop_Set_Enclosings (Only_Objects (Item.Properties)), + F.New_Statement)); + + function Base_Getters is new Generic_List_Reduce + (Classes.Property, Classes.Property_Array, Base_Getter, F); + + BG : constant Ada_Pretty.Node_Access := Base_Getters + (Only_Objects (Item.Properties) & Only_Booleans (Parent_Props)); + + function Node_Getters is new Generic_List_Reduce + (Classes.Property, Classes.Property_Array, Node_Getter, F); + + NG : constant Ada_Pretty.Node_Access := Node_Getters + (Only_Tokens (Item.Properties) + & Only_Booleans (Item.Properties) + & Only_Texts (Item.Properties & Parent_Props)); + + function Impl_Getters is new Generic_List_Reduce + (Classes.Property, Classes.Property_Array, Impl_Getter, F); + + IG : constant Ada_Pretty.Node_Access := Impl_Getters + (Bool_Props & Only_Texts (Item.Properties & Parent_Props)); + + Visit : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Body + (Visit_Spec (F, Base_Name, False), + Statements => F.New_Statement + (F.New_Apply + (F.New_Selected_Name (F.New_Name (+""Visitor""), Node_Name), + F.New_Name (+""Self"")))); + + Node_To_Text : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Body + (Specification => To_Text_Spec (F, Item, Node_Name), + Statements => F.New_Return + (F.New_Name (+""Self'Unchecked_Access""))); + + Implicit_To_Text : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Body + (Specification => To_Text_Spec (F, Item, Implicit_Name), + Declarations => Unreferenced, + Statements => F.New_Return + (F.New_Name (+""null""))); + + List : constant Ada_Pretty.Node_Access_Array := + (Create_Node, Create_Implicit, + F.New_List (BG, + F.New_List (NG, + F.New_List (IG, Base_Init))), + Prop_Checks (All_Parents (Item, Vector)), + Visit, + Node_To_Text, + Implicit_To_Text); + + Root : constant Ada_Pretty.Node_Access := + F.New_Package_Body + (F.New_Selected_Name (Package_Name), F.New_List (List)); + + Unit : constant Ada_Pretty.Node_Access := + F.New_Compilation_Unit (Root); + + Output : Ada.Wide_Wide_Text_IO.File_Type; + begin + Open_File (Output, Package_Name, ""nodes/"", Spec => False); + + Ada.Wide_Wide_Text_IO.Put_Line + (Output, + F.To_Text (Unit).Join (Ada.Characters.Wide_Wide_Latin_1.LF) + .To_Wide_Wide_String); + + Ada.Wide_Wide_Text_IO.Close (Output); + end Write_One_Node_Body; + + -------------------- + -- Write_Visitors -- + -------------------- + + procedure Write_Visitors (Vector : Meta.Read.Class_Vectors.Vector) is + + function Methods return Ada_Pretty.Node_Access; + + Package_Name : constant League.Strings.Universal_String := + Get_Package_Name (Element_Visitor); + + F : aliased Ada_Pretty.Factory; + + Pure : constant Ada_Pretty.Node_Access := + F.New_Pragma + (F.New_Name (+""Pure""), F.New_Selected_Name (Package_Name)); + + Type_Name : constant Ada_Pretty.Node_Access := + F.New_Name (Element_Visitor); + + Type_Decl : constant Ada_Pretty.Node_Access := + F.New_Type + (Type_Name, + Definition => F.New_Interface + (Is_Limited => True)); + + function Methods return Ada_Pretty.Node_Access is + Result : Ada_Pretty.Node_Access; + begin + for Item of Vector loop + if not Item.Is_Abstract then + declare + Element_Name : constant League.Strings.Universal_String := + To_Element_Name (Item.Name); + + Funct : constant Ada_Pretty.Node_Access := + F.New_Subprogram_Declaration + (F.New_Subprogram_Specification + (Name => F.New_Name (Element_Name), + Parameters => F.New_List + (F.New_Parameter + (Name => F.New_Name (+""Self""), + Is_In => True, + Is_Out => True, + Type_Definition => F.New_Name + (Element_Visitor)), + F.New_Parameter + (Name => F.New_Name (Element), + Type_Definition => F.New_Null_Exclusion + (F.New_Selected_Name + (Full_Access_Name (Item.Name)))))), + Is_Null => True); + begin + Result := F.New_List (Result, Funct);" +procedure Ada_LARL is,"use type Anagram.Grammars.Rule_Count; + use type Anagram.Grammars.LR.State_Count; + + procedure Put_Proc_Decl + (Output : in out Writer; + Suffix : Wide_Wide_String); + + procedure Put_Piece + (Piece : in out Writer; + From : Anagram.Grammars.Production_Index; + To : Anagram.Grammars.Production_Index); + + procedure Put_Rule + (Output : in out Writer; + Prod : Anagram.Grammars.Production; + Rule : Anagram.Grammars.Rule); + + function Image (X : Integer) return Wide_Wide_String; + + procedure Print_Go_To; + procedure Print_Action; + + File : constant String := Ada.Command_Line.Argument (1); + G : constant Anagram.Grammars.Grammar := + Anagram.Grammars.Reader.Read (File); + Plain : constant Anagram.Grammars.Grammar := + Anagram.Grammars_Convertors.Convert (G, Left => False); + AG : constant Anagram.Grammars.Grammar := + Anagram.Grammars.Constructors.To_Augmented (Plain); + Table : constant Anagram.Grammars.LR_Tables.Table_Access := + Anagram.Grammars.LR.LALR.Build + (Input => AG, + Right_Nulled => False); + Resolver : Anagram.Grammars.Conflicts.Resolver; + Output : Writer; + + ----------- + -- Image -- + ----------- + + function Image (X : Integer) return Wide_Wide_String is + Img : constant Wide_Wide_String := Integer'Wide_Wide_Image (X); + begin + return Img (2 .. Img'Last); + end Image; + + ------------------ + -- Print_Action -- + ------------------ + + procedure Print_Action is + use type Anagram.Grammars.Production_Count; + use type Anagram.Grammars.Part_Count; + type Action_Code is mod 2 ** 16; + + Count : Natural; + Code : Action_Code; + begin + Output.P ("" type Action_Code is mod 2 ** 16;""); + Output.P ("" for Action_Code'Size use 16;""); + Output.P; + Output.P ("" Action_Table : constant array""); + Output.N ("" (State_Index range 1 .. ""); + Output.N (Natural (Anagram.Grammars.LR_Tables.Last_State (Table.all))); + Output.P ("",""); + Output.N ("" Anagram.Grammars.Terminal_Count range 0 .. ""); + Output.N (Natural (Plain.Last_Terminal)); + Output.P ("") of Action_Code :=""); + + for State in 1 .. Anagram.Grammars.LR_Tables.Last_State (Table.all) loop + if State = 1 then + Output.N ("" (""); + else + Output.P ("",""); + Output.N ("" ""); + end if; + Output.N (Natural (State)); + Output.P ("" =>""); + Output.N ("" (""); + Count := 0; + + for T in 0 .. Plain.Last_Terminal loop + declare + use Anagram.Grammars.LR_Tables; + S : constant Anagram.Grammars.LR.State_Count := + Shift (Table.all, State, T); + R : constant Reduce_Iterator := Reduce (Table.all, State, T); + begin + if S /= 0 then + Code := Action_Code (S) + 16#80_00#; + elsif not Is_Empty (R) then + Code := Action_Code (Production (R)); + else + Code := 0; + end if; + + if Code /= 0 then + Output.N (Natural (T)); + Output.N ("" => ""); + Output.N (Natural (Code)); + Count := Count + 1; + if Count < 4 then + Output.N ("", ""); + else + Count := 0; + Output.P ("",""); + Output.N ("" ""); + end if; + end if;" +procedure Print_Go_To is,"Count : Natural; + begin + Output.P ("" Go_To_Table : constant array""); + Output.N ("" (Anagram.Grammars.LR_Parsers.State_Index range 1 .. ""); + Output.N (Natural (Anagram.Grammars.LR_Tables.Last_State (Table.all))); + Output.P ("",""); + Output.N ("" Anagram.Grammars.Non_Terminal_Index range 1 .. ""); + Output.N (Natural (Plain.Last_Non_Terminal)); + Output.P ("") of State_Index :=""); + + for State in 1 .. Anagram.Grammars.LR_Tables.Last_State (Table.all) loop + if State = 1 then + Output.N ("" (""); + else + Output.P ("",""); + Output.N ("" ""); + end if; + Output.N (Natural (State)); + Output.P ("" =>""); + Output.N ("" (""); + Count := 0; + + for NT in 1 .. Plain.Last_Non_Terminal loop + declare + use Anagram.Grammars.LR; + Next : constant State_Count := + Anagram.Grammars.LR_Tables.Shift (Table.all, State, NT); + begin + if Next /= 0 then + Output.N (Natural (NT)); + Output.N ("" => ""); + Output.N (Natural (Next)); + Count := Count + 1; + if Count < 4 then + Output.N ("", ""); + else + Count := 0; + Output.P ("",""); + Output.N ("" ""); + end if; + end if;" +procedure Dump_Standard is,"procedure Print (View : Program.Visibility.View); + procedure Print (View : Program.Visibility.View_Array); + + Ctx : aliased Program.Plain_Contexts.Context; + Env : aliased Program.Visibility.Context; + + ----------- + -- Print -- + ----------- + + procedure Print (View : Program.Visibility.View_Array) is + begin + for J in View'Range loop + Print (View (J)); + end loop; + end Print; + + ----------- + -- Print -- + ----------- + + procedure Print (View : Program.Visibility.View) is + use Program.Visibility; + Name : constant Program.Elements.Defining_Names.Defining_Name_Access := + Program.Visibility.Name (View); + begin + if Name.Assigned then + Ada.Wide_Wide_Text_IO.Put_Line + (Name.Image + & "" ["" + & View_Kind'Wide_Wide_Image (View.Kind) + & ""]""); + else + Ada.Wide_Wide_Text_IO.Put_Line + (""___ ["" + & View_Kind'Wide_Wide_Image (View.Kind) + & ""]""); + end if; + + case View.Kind is + when Enumeration_Type_View => + Print (Enumeration_Literals (View)); + when Signed_Integer_Type_View => + null; + when Modular_Type_View => + null; + when Float_Point_Type_View => + null; + when Array_Type_View => + declare + Indexes : constant Program.Visibility.View_Array := + Program.Visibility.Indexes (View); + begin + for J in Indexes'Range loop + Ada.Wide_Wide_Text_IO.Put ("" ""); + Print (Indexes (J)); + end loop; + Ada.Wide_Wide_Text_IO.Put ("" => ""); + Print (Program.Visibility.Component (View));" +function Immediate_Visible,"(Self : access constant Context; + Region : Item_Offset; + Symbol : Program.Visibility.Symbol) return View_Array; + + ----------------- + -- Append_Item -- + ----------------- + + procedure Append_Item + (Self : in out Context'Class; + Value : Item) is + begin + Self.Last_Entity := Self.Last_Entity + 1; + Self.Data.Append (Value); + + if not Self.Stack.Is_Empty then + Self.Data (Self.Stack.Last_Element.Enclosing_Item).Region.Append + (Self.Data.Last_Index); + end if; + end Append_Item; + + --------------- + -- Component -- + --------------- + + function Component (Self : View) return View is + Type_Item : Item renames Self.Env.Data (Self.Index); + begin + return Self.Env.Get_View (Type_Item.Component); + end Component; + + ----------------------- + -- Create_Array_Type -- + ----------------------- + + not overriding procedure Create_Array_Type + (Self : in out Context; + Symbol : Program.Visibility.Symbol; + Name : Defining_Name; + Indexes : View_Array; + Component : View) + is + Value : constant Item := + (Kind => Array_Type_View, + Symbol => Symbol, + Name => Name, + Entity_Id => Self.Last_Entity + 1, + Indexes => To_Vector (Indexes), + Component => Component.Index); + + begin + Self.Append_Item (Value); + end Create_Array_Type; + + ------------------------------ + -- Create_Character_Literal -- + ------------------------------ + + not overriding procedure Create_Character_Literal + (Self : in out Context; + Symbol : Program.Visibility.Symbol; + Name : Defining_Name; + Enumeration_Type : View) + is + Value : constant Item := + (Kind => Character_Literal_View, + Symbol => Symbol, + Name => Name, + Entity_Id => Self.Last_Entity + 1, + Character_Type => Enumeration_Type.Index); + + begin + Self.Append_Item (Value); + + declare + Type_Item : Item renames Self.Data (Enumeration_Type.Index); + begin + Type_Item.Enumeration_Literals.Append (Self.Data.Last_Index);" +function Immediate_Visible,"(Self : access constant Context; + Region : Item_Offset; + Symbol : Program.Visibility.Symbol) return View_Array + is + Result : View_Array (1 .. 10); + Last : Natural := 0; + Value : Item renames Self.Data (Region); + begin + if Value.Kind in Has_Region_Kind then + for Index of Value.Region loop + declare + Value : constant Item := Self.Data (Index); + begin + if Value.Symbol = Symbol then + Last := Last + 1; + Result (Last) := (Value.Kind, Self, Index); + end if;" +function Immediate_Visible,"(Self : View; + Symbol : Program.Visibility.Symbol) return View_Array is + begin + return Immediate_Visible (Self.Env, Self.Index, Symbol); + end Immediate_Visible; + + ----------------------- + -- Immediate_Visible -- + ----------------------- + + not overriding function Immediate_Visible + (Self : aliased Context; Symbol : Program.Visibility.Symbol) + return View_Array + is + procedure Append (List : View_Array); + Result : View_Array (1 .. 10); + Last : Natural := 0; + + procedure Append (List : View_Array) is + begin + Result (Last + 1 .. Last + List'Length) := List; + Last := Last + List'Length; + end Append; + + begin + for J of reverse Self.Stack loop + Append (Immediate_Visible (Self'Access, J.Enclosing_Item, Symbol)); + end loop; + + if Symbol = Standard and then not Self.Stack.Is_Empty then + declare + Top : constant View := + (Package_View, + Self'Access, + Self.Stack.First_Element.Enclosing_Item); + begin + Append ((1 => Top));" +not overriding function Create_Discrete_Range_Vector,"(Self : Element_Vector_Factory; + Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class) + return Program.Elements.Discrete_Ranges.Discrete_Range_Vector_Access + is + Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First; + begin + if not Program.Element_Vectors.Has_Element (Cursor) then + return null; + end if; + + declare + Result : constant Discrete_Range_Vector_Access := + new (Self.Subpool) + Program.Nodes.Discrete_Range_Vectors.Vector' + (Program.Nodes.Discrete_Range_Vectors.Create (Each)); + begin + return Program.Elements.Discrete_Ranges + .Discrete_Range_Vector_Access (Result);" +not overriding function Create_Discriminant_Association_Vector,"(Self : Element_Vector_Factory; + Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class) + return Program.Elements.Discriminant_Associations + .Discriminant_Association_Vector_Access + is + Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First; + begin + if not Program.Element_Vectors.Has_Element (Cursor) then + return null; + end if; + + declare + Result : constant Discriminant_Association_Vector_Access := + new (Self.Subpool) + Program.Nodes.Discriminant_Association_Vectors.Vector' + (Program.Nodes.Discriminant_Association_Vectors.Create (Each)); + begin + return Program.Elements.Discriminant_Associations + .Discriminant_Association_Vector_Access (Result);" +not overriding function Create_Discriminant_Specification_Vector,"(Self : Element_Vector_Factory; + Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class) + return Program.Elements.Discriminant_Specifications + .Discriminant_Specification_Vector_Access + is + Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First; + begin + if not Program.Element_Vectors.Has_Element (Cursor) then + return null; + end if; + + declare + Result : constant Discriminant_Specification_Vector_Access := + new (Self.Subpool) + Program.Nodes.Discriminant_Specification_Vectors.Vector' + (Program.Nodes.Discriminant_Specification_Vectors.Create + (Each)); + begin + return Program.Elements.Discriminant_Specifications + .Discriminant_Specification_Vector_Access (Result);" +procedure Init is,"RCC : RCC_Peripheral renames RCC_Periph; + begin + if PLL_Source = HSE_Input then + RCC.CR.HSEON := 1; + while RCC.CR.HSERDY = 0 loop + null; + end loop; + end if; + RCC.CFGR := ( + PLLMUL => UInt4 (PLL_Mul), + PLLSRC => ( + case PLL_Source is + when HSI_Input => 1, + when HSE_Input => 1), + others => <>);" +procedure Init is,"RCC : RCC_Peripheral renames RCC_Periph; + begin + if PLL_Source = HSE_Input then + RCC.CR.HSEON := 1; + while RCC.CR.HSERDY = 0 loop + null; + end loop; + end if;" +procedure Wait_For_Trigger is,"begin + STM32GD.EXTI.IRQ.IRQ_Handler.Wait; + end Wait_For_Trigger; + + procedure Clear_Trigger is + begin + STM32GD.EXTI.IRQ.IRQ_Handler.Reset_Status (Interrupt_Line_Number); + end Clear_Trigger; + + function Triggered return Boolean is + begin + return False;" +procedure Init is,"begin + STM32_SVD.RCC.RCC_Periph.APB2ENR.AFIOEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPAEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPBEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPCEN := 1; + STM32_SVD.NVIC.NVIC_Periph.ISER0 := 2#00000000_10000000_00000000_00000000#; + BUTTON.Init; + USB_DISC.Init; + SWO.Init; + LED.Init; + LED2.Init; + end Init; + + procedure USB_Re_Enumerate is + begin + Ada.Text_IO.Put_Line (""Re-enumerate""); + USB_DISC.Set; + declare + I : UInt32 with volatile; + begin + I := 10000; + while I > 0 loop + I := I - 1; + end loop;" +procedure Init is,"begin + STM32_SVD.RCC.RCC_Periph.APB2ENR.AFIOEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPAEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPBEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPCEN := 1; + STM32_SVD.NVIC.NVIC_Periph.ISER0 := 2#00000000_10000000_00000000_00000000#; + BUTTON.Init; + -- SWO.Init; + LED.Init; + LED2.Init; + end Init; + + procedure USB_Re_Enumerate is + begin + STM32_SVD.GPIO.GPIOA_Periph.CRH.CNF12 := 0; + STM32_SVD.GPIO.GPIOA_Periph.CRH.MODE12 := 1; + STM32_SVD.GPIO.GPIOA_Periph.BSRR.BR.Arr (12) := 1; + declare + I : UInt32 with volatile; + begin + I := 100000; + while I > 0 loop + I := I - 1; + end loop;" +procedure Init is,"begin + Clocks.Init; + STM32_SVD.RCC.RCC_Periph.APB2ENR.AFIOEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPAEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPBEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.IOPCEN := 1; + STM32_SVD.RCC.RCC_Periph.APB2ENR.USART1EN := 1; + BUTTON.Init; + LED.Init; + LED2.Init; + TX.Init; + RX.Init; + USART.Init; + RTC.Init; + end Init; + + procedure USB_Re_Enumerate is + begin + STM32_SVD.GPIO.GPIOA_Periph.CRH.CNF12 := 0; + STM32_SVD.GPIO.GPIOA_Periph.CRH.MODE12 := 1; + STM32_SVD.GPIO.GPIOA_Periph.BSRR.BR.Arr (12) := 1; + declare + I : UInt32 with volatile; + begin + I := 100000; + while I > 0 loop + I := I - 1; + end loop;" +procedure Init is,"RCC : RCC_Peripheral renames RCC_Periph; + begin + if PLL_Source = HSE_Input then + RCC.CR.HSEON := 1; + while RCC.CR.HSERDY = 0 loop + null; + end loop; + end if; + RCC.CFGR := ( + PLLMUL => UInt4 (PLL_Mul), + PLLSRC => ( + case PLL_Source is + when HSI_Input => 1, + when HSE_Input => 1), + others => <>);" +procedure bot is,"game : T_game; + logic : T_logic; + message : T_round; + + MAX_LINE_LENGTH : constant integer := 100; + line : string(1..MAX_LINE_LENGTH); + line_length : integer; + + last_command : T_command; + + winning_chances : Float; + + NbBluffInit : Constant integer :=3; + CompteurBluffInit : Integer :=0; + +begin + + initGame(game); + + while not End_Of_File loop + get_line(line, line_length); + + last_command := splitLine(line, line_length); + + case last_command.prefix is + --Settings + when settings => readSettings(last_command, game); + + --update_game + when update_game => readUpdateGame(last_command, game); + + --update_hand + when update_hand => readUpdateHand(last_command, game, logic); + + when action => + + winning_chances := get_winning_chances(logic); + + if CompteurBluffInit= LOW) then + message := strat(logic, game); + + else + if get_my_money(game) > get_op_money(game) then + message := create_round(bet,Integer(IDIOT_OP*get_op_money(game))); + else + message:= create_round(bet, Integer(IDIOT_OWN*get_my_money(game))); + end if; + CompteurBluffInit := CompteurBluffInit +1; + end if; + else + message := strat(logic, game); + + + end if; + Put_Line(Standard_Error,To_Lower(ToString(message))); + printCard(get_card(get_hand(game),0)); + printCard(get_card(get_hand(game),1)); + Put_Line(Standard_Error, winning_chances'Img); + Put_line(To_Lower(ToString(message))); + + end case; + end loop; + Put_Line(Standard_Error, can_bluff(logic)'Img&can_get_bluffed(logic)'Img&can_semi_bluff(logic)'Img);" +procedure Stop_Driver is,"begin + SPI.Stop; + GPIO.Close; + end Stop_Driver; + + procedure Init_Display is + begin + OLED_SH1106.Display.Reset; + OLED_SH1106.Display.Init_Reg; + delay 0.2; + Write_Reg(16#AF#); + end Init_Display; + + procedure Show is + Start : Natural := 0; + begin + for Page in 0..7 loop + -- set page address + Write_Reg(16#B0# + Unsigned_8(Page)); + -- set low column address + Write_Reg(16#02#); + -- set high column address + Write_Reg(16#10#); + + -- write data + Start_Data; + for I in Start..(Start+Display_Width-1) loop + Write_Data(Buffer.Data(i)); + end loop; + Start := Start + Display_Width; + end loop; + end Show; + + -- Clear the screen. + procedure Clear(Clr: Color:= Black) is + begin + Graphics.Set(Buffer'access, Clr); + end Clear; + + -- Draw a point with size ""Size"" at poiny X,Y. + procedure Dot(P: Point; Size: Positive:=1; Clr: Color:=White) is + begin + Graphics.Dot(Buffer'access, P, Size, Clr); + end Dot; + + procedure Line + (P,Q: Point; Size: Positive:= 1; Clr:Color:= White) is + begin + Graphics.Line(Buffer'access, P, Q, Size, Clr); + end Line; + + procedure Rectangle + (P, Q: Point; Size: Positive:= 1; Clr: Color:= White) is + begin + Graphics.Rectangle(Buffer'access, P, Q, Size, Clr); + end Rectangle; + + procedure Fill_Rectangle + (P, Q: Point; Clr: Color := White) is + begin + Graphics.Fill_Rectangle(Buffer'access, P, Q, Clr); + end Fill_Rectangle; + + + procedure Circle + (Center: Point; R:Natural; Size: Positive := 1; Clr: Color:= White) is + begin + Graphics.Circle(Buffer'access, Center, R, Size, Clr); + end Circle; + + procedure Fill_Circle + (Center: Point; R: Natural; Clr: Color:= White) is + begin + Graphics.Fill_Circle(Buffer'access, Center, R, Clr); + end Fill_Circle; + + procedure Put + (P : Point; + Ch : Character; + Size : Positive:= 12; + Fgnd : Color := White; + Bgnd : Color := Black) is + begin + Graphics.Put(Buffer'access, P, Ch, Size, Fgnd, Bgnd); + end Put; + + + procedure Put + (P : Point; + Text : String; + Size : Positive:= 12; + Fgnd : Color := White; + Bgnd : Color := Black) is + begin + Graphics.Put(Buffer'access, P, Text, Size, Fgnd, Bgnd); + end Put; + + + -- Draw a number to the display + procedure Put + (P : Point; -- Position + Num : Natural; -- The number to draw + Size : Positive := 12; -- Font size + Fgnd : Color := White; -- Foreground color + Bgnd : Color := Black) is -- Background color + begin + Graphics.Put(Buffer'access, P, Num, Size, Fgnd, Bgnd); + end Put; + + + procedure Bitmap + (P: Point; Bytes : Byte_Array_Access; S: Size) is + begin + Graphics.Bitmap(Buffer'access, P, Bytes, S); + end Bitmap; + + procedure Bitmap + (P: Point; Icon: Bitmap_Icon) is + begin + Graphics.Bitmap(Buffer'access, P, Icon);" +procedure Tests is,"Failures : Natural := 0; +begin + + for Kind in Testsuite.Encode.Encoder_Kind + loop + declare + Suite : aliased AUnit.Test_Suites.Test_Suite; + + function Get_Suite return AUnit.Test_Suites.Access_Test_Suite + is (Suite'Unchecked_Access); + + function Runner is new AUnit.Run.Test_Runner_With_Status (Get_Suite); + + Reporter : AUnit.Reporter.Text.Text_Reporter; + begin + + Ada.Text_IO.New_Line; + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (""Testing "" & Kind'Img & "" encoder:""); + Testsuite.Encode.Set_Encoder_Kind (Kind); + Testsuite.Encode.Add_Tests (Suite); + + Reporter.Set_Use_ANSI_Colors (True); + + if Runner (Reporter, + (Global_Timer => True, + Test_Case_Timer => True, + Report_Successes => True, + others => <>)) + /= AUnit.Success + then + Failures := Failures + 1; + end if;" +function Runner is new AUnit.Run.Test_Runner_With_Status (Get_Suite);,"Reporter : AUnit.Reporter.Text.Text_Reporter; + begin + + Ada.Text_IO.New_Line; + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (""Testing "" & Kind'Img & "" decoder:""); + Testsuite.Decode.Set_Decoder_Kind (Kind); + Testsuite.Decode.Add_Tests (Suite); + + Reporter.Set_Use_ANSI_Colors (True); + + if Runner (Reporter, + (Global_Timer => True, + Test_Case_Timer => True, + Report_Successes => True, + others => <>)) + /= AUnit.Success + then + Failures := Failures + 1; + end if;" +function Runner is new AUnit.Run.Test_Runner_With_Status,"(Get_Suite); + + Reporter : AUnit.Reporter.Text.Text_Reporter; + begin + + Ada.Text_IO.New_Line; + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (""Testing "" & E_Kind'Img & "" encoder"" & + "" with "" & D_Kind'Img & "" decoder""); + Testsuite.Encode_Decode.Set_Kinds (E_Kind, D_Kind); + Testsuite.Encode_Decode.Add_Tests (Suite); + + Reporter.Set_Use_ANSI_Colors (True); + + if Runner (Reporter, + (Global_Timer => True, + Test_Case_Timer => True, + Report_Successes => True, + others => <>)) + /= AUnit.Success + then + Failures := Failures + 1; + end if;" +procedure Refresh is,"begin + --clear screen + --New_Line(100); + Put(ASCII.ESC & ""[;H""); + --fill screen + For Y in Integer Range 0..Screen_Height loop + For X in Integer Range 0..Screen_Width loop + begin + Put(Screen(X,Y).color); + if(Character'Pos(Screen(X,Y).char) >= 32) then + Put(Screen(X,Y).char); + else + Put(' '); + end if; + exception + when others => + null;" +procedure spritemaker is,"procedure showFile(Filename : String) is + File : File_Type; + begin + Open(File, In_File, Filename); + while(not End_Of_File(File)) loop + Put(Get_Line(File => File)); + new_line; + end loop; + Close(File); + end showFile; + + + function LoadSpriteNoFormat(FileName : String) return SpriteType is + File : File_Type; + width : Integer; + height : Integer; + sprite : SpriteType; + line: String(1..128); + color : colorType := colorDefault; + offset : Positive := 1; + begin + --clear garbage data + width := 127; + height := 63; + For Y in Integer range 0..height loop + For X in Integer range 0..width loop + sprite.Image(X,Y).char := ' '; + sprite.color := colorDefault; + end loop; + end loop; + --load sprite + Open(File, In_File, FileName); + Get(File => File, Item => width); + Get(File => File, Item => height); + sprite.Width := width; + sprite.Height := height; + Skip_Line(File); + For Y in Integer range 0..height-1 loop + Get_Line(File => File, Item => line, Last => width); + Width := Width - 1; + offset := 1; + For X in Integer range 0..width loop + sprite.Image(X,Y).char := line(X+offset); + sprite.Image(X,Y).color := colorDefault; + put(line(X+offset)); + end loop; + --Put("" ""); + new_line; + end loop; + Close(File); + Return sprite; + end LoadSpriteNoFormat; + + procedure saveSprite(sprite : SpriteType; FileName : String) is + File : File_Type; + width : Natural := sprite.width; + height : Natural := sprite.height; + begin + Create(File, Out_File, FileName); + Put(File => File, Item => sprite.width , Width => 0); + Put(File => File, Item => "" ""); + Put(File => File, Item => sprite.height, Width => 0); + New_Line(File); + For Y in Integer range 0..height loop + For X in Integer range 0..width loop + Put(File => File, Item => sprite.Image(X,Y).color); + Put(File => File, Item => sprite.Image(X,Y).char); + end loop; + New_Line(File); + end loop; + Close(File); + end saveSprite; + + --paint tools + procedure boxFill (X,Y,W,H : Integer) is + begin + null;--do stuff" +procedure ShowCommands is,"posX : Integer := Screen_Width-14; + posY : Integer := 2; + begin + + for I in 0..Screen_Height loop + setPixel(posX-02,I,character'val(186), colorDefault); + setPixel(posX+14,I,character'val(186), colorDefault); + end loop; + + SetText(posX, posY+00, ""Color "", currentCol); + SetText(posX, posY+02, ""Black : 0""); + SetText(posX, posY+03, ""Red : 1""); + SetText(posX, posY+04, ""Green : 2""); + SetText(posX, posY+05, ""Yellow : 3""); + SetText(posX, posY+06, ""Blue : 4""); + SetText(posX, posY+07, ""Magenta : 5""); + SetText(posX, posY+08, ""Cyan : 6""); + SetText(posX, posY+09, ""White : 7""); + SetText(posX, posY+10, ""Shade : 8""); + SetText(posX, posY+11, ""Invert : 9""); + SetText(posX, posY+12, ""Set : Space""); + SetText(posX, posY+13, ""Auto : S""); + SetText(posX, posY+14, ""Fill : F""); + --SetText(posX, posY+15, ""\Box Fill: B""); + + SetText(posX, posY+20, ""Save : -""); + SetText(posX, posY+21, ""Quit : Q""); + end ShowCommands; + + line : String(1..250); + len : Natural; + editSprite : SpriteType; + + useBox : Boolean := False; + boxStartX : Integer := 0; + boxStartY : Integer := 0; + +begin + + put(ASCII.ESC & ""[?25l""); -- cursor off (?25h for on) + + cursorX := 0; + cursorY := 0; + + Initialize(140,50); + + --primary menu + loop + WipeScreen; + setText(4, 12, ""What would you like to load?""); + setText(6, 14, ""1 - Unformatted sprite""); + setText(6, 15, ""2 - Existing Sprite file""); + refresh; + get_immediate(input); + exit when input = '1'; + exit when input = '2'; + end loop; + + loop + Put(""Enter File to load""); + new_line; + Get_Line(Item => line, Last => len); + Put(""Loading "" & line(1..len)); + new_line; + + begin--exception + if(input = '1') then + editSprite := LoadSpriteNoFormat(line(1..len)); + Put(""----""); + exit; + elsif(input = '2') then + editSprite := LoadSprite(line(1..len)); + Put(""----""); + end if; + exit; + + exception + when others => + Put(""File does not exist or the file format is incorrect."");" +procedure Monitor is,"ptr : Proxy.ManagerPtr := Proxy.GetManager; +begin + ptr.Start; + LOG_INFO (""LOG "", ""Start Manager""); + + loop + declare + str : String := Get_Line; + begin + exit when str = ""quit"" or else str = ""exit"";" +"procedure Free is new Ada.Unchecked_Deallocation (SinkOutputer, SinkOutputerPtr);","begin + self.handler.Stop; + Free (self.handler); + end Close; + + ----------------------------------------------------------------------------- + task body SinkOutputer is + isWorked : Pal.bool := true; + sinkTag : ESinkType; + severity : Logging_Message.ESeverity; + channel : Logging_Message.LogChannel; + var : Pal.uint32_t; + begin + accept Start (tag : ESinkType; + sev : Logging_Message.ESeverity; + ch : Logging_Message.LogChannel) do + sinkTag := tag; + severity := sev; + channel := ch; + end Start; + + while isWorked loop + select + accept Write (logs : in LogMessages; + file : in ASU.Unbounded_String := ASU.Null_Unbounded_String) do + for i in logs.Get.First_Index .. logs.Get.Last_Index loop + declare + msg : Logging_Message.LogMessage := logs.Get.Element (i); + begin + if msg.Get.lchannel = channel and then + msg.Get.severity >= severity and then + msg.Get.command = Logging_Message.eMessage then + if sinkTag = CONSOLE_SINK then + Put_Line (FormatMessage (msg.Get)); + elsif sinkTag = FILE_SINK then + -- TODO: implement + null; + end if; + end if;" +"procedure Free is new Ada.Unchecked_Deallocation (RTI_Connext_Replier, RTI_Connext_Replier_Access);","begin + Free (Self);" +"procedure free is new ada.Unchecked_Deallocation (Ref'class, ref_access);","------------ + -- Create -- + ------------ + + function Create + (Participant : DDS.DomainParticipant.Ref_Access; + Service_Name : DDS.String; + Library_Name : DDS.String; + Profile_Name : DDS.String; + Publisher : DDS.Publisher.Ref_Access := null; + Subscriber : DDS.Subscriber.Ref_Access := null; + Listner : Replyer_Listeners.Ref_Access := null; + Mask : DDS.StatusKind := DDS.STATUS_MASK_NONE) return Ref_Access + is + Request_Topic_Name : DDS.String := DDS.Request_Reply.Impl.Create_Request_Topic_Name_From_Service_Name (Service_Name); + Reply_Topic_Name : DDS.String := DDS.Request_Reply.Impl.Create_Reply_Topic_Name_From_Service_Name (Service_Name); + Ret : Ref_Access; + begin + Ret := Create (Participant, + Request_Topic_Name, + Reply_Topic_Name, + Library_Name, + Profile_Name, + Publisher, + Subscriber, + Listner, Mask); + Finalize (Request_Topic_Name); + Finalize (Reply_Topic_Name); + return Ret; + + end Create; + + ------------ + -- Create -- + ------------ + + function Create + (Participant : DDS.DomainParticipant.Ref_Access; + Request_Topic_Name : DDS.String; + Reply_Topic_Name : DDS.String; + Library_Name : DDS.String; + Profile_Name : DDS.String; + Publisher : DDS.Publisher.Ref_Access := null; + Subscriber : DDS.Subscriber.Ref_Access := null; + Listner : Replyer_Listeners.Ref_Access := null; + Mask : DDS.StatusKind := DDS.STATUS_MASK_NONE) return Ref_Access + is + Datawriter_Qos : DDS.DataWriterQos; + Datareader_Qos : DDS.DataReaderQos; + Request_Topic_QoS : DDS.TopicQos; + Reply_Topic_Qos : DDS.TopicQos; + begin + Participant.Get_Factory.Get_Datareader_Qos_From_Profile_W_Topic_Name (Datareader_Qos, Library_Name, Profile_Name, Request_Topic_Name); + Participant.Get_Factory.Get_Datawriter_Qos_From_Profile_W_Topic_Name (DataWriter_Qos, Library_Name, Profile_Name, Reply_Topic_Name); + Participant.Get_Factory.Get_Topic_Qos_From_Profile_W_Topic_Name (Request_Topic_QoS, Library_Name, Profile_Name, Request_Topic_Name); + Participant.Get_Factory.Get_Topic_Qos_From_Profile_W_Topic_Name (Reply_Topic_Qos, Library_Name, Profile_Name, Reply_Topic_Name); + + return Create (Participant => Participant, + Request_Topic_Name => Request_Topic_Name, + Reply_Topic_Name => Reply_Topic_Name, + Datawriter_Qos => Datawriter_Qos, + Datareader_Qos => Datareader_Qos, + Reply_Topic_Qos => Reply_Topic_Qos, + Request_Topic_QoS => Request_Topic_QoS, + Publisher => Publisher, + Subscriber => Subscriber, + Listner => Listner, + Mask => Mask); + + end Create; + + ------------ + -- Create -- + ------------ + + function Create + (Participant : DDS.DomainParticipant.Ref_Access; + Service_Name : DDS.String; + Datawriter_Qos : DDS.DataWriterQos; + Datareader_Qos : DDS.DataReaderQos; + Reply_Topic_Qos : DDS.TopicQos; + Request_Topic_Qos : DDS.TopicQos; + Publisher : DDS.Publisher.Ref_Access := null; + Subscriber : DDS.Subscriber.Ref_Access := null; + Listner : Replyer_Listeners.Ref_Access := null; + Mask : DDS.StatusKind := DDS.STATUS_MASK_NONE) return Ref_Access + is + Request_Topic_Name : DDS.String := DDS.Request_Reply.Impl.Create_Request_Topic_Name_From_Service_Name (Service_Name); + Reply_Topic_Name : DDS.String := DDS.Request_Reply.Impl.Create_Reply_Topic_Name_From_Service_Name (Service_Name); + Ret : Ref_Access; + begin + Ret := Create (Participant => Participant, + Request_Topic_Name => Request_Topic_Name, + Reply_Topic_Name => Reply_Topic_Name, + Datawriter_Qos => Datawriter_Qos, + Datareader_Qos => Datareader_Qos, + Reply_Topic_Qos => Reply_Topic_Qos, + Request_Topic_Qos => Request_Topic_Qos, + Publisher => Publisher, + Subscriber => Subscriber, + Listner => Listner, + Mask => Mask); + Finalize (Request_Topic_Name); + Finalize (Reply_Topic_Name); + return Ret; + end Create; + + ------------ + -- Create -- + ------------ + function Create + (Participant : DDS.DomainParticipant.Ref_Access; + Request_Topic_Name : DDS.String; + Reply_Topic_Name : DDS.String; + Datawriter_Qos : DDS.DataWriterQos; + Datareader_Qos : DDS.DataReaderQos; + Reply_Topic_Qos : DDS.TopicQos; + Request_Topic_Qos : DDS.TopicQos; + Publisher : DDS.Publisher.Ref_Access := null; + Subscriber : DDS.Subscriber.Ref_Access := null; + Listner : Replyer_Listeners.Ref_Access := null; + Mask : DDS.StatusKind := DDS.STATUS_MASK_NONE) return Ref_Access + is + Ret : ref_access := new Ref; + begin + Ret.Listner := Listner; + ret.Participant := Participant; + ret.Publisher := (if Publisher /= null then + Publisher + else + Participant.Get_Implicit_Publisher); + ret.Subscriber := (if Subscriber /= null then + Subscriber + else + Participant.Get_Implicit_Subscriber); + + Ret.Reply_Topic := Ret.Create_Reply_Topic (Reply_Topic_Name, Reply_DataWriter.Treats.Get_Type_Name, Reply_Topic_Qos); + + Ret.Request_Topic := Ret.Create_Request_Topic (Request_Topic_Name, Request_DataReader.Treats.Get_Type_Name, Request_Topic_Qos); + + ret.Reader := DDS.DataReader_Impl.Ref_Access (ret.Subscriber.Create_DataReader + (Topic => ret.Request_Topic, + Qos => Datareader_Qos, + A_Listener => ret.Reader_Listner'access, + Mask => Mask)); + + Ret.Writer := DDS.DataWriter_Impl.Ref_Access (Ret.Publisher.Create_DataWriter + (A_Topic => Ret.Reply_Topic, + Qos => Datawriter_Qos, + A_Listener => Ret.Writer_Listner'Access, + Mask => Mask)); + Ret.Any_Sample_Cond := Ret.Reader.Create_Readcondition + (Sample_States => DDS.ANY_SAMPLE_STATE, + View_States => DDS.ANY_VIEW_STATE, + Instance_States => DDS.ANY_INSTANCE_STATE); + Ret.Not_Read_Sample_Cond := Ret.Reader.Create_Readcondition + (Sample_States => DDS.NOT_READ_SAMPLE_STATE, + View_States => DDS.ANY_VIEW_STATE, + Instance_States => DDS.ANY_INSTANCE_STATE); + return ret; + exception + when others => + ret.Delete; + free (ret); + raise; + end Create; + + ------------ + -- Delete -- + ------------ + + procedure Delete (Self : in out Ref_Access) is + begin + -- pragma Compile_Time_Warning (Standard.True, ""Delete unimplemented""); + raise Program_Error with ""Unimplemented procedure Delete""; + end Delete; + + ---------------- + -- Send_Reply -- + ---------------- + + ---------------- + -- Send_Reply -- + ---------------- + + procedure Send_Reply + (Self : not null access Ref; + Reply : Reply_DataWriter.Treats.Data_Type; + Id : DDS.SampleIdentity_T) + is + params : DDS.WriteParams_t; + begin + self.send_Sample (Data => Reply , Related_Request_Info => Id, WriteParams => params); + end Send_Reply; + + --------------------- + -- Receive_Request -- + --------------------- + + function Receive_Request + (Self : not null access Ref; + Request : in out Request_DataReader.Treats.Data_Type; + SampleInfo : in out DDS.SampleInfo; + Timeout : DDS.Duration_T := DDS.DURATION_INFINITE) return DDS.ReturnCode_T + is + begin + return Ret : DDS.ReturnCode_T := DDS.RETCODE_NO_DATA do + for I of Self.Receive_Request (Min_Reply_Count => 1, Max_Reply_Count => 1, Timeout => Timeout) loop + if I.Sample_Info.Valid_Data then + Request_DataReader.Treats.Copy (Request, I.Data.all); + Copy (SampleInfo, I.Sample_Info.all); + Ret := DDS.RETCODE_OK; + end if; + end loop; + end return; + end Receive_Request; + + --------------------- + -- Receive_Request -- + --------------------- + + procedure Receive_Request + (Self : not null access Ref; + Request : in out Request_DataReader.Treats.Data_Type; + Info_Seq : in out DDS.SampleInfo; + Timeout : DDS.Duration_T := DDS.DURATION_INFINITE) + is + begin + Dds.Ret_Code_To_Exception (Self.Receive_Request (Request, Info_Seq, Timeout)); + end Receive_Request; + + --------------------- + -- Receive_Request -- + --------------------- + + function Receive_Request + (Self : not null access Ref; Timeout : DDS.Duration_T) + return Request_DataReader.Container'class + is + begin + return Request_DataReader.Ref_Access (Self.Reader).Take; + end Receive_Request; + + + + ---------------------- + -- Receive_Requests -- + ---------------------- + + + ---------------------- + -- Receive_Requests -- + ---------------------- + + + --------------------- + -- Receive_Request -- + --------------------- + + function Take_Request + (Self : not null access Ref; + Max_Reply_Count : DDS.long := DDS.INFINITE) + return Request_DataReader.Container'Class is + begin + return Self.Get_Request_Data_Reader.Take (Max_Samples => Max_Reply_Count);" +procedure On_Offered_Deadline_Missed,"(Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Status : in DDS.OfferedDeadlineMissedStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Offered_Deadline_Missed (Self.Parent.all'Access, Status); + end if; + end On_Offered_Deadline_Missed; + + ----------------------- + -- On_Data_Available -- + ----------------------- + + procedure On_Data_Available + (Self : not null access DataReader_Listner; + The_Reader : in DDS.DataReaderListener.DataReader_Access) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Request_Avalible (Self.Parent.all'Access); + end if; + end On_Data_Available; + + --------------------------------- + -- On_Offered_Incompatible_Qos -- + --------------------------------- + + procedure On_Offered_Incompatible_Qos + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Status : in DDS.OfferedIncompatibleQosStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Offered_Incompatible_Qos (Self.Parent.all'Access, Status); + end if; + end On_Offered_Incompatible_Qos; + + ------------------------ + -- On_Liveliness_Lost -- + ------------------------ + + procedure On_Liveliness_Lost + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Status : in DDS.LivelinessLostStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Liveliness_Lost (Self.Parent.all'Access, Status); + end if; + end On_Liveliness_Lost; + + ---------------------------- + -- On_Publication_Matched -- + ---------------------------- + + procedure On_Publication_Matched + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Status : in DDS.PublicationMatchedStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Publication_Matched (Self.Parent.all'Access, Status); + end if; + end On_Publication_Matched; + + -------------------------------------- + -- On_Reliable_Writer_Cache_Changed -- + -------------------------------------- + + procedure On_Reliable_Writer_Cache_Changed + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Status : in DDS.ReliableWriterCacheChangedStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Reliable_Writer_Cache_Changed (Self.Parent.all'Access, Status); + end if; + end On_Reliable_Writer_Cache_Changed; + + ----------------------------------------- + -- On_Reliable_Reader_Activity_Changed -- + ----------------------------------------- + + procedure On_Reliable_Reader_Activity_Changed + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Status : in DDS.ReliableReaderActivityChangedStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Reliable_Reader_Activity_Changed (Self.Parent.all'Access, Status); + end if; + end On_Reliable_Reader_Activity_Changed; + + -------------------------------- + -- On_Destination_Unreachable -- + -------------------------------- + + procedure On_Destination_Unreachable + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Instance : in DDS.InstanceHandle_T; Locator : in DDS.Locator_T) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Destination_Unreachable (Self.Parent.all'Access, Instance, Locator); + end if; + end On_Destination_Unreachable; + + --------------------- + -- On_Data_Request -- + --------------------- + + procedure On_Data_Request + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Cookie : in DDS.Cookie_T; + Request : in out System.Address) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Data_Request (Self.Parent.all'Access, Cookie, Request); + end if; + end On_Data_Request; + + -------------------- + -- On_Data_Return -- + -------------------- + + procedure On_Data_Return + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Arg : System.Address; + Cookie : in DDS.Cookie_T) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Data_Return (Self.Parent.all'Access, Arg, Cookie); + end if; + end On_Data_Return; + + ----------------------- + -- On_Sample_Removed -- + ----------------------- + + procedure On_Sample_Removed + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Cookie : in DDS.Cookie_T) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Sample_Removed (Self.Parent.all'Access, Cookie); + end if; + end On_Sample_Removed; + + -------------------------- + -- On_Instance_Replaced -- + -------------------------- + + procedure On_Instance_Replaced + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Instance : in DDS.InstanceHandle_T) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Instance_Replaced (Self.Parent.all'Access, Instance); + end if; + end On_Instance_Replaced; + + ----------------------------------- + -- On_Application_Acknowledgment -- + ----------------------------------- + + procedure On_Application_Acknowledgment + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Info : in DDS.AcknowledgmentInfo) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Application_Acknowledgment (Self.Parent.all'Access, Info); + end if; + end On_Application_Acknowledgment; + + --------------------------------- + -- On_Service_Request_Accepted -- + --------------------------------- + + procedure On_Service_Request_Accepted + (Self : not null access DataReader_Listner; + Writer : access DDS.DataWriter.Ref'Class; + Info : in DDS.ServiceRequestAcceptedStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Service_Request_Accepted (Self.Parent.all'Access, Info); + end if; + end On_Service_Request_Accepted; + + ---------------------------------- + -- On_Requested_Deadline_Missed -- + ---------------------------------- + + procedure On_Requested_Deadline_Missed + (Self : not null access DataWriter_Listner; + The_Reader : in DDS.DataReaderListener.DataReader_Access; + Status : in DDS.RequestedDeadlineMissedStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Requested_Deadline_Missed (Self.Parent.all'Access, Status); + end if; + end On_Requested_Deadline_Missed; + + ----------------------------------- + -- On_Requested_Incompatible_Qos -- + ----------------------------------- + + procedure On_Requested_Incompatible_Qos + (Self : not null access DataWriter_Listner; + The_Reader : in DDS.DataReaderListener.DataReader_Access; + Status : in DDS.RequestedIncompatibleQosStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Requested_Incompatible_Qos (Self.Parent.all'Access, Status); + end if; + end On_Requested_Incompatible_Qos; + + ------------------------ + -- On_Sample_Rejected -- + ------------------------ + + procedure On_Sample_Rejected + (Self : not null access DataWriter_Listner; + The_Reader : in DDS.DataReaderListener.DataReader_Access; + Status : in DDS.SampleRejectedStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Sample_Rejected (Self.Parent.all'Access, Status); + end if; + end On_Sample_Rejected; + + --------------------------- + -- On_Liveliness_Changed -- + --------------------------- + + procedure On_Liveliness_Changed + (Self : not null access DataWriter_Listner; + The_Reader : in DDS.DataReaderListener.DataReader_Access; + Status : in DDS.LivelinessChangedStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Liveliness_Changed (Self.Parent.all'Access, Status); + end if; + end On_Liveliness_Changed; + + ----------------------- + -- On_Data_Available -- + ----------------------- + + -- procedure On_Data_Available + -- (Self : not null access DataWriter_Listner; + -- The_Reader : in DDS.DataReaderListener.DataReader_Access) + -- is + -- begin + -- if Self.Parent.Listner /= null then + -- Self.Parent.Listner.On_Request_Avalible (Self.all'Access); + -- end if; + -- end On_Data_Available; + + ----------------------------- + -- On_Subscription_Matched -- + ----------------------------- + + procedure On_Subscription_Matched + (Self : not null access DataWriter_Listner; + The_Reader : in DDS.DataReaderListener.DataReader_Access; + Status : in DDS.SubscriptionMatchedStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Subscription_Matched (Self.Parent.all'Access, Status); + end if; + end On_Subscription_Matched; + + -------------------- + -- On_Sample_Lost -- + -------------------- + + procedure On_Sample_Lost + (Self : not null access DataWriter_Listner; + The_Reader : in DDS.DataReaderListener.DataReader_Access; + Status : in DDS.SampleLostStatus) + is + begin + if Self.Parent.Listner /= null then + Self.Parent.Listner.On_Sample_Lost (Self.Parent.all'Access, Status); + end if; + end On_Sample_Lost; + procedure Send_Sample (Self : not null access Ref; + Data : Reply_DataWriter.Treats.Data_Type; + Related_Request_Info : DDS.SampleIdentity_T; + WriteParams : in out DDS.WriteParams_T) is + begin + Self.Configure_Params_For_Reply (WriteParams, Related_Request_Info); + Reply_DataWriter.Ref_Access (Self.Writer).Write_W_Params (Data, WriteParams);" +"function To_Bits is new Ada.Unchecked_Conversion (Address, Bits);","LE : constant := Standard'Default_Bit_Order; + -- Static constant set to 0 for big-endian, 1 for little-endian + + -- The following is an array of masks used to mask the final byte, either + -- at the high end (big-endian case) or the low end (little-endian case). + + Masks : constant array (1 .. 7) of Packed_Byte := ( + (1 - LE) * 2#1000_0000# + LE * 2#0000_0001#, + (1 - LE) * 2#1100_0000# + LE * 2#0000_0011#, + (1 - LE) * 2#1110_0000# + LE * 2#0000_0111#, + (1 - LE) * 2#1111_0000# + LE * 2#0000_1111#, + (1 - LE) * 2#1111_1000# + LE * 2#0001_1111#, + (1 - LE) * 2#1111_1100# + LE * 2#0011_1111#, + (1 - LE) * 2#1111_1110# + LE * 2#0111_1111#); + + ----------------------- + -- Local Subprograms -- + ----------------------- + + procedure Raise_Error; + -- Raise Constraint_Error, complaining about unequal lengths + + ------------- + -- Bit_And -- + ------------- + + procedure Bit_And + (Left : Address; + Llen : Natural; + Right : Address; + Rlen : Natural; + Result : Address) + is +-- LeftB : constant Bits := To_Bits (Left); +-- RightB : constant Bits := To_Bits (Right); +-- ResultB : constant Bits := To_Bits (Result); +-- pragma Unreferenced (Llen); + pragma Unreferenced (Rlen); + begin + -- for the time being we don't provide dynamic range checks + -- if Llen /= Rlen then + -- Raise_Error; + -- end if; + + -- this routine is called only for 1, 2, or 4 byte lengths. + -- The Rlen/Llen parameter is either, 8, 16, or 32. + if Llen = 8 then + declare + use Interfaces; + Left_Byte : Unsigned_8; + for Left_Byte'Address use Left; + Right_Byte : Unsigned_8; + for Right_Byte'Address use Right; + Result_Byte : Unsigned_8; + for Result_Byte'Address use Result; + begin + Result_Byte := Left_Byte and Right_Byte;" +"function To_Bits is new Ada.Unchecked_Conversion (Address, Bits);","LE : constant := Standard'Default_Bit_Order; + -- Static constant set to 0 for big-endian, 1 for little-endian + + -- The following is an array of masks used to mask the final byte, either + -- at the high end (big-endian case) or the low end (little-endian case). + + Masks : constant array (1 .. 7) of Packed_Byte := ( + (1 - LE) * 2#1000_0000# + LE * 2#0000_0001#, + (1 - LE) * 2#1100_0000# + LE * 2#0000_0011#, + (1 - LE) * 2#1110_0000# + LE * 2#0000_0111#, + (1 - LE) * 2#1111_0000# + LE * 2#0000_1111#, + (1 - LE) * 2#1111_1000# + LE * 2#0001_1111#, + (1 - LE) * 2#1111_1100# + LE * 2#0011_1111#, + (1 - LE) * 2#1111_1110# + LE * 2#0111_1111#); + + ----------------------- + -- Local Subprograms -- + ----------------------- + + procedure Raise_Error; + -- Raise Constraint_Error, complaining about unequal lengths + + ------------- + -- Bit_And -- + ------------- + + procedure Bit_And + (Left : Address; + Llen : Natural; + Right : Address; + Rlen : Natural; + Result : Address) + is +-- LeftB : constant Bits := To_Bits (Left); +-- RightB : constant Bits := To_Bits (Right); +-- ResultB : constant Bits := To_Bits (Result); +-- pragma Unreferenced (Llen); + pragma Unreferenced (Rlen); + begin + -- for the time being we don't provide dynamic range checks + -- if Llen /= Rlen then + -- Raise_Error; + -- end if; + + -- this routine is called only for 1, 2, or 4 byte lengths. + -- The Rlen/Llen parameter is either, 8, 16, or 32. + if Llen = 8 then + declare + use Interfaces; + Left_Byte : Unsigned_8; + for Left_Byte'Address use Left; + Right_Byte : Unsigned_8; + for Right_Byte'Address use Right; + Result_Byte : Unsigned_8; + for Result_Byte'Address use Result; + begin + Result_Byte := Left_Byte and Right_Byte;" +function To_Stack_Pool is new,"Ada.Unchecked_Conversion (Address, Stk_Pool_Access); + + pragma Warnings (Off); + function To_Global_Ptr is new + Ada.Unchecked_Conversion (Address, SS_Stack_Ptr); + pragma Warnings (On); + -- Suppress aliasing warning since the pointer we return will + -- be the only access to the stack. + + Local_Stk_Address : System.Address; + + begin + Num_Of_Assigned_Stacks := Num_Of_Assigned_Stacks + 1; + + Local_Stk_Address := + To_Stack_Pool + (Default_Sized_SS_Pool) (Num_Of_Assigned_Stacks)'Address; + Stack := To_Global_Ptr (Local_Stk_Address);" +procedure Main is,"package Positive_IO is new Ada.Text_IO.Integer_IO (Positive); + + type Image_Access is access all Bitmaps.RGB.Image; + package Image_Problem is new Problem (Image_Access); + + function Opt_Iterations return Positive is + Result : Positive := 1000000; + Last : Positive; + begin + if Ada.Environment_Variables.Exists (""ANNEALING_ITERATIONS"") then + Positive_IO.Get + (From => Ada.Environment_Variables.Value (""ANNEALING_ITERATIONS""), + Item => Result, Last => Last); + end if; + return Result; + end Opt_Iterations; + + function Opt_Temperature return Float is + Result : Float := 100.0; + Last : Positive; + begin + if Ada.Environment_Variables.Exists (""ANNEALING_TEMPERATURE"") then + Ada.Float_Text_IO.Get + (From => Ada.Environment_Variables.Value (""ANNEALING_TEMPERATURE""), + Item => Result, Last => Last); + end if; + return Result; + end Opt_Temperature; + + function Opt_Size return Positive is + Result : Positive := 64; + Last : Positive; + begin + if Ada.Environment_Variables.Exists(""ANNEALING_SIZE"") then + Positive_IO.Get + (From => Ada.Environment_Variables.Value(""ANNEALING_SIZE""), + Item => Result, Last => Last); + end if; + return Result; + end Opt_Size; + + Bitmap_Size : constant Positive := Opt_Size; + + B : aliased Bitmaps.RGB.Image (Bitmap_Size, Bitmap_Size); + S : Image_Problem.State; +begin + ImageOps.Noise (B); + + S.Img := B'Access; + S.E := ImageOps.Adj_Distance_Sum (B); + Image_Problem.Roll (S); + S.Visited := False; + + declare + M : Image_Problem.Opt.Minimization := Image_Problem.Opt.Minimize (S); + Sched : Simulated_Annealing.Scheduler := + Simulated_Annealing.Exponential (Opt_Iterations, Opt_Temperature); + Improved : Boolean := False; + begin + while Image_Problem.Opt.Step (M, Sched, Improved) loop + if Improved then + Ada.Text_IO.Put (""T = ""); + Ada.Float_Text_IO.Put (Simulated_Annealing.Temperature (Sched)); + Ada.Text_IO.Put ("", E = ""); + Ada.Long_Integer_Text_IO.Put + (Image_Problem.Opt.Minimum (M).E, Width => 0); + Ada.Text_IO.New_Line; + + if Ada.Command_Line.Argument_Count > 0 then + declare + CF : RAII.Controlled_File; + begin + Ada.Text_IO.Open + (CF.File, Ada.Text_IO.Out_File, + Ada.Command_Line.Argument (1)); + Bitmaps.IO.Write_PPM_P6 + (Ada.Text_IO.Text_Streams.Stream (CF.File), B);" +function New_FlagRegister return FlagRegister; -- ./registers.hpp:16,"pragma CPP_Constructor (New_FlagRegister, ""_ZN12FlagRegisterC1Ev""); + + procedure setFlag (this : access FlagRegister; the_flag : Flag); -- ./registers.hpp:18 + pragma Import (CPP, setFlag, ""_ZN12FlagRegister7setFlagE4Flag""); + + procedure unsetFlag (this : access FlagRegister; the_flag : Flag); -- ./registers.hpp:19 + pragma Import (CPP, unsetFlag, ""_ZN12FlagRegister9unsetFlagE4Flag""); + + function getFlag (this : access FlagRegister; the_flag : Flag) return Extensions.bool; -- ./registers.hpp:20 + pragma Import (CPP, getFlag, ""_ZN12FlagRegister7getFlagE4Flag""); + + function get_value (this : access FlagRegister) return unsigned_char; -- ./registers.hpp:21 + pragma Import (CPP, get_value, ""_ZN12FlagRegister9get_valueEv""); + + procedure set_value (this : access FlagRegister; val : unsigned_char); -- ./registers.hpp:22 + pragma Import (CPP, set_value, ""_ZN12FlagRegister9set_valueEh"");" +procedure disableIME (this : access Processor); -- ./processor.hpp:81,"pragma Import (CPP, disableIME, ""_ZN9Processor10disableIMEEv""); + + procedure enableIMEDelay (this : access Processor); -- ./processor.hpp:84 + pragma Import (CPP, enableIMEDelay, ""_ZN9Processor14enableIMEDelayEv""); + + procedure HALT (this : access Processor); -- ./processor.hpp:95 + pragma Import (CPP, HALT, ""_ZN9Processor4HALTEv""); + + procedure STOP (this : access Processor); -- ./processor.hpp:103 + pragma Import (CPP, STOP, ""_ZN9Processor4STOPEv""); + + procedure push_word (this : access Processor; word : word_operations_hpp.uint16_t); -- ./processor.hpp:107 + pragma Import (CPP, push_word, ""_ZN9Processor9push_wordEt""); + + function pop_word (this : access Processor) return word_operations_hpp.uint16_t; -- ./processor.hpp:108 + pragma Import (CPP, pop_word, ""_ZN9Processor8pop_wordEv""); + + function handleInterrupts (this : access Processor) return int; -- ./processor.hpp:112 + pragma Import (CPP, handleInterrupts, ""_ZN9Processor16handleInterruptsEv""); + + procedure setupInterrupt (this : access Processor; inter : unsigned); -- ./processor.hpp:115 + pragma Import (CPP, setupInterrupt, ""_ZN9Processor14setupInterruptEj""); + + function execCurrentInstruction (this : access Processor) return int; -- ./processor.hpp:117 + pragma Import (CPP, execCurrentInstruction, ""_ZN9Processor22execCurrentInstructionEv""); + + procedure fetchNextInstruction (this : access Processor); -- ./processor.hpp:119 + pragma Import (CPP, fetchNextInstruction, ""_ZN9Processor20fetchNextInstructionEv""); + + procedure operator_as (this : access Processor; arg2 : access constant Processor); -- ./processor.hpp:122 + pragma Import (CPP, operator_as, ""_ZN9ProcessoraSERKS_""); + + INTERRUPT_VECTOR : aliased word_operations_hpp.uint16_t; -- ./processor.hpp:43 + pragma Import (CPP, INTERRUPT_VECTOR, ""_ZN9Processor16INTERRUPT_VECTORE"");" +function New_FlagRegister return FlagRegister; -- ./registers.hpp:16,"pragma CPP_Constructor (New_FlagRegister, ""_ZN12FlagRegisterC1Ev""); + + procedure setFlag (this : access FlagRegister; the_flag : Flag); -- ./registers.hpp:18 + pragma Import (CPP, setFlag, ""_ZN12FlagRegister7setFlagE4Flag""); + + procedure unsetFlag (this : access FlagRegister; the_flag : Flag); -- ./registers.hpp:19 + pragma Import (CPP, unsetFlag, ""_ZN12FlagRegister9unsetFlagE4Flag""); + + function getFlag (this : access FlagRegister; the_flag : Flag) return Extensions.bool; -- ./registers.hpp:20 + pragma Import (CPP, getFlag, ""_ZN12FlagRegister7getFlagE4Flag""); + + function get_value (this : access FlagRegister) return unsigned_char; -- ./registers.hpp:21 + pragma Import (CPP, get_value, ""_ZN12FlagRegister9get_valueEv""); + + procedure set_value (this : access FlagRegister; val : unsigned_char); -- ./registers.hpp:22 + pragma Import (CPP, set_value, ""_ZN12FlagRegister9set_valueEh"");" +procedure disableIME (this : access Processor); -- ./processor.hpp:81,"pragma Import (CPP, disableIME, ""_ZN9Processor10disableIMEEv""); + + procedure enableIMEDelay (this : access Processor); -- ./processor.hpp:84 + pragma Import (CPP, enableIMEDelay, ""_ZN9Processor14enableIMEDelayEv""); + + procedure HALT (this : access Processor); -- ./processor.hpp:95 + pragma Import (CPP, HALT, ""_ZN9Processor4HALTEv""); + + procedure STOP (this : access Processor); -- ./processor.hpp:103 + pragma Import (CPP, STOP, ""_ZN9Processor4STOPEv""); + + procedure push_word (this : access Processor; word : word_operations_hpp.uint16_t); -- ./processor.hpp:107 + pragma Import (CPP, push_word, ""_ZN9Processor9push_wordEt""); + + function pop_word (this : access Processor) return word_operations_hpp.uint16_t; -- ./processor.hpp:108 + pragma Import (CPP, pop_word, ""_ZN9Processor8pop_wordEv""); + + function handleInterrupts (this : access Processor) return int; -- ./processor.hpp:112 + pragma Import (CPP, handleInterrupts, ""_ZN9Processor16handleInterruptsEv""); + + procedure setupInterrupt (this : access Processor; inter : unsigned); -- ./processor.hpp:115 + pragma Import (CPP, setupInterrupt, ""_ZN9Processor14setupInterruptEj""); + + function execCurrentInstruction (this : access Processor) return int; -- ./processor.hpp:117 + pragma Import (CPP, execCurrentInstruction, ""_ZN9Processor22execCurrentInstructionEv""); + + procedure fetchNextInstruction (this : access Processor); -- ./processor.hpp:119 + pragma Import (CPP, fetchNextInstruction, ""_ZN9Processor20fetchNextInstructionEv""); + + procedure operator_as (this : access Processor; arg2 : access constant Processor); -- ./processor.hpp:122 + pragma Import (CPP, operator_as, ""_ZN9ProcessoraSERKS_""); + + INTERRUPT_VECTOR : aliased word_operations_hpp.uint16_t; -- ./processor.hpp:43 + pragma Import (CPP, INTERRUPT_VECTOR, ""_ZN9Processor16INTERRUPT_VECTORE"");" +procedure Convert_Card_Identification_Data_Register,"(W0, W1, W2, W3 : UInt32; + Res : out Card_Identification_Data_Register); + -- Convert the R2 reply to CID + + procedure Convert_Card_Specific_Data_Register + (W0, W1, W2, W3 : UInt32; + Card_Type : Supported_SD_Memory_Cards; + CSD : out Card_Specific_Data_Register); + -- Convert the R2 reply to CSD + + procedure Convert_SDCard_Configuration_Register + (W0, W1 : UInt32; + SCR : out SDCard_Configuration_Register); + -- Convert W0 (MSB) / W1 (LSB) to SCR. + + function Compute_Card_Capacity + (CSD : Card_Specific_Data_Register; + Card_Type : Supported_SD_Memory_Cards) return UInt64; + -- Compute the card capacity (in bytes) from the CSD + + function Compute_Card_Block_Size + (CSD : Card_Specific_Data_Register; + Card_Type : Supported_SD_Memory_Cards) return UInt32; + -- Compute the card block size (in bytes) from the CSD. + + function Get_Transfer_Rate + (CSD : Card_Specific_Data_Register) return Natural; + -- Compute transfer rate from CSD + + function Swap32 (Val : UInt32) return UInt32 with Inline_Always; + + function BE32_To_Host (Val : UInt32) return UInt32 with Inline_Always; + + -- Swap bytes in a word + ------------ + -- Swap32 -- + ------------ + + function Swap32 (Val : UInt32) return UInt32 is + begin + return Shift_Left (Val and 16#00_00_00_ff#, 24) + or Shift_Left (Val and 16#00_00_ff_00#, 8) + or Shift_Right (Val and 16#00_ff_00_00#, 8) + or Shift_Right (Val and 16#ff_00_00_00#, 24); + end Swap32; + + ------------------ + -- BE32_To_Host -- + ------------------ + + function BE32_To_Host (Val : UInt32) return UInt32 is + use System; + begin + if Default_Bit_Order = Low_Order_First then + return Swap32 (Val); + else + return Val; + end if; + end BE32_To_Host; + + --------------------------------- + -- Card_Identification_Process -- + --------------------------------- + + procedure Card_Identification_Process + (This : in out SDMMC_Driver'Class; + Info : out Card_Information; + Status : out SD_Error) + is + Rsp : UInt32; + W0, W1, W2, W3 : UInt32; + Rca : UInt32; + + begin + -- Reset controller + This.Reset (Status); + + if Status /= OK then + return; + end if; + + -- CMD0: Sets the SDCard state to Idle + Send_Cmd (This, Go_Idle_State, 0, Status); + + if Status /= OK then + return; + end if; + + -- CMD8: IF_Cond, voltage supplied: 0x1 (2.7V - 3.6V) + -- It is mandatory for the host compliant to Physical Spec v2.00 + -- to send CMD8 before ACMD41 + Send_Cmd (This, Send_If_Cond, 16#1a5#, Status); + + if Status = OK then + -- at least SD Card 2.0 + Info.Card_Type := STD_Capacity_SD_Card_v2_0; + + Read_Rsp48 (This, Rsp); + + if (Rsp and 16#fff#) /= 16#1a5# then + -- Bad voltage or bad pattern. + Status := Error; + return; + end if; + else + -- If SD Card, then it's v1.1 + Info.Card_Type := STD_Capacity_SD_Card_V1_1; + end if; + + for I in 1 .. 5 loop + This.Delay_Milliseconds (200); + + -- CMD55: APP_CMD + -- This is done manually to handle error (this command is not + -- supported by mmc). + Send_Cmd (This, Cmd_Desc (App_Cmd), 0, Status); + + if Status /= OK then + if Status = Command_Timeout_Error + and then I = 1 + and then Info.Card_Type = STD_Capacity_SD_Card_V1_1 + then + -- Not an SDCard. Suppose MMC. + Info.Card_Type := Multimedia_Card; + exit; + end if; + return; + end if; + + -- ACMD41: SD_SEND_OP_COND (no crc check) + -- Arg: HCS=1, XPC=0, S18R=0 + Send_Cmd + (This, Acmd_Desc (SD_App_Send_Op_Cond), 16#40ff_0000#, Status); + if Status /= OK then + return; + end if; + + Read_Rsp48 (This, Rsp); + + if (Rsp and SD_OCR_High_Capacity) = SD_OCR_High_Capacity then + Info.Card_Type := High_Capacity_SD_Card; + end if; + + if (Rsp and SD_OCR_Power_Up) = 0 then + Status := Error; + + else + Status := OK; + exit; + end if; + end loop; + + if Status = Command_Timeout_Error + and then Info.Card_Type = Multimedia_Card + then + for I in 1 .. 5 loop + This.Delay_Milliseconds (200); + + -- CMD1: SEND_OP_COND query voltage + Send_Cmd (This, Cmd_Desc (Send_Op_Cond), 16#00ff_8000#, Status); + if Status /= OK then + return; + end if; + + Read_Rsp48 (This, Rsp); + + if (Rsp and SD_OCR_Power_Up) = 0 then + Status := Error; + else + if (Rsp and 16#00ff_8000#) /= 16#00ff_8000# then + Status := Error; + return; + end if; + Status := OK; + exit; + end if; + end loop; + end if; + + if Status /= OK then + return; + end if; + + -- TODO: Switch voltage + + -- CMD2: ALL_SEND_CID (136 bits) + Send_Cmd (This, All_Send_CID, 0, Status); + if Status /= OK then + return; + end if; + + Read_Rsp136 (This, W0, W1, W2, W3); + Convert_Card_Identification_Data_Register (W0, W1, W2, W3, Info.SD_CID); + + -- CMD3: SEND_RELATIVE_ADDR + case Info.Card_Type is + when Multimedia_Card => + Rca := 16#01_0000#; + when others => + Rca := 0; + end case; + + Send_Cmd (This, Send_Relative_Addr, Rca, Status); + if Status /= OK then + return; + end if; + case Info.Card_Type is + when Multimedia_Card => + null; + when others => + Read_Rsp48 (This, Rsp); + Rca := Rsp and 16#ffff_0000#; + if (Rsp and 16#e100#) /= 16#0100# then + return; + end if; + end case; + Info.RCA := UInt16 (Shift_Right (Rca, 16)); + + -- Switch to 25Mhz + case Info.Card_Type is + when Multimedia_Card => + Set_Clock (This, Get_Transfer_Rate (Info.SD_CSD)); + when STD_Capacity_SD_Card_V1_1 + | STD_Capacity_SD_Card_v2_0 + | High_Capacity_SD_Card => + Set_Clock (This, 25_000_000); + when others => + -- Not yet handled + raise Program_Error; + end case; + + -- CMD10: SEND_CID (136 bits) + Send_Cmd (This, Send_CID, Rca, Status); + if Status /= OK then + return; + end if; + + -- CMD9: SEND_CSD + Send_Cmd (This, Send_CSD, Rca, Status); + if Status /= OK then + return; + end if; + Read_Rsp136 (This, W0, W1, W2, W3); + Convert_Card_Specific_Data_Register + (W0, W1, W2, W3, Info.Card_Type, Info.SD_CSD); + Info.Card_Capacity := + Compute_Card_Capacity (Info.SD_CSD, Info.Card_Type); + Info.Card_Block_Size := + Compute_Card_Block_Size (Info.SD_CSD, Info.Card_Type); + + -- CMD7: SELECT + Send_Cmd (This, Select_Card, Rca, Status); + if Status /= OK then + return; + end if; + + -- CMD13: STATUS + Send_Cmd (This, Send_Status, Rca, Status); + if Status /= OK then + return; + end if; + + -- Bus size + case Info.Card_Type is + when STD_Capacity_SD_Card_V1_1 + | STD_Capacity_SD_Card_v2_0 + | High_Capacity_SD_Card => + Send_ACmd (This, SD_App_Set_Bus_Width, Info.RCA, 2, Status); + if Status /= OK then + return; + else + Set_Bus_Size (This, Wide_Bus_4B); + end if; + when others => + null; + end case; + + if (Info.SD_CSD.Card_Command_Class and 2**10) /= 0 then + -- Class 10 supported. + declare + subtype Switch_Status_Type is UInt32_Array (1 .. 16); + + Switch_Status : Switch_Status_Type; + begin + -- CMD6 + Read_Cmd (This, Cmd_Desc (Switch_Func), 16#00_fffff0#, + Switch_Status, Status); + if Status /= OK then + return; + end if; + + -- Handle endianness + for I in Switch_Status'Range loop + Switch_Status (I) := BE32_To_Host (Switch_Status (I)); + end loop; + + -- Switch tp 50Mhz if possible. + if (Switch_Status (4) and 2**(16 + 1)) /= 0 then + Read_Cmd (This, Cmd_Desc (Switch_Func), 16#80_fffff1#, + Switch_Status, Status); + if Status /= OK then + return; + end if; + + -- Switch to 50Mhz + Set_Clock (This, 50_000_000); + end if;" +"function Convert is new Ada.Unchecked_Conversion (HALFS.Status_Code, Status_Code);","function Convert is new Ada.Unchecked_Conversion (File_Mode, HALFS.File_Mode); + function Convert is new Ada.Unchecked_Conversion (File_Size, HALFS.File_Size); + function Convert is new Ada.Unchecked_Conversion (HALFS.File_Size, File_Size); + function Convert is new Ada.Unchecked_Conversion (Seek_Mode, HALFS.Seek_Mode); + + type Mount_Record is record + Is_Free : Boolean := True; + Name : String (1 .. MAX_MOUNT_NAME_LENGTH); + Name_Len : Positive; + FS : Any_Filesystem_Driver; + end record; + + subtype Mount_Index is Integer range 0 .. MAX_MOUNT_POINTS; + subtype Valid_Mount_Index is Mount_Index range 1 .. MAX_MOUNT_POINTS; + type Mount_Array is array (Valid_Mount_Index) of Mount_Record; + + type VFS_Directory_Handle is new Directory_Handle with record + Is_Free : Boolean := True; + Mount_Id : Mount_Index; + end record; + + overriding function Get_FS + (Dir : VFS_Directory_Handle) return Any_Filesystem_Driver; + -- Return the filesystem the handle belongs to. + + overriding function Read + (Dir : in out VFS_Directory_Handle; + Handle : out Any_Node_Handle) return HALFS.Status_Code; + -- Reads the next directory entry. If no such entry is there, an error + -- code is returned in Status. + + overriding procedure Reset (Dir : in out VFS_Directory_Handle); + -- Resets the handle to the first node + + overriding procedure Close (Dir : in out VFS_Directory_Handle); + -- Closes the handle, and free the associated resources. + + function Open + (Path : String; + Handle : out Any_Directory_Handle) + return Status_Code; + + function Open + (Path : String; + Mode : File_Mode; + Handle : out Any_File_Handle) + return Status_Code; + + Mount_Points : Mount_Array; + + Handles : array (1 .. 2) of aliased VFS_Directory_Handle; + + function Name (Point : Mount_Record) return Mount_Path; + procedure Set_Name (Point : in out Mount_Record; + Path : Mount_Path); + procedure Split + (Path : String; + FS : out Any_Filesystem_Driver; + Start_Index : out Natural); + + ---------- + -- Open -- + ---------- + + function Open + (File : in out File_Descriptor; + Name : String; + Mode : File_Mode) + return Status_Code + is + Ret : Status_Code; + begin + if Is_Open (File) then + return Invalid_Parameter; + end if; + Ret := Open (Name, Mode, File.Handle); + + if Ret /= OK then + File.Handle := null; + end if; + + return Ret; + end Open; + + ----------- + -- Close -- + ----------- + + procedure Close (File : in out File_Descriptor) is + begin + if File.Handle /= null then + File.Handle.Close; + File.Handle := null; + end if; + end Close; + + ------------- + -- Is_Open -- + ------------- + + function Is_Open + (File : File_Descriptor) + return Boolean + is (File.Handle /= null); + + ----------- + -- Flush -- + ----------- + + function Flush + (File : File_Descriptor) + return Status_Code + is + begin + if File.Handle /= null then + return Convert (File.Handle.Flush); + else + return Invalid_Parameter; + end if; + end Flush; + + ---------- + -- Size -- + ---------- + + function Size + (File : File_Descriptor) + return File_Size + is + begin + if File.Handle = null then + return 0; + else + return Convert (File.Handle.Size); + end if; + end Size; + + ---------- + -- Read -- + ---------- + + function Read + (File : File_Descriptor; + Addr : System.Address; + Length : File_Size) + return File_Size + is + Ret : HALFS.File_Size; + Status : Status_Code; + begin + if File.Handle = null then + return 0; + end if; + + Ret := Convert (Length); + Status := Convert (File.Handle.Read (Addr, Ret)); + + if Status /= OK then + return 0; + else + return Convert (Ret); + end if; + end Read; + + ----------- + -- Write -- + ----------- + + function Write + (File : File_Descriptor; + Addr : System.Address; + Length : File_Size) + return File_Size + is + Ret : HALFS.File_Size; + Status : Status_Code; + begin + if File.Handle = null then + return 0; + end if; + + Ret := Convert (Length); + Status := Convert (File.Handle.Write (Addr, Ret)); + + if Status /= OK then + return 0; + else + return Convert (Ret); + end if; + end Write; + + ------------ + -- Offset -- + ------------ + + function Offset + (File : File_Descriptor) + return File_Size + is + begin + if File.Handle /= null then + return Convert (File.Handle.Offset); + else + return 0; + end if; + end Offset; + + ---------- + -- Seek -- + ---------- + + function Seek + (File : in out File_Descriptor; + Origin : Seek_Mode; + Amount : in out File_Size) + return Status_Code + is + Ret : Status_Code; + HALFS_Amount : HALFS.File_Size; + begin + if File.Handle /= null then + HALFS_Amount := Convert (Amount); + Ret := Convert (File.Handle.Seek (Convert (Origin), HALFS_Amount)); + Amount := Convert (HALFS_Amount); + return Ret; + else + return Invalid_Parameter; + end if; + end Seek; + + ------------------- + -- Generic_Write -- + ------------------- + + function Generic_Write + (File : File_Descriptor; + Value : T) + return Status_Code + is + begin + if File.Handle /= null then + return Convert (File.Handle.Write (Value'Address, T'Size / 8)); + else + return Invalid_Parameter; + end if; + end Generic_Write; + + ------------------ + -- Generic_Read -- + ------------------ + + function Generic_Read + (File : File_Descriptor; + Value : out T) + return Status_Code + is + L : HALFS.File_Size := T'Size / 8; + begin + if File.Handle /= null then + return Convert (File.Handle.Read (Value'Address, L)); + else + return Invalid_Parameter; + end if; + end Generic_Read; + + ---------- + -- Open -- + ---------- + + function Open + (Dir : in out Directory_Descriptor; + Name : String) + return Status_Code + is + Ret : Status_Code; + begin + if Dir.Handle /= null then + return Invalid_Parameter; + end if; + Ret := Open (Name, Dir.Handle); + + if Ret /= OK then + Dir.Handle := null; + end if; + + return Ret; + end Open; + + ----------- + -- Close -- + ----------- + + procedure Close (Dir : in out Directory_Descriptor) is + begin + if Dir.Handle /= null then + Dir.Handle.Close; + end if; + end Close; + + ---------- + -- Read -- + ---------- + + function Read (Dir : in out Directory_Descriptor) + return Directory_Entry + is + Node : Any_Node_Handle; + Status : Status_Code; + begin + if Dir.Handle = null then + return Invalid_Dir_Entry; + end if; + + Status := Convert (Dir.Handle.Read (Node)); + if Status /= OK then + return Invalid_Dir_Entry; + end if; + + declare + Name : constant String := Node.Basename; + Ret : Directory_Entry (Name_Length => Name'Length); + begin + Ret.Name := Name; + Ret.Subdirectory := Node.Is_Subdirectory; + Ret.Read_Only := Node.Is_Read_Only; + Ret.Hidden := Node.Is_Hidden; + Ret.Symlink := Node.Is_Symlink; + Ret.Size := Convert (Node.Size); + Node.Close; + return Ret;" +function To_Data is new Ada.Unchecked_Conversion,"(FAT_Directory_Entry, Entry_Data); + function To_Data is new Ada.Unchecked_Conversion + (VFAT_Directory_Entry, Entry_Data); + + function Find_Empty_Entry_Sequence + (Parent : access FAT_Directory_Handle; + Num_Entries : Natural) return Entry_Index; + -- Finds a sequence of deleted entries that can fit Num_Entries. + -- Returns the first entry of this sequence + + -------------- + -- Set_Size -- + -------------- + + procedure Set_Size + (E : in out FAT_Node; + Size : FAT_File_Size) + is + begin + if E.Size /= Size then + E.Size := Size; + E.Is_Dirty := True; + end if; + end Set_Size; + + ---------- + -- Find -- + ---------- + + function Find + (Parent : FAT_Node; + Filename : FAT_Name; + DEntry : out FAT_Node) return Status_Code + is + -- We use a copy of the handle, so as not to touch the state of initial + -- handle + Status : Status_Code; + Cluster : Cluster_Type := Parent.Start_Cluster; + Block : Block_Offset := Parent.FS.Cluster_To_Block (Cluster); + Index : Entry_Index := 0; + + begin + loop + Status := Next_Entry + (FS => Parent.FS, + Current_Cluster => Cluster, + Current_Block => Block, + Current_Index => Index, + DEntry => DEntry); + + if Status /= OK then + return No_Such_File; + end if; + + if Long_Name (DEntry) = Filename or else + (DEntry.L_Name.Len = 0 and then Short_Name (DEntry) = Filename) + then + return OK; + end if; + end loop; + end Find; + + ---------- + -- Find -- + ---------- + + function Find + (FS : in out FAT_Filesystem; + Path : String; + DEntry : out FAT_Node) return Status_Code + is + Status : Status_Code; + Idx : Natural; -- Idx is used to walk through the Path + Token : FAT_Name; + + begin + DEntry := Root_Entry (FS); + + -- Looping through the Path. We start at 2 as we ignore the initial '/' + Idx := Path'First + 1; + + while Idx <= Path'Last loop + Token.Len := 0; + + for J in Idx .. Path'Last loop + if Path (J) = '/' then + exit; + end if; + + Token.Len := Token.Len + 1; + Token.Name (Token.Len) := Path (J); + end loop; + + Idx := Idx + Token.Len + 1; + + Status := Find (DEntry, Token, DEntry); + + if Status /= OK then + return No_Such_File; + end if; + + if Idx < Path'Last then + -- Intermediate entry: needs to be a directory + if not Is_Subdirectory (DEntry) then + return No_Such_Path; + end if; + end if; + end loop; + + return OK; + end Find; + + ------------------ + -- Update_Entry -- + ------------------ + + function Update_Entry + (Parent : FAT_Node; + Value : in out FAT_Node) return Status_Code + is + subtype Entry_Block is Block (1 .. 32); + function To_Block is new + Ada.Unchecked_Conversion (FAT_Directory_Entry, Entry_Block); + function To_Entry is new + Ada.Unchecked_Conversion (Entry_Block, FAT_Directory_Entry); + + Ent : FAT_Directory_Entry; + Cluster : Cluster_Type := Parent.Start_Cluster; + Offset : FAT_File_Size := FAT_File_Size (Value.Index) * 32; + Block_Off : Natural; + Block : Block_Offset; + Ret : Status_Code; + + begin + if not Value.Is_Dirty then + return OK; + end if; + + while Offset > Parent.FS.Cluster_Size loop + Cluster := Parent.FS.Get_FAT (Cluster); + Offset := Offset - Parent.FS.Cluster_Size; + end loop; + + Block := Block_Offset (Offset / Parent.FS.Block_Size); + Block_Off := Natural (Offset mod Parent.FS.Block_Size); + + Ret := Parent.FS.Ensure_Block + (Parent.FS.Cluster_To_Block (Cluster) + Block); + if Ret /= OK then + return Ret; + end if; + + Ent := To_Entry (Parent.FS.Window (Block_Off .. Block_Off + 31)); + + -- For now only the size can be modified, so just apply this + -- modification + Ent.Size := Value.Size; + Value.Is_Dirty := False; + + Parent.FS.Window (Block_Off .. Block_Off + 31) := To_Block (Ent); + Ret := Parent.FS.Write_Window; + + return Ret; + end Update_Entry; + + ---------------- + -- Root_Entry -- + ---------------- + + function Root_Entry (FS : in out FAT_Filesystem) return FAT_Node + is + Ret : FAT_Node; + begin + Ret.FS := FS'Unchecked_Access; + Ret.Attributes := (Subdirectory => True, + others => False); + Ret.Is_Root := True; + Ret.L_Name := (Name => (others => ' '), + Len => 0); + if FS.Version = FAT16 then + Ret.Start_Cluster := 0; + else + Ret.Start_Cluster := FS.Root_Dir_Cluster; + end if; + Ret.Index := 0; + + return Ret; + end Root_Entry; + + ---------------- + -- Next_Entry -- + ---------------- + + function Next_Entry + (FS : access FAT_Filesystem; + Current_Cluster : in out Cluster_Type; + Current_Block : in out Block_Offset; + Current_Index : in out Entry_Index; + DEntry : out FAT_Directory_Entry) return Status_Code + is + subtype Entry_Data is Block (1 .. 32); + function To_Entry is new Ada.Unchecked_Conversion + (Entry_Data, FAT_Directory_Entry); + + Ret : Status_Code; + Block_Off : Natural; + + begin + if Current_Index = 16#FFFF# then + return No_More_Entries; + end if; + + if Current_Cluster = 0 and then FS.Version = FAT16 then + if Current_Index > + Entry_Index (FS.FAT16_Root_Dir_Num_Entries) + then + return No_More_Entries; + else + Block_Off := + Natural (FAT_File_Size (Current_Index * 32) mod + FS.Block_Size); + Current_Block := + FS.Root_Dir_Area + + Block_Offset + (FAT_File_Size (Current_Index * 32) / FS.Block_Size); + end if; + + else + Block_Off := Natural + (FAT_File_Size (Current_Index * 32) mod FS.Block_Size); + + -- Check if we're on a block boundare + if Unsigned_32 (Block_Off) = 0 and then Current_Index /= 0 then + Current_Block := Current_Block + 1; + end if; + + -- Check if we're on the boundary of a new cluster + if Current_Block - FS.Cluster_To_Block (Current_Cluster) + = FS.Blocks_Per_Cluster + then + -- The block we need to read is outside of the current cluster. + -- Let's move on to the next + + -- Read the FAT table to determine the next cluster + Current_Cluster := FS.Get_FAT (Current_Cluster); + + if Current_Cluster = 1 + or else FS.Is_Last_Cluster (Current_Cluster) + then + return Internal_Error; + end if; + + Current_Block := FS.Cluster_To_Block (Current_Cluster); + end if; + end if; + + Ret := FS.Ensure_Block (Current_Block); + + if Ret /= OK then + return Ret; + end if; + + if FS.Window (Block_Off) = 0 then + -- End of entries: we stick the index here to make sure that further + -- calls to Next_Entry always end-up here + return No_More_Entries; + end if; + + DEntry := To_Entry (FS.Window (Block_Off .. Block_Off + 31)); + Current_Index := Current_Index + 1; + + return OK; + end Next_Entry; + + ---------------- + -- Next_Entry -- + ---------------- + + function Next_Entry + (FS : access FAT_Filesystem; + Current_Cluster : in out Cluster_Type; + Current_Block : in out Block_Offset; + Current_Index : in out Entry_Index; + DEntry : out FAT_Node) return Status_Code + is + procedure Prepend + (Name : Wide_String; + Full : in out String; + Idx : in out Natural); + -- Prepends Name to Full + + ------------- + -- Prepend -- + ------------- + + procedure Prepend + (Name : Wide_String; + Full : in out String; + Idx : in out Natural) + is + Val : Unsigned_16; + begin + for J in reverse Name'Range loop + Val := Wide_Character'Pos (Name (J)); + if Val /= 16#FFFF# + and then Val /= 0 + then + Idx := Idx - 1; + + exit when Idx not in Full'Range; + + if Val < 255 then + Full (Idx) := Character'Val (Val); + elsif Val = 16#F029# then + -- Path ends with a '.' + Full (Idx) := '.'; + elsif Val = 16#F028# then + -- Path ends with a ' ' + Full (Idx) := ' '; + else + Full (Idx) := '?'; + end if; + end if; + end loop; + end Prepend; + + Ret : Status_Code; + D_Entry : FAT_Directory_Entry; + V_Entry : VFAT_Directory_Entry; + function To_VFAT_Entry is new Ada.Unchecked_Conversion + (FAT_Directory_Entry, VFAT_Directory_Entry); + + C : Unsigned_8; + Last_Seq : VFAT_Sequence_Number := 0; + CRC : Unsigned_8 := 0; + Matches : Boolean; + Current_CRC : Unsigned_8; + L_Name : String (1 .. MAX_FILENAME_LENGTH); + L_Name_First : Natural; + + begin + L_Name_First := L_Name'Last + 1; + + loop + Ret := Next_Entry + (FS, + Current_Cluster => Current_Cluster, + Current_Block => Current_Block, + Current_Index => Current_Index, + DEntry => D_Entry); + + if Ret /= OK then + return Ret; + end if; + + -- Check if we have a VFAT entry here by checking that the + -- attributes are 16#0F# (e.g. all attributes set except + -- subdirectory and archive) + if D_Entry.Attributes = VFAT_Directory_Entry_Attribute then + V_Entry := To_VFAT_Entry (D_Entry); + + if V_Entry.VFAT_Attr.Stop_Bit then + L_Name_First := L_Name'Last + 1; + + else + if Last_Seq = 0 + or else Last_Seq - 1 /= V_Entry.VFAT_Attr.Sequence + then + L_Name_First := L_Name'Last + 1; + end if; + end if; + + Last_Seq := V_Entry.VFAT_Attr.Sequence; + + Prepend (V_Entry.Name_3, L_Name, L_Name_First); + Prepend (V_Entry.Name_2, L_Name, L_Name_First); + Prepend (V_Entry.Name_1, L_Name, L_Name_First); + + if V_Entry.VFAT_Attr.Sequence = 1 then + CRC := V_Entry.Checksum; + end if; + + -- Ignore Volumes and deleted files + elsif not D_Entry.Attributes.Volume_Label + and then Character'Pos (D_Entry.Filename (1)) /= 16#E5# + then + if L_Name_First not in L_Name'Range then + Matches := False; + else + Current_CRC := 0; + Last_Seq := 0; + + for Ch of String'(D_Entry.Filename & D_Entry.Extension) loop + C := Character'Enum_Rep (Ch); + Current_CRC := Shift_Right (Current_CRC and 16#FE#, 1) + or Shift_Left (Current_CRC and 16#01#, 7); + -- Modulo addition + Current_CRC := Current_CRC + C; + end loop; + + Matches := Current_CRC = CRC; + end if; + + DEntry := + (FS => FAT_Filesystem_Access (FS), + L_Name => <>, + S_Name => D_Entry.Filename, + S_Name_Ext => D_Entry.Extension, + Attributes => D_Entry.Attributes, + Start_Cluster => (if FS.Version = FAT16 + then Cluster_Type (D_Entry.Cluster_L) + else Cluster_Type (D_Entry.Cluster_L) or + Shift_Left + (Cluster_Type (D_Entry.Cluster_H), 16)), + Size => D_Entry.Size, + Index => Current_Index - 1, + Is_Root => False, + Is_Dirty => False); + + if Matches then + DEntry.L_Name := -L_Name (L_Name_First .. L_Name'Last); + else + DEntry.L_Name.Len := 0; + end if; + + return OK; + end if; + end loop; + end Next_Entry; + + ---------- + -- Read -- + ---------- + + function Read + (Dir : in out FAT_Directory_Handle; + DEntry : out FAT_Node) return Status_Code + is + begin + return Next_Entry + (Dir.FS, + Current_Cluster => Dir.Current_Cluster, + Current_Block => Dir.Current_Block, + Current_Index => Dir.Current_Index, + DEntry => DEntry); + end Read; + + ------------------- + -- Create_Subdir -- + ------------------- + + function Create_Subdir + (Dir : FAT_Node; + Name : FAT_Name; + New_Dir : out FAT_Node) return Status_Code + is + Handle : FAT_Directory_Handle_Access; + Ret : Status_Code; + Block : Block_Offset; + Dot : FAT_Directory_Entry; + Dot_Dot : FAT_Directory_Entry; + + begin + Ret := Dir.FAT_Open (Handle); + + if Ret /= OK then + return Ret; + end if; + + Ret := Allocate_Entry + (Parent => Handle, + Name => Name, + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => True, + Archive => False), + E => New_Dir); + + if Ret /= OK then + return Ret; + end if; + + Block := Dir.FS.Cluster_To_Block (New_Dir.Start_Cluster); + Ret := Handle.FS.Ensure_Block (Block); + if Ret /= OK then + return Ret; + end if; + + -- Allocate '.', '..' and the directory entry terminator + Dot := + (Filename => (1 => '.', others => ' '), + Extension => (others => ' '), + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => True, + Archive => False), + Reserved => (others => ASCII.NUL), + Cluster_H => + Unsigned_16 + (Shift_Right + (Unsigned_32 + (New_Dir.Start_Cluster) and 16#FFFF_0000#, 16)), + Time => 0, + Date => 0, + Cluster_L => Unsigned_16 (New_Dir.Start_Cluster and 16#FFFF#), + Size => 0); + Dot_Dot := + (Filename => (1 .. 2 => '.', others => ' '), + Extension => (others => ' '), + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => True, + Archive => False), + Reserved => (others => ASCII.NUL), + Cluster_H => + Unsigned_16 + (Shift_Right + (Unsigned_32 (Handle.Start_Cluster) and 16#FFFF_0000#, 16)), + Time => 0, + Date => 0, + Cluster_L => Unsigned_16 (Handle.Start_Cluster and 16#FFFF#), + Size => 0); + + Handle.FS.Window (0 .. 31) := To_Data (Dot); + Handle.FS.Window (32 .. 63) := To_Data (Dot_Dot); + Handle.FS.Window (64 .. 95) := (others => 0); + Ret := Handle.FS.Write_Window; + + Close (Handle.all); + + return Ret; + end Create_Subdir; + + ---------------------- + -- Create_File_Node -- + ---------------------- + + function Create_File_Node + (Dir : FAT_Node; + Name : FAT_Name; + New_File : out FAT_Node) return Status_Code + is + Handle : FAT_Directory_Handle_Access; + Ret : Status_Code; + + begin + Ret := Dir.FAT_Open (Handle); + + if Ret /= OK then + return Ret; + end if; + + Ret := Allocate_Entry + (Parent => Handle, + Name => Name, + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => False, + Archive => True), + E => New_File); + + Close (Handle.all); + + if Ret /= OK then + return Ret; + end if; + + return Ret; + end Create_File_Node; + + ------------------- + -- Delete_Subdir -- + ------------------- + + function Delete_Subdir + (Dir : FAT_Node; + Recursive : Boolean) return Status_Code + is + Parent : FAT_Node; + Handle : FAT_Directory_Handle_Access; + Ent : FAT_Node; + Ret : Status_Code; + + begin + Ret := Dir.FAT_Open (Handle); + + if Ret /= OK then + return Ret; + end if; + + while Read (Handle.all, Ent) = OK loop + if -Long_Name (Ent) = ""."" then + null; + elsif -Long_Name (Ent) = "".."" then + Parent := Ent; + elsif not Recursive then + return Non_Empty_Directory; + else + if Ent.Attributes.Subdirectory then + Ret := Delete_Subdir (Ent, True); + else + Ret := Delete_Entry (Dir, Ent); + end if; + + if Ret /= OK then + Close (Handle.all); + + return Ret; + end if; + end if; + end loop; + + Close (Handle.all); + + -- Free the clusters associated to the subdirectory + Ret := Delete_Entry (Parent, Dir); + + if Ret /= OK then + return Ret; + end if; + + return Ret; + end Delete_Subdir; + + ------------------ + -- Delete_Entry -- + ------------------ + + function Delete_Entry + (Dir : FAT_Node; + Ent : FAT_Node) return Status_Code + is + Current : Cluster_Type := Ent.Start_Cluster; + Handle : FAT_Directory_Handle_Access; + Next : Cluster_Type; + Child_Ent : FAT_Node; + Ret : Status_Code; + Block_Off : Natural; + + begin + -- Mark the entry's cluster chain as available + loop + Next := Ent.FS.Get_FAT (Current); + Ret := Ent.FS.Set_FAT (Current, FREE_CLUSTER_VALUE); + + exit when Ret /= OK; + exit when Ent.FS.Is_Last_Cluster (Next); + Current := Next; + end loop; + + -- Mark the parent's entry as deleted + Ret := Dir.FAT_Open (Handle); + if Ret /= OK then + return Ret; + end if; + + while Read (Handle.all, Child_Ent) = OK loop + if Long_Name (Child_Ent) = Long_Name (Ent) then + Block_Off := Natural + ((FAT_File_Size (Handle.Current_Index - 1) * 32) + mod Dir.FS.Block_Size); + -- Mark the entry as deleted: first basename character set to + -- 16#E5# + Handle.FS.Window (Block_Off) := 16#E5#; + Ret := Handle.FS.Write_Window; + + exit; + end if; + end loop; + + Close (Handle.all); + + return Ret; + end Delete_Entry; + + --------------------- + -- Adjust_Clusters -- + --------------------- + + function Adjust_Clusters (Ent : FAT_Node) return Status_Code + is + B_Per_Cluster : constant FAT_File_Size := + FAT_File_Size (Ent.FS.Blocks_Per_Cluster) * + Ent.FS.Block_Size; + Size : FAT_File_Size := Ent.Size; + Current : Cluster_Type := Ent.Start_Cluster; + Next : Cluster_Type; + Ret : Status_Code := OK; + + begin + if Ent.Attributes.Subdirectory then + -- ??? Do nothing for now + return OK; + end if; + + loop + Next := Ent.FS.Get_FAT (Current); + + if Size > B_Per_Cluster then + -- Current cluster is fully used + Size := Size - B_Per_Cluster; + elsif Size > 0 or else Current = Ent.Start_Cluster then + -- Partially used cluster, but the last one + Size := 0; + if Next /= LAST_CLUSTER_VALUE then + Ret := Ent.FS.Set_FAT (Current, LAST_CLUSTER_VALUE); + end if; + else + -- We don't need more clusters + Ret := Ent.FS.Set_FAT (Current, FREE_CLUSTER_VALUE); + end if; + + exit when Ret /= OK; + exit when Ent.FS.Is_Last_Cluster (Next); + Current := Next; + Size := Size - B_Per_Cluster; + end loop; + + return Ret; + end Adjust_Clusters; + + ------------------------------- + -- Find_Empty_Entry_Sequence -- + ------------------------------- + + function Find_Empty_Entry_Sequence + (Parent : access FAT_Directory_Handle; + Num_Entries : Natural) return Entry_Index + is + Status : Status_Code; + D_Entry : FAT_Directory_Entry; + Sequence : Natural := 0; + Ret : Entry_Index; + Cluster : Cluster_Type := Parent.Start_Cluster; + Block : Block_Offset := Cluster_To_Block (Parent.FS.all, Cluster); + begin + Parent.Current_Index := 0; + loop + Status := Next_Entry + (Parent.FS, + Current_Cluster => Cluster, + Current_Block => Block, + Current_Index => Parent.Current_Index, + DEntry => D_Entry); + + if Status /= OK then + return Null_Index; + end if; + + if D_Entry.Attributes = VFAT_Directory_Entry_Attribute then + if Sequence = 0 then + -- Parent.Current_Index points to the next unread value. + -- So the just read entry is at Parent.Current_Index - 1 + Ret := Parent.Current_Index - 1; + end if; + + Sequence := Sequence + 1; + + elsif Character'Pos (D_Entry.Filename (1)) = 16#E5# then + -- A deleted entry has been found + if Sequence >= Num_Entries then + return Ret; + else + Sequence := 0; + end if; + + else + Sequence := 0; + end if; + end loop; + end Find_Empty_Entry_Sequence; + + -------------------- + -- Allocate_Entry -- + -------------------- + + function Allocate_Entry + (Parent : access FAT_Directory_Handle; + Name : FAT_Name; + Attributes : FAT_Directory_Entry_Attribute; + E : out FAT_Node) return Status_Code + is + subtype Short_Name is String (1 .. 8); + subtype Extension is String (1 .. 3); + + function Is_Legal_Character (C : Character) return Boolean + is (C in 'A' .. 'Z' + or else C in '0' .. '9' + or else C = '!' + or else C = '#' + or else C = '$' + or else C = '%' + or else C = '&' + or else C = ''' + or else C = '(' + or else C = ')' + or else C = '-' + or else C = '@' + or else C = '^' + or else C = '_' + or else C = '`' + or else C = '{' + or else C = '}' + or else C = '~'); + + Block_Off : Natural; + Status : Status_Code; + DEntry : FAT_Node; + SName : Short_Name := (others => ' '); + SExt : Extension := (others => ' '); + Index : Entry_Index; + + -- Retrieve the number of VFAT entries that are needed, plus one for + -- the regular FAT entry. + N_Entries : Natural := Get_Num_VFAT_Entries (Name) + 1; + Bytes : Entry_Data; + + procedure To_Short_Name + (Name : FAT_Name; + SName : out Short_Name; + Ext : out Extension); + -- Translates a long name into short 8.3 name + -- If the long name is mixed or lower case. then 8.3 will be uppercased + -- If the long name contains characters not allowed in an 8.3 name, then + -- the name is stripped of invalid characters such as space and extra + -- periods. Other unknown characters are changed to underscores. + -- The stripped name is then truncated, followed by a ~1. Inc_SName + -- below will increase the digit number in case there's overloaded 8.3 + -- names. + -- If the long name is longer than 8.3, then ~1 suffix will also be + -- used. + + function To_Upper (C : Character) return Character is + (if C in 'a' .. 'z' + then Character'Val + (Character'Pos (C) + Character'Pos ('A') - Character'Pos ('a')) + else C); + + function Value (S : String) return Natural; + -- For a positive int represented in S, returns its value + + procedure Inc_SName (SName : in out String); + -- Increment the suffix of the short FAT name + -- e.g.: + -- ABCDEFGH => ABCDEF~1 + -- ABC => ABC~1 + -- ABC~9 => ABC~10 + -- ABCDEF~9 => ABCDE~10 + + procedure To_WString + (S : FAT_Name; + Idx : in out Natural; + WS : in out Wide_String); + -- Dumps S (Idx .. Idx + WS'Length - 1) into WS and increments Idx + + ----------- + -- Value -- + ----------- + + function Value (S : String) return Natural + is + Val : constant String := Trim (S); + Digit : Natural; + Ret : Natural := 0; + begin + for J in Val'Range loop + Digit := Character'Pos (Val (J)) - Character'Pos ('0'); + Ret := Ret * 10 + Digit; + end loop; + + return Ret; + end Value; + + ------------------- + -- To_Short_Name -- + ------------------- + + procedure To_Short_Name + (Name : FAT_Name; + SName : out Short_Name; + Ext : out Extension) + is + S_Idx : Natural := 0; + Add_Tilde : Boolean := False; + Last : Natural := Name.Len; + + begin + -- Copy the file extension + + Ext := (others => ' '); + + for J in reverse 1 .. Name.Len loop + if Name.Name (J) = '.' then + if J = Name.Len then + -- Take care of names ending with a '.' (e.g. no extension, + -- the final '.' is part of the basename) + Last := J; + Ext := (others => ' '); + else + Last := J - 1; + S_Idx := Ext'First; + + for K in J + 1 .. Name.Len loop + Ext (S_Idx) := To_Upper (Name.Name (K)); + S_Idx := S_Idx + 1; + -- In case the extension is more than 3 characters, we + -- keep the first 3 ones. + exit when S_Idx > Ext'Last; + end loop; + end if; + + exit; + end if; + end loop; + + S_Idx := 0; + SName := (others => ' '); + + for J in 1 .. Last loop + exit when Add_Tilde and then S_Idx >= 6; + exit when not Add_Tilde and then S_Idx = 8; + + if Name.Name (J) in 'a' .. 'z' then + S_Idx := S_Idx + 1; + SName (S_Idx) := To_Upper (Name.Name (J)); + + elsif Is_Legal_Character (Name.Name (J)) then + S_Idx := S_Idx + 1; + SName (S_Idx) := Name.Name (J); + + elsif Name.Name (J) = '.' + or else Name.Name (J) = ' ' + then + -- dots that are not used as extension delimiters are invalid + -- in FAT short names and ignored in long names to short names + -- translation + Add_Tilde := True; + + else + -- Any other character is translated as '_' + Add_Tilde := True; + S_Idx := S_Idx + 1; + SName (S_Idx) := '_'; + end if; + end loop; + + if Add_Tilde then + if S_Idx >= 6 then + SName (7 .. 8) := ""~1""; + else + SName (S_Idx + 1 .. S_Idx + 2) := ""~1""; + end if; + end if; + end To_Short_Name; + + --------------- + -- Inc_SName -- + --------------- + + procedure Inc_SName (SName : in out String) + is + Idx : Natural := 0; + Num : Natural := 0; + + begin + for J in reverse SName'Range loop + if Idx = 0 then + if SName (J) = ' ' then + null; + elsif SName (J) in '0' .. '9' then + Idx := J; + else + SName (SName'Last - 1 .. SName'Last) := ""~1""; + + return; + end if; + + elsif SName (J) in '0' .. '9' then + Idx := J; + + elsif SName (J) = '~' then + Num := Value (SName (Idx .. SName'Last)) + 1; + -- make Idx point to '~' + Idx := J; + + declare + N_Suffix : String := Natural'Image (Num); + begin + N_Suffix (N_Suffix'First) := '~'; + + if Idx + N_Suffix'Length - 1 > SName'Last then + SName (SName'Last - N_Suffix'Length + 1 .. SName'Last) := + N_Suffix; + else + SName (Idx .. Idx + N_Suffix'Length - 1) := N_Suffix; + end if; + + return;" +function To_Disk_Parameter is new Ada.Unchecked_Conversion,"(Disk_Parameter_Block, FAT_Disk_Parameter); + + subtype FSInfo_Block is Block (0 .. 11); + function To_FSInfo is new Ada.Unchecked_Conversion + (FSInfo_Block, FAT_FS_Info); + + begin + FS.Window_Block := 16#FFFF_FFFF#; + Status := FS.Ensure_Block (0); + + if Status /= OK then + return; + end if; + + if FS.Window (510 .. 511) /= (16#55#, 16#AA#) then + Status := No_Filesystem; + return; + end if; + + FS.Disk_Parameters := + To_Disk_Parameter (FS.Window (0 .. 91)); + + if FS.Version = FAT32 then + Status := + FS.Ensure_Block (Block_Offset (FS.FSInfo_Block_Number)); + + if Status /= OK then + return; + end if; + + -- Check the generic FAT block signature + if FS.Window (510 .. 511) /= (16#55#, 16#AA#) then + Status := No_Filesystem; + return; + end if; + + FS.FSInfo := + To_FSInfo (FS.Window (16#1E4# .. 16#1EF#)); + FS.FSInfo_Changed := False; + end if; + + declare + FAT_Size_In_Block : constant Unsigned_32 := + FS.FAT_Table_Size_In_Blocks * + Unsigned_32 (FS.Number_Of_FATs); + Root_Dir_Size : Block_Offset; + begin + FS.FAT_Addr := Block_Offset (FS.Reserved_Blocks); + FS.Data_Area := FS.FAT_Addr + Block_Offset (FAT_Size_In_Block); + + if FS.Version = FAT16 then + -- Add space for the root directory + FS.Root_Dir_Area := FS.Data_Area; + Root_Dir_Size := + (Block_Offset (FS.FAT16_Root_Dir_Num_Entries) * 32 + + Block_Offset (FS.Block_Size) - 1) / + Block_Offset (FS.Block_Size); + -- Align on clusters + Root_Dir_Size := + ((Root_Dir_Size + FS.Blocks_Per_Cluster - 1) / + FS.Blocks_Per_Cluster) * + FS.Blocks_Per_Cluster; + + FS.Data_Area := FS.Data_Area + Root_Dir_Size; + end if; + + FS.Num_Clusters := + Cluster_Type + ((FS.Total_Number_Of_Blocks - Unsigned_32 (FS.Data_Area)) / + Unsigned_32 (FS.Blocks_Per_Cluster));" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2ENR.USART1EN := True; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1ENR.USART2EN := True; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1ENR.USART3EN := True; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1ENR.UART4EN := True; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1ENR.UART5EN := True; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2ENR.USART6EN := True; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1ENR.UART7ENR := True; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1ENR.UART8ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2RSTR.USART1RST := True; + RCC_Periph.APB2RSTR.USART1RST := False; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1RSTR.UART2RST := True; + RCC_Periph.APB1RSTR.UART2RST := False; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1RSTR.UART3RST := True; + RCC_Periph.APB1RSTR.UART3RST := False; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1RSTR.UART4RST := True; + RCC_Periph.APB1RSTR.UART4RST := False; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1RSTR.UART5RST := True; + RCC_Periph.APB1RSTR.UART5RST := False; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2RSTR.USART6RST := True; + RCC_Periph.APB2RSTR.USART6RST := False; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1RSTR.UART7RST := True; + RCC_Periph.APB1RSTR.UART7RST := False; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1RSTR.UART8RST := True; + RCC_Periph.APB1RSTR.UART8RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out SPI_Port'Class) is + begin + if This'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SAI_Port) + is + begin + pragma Assert (This'Address = SAI_Base); + RCC_Periph.APB2ENR.SAI1EN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SAI_Port) + is + begin + pragma Assert (This'Address = SAI_Base); + RCC_Periph.APB2RSTR.SAI1RST := True; + RCC_Periph.APB2RSTR.SAI1RST := False; + end Reset; + + --------------------- + -- Get_Input_Clock -- + --------------------- + + function Get_Input_Clock (Periph : SAI_Port) return UInt32 + is + Input_Selector : UInt2; + VCO_Input : UInt32; + SAI_First_Level : UInt32; + begin + if Periph'Address /= SAI_Base then + raise Unknown_Device; + end if; + + Input_Selector := RCC_Periph.DCKCFGR.SAI1ASRC; + + -- This driver doesn't support external source clock + if Input_Selector > 1 then + raise Constraint_Error + with ""External PLL SAI source clock unsupported""; + end if; + + if not RCC_Periph.PLLCFGR.PLLSRC then + -- PLLSAI SRC is HSI + VCO_Input := HSI_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + else + -- PLLSAI SRC is HSE + VCO_Input := HSE_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + end if; + + if Input_Selector = 0 then + -- PLLSAI is the clock source + + -- VCO out = VCO in & PLLSAIN + -- SAI firstlevel = VCO out / PLLSAIQ + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIN) / + UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIQ); + + -- SAI frequency is SAI First level / PLLSAIDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DCKCFGR.PLLSAIDIVQ); + + else + -- PLLI2S as clock source + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SN) / + UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SQ); + -- SAI frequency is SAI First level / PLLI2SDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DCKCFGR.PLLIS2DIVQ + 1); + end if; + end Get_Input_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDIO_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2ENR.SDIOEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDIO_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2RSTR.SDIORST := True; + RCC_Periph.APB2RSTR.SDIORST := False; + end Reset; + + ---------------------- + -- Set_Clock_Source -- + ---------------------- + + procedure Set_Clock_Source + (This : in out SDMMC_Controller; + Src : SDIO_Clock_Source) + is + Src_Val : constant Boolean := Src = Src_Sysclk; + begin + if This.Periph.all'Address /= SDIO_Base then + raise Unknown_Device; + end if; + + RCC_Periph.DCKCFGR.SDMMCSEL := Src_Val; + + case Src is + when Src_Sysclk => + STM32.SDMMC.Set_Clk_Src_Speed + (This, System_Clock_Frequencies.SYSCLK); + when Src_48Mhz => + STM32.SDMMC.Set_Clk_Src_Speed + (This, 48_000_000); + end case; + end Set_Clock_Source; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + +-- procedure Enable_Clock (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2ENR.USART1EN := True; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1ENR.USART2EN := True; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1ENR.USART3EN := True; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1ENR.UART4EN := True; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1ENR.UART5EN := True; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2ENR.USART6EN := True; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1ENR.UART7ENR := True; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1ENR.UART8ENR := True; +-- else +-- raise Unknown_Device; +-- end if; +-- end Enable_Clock; + + ----------- + -- Reset -- + ----------- + +-- procedure Reset (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2RSTR.USART1RST := True; +-- RCC_Periph.APB2RSTR.USART1RST := False; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1RSTR.UART2RST := True; +-- RCC_Periph.APB1RSTR.UART2RST := False; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1RSTR.UART3RST := True; +-- RCC_Periph.APB1RSTR.UART3RST := False; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1RSTR.UART4RST := True; +-- RCC_Periph.APB1RSTR.UART4RST := False; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1RSTR.UART5RST := True; +-- RCC_Periph.APB1RSTR.UART5RST := False; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2RSTR.USART6RST := True; +-- RCC_Periph.APB2RSTR.USART6RST := False; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1RSTR.UART7RST := True; +-- RCC_Periph.APB1RSTR.UART7RST := False; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1RSTR.UART8RST := True; +-- RCC_Periph.APB1RSTR.UART8RST := False; +-- else +-- raise Unknown_Device; +-- end if; +-- end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + elsif Port.Periph.all'Address = I2C4_Base then + return I2C_Id_4; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + when I2C_Id_4 => + RCC_Periph.APB1ENR.I2C4EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + when I2C_Id_4 => + RCC_Periph.APB1RSTR.I2C4RST := True; + RCC_Periph.APB1RSTR.I2C4RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2ENR.SAI1EN := True; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2ENR.SAI2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2RSTR.SAI1RST := True; + RCC_Periph.APB2RSTR.SAI1RST := False; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2RSTR.SAI2RST := True; + RCC_Periph.APB2RSTR.SAI2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + --------------------- + -- Get_Input_Clock -- + --------------------- + + function Get_Input_Clock (Periph : SAI_Port) return UInt32 + is + Input_Selector : UInt2; + VCO_Input : UInt32; + SAI_First_Level : UInt32; + begin + if Periph'Address = SAI1_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI1SEL; + elsif Periph'Address = SAI2_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI2SEL; + else + raise Unknown_Device; + end if; + + + -- This driver doesn't support external source clock + if Input_Selector > 1 then + raise Constraint_Error + with ""External PLL SAI source clock unsupported""; + end if; + + if not RCC_Periph.PLLCFGR.PLLSRC then + -- PLLSAI SRC is HSI + VCO_Input := HSI_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + else + -- PLLSAI SRC is HSE + VCO_Input := HSE_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + end if; + + if Input_Selector = 0 then + -- PLLSAI is the clock source + + -- VCO out = VCO in & PLLSAIN + -- SAI firstlevel = VCO out / PLLSAIQ + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIN) / + UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIQ); + + -- SAI frequency is SAI First level / PLLSAIDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLSAIDIVQ); + + else + -- PLLI2S as clock source + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SN) / + UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SQ); + -- SAI frequency is SAI First level / PLLI2SDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLI2SDIV + 1); + end if; + end Get_Input_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address = SDMMC1_Base then + RCC_Periph.APB2ENR.SDMMC1EN := True; + elsif This.Periph.all'Address = SDMMC2_Base then + RCC_Periph.APB2ENR.SDMMC2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address = SDMMC1_Base then + RCC_Periph.APB2RSTR.SDMMC1RST := True; + RCC_Periph.APB2RSTR.SDMMC1RST := False; + elsif This.Periph.all'Address = SDMMC2_Base then + RCC_Periph.APB2RSTR.SDMMC2RST := True; + RCC_Periph.APB2RSTR.SDMMC2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------------- + -- Set_Clock_Source -- + ---------------------- + + procedure Set_Clock_Source + (This : in out SDMMC_Controller; + Src : SDMMC_Clock_Source) + is + Sel_Value : constant Boolean := Src = Src_Sysclk; + begin + if This.Periph.all'Address = SDMMC1_Base then + RCC_Periph.DKCFGR2.SDMMC1SEL := Sel_Value; + elsif This.Periph.all'Address = SDMMC2_Base then + RCC_Periph.DKCFGR2.SDMMC2SEL := Sel_Value; + else + raise Unknown_Device; + end if; + + case Src is + when Src_Sysclk => + STM32.SDMMC.Set_Clk_Src_Speed + (This, System_Clock_Frequencies.SYSCLK); + when Src_48Mhz => + STM32.SDMMC.Set_Clk_Src_Speed + (This, 48_000_000); + end case; + end Set_Clock_Source; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2ENR.USART1EN := True; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1ENR.USART2EN := True; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1ENR.USART3EN := True; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2ENR.USART6EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2RSTR.USART1RST := True; + RCC_Periph.APB2RSTR.USART1RST := False; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1RSTR.UART2RST := True; + RCC_Periph.APB1RSTR.UART2RST := False; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1RSTR.UART3RST := True; + RCC_Periph.APB1RSTR.UART3RST := False; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2RSTR.USART6RST := True; + RCC_Periph.APB2RSTR.USART6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1ENR.SPI3EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant + UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant + UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2ENR.USART1EN := True; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1ENR.USART2EN := True; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1ENR.USART3EN := True; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1ENR.UART4EN := True; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1ENR.UART5EN := True; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2ENR.USART6EN := True; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1ENR.UART7ENR := True; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1ENR.UART8ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2RSTR.USART1RST := True; + RCC_Periph.APB2RSTR.USART1RST := False; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1RSTR.UART2RST := True; + RCC_Periph.APB1RSTR.UART2RST := False; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1RSTR.UART3RST := True; + RCC_Periph.APB1RSTR.UART3RST := False; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1RSTR.UART4RST := True; + RCC_Periph.APB1RSTR.UART4RST := False; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1RSTR.UART5RST := True; + RCC_Periph.APB1RSTR.UART5RST := False; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2RSTR.USART6RST := True; + RCC_Periph.APB2RSTR.USART6RST := False; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1RSTR.UART7RST := True; + RCC_Periph.APB1RSTR.UART7RST := False; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1RSTR.UART8RST := True; + RCC_Periph.APB1RSTR.UART8RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + +-- procedure Enable_Clock (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2ENR.USART1EN := True; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1ENR.USART2EN := True; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1ENR.USART3EN := True; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1ENR.UART4EN := True; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1ENR.UART5EN := True; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2ENR.USART6EN := True; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1ENR.UART7ENR := True; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1ENR.UART8ENR := True; +-- else +-- raise Unknown_Device; +-- end if; +-- end Enable_Clock; + + ----------- + -- Reset -- + ----------- + +-- procedure Reset (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2RSTR.USART1RST := True; +-- RCC_Periph.APB2RSTR.USART1RST := False; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1RSTR.UART2RST := True; +-- RCC_Periph.APB1RSTR.UART2RST := False; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1RSTR.UART3RST := True; +-- RCC_Periph.APB1RSTR.UART3RST := False; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1RSTR.UART4RST := True; +-- RCC_Periph.APB1RSTR.UART4RST := False; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1RSTR.UART5RST := True; +-- RCC_Periph.APB1RSTR.UART5RST := False; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2RSTR.USART6RST := True; +-- RCC_Periph.APB2RSTR.USART6RST := False; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1RSTR.UART7RST := True; +-- RCC_Periph.APB1RSTR.UART7RST := False; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1RSTR.UART8RST := True; +-- RCC_Periph.APB1RSTR.UART8RST := False; +-- else +-- raise Unknown_Device; +-- end if; +-- end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + elsif Port.Periph.all'Address = I2C4_Base then + return I2C_Id_4; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + when I2C_Id_4 => + RCC_Periph.APB1ENR.I2C4EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + when I2C_Id_4 => + RCC_Periph.APB1RSTR.I2C4RST := True; + RCC_Periph.APB1RSTR.I2C4RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2ENR.SAI1EN := True; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2ENR.SAI2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2RSTR.SAI1RST := True; + RCC_Periph.APB2RSTR.SAI1RST := False; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2RSTR.SAI2RST := True; + RCC_Periph.APB2RSTR.SAI2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + --------------------- + -- Get_Input_Clock -- + --------------------- + + function Get_Input_Clock (Periph : SAI_Port) return UInt32 + is + Input_Selector : UInt2; + VCO_Input : UInt32; + SAI_First_Level : UInt32; + begin + if Periph'Address = SAI1_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI1SEL; + elsif Periph'Address = SAI2_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI2SEL; + else + raise Unknown_Device; + end if; + + + -- This driver doesn't support external source clock + if Input_Selector > 1 then + raise Constraint_Error + with ""External PLL SAI source clock unsupported""; + end if; + + if not RCC_Periph.PLLCFGR.PLLSRC then + -- PLLSAI SRC is HSI + VCO_Input := HSI_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + else + -- PLLSAI SRC is HSE + VCO_Input := HSE_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + end if; + + if Input_Selector = 0 then + -- PLLSAI is the clock source + + -- VCO out = VCO in & PLLSAIN + -- SAI firstlevel = VCO out / PLLSAIQ + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIN) / + UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIQ); + + -- SAI frequency is SAI First level / PLLSAIDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLSAIDIVQ); + + else + -- PLLI2S as clock source + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SN) / + UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SQ); + -- SAI frequency is SAI First level / PLLI2SDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLI2SDIV + 1); + end if; + end Get_Input_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDMMC_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2ENR.SDMMC1EN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDMMC_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2RSTR.SDMMC1RST := True; + RCC_Periph.APB2RSTR.SDMMC1RST := False; + end Reset; + + ---------------------- + -- Set_Clock_Source -- + ---------------------- + + procedure Set_Clock_Source + (This : in out SDMMC_Controller; + Src : SDMMC_Clock_Source) + is + begin + if This.Periph.all'Address /= SDMMC_Base then + raise Unknown_Device; + end if; + + RCC_Periph.DKCFGR2.SDMMCSEL := Src = Src_Sysclk; + + case Src is + when Src_Sysclk => + STM32.SDMMC.Set_Clk_Src_Speed + (This, System_Clock_Frequencies.SYSCLK); + when Src_48Mhz => + STM32.SDMMC.Set_Clk_Src_Speed + (This, 48_000_000); + end case; + end Set_Clock_Source; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Disable,"(This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.EN1 := False; + when Channel_2 => + This.CR.EN2 := False; + end case; + end Disable; + + ------------- + -- Enabled -- + ------------- + + function Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean is + begin + case Channel is + when Channel_1 => + return This.CR.EN1; + when Channel_2 => + return This.CR.EN2; + end case; + end Enabled; + + ---------------- + -- Set_Output -- + ---------------- + + procedure Set_Output + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel; + Value : UInt32; + Resolution : DAC_Resolution; + Alignment : Data_Alignment) + is + begin + case Channel is + + when Channel_1 => + case Resolution is + when DAC_Resolution_12_Bits => + case Alignment is + when Left_Aligned => + This.DHR12L1.DACC1DHR := + UInt12 (Value and Max_12bit_Resolution); + when Right_Aligned => + This.DHR12R1.DACC1DHR := + UInt12 (Value and Max_12bit_Resolution); + end case; + when DAC_Resolution_8_Bits => + This.DHR8R1.DACC1DHR := UInt8 (Value and Max_8bit_Resolution); + end case; + + when Channel_2 => + case Resolution is + when DAC_Resolution_12_Bits => + case Alignment is + when Left_Aligned => + This.DHR12L2.DACC2DHR := + UInt12 (Value and Max_12bit_Resolution); + when Right_Aligned => + This.DHR12R2.DACC2DHR := + UInt12 (Value and Max_12bit_Resolution); + end case; + when DAC_Resolution_8_Bits => + This.DHR8R2.DACC2DHR := UInt8 (Value and Max_8bit_Resolution); + end case; + + end case; + end Set_Output; + + ------------------------------------ + -- Trigger_Conversion_By_Software -- + ------------------------------------ + + procedure Trigger_Conversion_By_Software + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.SWTRIGR.SWTRIG.Arr (1) := True; -- cleared by hardware + when Channel_2 => + This.SWTRIGR.SWTRIG.Arr (2) := True; -- cleared by hardware + end case; + end Trigger_Conversion_By_Software; + + ---------------------------- + -- Converted_Output_Value -- + ---------------------------- + + function Converted_Output_Value + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return UInt32 + is + begin + case Channel is + when Channel_1 => + return UInt32 (This.DOR1.DACC1DOR); + when Channel_2 => + return UInt32 (This.DOR2.DACC2DOR); + end case; + end Converted_Output_Value; + + ------------------------------ + -- Set_Dual_Output_Voltages -- + ------------------------------ + + procedure Set_Dual_Output_Voltages + (This : in out Digital_To_Analog_Converter; + Channel_1_Value : UInt32; + Channel_2_Value : UInt32; + Resolution : DAC_Resolution; + Alignment : Data_Alignment) + is + begin + case Resolution is + when DAC_Resolution_12_Bits => + case Alignment is + when Left_Aligned => + This.DHR12LD.DACC1DHR := + UInt12 (Channel_1_Value and Max_12bit_Resolution); + This.DHR12LD.DACC2DHR := + UInt12 (Channel_2_Value and Max_12bit_Resolution); + when Right_Aligned => + This.DHR12RD.DACC1DHR := + UInt12 (Channel_1_Value and Max_12bit_Resolution); + This.DHR12RD.DACC2DHR := + UInt12 (Channel_2_Value and Max_12bit_Resolution); + end case; + when DAC_Resolution_8_Bits => + This.DHR8RD.DACC1DHR := + UInt8 (Channel_1_Value and Max_8bit_Resolution); + This.DHR8RD.DACC2DHR := + UInt8 (Channel_2_Value and Max_8bit_Resolution); + end case; + end Set_Dual_Output_Voltages; + + --------------------------------- + -- Converted_Dual_Output_Value -- + --------------------------------- + + function Converted_Dual_Output_Value (This : Digital_To_Analog_Converter) + return Dual_Channel_Output + is + Result : Dual_Channel_Output; + begin + Result.Channel_1_Data := UInt16 (This.DOR1.DACC1DOR); + Result.Channel_2_Data := UInt16 (This.DOR2.DACC2DOR); + return Result; + end Converted_Dual_Output_Value; + + -------------------------- + -- Enable_Output_Buffer -- + -------------------------- + + procedure Enable_Output_Buffer + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.BOFF1 := True; + when Channel_2 => + This.CR.BOFF2 := True; + end case; + end Enable_Output_Buffer; + + --------------------------- + -- Disable_Output_Buffer -- + --------------------------- + + procedure Disable_Output_Buffer + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.BOFF1 := False; + when Channel_2 => + This.CR.BOFF2 := False; + end case; + end Disable_Output_Buffer; + + --------------------------- + -- Output_Buffer_Enabled -- + --------------------------- + + function Output_Buffer_Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean + is + begin + case Channel is + when Channel_1 => + return This.CR.BOFF1; + when Channel_2 => + return This.CR.BOFF2; + end case; + end Output_Buffer_Enabled; + + -------------------- + -- Select_Trigger -- + -------------------- + + procedure Select_Trigger + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel; + Trigger : External_Event_Trigger_Selection) + is + begin + case Channel is + when Channel_1 => + This.CR.TSEL1 := + External_Event_Trigger_Selection'Enum_Rep (Trigger); + when Channel_2 => + This.CR.TSEL2 := + External_Event_Trigger_Selection'Enum_Rep (Trigger); + end case; + end Select_Trigger; + + ----------------------- + -- Trigger_Selection -- + ----------------------- + + function Trigger_Selection + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return External_Event_Trigger_Selection + is + begin + case Channel is + when Channel_1 => + return External_Event_Trigger_Selection'Val (This.CR.TSEL1); + when Channel_2 => + return External_Event_Trigger_Selection'Val (This.CR.TSEL2); + end case; + end Trigger_Selection; + + -------------------- + -- Enable_Trigger -- + -------------------- + + procedure Enable_Trigger + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.TEN1 := True; + when Channel_2 => + This.CR.TEN2 := True; + end case; + end Enable_Trigger; + + --------------------- + -- Disable_Trigger -- + --------------------- + + procedure Disable_Trigger + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.TEN1 := False; + when Channel_2 => + This.CR.TEN2 := False; + end case; + end Disable_Trigger; + + --------------------- + -- Trigger_Enabled -- + --------------------- + + function Trigger_Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean + is + begin + case Channel is + when Channel_1 => + return This.CR.TEN1; + when Channel_2 => + return This.CR.TEN2; + end case; + end Trigger_Enabled; + + ---------------- + -- Enable_DMA -- + ---------------- + + procedure Enable_DMA + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.DMAEN1 := True; + when Channel_2 => + This.CR.DMAEN2 := True; + end case; + end Enable_DMA; + + ----------------- + -- Disable_DMA -- + ----------------- + + procedure Disable_DMA + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.DMAEN1 := False; + when Channel_2 => + This.CR.DMAEN2 := False; + end case; + end Disable_DMA; + + ----------------- + -- DMA_Enabled -- + ----------------- + + function DMA_Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean + is + begin + case Channel is + when Channel_1 => + return This.CR.DMAEN1; + when Channel_2 => + return This.CR.DMAEN2; + end case; + end DMA_Enabled; + + ------------ + -- Status -- + ------------ + + function Status + (This : Digital_To_Analog_Converter; + Flag : DAC_Status_Flag) + return Boolean + is + begin + case Flag is + when DMA_Underrun_Channel_1 => + return This.SR.DMAUDR1; + when DMA_Underrun_Channel_2 => + return This.SR.DMAUDR2; + end case; + end Status; + + ------------------ + -- Clear_Status -- + ------------------ + + procedure Clear_Status + (This : in out Digital_To_Analog_Converter; + Flag : DAC_Status_Flag) + is + begin + case Flag is + when DMA_Underrun_Channel_1 => + This.SR.DMAUDR1 := True; -- set to 1 to clear + when DMA_Underrun_Channel_2 => + This.SR.DMAUDR2 := True; -- set to 1 to clear + end case; + end Clear_Status; + + ----------------------- + -- Enable_Interrupts -- + ----------------------- + + procedure Enable_Interrupts + (This : in out Digital_To_Analog_Converter; + Source : DAC_Interrupts) + is + begin + case Source is + when DMA_Underrun_Channel_1 => + This.CR.DMAUDRIE1 := True; + when DMA_Underrun_Channel_2 => + This.CR.DMAUDRIE2 := True; + end case; + end Enable_Interrupts; + + ------------------------ + -- Disable_Interrupts -- + ------------------------ + + procedure Disable_Interrupts + (This : in out Digital_To_Analog_Converter; + Source : DAC_Interrupts) + is + begin + case Source is + when DMA_Underrun_Channel_1 => + This.CR.DMAUDRIE1 := False; + when DMA_Underrun_Channel_2 => + This.CR.DMAUDRIE2 := False; + end case; + end Disable_Interrupts; + + ----------------------- + -- Interrupt_Enabled -- + ----------------------- + + function Interrupt_Enabled + (This : Digital_To_Analog_Converter; + Source : DAC_Interrupts) + return Boolean + is + begin + case Source is + when DMA_Underrun_Channel_1 => + return This.CR.DMAUDRIE1; + when DMA_Underrun_Channel_2 => + return This.CR.DMAUDRIE2; + end case; + end Interrupt_Enabled; + + ---------------------- + -- Interrupt_Source -- + ---------------------- + + function Interrupt_Source + (This : Digital_To_Analog_Converter) + return DAC_Interrupts + is + begin + if This.CR.DMAUDRIE1 then + return DMA_Underrun_Channel_1; + else + return DMA_Underrun_Channel_2; + end if; + end Interrupt_Source; + + ----------------------------- + -- Clear_Interrupt_Pending -- + ----------------------------- + + procedure Clear_Interrupt_Pending + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.SR.DMAUDR1 := False; + when Channel_2 => + This.SR.DMAUDR2 := False; + end case; + end Clear_Interrupt_Pending; + + ---------------------------- + -- Select_Wave_Generation -- + ---------------------------- + + procedure Select_Wave_Generation + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel; + Selection : Wave_Generation) + is + + function As_UInt4 is new Ada.Unchecked_Conversion + (Source => Noise_Wave_Mask_Selection, Target => UInt4); + + function As_UInt4 is new Ada.Unchecked_Conversion + (Source => Triangle_Wave_Amplitude_Selection, Target => UInt4); + + begin + case Channel is + when Channel_1 => + This.CR.WAVE1 := + Wave_Generation_Selection'Enum_Rep (Selection.Kind); + when Channel_2 => + This.CR.WAVE2 := + Wave_Generation_Selection'Enum_Rep (Selection.Kind); + end case; + + case Selection.Kind is + + when No_Wave_Generation => + null; + + when Noise_Wave => + case Channel is + when Channel_1 => + This.CR.MAMP1 := As_UInt4 (Selection.Mask); + when Channel_2 => + This.CR.MAMP2 := As_UInt4 (Selection.Mask); + end case; + + when Triangle_Wave => + case Channel is + when Channel_1 => + This.CR.MAMP1 := As_UInt4 (Selection.Amplitude); + when Channel_2 => + This.CR.MAMP2 := As_UInt4 (Selection.Amplitude); + end case; + + end case; + end Select_Wave_Generation; + + ------------------------------ + -- Selected_Wave_Generation -- + ------------------------------ + + function Selected_Wave_Generation + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Wave_Generation + is + Kind : Wave_Generation_Selection; + + function As_Mask is new Ada.Unchecked_Conversion + (Target => Noise_Wave_Mask_Selection, Source => UInt4); + + function As_Amplitude is new Ada.Unchecked_Conversion + (Target => Triangle_Wave_Amplitude_Selection, Source => UInt4); + + begin + case Channel is + when Channel_1 => + Kind := Wave_Generation_Selection'Val (This.CR.WAVE1); + when Channel_2 => + Kind := Wave_Generation_Selection'Val (This.CR.WAVE2); + end case; + declare + Result : Wave_Generation (Kind); + begin + case Kind is + when No_Wave_Generation => + null; + + when Noise_Wave => + case Channel is + when Channel_1 => + Result.Mask := As_Mask (This.CR.MAMP1); + when Channel_2 => + Result.Mask := As_Mask (This.CR.MAMP2); + end case; + + when Triangle_Wave => + case Channel is + when Channel_1 => + Result.Amplitude := As_Amplitude (This.CR.MAMP1); + when Channel_2 => + Result.Amplitude := As_Amplitude (This.CR.MAMP2); + end case; + end case; + + return Result;" +procedure Disable (This : in out Analog_To_Digital_Converter) is,"begin + This.CR2.ADON := False; + end Disable; + + ------------- + -- Enabled -- + ------------- + + function Enabled (This : Analog_To_Digital_Converter) return Boolean is + (This.CR2.ADON); + + ---------------------- + -- Conversion_Value -- + ---------------------- + + function Conversion_Value + (This : Analog_To_Digital_Converter) + return UInt16 + is + begin + return This.DR.DATA; + end Conversion_Value; + + --------------------------- + -- Data_Register_Address -- + --------------------------- + + function Data_Register_Address + (This : Analog_To_Digital_Converter) + return System.Address + is + (This.DR'Address); + + ------------------------------- + -- Injected_Conversion_Value -- + ------------------------------- + + function Injected_Conversion_Value + (This : Analog_To_Digital_Converter; + Rank : Injected_Channel_Rank) + return UInt16 + is + begin + case Rank is + when 1 => + return This.JDR1.JDATA; + when 2 => + return This.JDR2.JDATA; + when 3 => + return This.JDR3.JDATA; + when 4 => + return This.JDR4.JDATA; + end case; + end Injected_Conversion_Value; + + -------------------------------- + -- Multimode_Conversion_Value -- + -------------------------------- + + function Multimode_Conversion_Value return UInt32 is + (C_ADC_Periph.CDR.Val); + + -------------------- + -- Configure_Unit -- + -------------------- + + procedure Configure_Unit + (This : in out Analog_To_Digital_Converter; + Resolution : ADC_Resolution; + Alignment : Data_Alignment) + is + begin + This.CR1.RES := ADC_Resolution'Enum_Rep (Resolution); + This.CR2.ALIGN := Alignment = Left_Aligned; + end Configure_Unit; + + ------------------------ + -- Current_Resolution -- + ------------------------ + + function Current_Resolution + (This : Analog_To_Digital_Converter) + return ADC_Resolution + is (ADC_Resolution'Val (This.CR1.RES)); + + ----------------------- + -- Current_Alignment -- + ----------------------- + + function Current_Alignment + (This : Analog_To_Digital_Converter) + return Data_Alignment + is ((if This.CR2.ALIGN then Left_Aligned else Right_Aligned)); + + --------------------------------- + -- Configure_Common_Properties -- + --------------------------------- + + procedure Configure_Common_Properties + (Mode : Multi_ADC_Mode_Selections; + Prescalar : ADC_Prescalars; + DMA_Mode : Multi_ADC_DMA_Modes; + Sampling_Delay : Sampling_Delay_Selections) + is + begin + C_ADC_Periph.CCR.MULT := Multi_ADC_Mode_Selections'Enum_Rep (Mode); + C_ADC_Periph.CCR.DELAY_k := + Sampling_Delay_Selections'Enum_Rep (Sampling_Delay); + C_ADC_Periph.CCR.DMA := Multi_ADC_DMA_Modes'Enum_Rep (DMA_Mode); + C_ADC_Periph.CCR.ADCPRE := ADC_Prescalars'Enum_Rep (Prescalar); + end Configure_Common_Properties; + + ----------------------------------- + -- Configure_Regular_Conversions -- + ----------------------------------- + + procedure Configure_Regular_Conversions + (This : in out Analog_To_Digital_Converter; + Continuous : Boolean; + Trigger : Regular_Channel_Conversion_Trigger; + Enable_EOC : Boolean; + Conversions : Regular_Channel_Conversions) + is + begin + This.CR2.EOCS := Enable_EOC; + This.CR2.CONT := Continuous; + + This.CR1.SCAN := Conversions'Length > 1; + + if Trigger.Enabler /= Trigger_Disabled then + This.CR2.EXTSEL := External_Events_Regular_Group'Enum_Rep (Trigger.Event); + This.CR2.EXTEN := External_Trigger'Enum_Rep (Trigger.Enabler); + else + This.CR2.EXTSEL := 0; + This.CR2.EXTEN := 0; + end if; + + for Rank in Conversions'Range loop + declare + Conversion : Regular_Channel_Conversion renames Conversions (Rank); + begin + Configure_Regular_Channel + (This, Conversion.Channel, Rank, Conversion.Sample_Time); + + -- We check the VBat first because that channel is also used for + -- the temperature sensor channel on some MCUs, in which case the + -- VBat conversion is the only one done. This order reflects that + -- hardware behavior. + if VBat_Conversion (This, Conversion.Channel) then + Enable_VBat_Connection; + elsif VRef_TemperatureSensor_Conversion (This, Conversion.Channel) + then + Enable_VRef_TemperatureSensor_Connection; + end if;" +procedure Disable_Interrupt,"(This : in out SDMMC_Controller; + Interrupt : SDMMC_Interrupts) + is + begin + case Interrupt is + when Data_End_Interrupt => + This.Periph.MASK.DATAENDIE := False; + when Data_CRC_Fail_Interrupt => + This.Periph.MASK.DCRCFAILIE := False; + when Data_Timeout_Interrupt => + This.Periph.MASK.DTIMEOUTIE := False; + when TX_FIFO_Empty_Interrupt => + This.Periph.MASK.TXFIFOEIE := False; + when RX_FIFO_Full_Interrupt => + This.Periph.MASK.RXFIFOFIE := False; + when TX_Underrun_Interrupt => + This.Periph.MASK.TXUNDERRIE := False; + when RX_Overrun_Interrupt => + This.Periph.MASK.RXOVERRIE := False; + end case; + end Disable_Interrupt; + + ------------------------ + -- Delay_Milliseconds -- + ------------------------ + + overriding procedure Delay_Milliseconds + (This : SDMMC_Controller; + Amount : Natural) + is + pragma Unreferenced (This); + begin + delay until Clock + Milliseconds (Amount); + end Delay_Milliseconds; + + ----------- + -- Reset -- + ----------- + + overriding procedure Reset + (This : in out SDMMC_Controller; + Status : out SD_Error) + is + begin + -- Make sure the POWER register is writable by waiting a bit after + -- the Power_Off command + DCTRL_Write_Delay; + + This.Periph.POWER.PWRCTRL := Power_Off; + + -- Use the Default SDMMC peripheral configuration for SD card init + This.Periph.CLKCR := (others => <>); + This.Set_Clock (400_000); + This.Periph.DTIMER := SD_DATATIMEOUT; + + This.Periph.CLKCR.CLKEN := False; + DCTRL_Write_Delay; + This.Periph.POWER.PWRCTRL := Power_On; + + -- Wait for the clock to stabilize. + DCTRL_Write_Delay; + + This.Periph.CLKCR.CLKEN := True; + + delay until Clock + Milliseconds (20); + + Status := OK; + end Reset; + + --------------- + -- Set_Clock -- + --------------- + + overriding procedure Set_Clock + (This : in out SDMMC_Controller; + Freq : Natural) + is + Div : UInt32; + CLKCR : CLKCR_Register; + begin + Div := (This.CLK_In + UInt32 (Freq) - 1) / UInt32 (Freq); + + -- Make sure the POWER register is writable by waiting a bit after + -- the Power_Off command + DCTRL_Write_Delay; + + if Div <= 1 then + This.Periph.CLKCR.BYPASS := True; + else + Div := Div - 2; + CLKCR := This.Periph.CLKCR; + CLKCR.BYPASS := False; + + if Div > UInt32 (CLKCR_CLKDIV_Field'Last) then + CLKCR.CLKDIV := CLKCR_CLKDIV_Field'Last; + else + CLKCR.CLKDIV := CLKCR_CLKDIV_Field (Div); + end if; + + This.Periph.CLKCR := CLKCR; + end if; + end Set_Clock; + + ------------------ + -- Set_Bus_Size -- + ------------------ + + overriding procedure Set_Bus_Size + (This : in out SDMMC_Controller; + Mode : Wide_Bus_Mode) + is + function To_WIDBUS_Field is new Ada.Unchecked_Conversion + (Wide_Bus_Mode, CLKCR_WIDBUS_Field); + begin + This.Periph.CLKCR.WIDBUS := To_WIDBUS_Field (Mode); + end Set_Bus_Size; + + ------------------ + -- Send_Command -- + ------------------ + + overriding procedure Send_Cmd + (This : in out SDMMC_Controller; + Cmd : Cmd_Desc_Type; + Arg : UInt32; + Status : out SD_Error) + is + CMD_Reg : CMD_Register := This.Periph.CMD; + begin + if Cmd.Rsp = Rsp_Invalid or else Cmd.Tfr = Tfr_Invalid then + raise Program_Error with ""Not implemented""; + end if; + + This.Periph.ARG := Arg; + CMD_Reg.CMDINDEX := CMD_CMDINDEX_Field (Cmd.Cmd); + CMD_Reg.WAITRESP := (case Cmd.Rsp is + when Rsp_No => No_Response, + when Rsp_R2 => Long_Response, + when others => Short_Response); + CMD_Reg.WAITINT := False; + CMD_Reg.CPSMEN := True; + This.Periph.CMD := CMD_Reg; + + case Cmd.Rsp is + when Rsp_No => + Status := This.Command_Error; + + when Rsp_R1 | Rsp_R1B => + Status := This.Response_R1_Error (Cmd.Cmd); + + when Rsp_R2 => + Status := This.Response_R2_Error; + + when Rsp_R3 => + Status := This.Response_R3_Error; + + when Rsp_R6 => + declare + RCA : UInt32; + begin + Status := This.Response_R6_Error (Cmd.Cmd, RCA); + This.RCA := UInt16 (Shift_Right (RCA, 16));" +procedure Disable_Data,"(This : in out SDMMC_Controller) + is + begin + This.Periph.DCTRL := (others => <>); + end Disable_Data; + + -------------------------- + -- Enable_DMA_Transfers -- + -------------------------- + + procedure Enable_DMA_Transfers + (This : in out SDMMC_Controller; + RX_Int : not null STM32.DMA.Interrupts.DMA_Interrupt_Controller_Access; + TX_Int : not null STM32.DMA.Interrupts.DMA_Interrupt_Controller_Access; + SD_Int : not null STM32.SDMMC_Interrupt.SDMMC_Interrupt_Handler_Access) + is + begin + This.TX_DMA_Int := TX_Int; + This.RX_DMA_Int := RX_Int; + This.SD_Int := SD_Int; + end Enable_DMA_Transfers; + + -------------------------- + -- Has_Card_Information -- + -------------------------- + + function Has_Card_Information + (This : SDMMC_Controller) + return Boolean + is (This.Has_Info); + + ---------------------- + -- Card_Information -- + ---------------------- + + function Card_Information + (This : SDMMC_Controller) + return HAL.SDMMC.Card_Information + is + begin + return This.Info; + end Card_Information; + + ---------------------------- + -- Clear_Card_Information -- + ---------------------------- + + procedure Clear_Card_Information + (This : in out SDMMC_Controller) + is + begin + This.Has_Info := False; + end Clear_Card_Information; + + --------------- + -- Read_FIFO -- + --------------- + + function Read_FIFO + (Controller : in out SDMMC_Controller) return UInt32 + is + begin + return Controller.Periph.FIFO; + end Read_FIFO; + + ------------------- + -- Command_Error -- + ------------------- + + function Command_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + Start : constant Time := Clock; + begin + while not Controller.Periph.STA.CMDSENT loop + if Clock - Start > Milliseconds (1000) then + return Timeout_Error; + end if; + end loop; + + Clear_Static_Flags (Controller); + + return OK; + end Command_Error; + + ----------------------- + -- Response_R1_Error -- + ----------------------- + + function Response_R1_Error + (Controller : in out SDMMC_Controller; + Command_Index : SD_Command) return SD_Error + is + Start : constant Time := Clock; + Timeout : Boolean := False; + R1 : UInt32; + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + if Clock - Start > Milliseconds (1000) then + Timeout := True; + + exit; + end if; + end loop; + + if Timeout or else Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + end if; + + if SD_Command (Controller.Periph.RESPCMD.RESPCMD) /= + Command_Index + then + return Illegal_Cmd; + end if; + + Clear_Static_Flags (Controller); + + R1 := Controller.Periph.RESP1; + + if (R1 and SD_OCR_ERRORMASK) = 0 then + return OK; + end if; + + if (R1 and SD_OCR_ADDR_OUT_OF_RANGE) /= 0 then + return Address_Out_Of_Range; + elsif (R1 and SD_OCR_ADDR_MISALIGNED) /= 0 then + return Address_Missaligned; + elsif (R1 and SD_OCR_BLOCK_LEN_ERR) /= 0 then + return Block_Length_Error; + elsif (R1 and SD_OCR_ERASE_SEQ_ERR) /= 0 then + return Erase_Seq_Error; + elsif (R1 and SD_OCR_BAD_ERASE_PARAM) /= 0 then + return Bad_Erase_Parameter; + elsif (R1 and SD_OCR_WRITE_PROT_VIOLATION) /= 0 then + return Write_Protection_Violation; + elsif (R1 and SD_OCR_LOCK_UNLOCK_FAILED) /= 0 then + return Lock_Unlock_Failed; + elsif (R1 and SD_OCR_COM_CRC_FAILED) /= 0 then + return CRC_Check_Fail; + elsif (R1 and SD_OCR_ILLEGAL_CMD) /= 0 then + return Illegal_Cmd; + elsif (R1 and SD_OCR_CARD_ECC_FAILED) /= 0 then + return Card_ECC_Failed; + elsif (R1 and SD_OCR_CC_ERROR) /= 0 then + return CC_Error; + elsif (R1 and SD_OCR_GENERAL_UNKNOWN_ERROR) /= 0 then + return General_Unknown_Error; + elsif (R1 and SD_OCR_STREAM_READ_UNDERRUN) /= 0 then + return Stream_Read_Underrun; + elsif (R1 and SD_OCR_STREAM_WRITE_UNDERRUN) /= 0 then + return Stream_Write_Underrun; + elsif (R1 and SD_OCR_CID_CSD_OVERWRITE) /= 0 then + return CID_CSD_Overwrite; + elsif (R1 and SD_OCR_WP_ERASE_SKIP) /= 0 then + return WP_Erase_Skip; + elsif (R1 and SD_OCR_CARD_ECC_DISABLED) /= 0 then + return Card_ECC_Disabled; + elsif (R1 and SD_OCR_ERASE_RESET) /= 0 then + return Erase_Reset; + elsif (R1 and SD_OCR_AKE_SEQ_ERROR) /= 0 then + return AKE_SEQ_Error; + else + return General_Unknown_Error; + end if; + end Response_R1_Error; + + ----------------------- + -- Response_R2_Error -- + ----------------------- + + function Response_R2_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + null; + end loop; + + if Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + end if; + + Clear_Static_Flags (Controller); + + return OK; + end Response_R2_Error; + + ----------------------- + -- Response_R3_Error -- + ----------------------- + + function Response_R3_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + null; + end loop; + + if Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + end if; + + Clear_Static_Flags (Controller); + + return OK; + end Response_R3_Error; + + ----------------------- + -- Response_R6_Error -- + ----------------------- + + function Response_R6_Error + (Controller : in out SDMMC_Controller; + Command_Index : SD_Command; + RCA : out UInt32) return SD_Error + is + Response : UInt32; + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + null; + end loop; + + if Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + end if; + + if SD_Command (Controller.Periph.RESPCMD.RESPCMD) /= + Command_Index + then + return Illegal_Cmd; + end if; + + Clear_Static_Flags (Controller); + + Response := Controller.Periph.RESP1; + + if (Response and SD_R6_Illegal_Cmd) = SD_R6_Illegal_Cmd then + return Illegal_Cmd; + + elsif (Response and SD_R6_General_Unknown_Error) = + SD_R6_General_Unknown_Error + then + return General_Unknown_Error; + + elsif (Response and SD_R6_Com_CRC_Failed) = SD_R6_Com_CRC_Failed then + return CRC_Check_Fail; + end if; + + RCA := Response and 16#FFFF_0000#; + + return OK; + end Response_R6_Error; + + ----------------------- + -- Response_R7_Error -- + ----------------------- + + function Response_R7_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + Start : constant Time := Clock; + Timeout : Boolean := False; + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + if Clock - Start > Milliseconds (1000) then + Timeout := True; + + exit; + end if; + end loop; + + if Timeout or else Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + + elsif Controller.Periph.STA.CMDREND then + Controller.Periph.ICR.CMDRENDC := True; + + return OK; + + else + return Error; + end if; + end Response_R7_Error; + + ------------------- + -- Stop_Transfer -- + ------------------- + + function Stop_Transfer + (This : in out SDMMC_Controller) return SD_Error + is + Ret : SD_Error; + begin + Send_Cmd (This, Cmd_Desc (Stop_Transmission), 0, Ret); + + return Ret; + end Stop_Transfer; + + ----------------------- + -- Set_Clk_Src_Speed -- + ----------------------- + + procedure Set_Clk_Src_Speed + (This : in out SDMMC_Controller; + CLK : UInt32) + is + begin + This.CLK_In := CLK; + end Set_Clk_Src_Speed; + + ---------------- + -- Initialize -- + ---------------- + + function Initialize + (This : in out SDMMC_Controller) return SD_Error + is + Ret : SD_Error; + begin + SDMMC_Init.Card_Identification_Process (This, This.Info, Ret); + This.Card_Type := This.Info.Card_Type; + This.RCA := This.Info.RCA; + + return Ret; + end Initialize; + + ---------- + -- Read -- + ---------- + + overriding + function Read + (This : in out SDMMC_Controller; + Block_Number : UInt64; + Data : out HAL.Block_Drivers.Block) return Boolean + is + Ret : Boolean; + SD_Err : SD_Error; + DMA_Err : DMA_Error_Code; + begin + + Ensure_Card_Informations (This); + + if This.RX_DMA_Int = null or else This.SD_Int = null then + SD_Err := Read_Blocks + (This, + Block_Number * 512, + Data); + return SD_Err = OK; + end if; + + This.SD_Int.Set_Transfer_State (This); + + SD_Err := Read_Blocks_DMA + (This, + Block_Number * 512, + Data); + + if SD_Err /= OK then + This.RX_DMA_Int.Clear_Transfer_State; + This.SD_Int.Clear_Transfer_State; + This.RX_DMA_Int.Abort_Transfer (DMA_Err); + + return False; + end if; + + This.SD_Int.Wait_Transfer (SD_Err); + + if SD_Err /= OK then + This.RX_DMA_Int.Clear_Transfer_State; + else + This.RX_DMA_Int.Wait_For_Completion (DMA_Err); + + loop + exit when not Get_Flag (This, RX_Active); + end loop; + end if; + + Ret := SD_Err = OK and then DMA_Err = DMA_No_Error; + + if Last_Operation (This) = + Read_Multiple_Blocks_Operation + then + SD_Err := Stop_Transfer (This); + Ret := Ret and then SD_Err = OK; + end if; + + Clear_All_Status (This.RX_DMA_Int.Controller.all, This.RX_DMA_Int.Stream); + Disable (This.RX_DMA_Int.Controller.all, This.RX_DMA_Int.Stream); + Disable_Data (This); + Clear_Static_Flags (This); + + Cortex_M.Cache.Invalidate_DCache + (Start => Data'Address, + Len => Data'Length); + + return Ret; + end Read; + + ----------- + -- Write -- + ----------- + + overriding + function Write + (This : in out SDMMC_Controller; + Block_Number : UInt64; + Data : HAL.Block_Drivers.Block) return Boolean + is + Ret : SD_Error; + DMA_Err : DMA_Error_Code; + begin + if This.TX_DMA_Int = null then + raise Program_Error with ""No TX DMA controller""; + end if; + + if This.SD_Int = null then + raise Program_Error with ""No SD interrupt controller""; + end if; + + Ensure_Card_Informations (This); + + -- Flush the data cache + Cortex_M.Cache.Clean_DCache + (Start => Data (Data'First)'Address, + Len => Data'Length); + + This.SD_Int.Set_Transfer_State (This); + + Ret := Write_Blocks_DMA + (This, + Block_Number * 512, + Data); + -- this always leaves the last 12 byte standing. Why? + -- also...NDTR is not what it should be. + + if Ret /= OK then + This.TX_DMA_Int.Clear_Transfer_State; + This.SD_Int.Clear_Transfer_State; + This.TX_DMA_Int.Abort_Transfer (DMA_Err); + + return False; + end if; + + This.TX_DMA_Int.Wait_For_Completion (DMA_Err); -- this unblocks + This.SD_Int.Wait_Transfer (Ret); -- TX underrun! + + -- this seems slow. Do we have to wait? + loop + -- FIXME: some people claim, that this goes wrong with multiblock, see + -- http://blog.frankvh.com/2011/09/04/stm32f2xx-sdio-sd-card-interface/ + exit when not Get_Flag (This, TX_Active); + end loop; + + if Last_Operation (This) = + Write_Multiple_Blocks_Operation + then + Ret := Stop_Transfer (This); + end if; + + Clear_All_Status (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream); + Disable (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream); + + declare + Data_Incomplete : constant Boolean := + This.TX_DMA_Int.Buffer_Error and then + Items_Transferred (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream) + /= Data'Length / 4; + begin + return Ret = OK + and then DMA_Err = DMA_No_Error + and then not Data_Incomplete;" +"function To_Word is new Ada.Unchecked_Conversion (System.Address, UInt32);","function Offset (Buffer : DMA2D_Buffer; + X, Y : Integer) return UInt32 with Inline_Always; + + DMA2D_Init_Transfer_Int : DMA2D_Sync_Procedure := null; + DMA2D_Wait_Transfer_Int : DMA2D_Sync_Procedure := null; + + ------------------ + -- DMA2D_DeInit -- + ------------------ + + procedure DMA2D_DeInit is + begin + RCC_Periph.AHB1ENR.DMA2DEN := False; + DMA2D_Init_Transfer_Int := null; + DMA2D_Wait_Transfer_Int := null; + end DMA2D_DeInit; + + ---------------- + -- DMA2D_Init -- + ---------------- + + procedure DMA2D_Init + (Init : DMA2D_Sync_Procedure; + Wait : DMA2D_Sync_Procedure) + is + begin + if DMA2D_Init_Transfer_Int = Init then + return; + end if; + + DMA2D_DeInit; + + DMA2D_Init_Transfer_Int := Init; + DMA2D_Wait_Transfer_Int := Wait; + + RCC_Periph.AHB1ENR.DMA2DEN := True; + RCC_Periph.AHB1RSTR.DMA2DRST := True; + RCC_Periph.AHB1RSTR.DMA2DRST := False; + end DMA2D_Init; + + ------------ + -- Offset -- + ------------ + + function Offset (Buffer : DMA2D_Buffer; + X, Y : Integer) return UInt32 + is + Off : constant UInt32 := UInt32 (X + Buffer.Width * Y); + begin + case Buffer.Color_Mode is + when ARGB8888 => + return 4 * Off; + when RGB888 => + return 3 * Off; + when ARGB1555 | ARGB4444 | RGB565 | AL88 => + return 2 * Off; + when L8 | AL44 | A8 => + return Off; + when L4 | A4 => + return Off / 2; + end case; + end Offset; + + ---------------- + -- DMA2D_Fill -- + ---------------- + + procedure DMA2D_Fill + (Buffer : DMA2D_Buffer; + Color : UInt32; + Synchronous : Boolean := False) + is + function Conv is new Ada.Unchecked_Conversion (UInt32, OCOLR_Register); + begin + DMA2D_Wait_Transfer_Int.all; + + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (R2M); + DMA2D_Periph.OPFCCR.CM := As_UInt3 (Buffer.Color_Mode); + DMA2D_Periph.OCOLR := Conv (Color); + DMA2D_Periph.OMAR := To_Word (Buffer.Addr); + DMA2D_Periph.OOR := (LO => 0, others => <>); + DMA2D_Periph.NLR := (NL => UInt16 (Buffer.Height), + PL => UInt14 (Buffer.Width), + others => <>); + + DMA2D_Init_Transfer_Int.all; + + if Synchronous then + DMA2D_Wait_Transfer_Int.all; + end if; + end DMA2D_Fill; + + --------------------- + -- DMA2D_Fill_Rect -- + --------------------- + + procedure DMA2D_Fill_Rect + (Buffer : DMA2D_Buffer; + Color : UInt32; + X : Integer; + Y : Integer; + Width : Integer; + Height : Integer; + Synchronous : Boolean := False) + is + function Conv is new Ada.Unchecked_Conversion (UInt32, OCOLR_Register); + Off : constant UInt32 := Offset (Buffer, X, Y); + + begin + DMA2D_Wait_Transfer_Int.all; + + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (R2M); + DMA2D_Periph.OPFCCR := + (CM => DMA2D_Color_Mode'Enum_Rep (Buffer.Color_Mode), + others => <>); + DMA2D_Periph.OCOLR := Conv (Color); + DMA2D_Periph.OMAR := To_Word (Buffer.Addr) + Off; + DMA2D_Periph.OOR.LO := UInt14 (Buffer.Width - Width); + DMA2D_Periph.NLR := + (NL => UInt16 (Height), PL => UInt14 (Width), others => <>); + + DMA2D_Init_Transfer_Int.all; + if Synchronous then + DMA2D_Wait_Transfer_Int.all; + end if; + end DMA2D_Fill_Rect; + + --------------------- + -- DMA2D_Draw_Rect -- + --------------------- + + procedure DMA2D_Draw_Rect + (Buffer : DMA2D_Buffer; + Color : UInt32; + X : Integer; + Y : Integer; + Width : Integer; + Height : Integer) + is + begin + DMA2D_Draw_Horizontal_Line (Buffer, Color, X, Y, Width); + DMA2D_Draw_Horizontal_Line (Buffer, Color, X, Y + Height - 1, Width); + DMA2D_Draw_Vertical_Line (Buffer, Color, X, Y, Height); + DMA2D_Draw_Vertical_Line (Buffer, Color, X + Width - 1, Y, Height, True); + end DMA2D_Draw_Rect; + + --------------------- + -- DMA2D_Copy_Rect -- + --------------------- + + procedure DMA2D_Copy_Rect + (Src_Buffer : DMA2D_Buffer; + X_Src : Natural; + Y_Src : Natural; + Dst_Buffer : DMA2D_Buffer; + X_Dst : Natural; + Y_Dst : Natural; + Bg_Buffer : DMA2D_Buffer; + X_Bg : Natural; + Y_Bg : Natural; + Width : Natural; + Height : Natural; + Synchronous : Boolean := False) + is + Src_Off : constant UInt32 := Offset (Src_Buffer, X_Src, Y_Src); + Dst_Off : constant UInt32 := Offset (Dst_Buffer, X_Dst, Y_Dst); + begin + DMA2D_Wait_Transfer_Int.all; + + if Bg_Buffer /= Null_Buffer then + -- PFC and blending + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (M2M_BLEND); + + elsif Src_Buffer.Color_Mode = Dst_Buffer.Color_Mode then + -- Direct memory transfer + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (M2M); + else + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (M2M_PFC); + end if; + + -- SOURCE CONFIGURATION + DMA2D_Periph.FGPFCCR := + (CM => DMA2D_Color_Mode'Enum_Rep (Src_Buffer.Color_Mode), + AM => DMA2D_AM'Enum_Rep (NO_MODIF), + ALPHA => 255, + others => <>); + + if Src_Buffer.Color_Mode = L8 or else Src_Buffer.Color_Mode = L4 then + + if Src_Buffer.CLUT_Addr = System.Null_Address then + raise Program_Error with ""Source CLUT address required""; + end if; + + DMA2D_Periph.FGCMAR := To_Word (Src_Buffer.CLUT_Addr); + + DMA2D_Periph.FGCMAR := To_Word (Src_Buffer.CLUT_Addr); + DMA2D_Periph.FGPFCCR.CS := (case Src_Buffer.Color_Mode is + when L8 => 2**8 - 1, + when L4 => 2**4 - 1, + when others => 0); + -- Set CLUT mode to RGB888 + DMA2D_Periph.FGPFCCR.CCM := Src_Buffer.CLUT_Color_Mode = RGB888; + + -- Start loading the CLUT + DMA2D_Periph.FGPFCCR.START := True; + + while DMA2D_Periph.FGPFCCR.START loop + -- Wait for CLUT loading... + null; + end loop; + end if; + + DMA2D_Periph.FGOR := (LO => UInt14 (Src_Buffer.Width - Width), + others => <>); + DMA2D_Periph.FGMAR := To_Word (Src_Buffer.Addr) + Src_Off; + + if Bg_Buffer /= Null_Buffer then + declare + Bg_Off : constant UInt32 := Offset (Bg_Buffer, X_Bg, Y_Bg); + begin + DMA2D_Periph.BGPFCCR.CM := + DMA2D_Color_Mode'Enum_Rep (Bg_Buffer.Color_Mode); + DMA2D_Periph.BGMAR := To_Word (Bg_Buffer.Addr) + Bg_Off; + DMA2D_Periph.BGPFCCR.CS := 0; + DMA2D_Periph.BGPFCCR.START := False; + DMA2D_Periph.BGOR := + (LO => UInt14 (Bg_Buffer.Width - Width), others => <>); + + if Bg_Buffer.Color_Mode = L8 or else Bg_Buffer.Color_Mode = L4 then + + if Bg_Buffer.CLUT_Addr = System.Null_Address then + raise Program_Error with ""Background CLUT address required""; + end if; + + DMA2D_Periph.BGCMAR := To_Word (Bg_Buffer.CLUT_Addr); + DMA2D_Periph.BGPFCCR.CS := (case Bg_Buffer.Color_Mode is + when L8 => 2**8 - 1, + when L4 => 2**4 - 1, + when others => 0); + -- Set CLUT mode to RGB888 + DMA2D_Periph.BGPFCCR.CCM := Bg_Buffer.CLUT_Color_Mode = RGB888; + + -- Start loading the CLUT + DMA2D_Periph.BGPFCCR.START := True; + + while DMA2D_Periph.BGPFCCR.START loop + -- Wait for CLUT loading... + null; + end loop; + end if;" +procedure Demo_Timer_PWM is -- low-level demo of the PWM capabilities,"Period : constant := 1000; + + Output_Channel : constant Timer_Channel := Channel_2; + -- The LED driven by this example is determined by the channel selected. + -- That is so because each channel of Timer_4 is connected to a specific + -- LED in the alternate function configuration on this board. We will + -- initialize all of the LEDs to be in the AF mode for Timer_4. The + -- particular channel selected is completely arbitrary, as long as the + -- selected GPIO port/pin for the LED matches the selected channel. + -- + -- Channel_1 is connected to the green LED. + -- Channel_2 is connected to the orange LED. + -- Channel_3 is connected to the red LED. + -- Channel_4 is connected to the blue LED. + + -------------------- + -- Configure_LEDs -- + -------------------- + + procedure Configure_LEDs; + + procedure Configure_LEDs is + begin + Enable_Clock (GPIO_D); + + Configure_IO + (All_LEDs, + (Mode_AF, + AF => GPIO_AF_TIM4_2, + AF_Speed => Speed_50MHz, + AF_Output_Type => Push_Pull, + Resistors => Floating)); + end Configure_LEDs; + + -- The SFP run-time library for these boards is intended for certified + -- environments and so does not contain the full set of facilities defined + -- by the Ada language. The elementary functions are not included, for + -- example. In contrast, the Ravenscar ""full"" run-times do have these + -- functions. + + function Sine (Input : Long_Float) return Long_Float; + + -- Therefore there are four choices: 1) use the ""ravescar-full-stm32f4"" + -- runtime library, 2) pull the sources for the language-defined elementary + -- function package into the board's run-time library and rebuild the + -- run-time, 3) pull the sources for those packages into the source + -- directory of your application and rebuild your application, or 4) roll + -- your own approximation to the functions required by your application. + + -- In this demonstration we roll our own approximation to the sine function + -- so that it doesn't matter which runtime library is used. + + function Sine (Input : Long_Float) return Long_Float is + Pi : constant Long_Float := 3.14159_26535_89793_23846; + X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0); + B : constant Long_Float := 4.0 / Pi; + C : constant Long_Float := (-4.0) / (Pi * Pi); + Y : constant Long_Float := B * X + C * X * abs (X); + P : constant Long_Float := 0.225; + begin + return P * (Y * abs (Y) - Y) + Y; + end Sine; + + -- We use the sine function to drive the power applied to the LED, thereby + -- making the LED increase and decrease in brightness. We attach the timer + -- to the LED and then control how much power is supplied by changing the + -- value of the timer's output compare register. The sine function drives + -- that value, thus the waxing/waning effect. + +begin + Configure_LEDs; + + Enable_Clock (Timer_4); + + Reset (Timer_4); + + Configure + (Timer_4, + Prescaler => 1, + Period => Period, + Clock_Divisor => Div1, + Counter_Mode => Up); + + Configure_Channel_Output + (Timer_4, + Channel => Output_Channel, + Mode => PWM1, + State => Enable, + Pulse => 0, + Polarity => High); + + Set_Autoreload_Preload (Timer_4, True); + + Enable_Channel (Timer_4, Output_Channel); + + Enable (Timer_4); + + declare + use STM32; + Arg : Long_Float := 0.0; + Pulse : UInt16; + Increment : constant Long_Float := 0.00003; + -- The Increment value controls the rate at which the brightness + -- increases and decreases. The value is more or less arbitrary, but + -- note that the effect of optimization is observable. + begin + loop + Pulse := UInt16 (Long_Float (Period / 2) * (1.0 + Sine (Arg))); + Set_Compare_Value (Timer_4, Output_Channel, Pulse); + Arg := Arg + Increment; + end loop;" +procedure Demo_PWM_ADT is -- demo the higher-level PWM abstract data type,"Selected_Timer : STM32.Timers.Timer renames Timer_4; + -- NOT arbitrary! We drive the on-board LEDs that are tied to the channels + -- of Timer_4 on some boards. Not all boards have this association. If you + -- use a difference board, select a GPIO point connected to your selected + -- timer and drive that instead. + + Timer_AF : constant STM32.GPIO_Alternate_Function := GPIO_AF_TIM4_2; + -- Note that this value MUST match the corresponding timer selected! + + Output_Channel : constant Timer_Channel := Channel_2; -- arbitrary + -- The LED driven by this example is determined by the channel selected. + -- That is so because each channel of Timer_4 is connected to a specific + -- LED in the alternate function configuration on this board. We will + -- initialize all of the LEDs to be in the AF mode. The + -- particular channel selected is completely arbitrary, as long as the + -- selected GPIO port/pin for the LED matches the selected channel. + -- + -- Channel_1 is connected to the green LED. + -- Channel_2 is connected to the orange LED. + -- Channel_3 is connected to the red LED. + -- Channel_4 is connected to the blue LED. + LED_For : constant array (Timer_Channel) of User_LED := + (Channel_1 => Green_LED, + Channel_2 => Orange_LED, + Channel_3 => Red_LED, + Channel_4 => Blue_LED); + + Requested_Frequency : constant Hertz := 30_000; -- arbitrary + + Power_Control : PWM_Modulator; + + -- The SFP run-time library for these boards is intended for certified + -- environments and so does not contain the full set of facilities defined + -- by the Ada language. The elementary functions are not included, for + -- example. In contrast, the Ravenscar ""full"" run-times do have these + -- functions. + function Sine (Input : Long_Float) return Long_Float; + + -- Therefore there are four choices: 1) use the ""ravescar-full-stm32f4"" + -- runtime library, 2) pull the sources for the language-defined elementary + -- function package into the board's run-time library and rebuild the + -- run-time, 3) pull the sources for those packages into the source + -- directory of your application and rebuild your application, or 4) roll + -- your own approximation to the functions required by your application. + + -- In this demonstration we roll our own approximation to the sine function + -- so that it doesn't matter which runtime library is used. + + function Sine (Input : Long_Float) return Long_Float is + Pi : constant Long_Float := 3.14159_26535_89793_23846; + X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0); + B : constant Long_Float := 4.0 / Pi; + C : constant Long_Float := (-4.0) / (Pi * Pi); + Y : constant Long_Float := B * X + C * X * abs (X); + P : constant Long_Float := 0.225; + begin + return P * (Y * abs (Y) - Y) + Y; + end Sine; + + -- We use the sine function to drive the power applied to the LED, thereby + -- making the LED increase and decrease in brightness. We attach the timer + -- to the LED and then control how much power is supplied by changing the + -- value of the timer's output compare register. The sine function drives + -- that value, thus the waxing/waning effect. + +begin + Configure_PWM_Timer (Selected_Timer'Access, Requested_Frequency); + + Power_Control.Attach_PWM_Channel + (Selected_Timer'Access, + Output_Channel, + LED_For (Output_Channel), + Timer_AF); + + Power_Control.Enable_Output; + + declare + Arg : Long_Float := 0.0; + Value : Percentage; + Increment : constant Long_Float := 0.00003; + -- The Increment value controls the rate at which the brightness + -- increases and decreases. The value is more or less arbitrary, but + -- note that the effect of optimization is observable. + begin + loop + Value := Percentage (50.0 * (1.0 + Sine (Arg))); + Set_Duty_Cycle (Power_Control, Value); + Arg := Arg + Increment; + end loop;" +procedure Demo_DAC_Basic is,"Output_Channel : constant DAC_Channel := Channel_1; -- arbitrary + + procedure Configure_DAC_GPIO (Output_Channel : DAC_Channel); + -- Once the channel is enabled, the corresponding GPIO pin is automatically + -- connected to the analog converter output. However, in order to avoid + -- parasitic consumption, the PA4 pin (Channel_1) or PA5 pin (Channel_2) + -- should first be configured to analog mode. See the note in the RM, page + -- 431. + + procedure Print (Value : UInt32); + -- Prints the image of the arg at a fixed location + + procedure Await_Button; + -- Wait for the user to press and then release the blue user button + + ----------- + -- Print -- + ----------- + + procedure Print (Value : UInt32) is + Value_Image : constant String := Value'Img; + begin + LCD_Std_Out.Put (170, 52, Value_Image (2 .. Value_Image'Last) & "" ""); + end Print; + + ------------------ + -- Await_Button -- + ------------------ + + procedure Await_Button is + begin + Await_Pressed : loop + exit Await_Pressed when Set (User_Button_Point); + end loop Await_Pressed; + + Await_Released : loop + exit Await_Released when not Set (User_Button_Point); + end loop Await_Released; + end Await_Button; + + ------------------------ + -- Configure_DAC_GPIO -- + ------------------------ + + procedure Configure_DAC_GPIO (Output_Channel : DAC_Channel) is + Output : constant GPIO_Point := (if Output_Channel = Channel_1 + then DAC_Channel_1_IO + else DAC_Channel_2_IO); + begin + Enable_Clock (Output); + Configure_IO (Output, (Mode => Mode_Analog, Resistors => Floating)); + end Configure_DAC_GPIO; + +begin + Initialize_LEDs; + All_LEDs_Off; + + LCD_Std_Out.Clear_Screen; + + Configure_User_Button_GPIO; + + Configure_DAC_GPIO (Output_Channel); + + Enable_Clock (DAC_1); + + Reset (DAC_1); + + Select_Trigger (DAC_1, Output_Channel, Software_Trigger); + + Enable_Trigger (DAC_1, Output_Channel); + + Enable (DAC_1, Output_Channel); + + declare + Value : UInt32 := 0; + Percent : UInt32; + + Resolution : constant DAC_Resolution := DAC_Resolution_12_Bits; + -- Arbitrary, change as desired. Counts will automatically adjust. + + Max_Counts : constant UInt32 := (if Resolution = DAC_Resolution_12_Bits + then Max_12bit_Resolution + else Max_8bit_Resolution); + begin + Put (0, 0, ""VRef+ is 2.95V""); -- measured + Put (0, 25, ""Button advances""); + Put (0, 52, ""Current %:""); + loop + for K in UInt32 range 0 .. 10 loop + Percent := K * 10; + Print (Percent); + + Value := (Percent * Max_Counts) / 100; + + Set_Output + (DAC_1, + Output_Channel, + Value, + Resolution, + Right_Aligned); + + Trigger_Conversion_By_Software (DAC_1, Output_Channel); + + Await_Button; + end loop; + end loop;" +procedure Demo_CRC is,"Checksum_CPU : UInt32 := 0; + -- the checksum obtained by calling a routine that uses the CPU to transfer + -- the memory block to the CRC processor + + Checksum_DMA : UInt32 := 0; + -- the checksum obtained by calling a routine that uses DMA to transfer the + -- memory block to the CRC processor + + -- see the STM32Cube_FW_F4_V1.6.0\Projects\ CRC example for data and + -- expected CRC checksum value + + Section1 : constant Block_32 := + (16#00001021#, 16#20423063#, 16#408450A5#, 16#60C670E7#, 16#9129A14A#, 16#B16BC18C#, + 16#D1ADE1CE#, 16#F1EF1231#, 16#32732252#, 16#52B54294#, 16#72F762D6#, 16#93398318#, + 16#A35AD3BD#, 16#C39CF3FF#, 16#E3DE2462#, 16#34430420#, 16#64E674C7#, 16#44A45485#, + 16#A56AB54B#, 16#85289509#, 16#F5CFC5AC#, 16#D58D3653#, 16#26721611#, 16#063076D7#, + 16#569546B4#, 16#B75BA77A#, 16#97198738#, 16#F7DFE7FE#, 16#C7BC48C4#, 16#58E56886#, + 16#78A70840#, 16#18612802#, 16#C9CCD9ED#, 16#E98EF9AF#, 16#89489969#, 16#A90AB92B#, + 16#4AD47AB7#, 16#6A961A71#, 16#0A503A33#, 16#2A12DBFD#, 16#FBBFEB9E#, 16#9B798B58#, + 16#BB3BAB1A#, 16#6CA67C87#, 16#5CC52C22#, 16#3C030C60#, 16#1C41EDAE#, 16#FD8FCDEC#, + 16#AD2ABD0B#, 16#8D689D49#, 16#7E976EB6#, 16#5ED54EF4#, 16#2E321E51#, 16#0E70FF9F#); + + Section2 : constant Block_32 := + (16#EFBEDFDD#, 16#CFFCBF1B#, 16#9F598F78#, 16#918881A9#, 16#B1CAA1EB#, 16#D10CC12D#, + 16#E16F1080#, 16#00A130C2#, 16#20E35004#, 16#40257046#, 16#83B99398#, 16#A3FBB3DA#, + 16#C33DD31C#, 16#E37FF35E#, 16#129022F3#, 16#32D24235#, 16#52146277#, 16#7256B5EA#, + 16#95A88589#, 16#F56EE54F#, 16#D52CC50D#, 16#34E224C3#, 16#04817466#, 16#64475424#, + 16#4405A7DB#, 16#B7FA8799#, 16#E75FF77E#, 16#C71DD73C#, 16#26D336F2#, 16#069116B0#, + 16#76764615#, 16#5634D94C#, 16#C96DF90E#, 16#E92F99C8#, 16#B98AA9AB#, 16#58444865#, + 16#78066827#, 16#18C008E1#, 16#28A3CB7D#, 16#DB5CEB3F#, 16#FB1E8BF9#, 16#9BD8ABBB#, + 16#4A755A54#, 16#6A377A16#, 16#0AF11AD0#, 16#2AB33A92#, 16#ED0FDD6C#, 16#CD4DBDAA#, + 16#AD8B9DE8#, 16#8DC97C26#, 16#5C644C45#, 16#3CA22C83#, 16#1CE00CC1#, 16#EF1FFF3E#, + 16#DF7CAF9B#, 16#BFBA8FD9#, 16#9FF86E17#, 16#7E364E55#, 16#2E933EB2#, 16#0ED11EF0#); + + -- expected CRC value for the data above is 379E9F06 hex, or 933142278 dec + Expected_Checksum : constant UInt32 := 933142278; + + Next_DMA_Interrupt : DMA_Interrupt; + + procedure Panic with No_Return; + -- flash the on-board LEDs, indefinitely, to indicate a failure + + procedure Panic is + begin + loop + Toggle_LEDs (All_LEDs); + delay until Clock + Milliseconds (100); + end loop; + end Panic; + +begin + Clear_Screen; + Initialize_LEDs; + + Enable_Clock (CRC_Unit); + + -- get the checksum using the CPU to transfer memory to the CRC processor; + -- verify it is the expected value + + Update_CRC (CRC_Unit, Input => Section1, Output => Checksum_CPU); + Update_CRC (CRC_Unit, Input => Section2, Output => Checksum_CPU); + + Put_Line (""CRC:"" & Checksum_CPU'Img); + + if Checksum_CPU /= Expected_Checksum then + Panic; + end if; + + -- get the checksum using DMA to transfer memory to the CRC processor + + Enable_Clock (Controller); + + Reset (Controller); + + Reset_Calculator (CRC_Unit); + + Update_CRC (CRC_Unit, Controller'Access, Stream, Input => Section1); + + DMA_IRQ_Handler.Await_Event (Next_DMA_Interrupt); + + if Next_DMA_Interrupt /= Transfer_Complete_Interrupt then + Panic; + end if; + + -- In this code fragment we use the approach suited for the case in which + -- we are calculating the CRC for a section of system memory rather than a + -- block of application data. We pretend that Section2 is a memory section. + -- All we need is a known starting address and a known length. Given that, + -- we can create a view of it as if it is an object of type Block_32 (or + -- whichever block type is appropriate). + declare + subtype Memory_Section is Block_32 (1 .. Section2'Length); + type Section_Pointer is access all Memory_Section with Storage_Size => 0; + function As_Memory_Section_Reference is new Ada.Unchecked_Conversion + (Source => System.Address, Target => Section_Pointer); + begin + Update_CRC + (CRC_Unit, + Controller'Access, + Stream, + Input => As_Memory_Section_Reference (Section2'Address).all);" +procedure DSB is,"begin + Asm (""dsb"", Volatile => True); + end DSB; + + --------- + -- ISB -- + --------- + + procedure ISB is + begin + Asm (""isb"", Volatile => True); + end ISB; + + ----------------------- + -- Cache_Maintenance -- + ----------------------- + + procedure Cache_Maintenance + (Start : System.Address; + Len : Natural) + is + begin + if not D_Cache_Enabled then + return; + end if; + + declare + function To_U32 is new Ada.Unchecked_Conversion + (System.Address, UInt32); + + Op_Size : Integer_32 := Integer_32 (Len); + Op_Addr : UInt32 := To_U32 (Start); + Reg : UInt32 with Volatile, Address => Reg_Address; + + begin + DSB; + + while Op_Size > 0 loop + Reg := Op_Addr; + Op_Addr := Op_Addr + Data_Cache_Line_Size; + Op_Size := Op_Size - Integer_32 (Data_Cache_Line_Size); + end loop; + + DSB; + ISB;" +procedure TC_FAT_Read is,"function Check_Dir (Dirname : String) return Boolean; + function Check_File (Basename : String; + Dirname : String) + return Boolean; + function Check_Expected_Number return Boolean; + + Number_Of_Files_Checked : Natural := 0; + + --------------- + -- Check_Dir -- + --------------- + + function Check_Dir (Dirname : String) return Boolean is + DD : Directory_Descriptor; + Status : File_IO.Status_Code; + begin + Put_Line (""Checking directory: '"" & Dirname & ""'""); + Status := Open (DD, Dirname); + + if Status /= OK then + Put_Line (""Cannot open directory: '"" & Dirname & ""'""); + Put_Line (""Status: "" & Status'Img); + return False; + end if; + + loop + declare + Ent : constant Directory_Entry := Read (DD); + begin + if Ent /= Invalid_Dir_Entry then + if Ent.Name = ""."" or else Ent.Name = "".."" then + null; -- do nothing + elsif Ent.Subdirectory then + + if not Check_Dir (Dirname & ""/"" & Ent.Name) then + return False; + end if; + elsif not Ent.Symlink then + if not Check_File (Ent.Name, Dirname) then + return False; + end if; + end if; + else + exit; + end if;" +procedure TC_FAT_Write is,"use type HAL.Filesystem.Status_Code; + + package Hash renames GNAT.MD5; + + Test_File_Size : constant := 2000; + + function Write_File (Filename : String) return String; + function Check_File (Filename : String; Md5 : String) return Boolean; + function Delete_Tree (Filename : String) return Boolean; + function Check_Read_Test_Dir return Boolean; + + ---------------- + -- Write_File -- + ---------------- + + function Write_File (Filename : String) return String is + FD : File_Descriptor; + Status : Status_Code; + + Context : aliased GNAT.MD5.Context := GNAT.MD5.Initial_Context; + + Buffer : Ada.Streams.Stream_Element_Array (1 .. Test_File_Size); + Last : Ada.Streams.Stream_Element_Offset; + Size : File_Size; + use type Ada.Streams.Stream_Element_Offset; + + begin + Status := Open (FD, Filename, Write_Only); + + if Status /= OK then + Put_Line (""Cannot open file: '"" & Filename & ""'""); + Put_Line (""Status: "" & Status'Img); + return """"; + end if; + + Size := Buffer'Length; + Buffer := (others => 42); + Last := Ada.Streams.Stream_Element_Offset (Size); + Hash.Update (Context, Buffer (1 .. Last)); + + if Write (FD, Buffer'Address, Size) /= Size then + Put_Line (""Cannot write file: '"" & Filename & ""'""); + Put_Line (""Status: "" & Status'Img); + return """"; + end if; + + Close (FD); + return Hash.Digest (Context); + end Write_File; + + ---------------- + -- Check_File -- + ---------------- + + function Check_File (Filename : String; + Md5 : String) + return Boolean + is + FD : File_Descriptor; + Status : Status_Code; + begin + Status := Open (FD, Filename, Read_Only); + + if Status /= OK then + Put_Line (""Cannot open file: '"" & Filename & ""'""); + Put_Line (""Status: "" & Status'Img); + return False; + end if; + + if Size (FD) /= Test_File_Size then + Put_Line (""Error: wrong file size: "" & Size (FD)'Img & + "" (expected "" & Test_File_Size'Img & "")""); + return False; + end if; + + declare + Hash_Str : constant String := Compare_Files.Compute_Hash (FD); + begin + if Hash_Str /= Md5 then + Put_Line (""Error: Hash is different than filename""); + return False; + else + return True; + end if;" +procedure TC_Virtual_Wire is,"pragma Assertion_Policy (Assert => Check); + + No_Pull_Wire : Virtual_Wire (Default_Pull => Floating, + Max_Points => 2); + + Pull_Up_Wire : Virtual_Wire (Default_Pull => Pull_Up, + Max_Points => 2); + + Pull_Down_Wire : Virtual_Wire (Default_Pull => Pull_Down, + Max_Points => 2); + + Unref : Boolean with Unreferenced; +begin + + -- Default mode -- + + pragma Assert (No_Pull_Wire.Point (1).Mode = Input, + ""Default point mode should be input""); + + -- State with only inputs and a wire pull resistor -- + + pragma Assert (Pull_Up_Wire.Point (1).Set, + ""Default state of pull up wire should be high""); + pragma Assert (not Pull_Down_Wire.Point (1).Set, + ""Default state of pull down wire should be low""); + + -- State with only inputs and a point pull resistor -- + + pragma Assert (No_Pull_Wire.Point (1).Set_Pull_Resistor (Pull_Up), + ""It should be possible to change the pull resitor""); + + pragma Assert (No_Pull_Wire.Point (1).Set, + ""State of wire with one pull up point should be high""); + + + Unref := No_Pull_Wire.Point (1).Set_Pull_Resistor (Pull_Down); + pragma Assert (not No_Pull_Wire.Point (1).Set, + ""State of wire with one pull down point should be low""); + + -- State with one input one output and no pull resistor -- + + pragma Assert (No_Pull_Wire.Point (1).Set_Mode (Input), + ""It should be possible to change the mode""); + Unref := No_Pull_Wire.Point (1).Set_Pull_Resistor (Pull_Down); + + Unref := No_Pull_Wire.Point (2).Set_Mode (Output); + Unref := No_Pull_Wire.Point (2).Set_Pull_Resistor (Floating); + + No_Pull_Wire.Point (2).Set; + pragma Assert (No_Pull_Wire.Point (1).Set, ""Should be high""); + No_Pull_Wire.Point (2).Clear; + pragma Assert (not No_Pull_Wire.Point (1).Set, ""Should be low""); + + -- State with one input one output and point pull resistor -- + + Unref := No_Pull_Wire.Point (1).Set_Mode (Input); + Unref := No_Pull_Wire.Point (1).Set_Pull_Resistor (Pull_Up); + + Unref := No_Pull_Wire.Point (2).Set_Mode (Output); + Unref := No_Pull_Wire.Point (2).Set_Pull_Resistor (Floating); + + No_Pull_Wire.Point (2).Set; + pragma Assert (No_Pull_Wire.Point (1).Set, ""Should be high""); + No_Pull_Wire.Point (2).Clear; + pragma Assert (not No_Pull_Wire.Point (1).Set, ""Should be low""); + + Unref := No_Pull_Wire.Point (1).Set_Pull_Resistor (Pull_Down); + + No_Pull_Wire.Point (2).Set; + pragma Assert (No_Pull_Wire.Point (1).Set, ""Should be high""); + No_Pull_Wire.Point (2).Clear; + pragma Assert (not No_Pull_Wire.Point (1).Set, ""Should be low""); + + -- Opposite pull on the same wire -- + declare + begin + Unref := Pull_Down_Wire.Point (1).Set_Pull_Resistor (Pull_Up); + exception + when Invalid_Configuration => + Put_Line (""Expected exception on oppposite pull (1)"");" +procedure TC_Log_Priorities is,"Maximum_Message_Length : constant := 64; + + package Log is new Logging_With_Priority + (Priorities => Natural, + Maximum_Message_Length => Maximum_Message_Length, + Maximum_Number_Of_Messages => 6); + + procedure Pop_And_Print; + procedure Fill_Queue; + procedure Empty_Queue; + + ------------------- + -- Pop_And_Print -- + ------------------- + + procedure Pop_And_Print is + Str : String (1 .. Maximum_Message_Length); + Length : Natural; + Prio : Natural; + begin + Log.Pop (Str, Length, Prio); + if Length /= 0 then + Ada.Text_IO.Put_Line (""Prio:"" & Prio'Img & "" -> "" & + Str (Str'First .. Str'First + Length - 1)); + else + Ada.Text_IO.Put_Line (""Pop : The queue is empty""); + end if; + end Pop_And_Print; + + ---------------- + -- Fill_Queue -- + ---------------- + + procedure Fill_Queue is + begin + Log.Log_Line (""Prio 1 - 1"", 1); + Log.Log_Line (""Prio 2 - 1"", 2); + Log.Log_Line (""Prio 5 - 1"", 5); + Log.Log_Line (""Prio 1 - 2"", 1); + Log.Log_Line (""Prio 5 - 2"", 5); + Log.Log_Line (""Prio 8 - 1"", 8); + + if not Log.Full then + raise Program_Error with ""The queue should be full""; + end if; + + end Fill_Queue; + + ----------------- + -- Empty_Queue -- + ----------------- + + procedure Empty_Queue is + begin + -- Empty the queue + for Cnt in 1 .. 6 loop + Pop_And_Print; + end loop; + + if not Log.Empty then + raise Program_Error with ""The queue should be empty""; + end if; + end Empty_Queue; + + +begin + Ada.Text_IO.Put_Line (""--- Log test begin ---""); + + declare + begin + Ada.Text_IO.Put_Line (""--- Test priorities ---""); + + -- Try to print but there should be nothing in the queue + Pop_And_Print; + + -- Insert a few messages with various priorities to check that the messages + -- will be properly sorted. + Fill_Queue; + Empty_Queue; + + -- Try to print but there should be nothing in the queue + Pop_And_Print;" +"function To_Char is new Ada.Unchecked_Conversion (Source => UInt8,","Target => Character); + function To_UInt8 is new Ada.Unchecked_Conversion (Source => Character, + Target => UInt8); + + procedure Write (This : in out TP_Device; Cmd : String); + procedure Read (This : in out TP_Device; Str : out String); + + ----------- + -- Write -- + ----------- + + procedure Write (This : in out TP_Device; Cmd : String) is + Status : UART_Status; + Data : UART_Data_8b (Cmd'Range); + begin + + for Index in Cmd'Range loop + Data (Index) := To_UInt8 (Cmd (Index)); + end loop; + + This.Port.Transmit (Data, Status); + + if Status /= Ok then + -- No error handling... + raise Program_Error; + end if; + -- This.Time.Delay_Microseconds ((11 * 1000000 / 19_2000) + Cmd'Length); + end Write; + + ---------- + -- Read -- + ---------- + + procedure Read (This : in out TP_Device; Str : out String) is + Status : UART_Status; + Data : UART_Data_8b (Str'Range); + begin + This.Port.Receive (Data, Status); + if Status /= Ok then + -- No error handling... + raise Program_Error; + end if; + + for Index in Str'Range loop + Str (Index) := To_Char (Data (Index)); + end loop; + end Read; + + ---------------------- + -- Set_Line_Spacing -- + ---------------------- + + procedure Set_Line_Spacing (This : in out TP_Device; Spacing : UInt8) is + begin + Write (This, ASCII.ESC & '3' & To_Char (Spacing)); + end Set_Line_Spacing; + + --------------- + -- Set_Align -- + --------------- + + procedure Set_Align (This : in out TP_Device; Align : Text_Align) is + Mode : Character; + begin + case Align is + when Left => Mode := '0'; + when Center => Mode := '1'; + when Right => Mode := '2'; + end case; + Write (This, ASCII.ESC & 'a' & Mode); + end Set_Align; + + ---------------------- + -- Set_Font_Enlarge -- + ---------------------- + + procedure Set_Font_Enlarge (This : in out TP_Device; Height, Width : Boolean) is + Data : UInt8 := 0; + begin + if Height then + Data := Data or 16#01#; + end if; + if Width then + Data := Data or 16#10#; + end if; + Write (This, ASCII.GS & '!' & To_Char (Data)); + end Set_Font_Enlarge; + + -------------- + -- Set_Bold -- + -------------- + + procedure Set_Bold (This : in out TP_Device; Bold : Boolean) is + begin + Write (This, ASCII.ESC & 'E' & To_Char (if Bold then 1 else 0)); + end Set_Bold; + + ---------------------- + -- Set_Double_Width -- + ---------------------- + + procedure Set_Double_Width (This : in out TP_Device; Double : Boolean) is + begin + if Double then + Write (This, ASCII.ESC & ASCII.SO); + else + Write (This, ASCII.ESC & ASCII.DC4); + end if; + end Set_Double_Width; + + ---------------- + -- Set_UpDown -- + ---------------- + + procedure Set_UpDown (This : in out TP_Device; UpDown : Boolean) is + begin + Write (This, ASCII.ESC & '{' & To_Char (if UpDown then 1 else 0)); + end Set_UpDown; + + ------------------ + -- Set_Reversed -- + ------------------ + + procedure Set_Reversed (This : in out TP_Device; Reversed : Boolean) is + begin + Write (This, ASCII.GS & 'B' & To_Char (if Reversed then 1 else 0)); + end Set_Reversed; + + -------------------------- + -- Set_Underline_Height -- + -------------------------- + + procedure Set_Underline_Height (This : in out TP_Device; Height : Underline_Height) is + begin + Write (This, ASCII.ESC & '-' & To_Char (Height)); + end Set_Underline_Height; + + ----------------------- + -- Set_Character_Set -- + ----------------------- + + procedure Set_Character_Set (This : in out TP_Device; Set : Character_Set) is + begin + Write (This, ASCII.ESC & 't' & To_Char (Character_Set'Pos (Set))); + end Set_Character_Set; + + ---------- + -- Feed -- + ---------- + + procedure Feed (This : in out TP_Device; Rows : UInt8) is + begin + Write (This, ASCII.ESC & 'd' & To_Char (Rows)); + end Feed; + + ------------------ + -- Print_Bitmap -- + ------------------ + + procedure Print_Bitmap (This : in out TP_Device; + BM : Thermal_Printer_Bitmap) + is + Nbr_Of_Rows : constant Natural := BM'Length (2); + Nbr_Of_Columns : constant Natural := BM'Length (1); + Str : String (1 .. Nbr_Of_Columns / 8); + begin + + Write (This, ASCII.DC2 & 'v' & + To_Char (UInt8 (Nbr_Of_Rows rem 256)) & + To_Char (UInt8 (Nbr_Of_Rows / 256))); + + for Row in 0 .. Nbr_Of_Rows - 1 loop + for Colum in 0 .. (Nbr_Of_Columns / 8) - 1 loop + declare + BM_Index : constant Natural := BM'First (1) + Colum * 8; + Str_Index : constant Natural := Str'First + Colum; + B : UInt8 := 0; + begin + for X in 0 .. 7 loop + B := B or (if BM (BM_Index + X, + BM'First (2) + Row) + then 2**X else 0); + end loop; + Str (Str_Index) := To_Char (B);" +function As_UInt8 is new Ada.Unchecked_Conversion,"(Source => High_Pass_Filter_Mode, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => High_Pass_Cutoff_Frequency, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Power_Mode_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Output_Data_Rate_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Axes_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Bandwidth_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Block_Data_Update_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Endian_Data_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Full_Scale_Selection, Target => UInt8); + + type Angle_Rate_Pointer is access all Angle_Rate with Storage_Size => 0; + + function As_Angle_Rate_Pointer is new Ada.Unchecked_Conversion + (Source => System.Address, Target => Angle_Rate_Pointer); + -- So that we can treat the address of a UInt8 as a pointer to a two-UInt8 + -- sequence representing a signed integer quantity. + + procedure Swap2 (Location : System.Address) with Inline; + -- Swaps the two UInt8s at Location and Location+1 + + procedure SPI_Mode (This : Three_Axis_Gyroscope; Enabled : Boolean); + -- Enable or disable SPI mode communication with the device. This is named + -- ""chip select"" in other demos/examples. + + ---------------- + -- Initialize -- + ---------------- + + procedure Initialize + (This : in out Three_Axis_Gyroscope; + Port : Any_SPI_Port; + Chip_Select : Any_GPIO_Point) + is + begin + This.Port := Port; + This.CS := Chip_Select; + + SPI_Mode (This, Enabled => False); + end Initialize; + + ----------------- + -- SPI_Mode -- + ----------------- + + procedure SPI_Mode (This : Three_Axis_Gyroscope; Enabled : Boolean) is + -- When the pin is low (cleared), the device is in SPI mode. + -- When the pin is high (set), the device is in I2C mode. + -- We want SPI mode communication, so Enabled, when True, + -- means we must drive the pin low. + begin + if Enabled then + This.CS.Clear; + else + This.CS.Set; + end if; + end SPI_Mode; + + ----------- + -- Write -- + ----------- + + procedure Write (This : Three_Axis_Gyroscope; Addr : Register; Data : UInt8) + is + Status : SPI_Status; + begin + SPI_Mode (This, Enabled => True); + + This.Port.Transmit (SPI_Data_8b'(1 => UInt8 (Addr)), Status); + if Status /= Ok then + raise Program_Error; + end if; + + This.Port.Transmit (SPI_Data_8b'(1 => Data), Status); + if Status /= Ok then + raise Program_Error; + end if; + + SPI_Mode (This, Enabled => False); + end Write; + + ---------- + -- Read -- + ---------- + + procedure Read + (This : Three_Axis_Gyroscope; + Addr : Register; + Data : out UInt8) + is + Status : SPI_Status; + Tmp_Data : SPI_Data_8b (1 .. 1); + begin + SPI_Mode (This, Enabled => True); + + This.Port.Transmit (SPI_Data_8b'(1 => UInt8 (Addr) or ReadWrite_CMD), + Status); + if Status /= Ok then + raise Program_Error; + end if; + + This.Port.Receive (Tmp_Data, Status); + if Status /= Ok then + raise Program_Error; + end if; + Data := Tmp_Data (Tmp_Data'First); + + SPI_Mode (This, Enabled => False); + end Read; + + ---------------- + -- Read_UInt8s -- + ---------------- + + procedure Read_UInt8s + (This : Three_Axis_Gyroscope; + Addr : Register; + Buffer : out SPI_Data_8b; + Count : Natural) + is + Index : Natural := Buffer'First; + Status : SPI_Status; + Tmp_Data : SPI_Data_8b (1 .. 1); + begin + SPI_Mode (This, Enabled => True); + + This.Port.Transmit + (SPI_Data_8b'(1 => UInt8 (Addr) or ReadWrite_CMD or MultiUInt8_CMD), + Status); + + if Status /= Ok then + raise Program_Error; + end if; + + for K in 1 .. Count loop + This.Port.Receive (Tmp_Data, Status); + if Status /= Ok then + raise Program_Error; + end if; + Buffer (Index) := Tmp_Data (Tmp_Data'First); + Index := Index + 1; + end loop; + + SPI_Mode (This, Enabled => False); + end Read_UInt8s; + + --------------- + -- Configure -- + --------------- + + procedure Configure + (This : in out Three_Axis_Gyroscope; + Power_Mode : Power_Mode_Selection; + Output_Data_Rate : Output_Data_Rate_Selection; + Axes_Enable : Axes_Selection; + Bandwidth : Bandwidth_Selection; + BlockData_Update : Block_Data_Update_Selection; + Endianness : Endian_Data_Selection; + Full_Scale : Full_Scale_Selection) + is + Ctrl1 : UInt8; + Ctrl4 : UInt8; + begin + Ctrl1 := As_UInt8 (Power_Mode) or + As_UInt8 (Output_Data_Rate) or + As_UInt8 (Axes_Enable) or + As_UInt8 (Bandwidth); + + Ctrl4 := As_UInt8 (BlockData_Update) or + As_UInt8 (Endianness) or + As_UInt8 (Full_Scale); + + Write (This, CTRL_REG1, Ctrl1); + Write (This, CTRL_REG4, Ctrl4); + end Configure; + + ----------- + -- Sleep -- + ----------- + + procedure Sleep (This : in out Three_Axis_Gyroscope) is + Ctrl1 : UInt8; + Sleep_Mode : constant := 2#1000#; -- per the Datasheet, Table 22, pg 32 + begin + Read (This, CTRL_REG1, Ctrl1); + Ctrl1 := Ctrl1 or Sleep_Mode; + Write (This, CTRL_REG1, Ctrl1); + end Sleep; + + -------------------------------- + -- Configure_High_Pass_Filter -- + -------------------------------- + + procedure Configure_High_Pass_Filter + (This : in out Three_Axis_Gyroscope; + Mode_Selection : High_Pass_Filter_Mode; + Cutoff_Frequency : High_Pass_Cutoff_Frequency) + is + Ctrl2 : UInt8; + begin + -- note that the two high-order bits must remain zero, per the datasheet + Ctrl2 := As_UInt8 (Mode_Selection) or As_UInt8 (Cutoff_Frequency); + Write (This, CTRL_REG2, Ctrl2); + end Configure_High_Pass_Filter; + + ----------------------------- + -- Enable_High_Pass_Filter -- + ----------------------------- + + procedure Enable_High_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- set HPen bit + Ctrl5 := Ctrl5 or HighPass_Filter_Enable; + Write (This, CTRL_REG5, Ctrl5); + end Enable_High_Pass_Filter; + + ------------------------------ + -- Disable_High_Pass_Filter -- + ------------------------------ + + procedure Disable_High_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- clear HPen bit + Ctrl5 := Ctrl5 and (not HighPass_Filter_Enable); + Write (This, CTRL_REG5, Ctrl5); + end Disable_High_Pass_Filter; + + ---------------------------- + -- Enable_Low_Pass_Filter -- + ---------------------------- + + procedure Enable_Low_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + Ctrl5 := Ctrl5 or LowPass_Filter_Enable; + Write (This, CTRL_REG5, Ctrl5); + end Enable_Low_Pass_Filter; + + ----------------------------- + -- Disable_Low_Pass_Filter -- + ----------------------------- + + procedure Disable_Low_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- clear HPen bit + Ctrl5 := Ctrl5 and (not LowPass_Filter_Enable); + Write (This, CTRL_REG5, Ctrl5); + end Disable_Low_Pass_Filter; + + --------------------- + -- Reference_Value -- + --------------------- + + function Reference_Value (This : Three_Axis_Gyroscope) return UInt8 is + Result : UInt8; + begin + Read (This, Reference, Result); + return Result; + end Reference_Value; + + ------------------- + -- Set_Reference -- + ------------------- + + procedure Set_Reference (This : in out Three_Axis_Gyroscope; Value : UInt8) is + begin + Write (This, Reference, Value); + end Set_Reference; + + ----------------- + -- Data_Status -- + ----------------- + + function Data_Status (This : Three_Axis_Gyroscope) return Gyro_Data_Status is + Result : UInt8; + function As_Gyro_Data_Status is + new Ada.Unchecked_Conversion (Source => UInt8, + Target => Gyro_Data_Status); + begin + Read (This, Status, Result); + return As_Gyro_Data_Status (Result); + end Data_Status; + + --------------- + -- Device_Id -- + --------------- + + function Device_Id (This : Three_Axis_Gyroscope) return UInt8 is + Result : UInt8; + begin + Read (This, Who_Am_I, Result); + return Result; + end Device_Id; + + ----------------- + -- Temperature -- + ----------------- + + function Temperature (This : Three_Axis_Gyroscope) return UInt8 is + Result : UInt8; + begin + Read (This, OUT_Temp, Result); + return Result; + end Temperature; + + ------------ + -- Reboot -- + ------------ + + procedure Reboot (This : Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- set the boot bit + Ctrl5 := Ctrl5 or Boot_Bit; + Write (This, CTRL_REG5, Ctrl5); + end Reboot; + + ---------------------------- + -- Full_Scale_Sensitivity -- + ---------------------------- + + function Full_Scale_Sensitivity (This : Three_Axis_Gyroscope) return Float is + Ctrl4 : UInt8; + Result : Float; + Fullscale_Selection : UInt8; + begin + Read (This, CTRL_REG4, Ctrl4); + + Fullscale_Selection := Ctrl4 and Fullscale_Selection_Bits; + + if Fullscale_Selection = L3GD20_Fullscale_250'Enum_Rep then + Result := Sensitivity_250dps; + elsif Fullscale_Selection = L3GD20_Fullscale_500'Enum_Rep then + Result := Sensitivity_500dps; + else + Result := Sensitivity_2000dps; + end if; + + return Result; + end Full_Scale_Sensitivity; + + ------------------------- + -- Get_Raw_Angle_Rates -- + ------------------------- + + procedure Get_Raw_Angle_Rates + (This : Three_Axis_Gyroscope; + Rates : out Angle_Rates) + is + + Ctrl4 : UInt8; + + UInt8s_To_Read : constant Integer := 6; -- ie, three 2-UInt8 integers + -- the number of UInt8s in an Angle_Rates record object + + Received : SPI_Data_8b (1 .. UInt8s_To_Read); + + begin + Read (This, CTRL_REG4, Ctrl4); + + Read_UInt8s (This, OUT_X_L, Received, UInt8s_To_Read); + -- The above has the effect of separate reads, as follows: + -- Read (This, OUT_X_L, Received (1)); + -- Read (This, OUT_X_H, Received (2)); + -- Read (This, OUT_Y_L, Received (3)); + -- Read (This, OUT_Y_H, Received (4)); + -- Read (This, OUT_Z_L, Received (5)); + -- Read (This, OUT_Z_H, Received (6)); + + if (Ctrl4 and Endian_Selection_Mask) = L3GD20_Big_Endian'Enum_Rep then + Swap2 (Received (1)'Address); + Swap2 (Received (3)'Address); + Swap2 (Received (5)'Address); + end if; + + Rates.X := As_Angle_Rate_Pointer (Received (1)'Address).all; + Rates.Y := As_Angle_Rate_Pointer (Received (3)'Address).all; + Rates.Z := As_Angle_Rate_Pointer (Received (5)'Address).all; + end Get_Raw_Angle_Rates; + + -------------------------- + -- Configure_Interrupt1 -- + -------------------------- + + procedure Configure_Interrupt1 + (This : in out Three_Axis_Gyroscope; + Triggers : Threshold_Event_List; + Latched : Boolean := False; + Active_Edge : Interrupt1_Active_Edge := L3GD20_Interrupt1_High_Edge; + Combine_Events : Boolean := False; + Sample_Count : Sample_Counter := 0) + is + Config : UInt8; + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 and 16#DF#; + Ctrl3 := Ctrl3 or Active_Edge'Enum_Rep; + Ctrl3 := Ctrl3 or INT1_Interrupt_Enable; + Write (This, CTRL_REG3, Ctrl3); + + if Sample_Count > 0 then + Set_Duration_Counter (This, Sample_Count); + end if; + + Config := 0; + + if Latched then + Config := Config or Int1_Latch_Enable_Bit; + end if; + + if Combine_Events then + Config := Config or Logically_And_Or_Events_Bit; + end if; + + for Event of Triggers loop + Config := Config or Axes_Interrupt_Enablers (Event.Axis); + end loop; + + Write (This, INT1_CFG, Config); + + for Event of Triggers loop + Set_Threshold (This, Event.Axis, Event.Threshold); + end loop; + end Configure_Interrupt1; + + ---------------------------- + -- Set_Interrupt_Pin_Mode -- + ---------------------------- + + procedure Set_Interrupt_Pin_Mode + (This : in out Three_Axis_Gyroscope; + Mode : Pin_Modes) + is + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 and (not Interrupt_Pin_Mode_Bit); + Ctrl3 := Ctrl3 or Mode'Enum_Rep; + Write (This, CTRL_REG3, Ctrl3); + end Set_Interrupt_Pin_Mode; + + ----------------------- + -- Enable_Interrupt1 -- + ----------------------- + + procedure Enable_Interrupt1 (This : in out Three_Axis_Gyroscope) is + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 or INT1_Interrupt_Enable; + Write (This, CTRL_REG3, Ctrl3); + end Enable_Interrupt1; + + ------------------------ + -- Disable_Interrupt1 -- + ------------------------ + + procedure Disable_Interrupt1 (This : in out Three_Axis_Gyroscope) is + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 and (not INT1_Interrupt_Enable); + Write (This, CTRL_REG3, Ctrl3); + end Disable_Interrupt1; + + ----------------------- + -- Interrupt1_Status -- + ----------------------- + + function Interrupt1_Source (This : Three_Axis_Gyroscope) return Interrupt1_Sources is + Result : UInt8; + function As_Interrupt_Source is new Ada.Unchecked_Conversion + (Source => UInt8, Target => Interrupt1_Sources); + begin + Read (This, INT1_SRC, Result); + return As_Interrupt_Source (Result); + end Interrupt1_Source; + + -------------------------- + -- Set_Duration_Counter -- + -------------------------- + + procedure Set_Duration_Counter + (This : in out Three_Axis_Gyroscope; + Value : Sample_Counter) + is + Wait_Bit : constant := 2#1000_0000#; + begin + Write (This, INT1_Duration, UInt8 (Value) or Wait_Bit); + end Set_Duration_Counter; + + ------------------ + -- Enable_Event -- + ------------------ + + procedure Enable_Event + (This : in out Three_Axis_Gyroscope; + Event : Axes_Interrupts) + is + Config : UInt8; + begin + Read (This, INT1_CFG, Config); + Config := Config or Axes_Interrupt_Enablers (Event); + Write (This, INT1_CFG, Config); + end Enable_Event; + + ------------------- + -- Disable_Event -- + ------------------- + + procedure Disable_Event + (This : in out Three_Axis_Gyroscope; + Event : Axes_Interrupts) + is + Config : UInt8; + begin + Read (This, INT1_CFG, Config); + Config := Config and (not Axes_Interrupt_Enablers (Event)); + Write (This, INT1_CFG, Config); + end Disable_Event; + + ------------------- + -- Set_Threshold -- + ------------------- + + procedure Set_Threshold + (This : in out Three_Axis_Gyroscope; + Event : Axes_Interrupts; + Value : Axis_Sample_Threshold) + is + begin + case Event is + when Z_High_Interrupt | Z_Low_Interrupt => + Write (This, INT1_TSH_ZL, UInt8 (Value)); + Write (This, INT1_TSH_ZH, UInt8 (Shift_Right (Value, 8))); + + when Y_High_Interrupt | Y_Low_Interrupt => + Write (This, INT1_TSH_YL, UInt8 (Value)); + Write (This, INT1_TSH_YH, UInt8 (Shift_Right (Value, 8))); + + when X_High_Interrupt | X_Low_Interrupt => + Write (This, INT1_TSH_XL, UInt8 (Value)); + Write (This, INT1_TSH_XH, UInt8 (Shift_Right (Value, 8))); + end case; + end Set_Threshold; + + ------------------- + -- Set_FIFO_Mode -- + ------------------- + + procedure Set_FIFO_Mode + (This : in out Three_Axis_Gyroscope; + Mode : FIFO_Modes) + is + FIFO : UInt8; + begin + Read (This, FIFO_CTRL, FIFO); + FIFO := FIFO and (not FIFO_Mode_Bits); -- clear the current bits + FIFO := FIFO or Mode'Enum_Rep; + Write (This, FIFO_CTRL, FIFO); + end Set_FIFO_Mode; + + ----------------- + -- Enable_FIFO -- + ----------------- + + procedure Enable_FIFO (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + Ctrl5 := Ctrl5 or FIFO_Enable_Bit; + Write (This, CTRL_REG5, Ctrl5); + end Enable_FIFO; + + ------------------ + -- Disable_FIFO -- + ------------------ + + procedure Disable_FIFO (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + Ctrl5 := Ctrl5 and (not FIFO_Enable_Bit); + Write (This, CTRL_REG5, Ctrl5); + end Disable_FIFO; + + ------------------------ + -- Set_FIFO_Watermark -- + ------------------------ + + procedure Set_FIFO_Watermark + (This : in out Three_Axis_Gyroscope; + Level : FIFO_Level) + is + Value : UInt8; + begin + Read (This, FIFO_CTRL, Value); + Value := Value and (not Watermark_Threshold_Bits); -- clear the bits + Value := Value or UInt8 (Level); + Write (This, FIFO_CTRL, Value); + end Set_FIFO_Watermark; + + ------------------------------ + -- Get_Raw_Angle_Rates_FIFO -- + ------------------------------ + + procedure Get_Raw_Angle_Rates_FIFO + (This : in out Three_Axis_Gyroscope; + Buffer : out Angle_Rates_FIFO_Buffer) + is + Ctrl4 : UInt8; + + Angle_Rate_Size : constant Integer := 6; -- UInt8s + UInt8s_To_Read : constant Integer := Buffer'Length * Angle_Rate_Size; + Received : SPI_Data_8b (0 .. UInt8s_To_Read - 1) + with Alignment => 2; + begin + Read (This, CTRL_REG4, Ctrl4); + + Read_UInt8s (This, OUT_X_L, Received, UInt8s_To_Read); + + if (Ctrl4 and Endian_Selection_Mask) = L3GD20_Big_Endian'Enum_Rep then + declare + J : Integer := 0; + begin + for K in Received'First .. Received'Last / 2 loop + Swap2 (Received (J)'Address); + J := J + 2; + end loop;" +function To_Map is new Ada.Unchecked_Conversion,"(SPAD_Map_Bytes, SPAD_Map); + function To_Bytes is new Ada.Unchecked_Conversion + (SPAD_Map, SPAD_Map_Bytes); + + SPAD_Count : UInt8; + SPAD_Is_Aperture : Boolean; + Ref_SPAD_Map_Bytes : SPAD_Map_Bytes; + Ref_SPAD_Map : SPAD_Map; + First_SPAD : UInt8; + SPADS_Enabled : UInt8; + Timing_Budget : UInt32; + + begin + Status := SPAD_Info (This, SPAD_Count, SPAD_Is_Aperture); + + if not Status then + return; + end if; + + Read + (This, REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_0, + Ref_SPAD_Map_Bytes, Status); + Ref_SPAD_Map := To_Map (Ref_SPAD_Map_Bytes); + + -- Set reference spads + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, REG_DYNAMIC_SPAD_REF_EN_START_OFFSET, + UInt8'(16#00#), Status); + end if; + if Status then + Write (This, REG_DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, + UInt8'(16#2C#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, REG_GLOBAL_CONFIG_REF_EN_START_SELECT, + UInt8'(16#B4#), Status); + end if; + + if Status then + if SPAD_Is_Aperture then + First_SPAD := 13; + else + First_SPAD := 1; + end if; + + SPADS_Enabled := 0; + + for J in UInt8 range 1 .. 48 loop + + if J < First_SPAD or else SPADS_Enabled = SPAD_Count then + -- This bit is lower than the first one that should be enabled, + -- or SPAD_Count bits have already been enabled, so zero this + -- bit + Ref_SPAD_Map (J) := False; + + elsif Ref_SPAD_Map (J) then + SPADS_Enabled := SPADS_Enabled + 1; + end if; + end loop; + end if; + + if Status then + Ref_SPAD_Map_Bytes := To_Bytes (Ref_SPAD_Map); + Write (This, REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_0, + Ref_SPAD_Map_Bytes, Status); + end if; + + -- Load tuning Settings + -- default tuning settings from vl53l0x_tuning.h + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#00#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#09#, UInt8'(16#00#), Status); + Write (This, 16#10#, UInt8'(16#00#), Status); + Write (This, 16#11#, UInt8'(16#00#), Status); + + Write (This, 16#24#, UInt8'(16#01#), Status); + Write (This, 16#25#, UInt8'(16#FF#), Status); + Write (This, 16#75#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#4E#, UInt8'(16#2C#), Status); + Write (This, 16#48#, UInt8'(16#00#), Status); + Write (This, 16#30#, UInt8'(16#20#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#30#, UInt8'(16#09#), Status); + Write (This, 16#54#, UInt8'(16#00#), Status); + Write (This, 16#31#, UInt8'(16#04#), Status); + Write (This, 16#32#, UInt8'(16#03#), Status); + Write (This, 16#40#, UInt8'(16#83#), Status); + Write (This, 16#46#, UInt8'(16#25#), Status); + Write (This, 16#60#, UInt8'(16#00#), Status); + Write (This, 16#27#, UInt8'(16#00#), Status); + Write (This, 16#50#, UInt8'(16#06#), Status); + Write (This, 16#51#, UInt8'(16#00#), Status); + Write (This, 16#52#, UInt8'(16#96#), Status); + Write (This, 16#56#, UInt8'(16#08#), Status); + Write (This, 16#57#, UInt8'(16#30#), Status); + Write (This, 16#61#, UInt8'(16#00#), Status); + Write (This, 16#62#, UInt8'(16#00#), Status); + Write (This, 16#64#, UInt8'(16#00#), Status); + Write (This, 16#65#, UInt8'(16#00#), Status); + Write (This, 16#66#, UInt8'(16#A0#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#22#, UInt8'(16#32#), Status); + Write (This, 16#47#, UInt8'(16#14#), Status); + Write (This, 16#49#, UInt8'(16#FF#), Status); + Write (This, 16#4A#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#7A#, UInt8'(16#0A#), Status); + Write (This, 16#7B#, UInt8'(16#00#), Status); + Write (This, 16#78#, UInt8'(16#21#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#23#, UInt8'(16#34#), Status); + Write (This, 16#42#, UInt8'(16#00#), Status); + Write (This, 16#44#, UInt8'(16#FF#), Status); + Write (This, 16#45#, UInt8'(16#26#), Status); + Write (This, 16#46#, UInt8'(16#05#), Status); + Write (This, 16#40#, UInt8'(16#40#), Status); + Write (This, 16#0E#, UInt8'(16#06#), Status); + Write (This, 16#20#, UInt8'(16#1A#), Status); + Write (This, 16#43#, UInt8'(16#40#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#34#, UInt8'(16#03#), Status); + Write (This, 16#35#, UInt8'(16#44#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#31#, UInt8'(16#04#), Status); + Write (This, 16#4B#, UInt8'(16#09#), Status); + Write (This, 16#4C#, UInt8'(16#05#), Status); + Write (This, 16#4D#, UInt8'(16#04#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#44#, UInt8'(16#00#), Status); + Write (This, 16#45#, UInt8'(16#20#), Status); + Write (This, 16#47#, UInt8'(16#08#), Status); + Write (This, 16#48#, UInt8'(16#28#), Status); + Write (This, 16#67#, UInt8'(16#00#), Status); + Write (This, 16#70#, UInt8'(16#04#), Status); + Write (This, 16#71#, UInt8'(16#01#), Status); + Write (This, 16#72#, UInt8'(16#FE#), Status); + Write (This, 16#76#, UInt8'(16#00#), Status); + Write (This, 16#77#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#0D#, UInt8'(16#01#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#80#, UInt8'(16#01#), Status); + Write (This, 16#01#, UInt8'(16#F8#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#8E#, UInt8'(16#01#), Status); + Write (This, 16#00#, UInt8'(16#01#), Status); + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + Set_GPIO_Config (This, GPIO_Function, Polarity_High, Status); + + if Status then + Timing_Budget := Measurement_Timing_Budget (This); + + -- Disable MSRC and TCC by default + -- MSRC = Minimum Signal Rate Check + -- TCC = Target CenterCheck + + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#E8#), Status); + end if; + + -- Recalculate the timing Budget + if Status then + Set_Measurement_Timing_Budget (This, Timing_Budget, Status); + end if; + end Static_Init; + + ------------------------------------ + -- Perform_Single_Ref_Calibration -- + ------------------------------------ + + procedure Perform_Single_Ref_Calibration + (This : VL53L0X_Ranging_Sensor; + VHV_Init : UInt8; + Status : out Boolean) + is + Val : UInt8; + + begin + Write (This, REG_SYSRANGE_START, VHV_Init or 16#01#, Status); + + if not Status then + return; + end if; + + loop + Read (This, REG_RESULT_INTERRUPT_STATUS, Val, Status); + exit when not Status; + exit when (Val and 16#07#) /= 0; + end loop; + + if not Status then + return; + end if; + + Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); + if not Status then + return; + end if; + + Write (This, REG_SYSRANGE_START, UInt8'(16#00#), Status); + end Perform_Single_Ref_Calibration; + + ----------------------------- + -- Perform_Ref_Calibration -- + ----------------------------- + + procedure Perform_Ref_Calibration + (This : in out VL53L0X_Ranging_Sensor; + Status : out Boolean) + is + begin + -- VHV calibration + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#01#), Status); + + if Status then + Perform_Single_Ref_Calibration (This, 16#40#, Status); + end if; + + -- Phase calibration + if Status then + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#02#), Status); + end if; + + if Status then + Perform_Single_Ref_Calibration (This, 16#00#, Status); + end if; + + -- Restore the sequence config + if Status then + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#E8#), Status); + end if; + end Perform_Ref_Calibration; + + ------------------------------------ + -- Start_Range_Single_Millimeters -- + ------------------------------------ + + procedure Start_Range_Single_Millimeters + (This : VL53L0X_Ranging_Sensor; + Status : out Boolean) + is + Val : UInt8; + begin + Write (This, 16#80#, UInt8'(16#01#), Status); + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#91#, This.Stop_Variable, Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + if Status then + Write (This, REG_SYSRANGE_START, UInt8'(16#01#), Status); + end if; + + if not Status then + return; + end if; + + loop + Read (This, REG_SYSRANGE_START, Val, Status); + exit when not Status; + exit when (Val and 16#01#) = 0; + end loop; + end Start_Range_Single_Millimeters; + + --------------------------- + -- Range_Value_Available -- + --------------------------- + + function Range_Value_Available + (This : VL53L0X_Ranging_Sensor) return Boolean + is + Status : Boolean with Unreferenced; + Val : UInt8; + begin + Read (This, REG_RESULT_INTERRUPT_STATUS, Val, Status); + return (Val and 16#07#) /= 0; + end Range_Value_Available; + + ---------------------------- + -- Read_Range_Millimeters -- + ---------------------------- + + function Read_Range_Millimeters + (This : VL53L0X_Ranging_Sensor) return HAL.UInt16 + is + Status : Boolean with Unreferenced; + Ret : HAL.UInt16; + begin + Read (This, REG_RESULT_RANGE_STATUS + 10, Ret, Status); + Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); + + return Ret; + end Read_Range_Millimeters; + + ----------------------------------- + -- Read_Range_Single_Millimeters -- + ----------------------------------- + + function Read_Range_Single_Millimeters + (This : VL53L0X_Ranging_Sensor) return HAL.UInt16 + is + Status : Boolean; + begin + Start_Range_Single_Millimeters (This, Status); + if not Status then + return 4000; + end if; + + while not Range_Value_Available (This) loop + null; + end loop; + + return Read_Range_Millimeters (This); + end Read_Range_Single_Millimeters; + + --------------------- + -- Set_GPIO_Config -- + --------------------- + + procedure Set_GPIO_Config + (This : in out VL53L0X_Ranging_Sensor; + Functionality : VL53L0X_GPIO_Functionality; + Polarity : VL53L0X_Interrupt_Polarity; + Status : out Boolean) + is + Data : UInt8; + Tmp : UInt8; + begin + case Functionality is + when No_Interrupt => + Data := 0; + when Level_Low => + Data := 1; + when Level_High => + Data := 2; + when Out_Of_Window => + Data := 3; + when New_Sample_Ready => + Data := 4; + end case; + + -- 16#04#: interrupt on new measure ready + Write (This, REG_SYSTEM_INTERRUPT_CONFIG_GPIO, Data, Status); + + -- Interrupt polarity + if Status then + case Polarity is + when Polarity_Low => + Data := 16#10#; + when Polarity_High => + Data := 16#00#; + end case; + + Read (This, REG_GPIO_HV_MUX_ACTIVE_HIGH, Tmp, Status); + Tmp := (Tmp and 16#EF#) or Data; + Write (This, REG_GPIO_HV_MUX_ACTIVE_HIGH, Tmp, Status); + end if; + + if Status then + Clear_Interrupt_Mask (This); + end if; + end Set_GPIO_Config; + + -------------------------- + -- Clear_Interrupt_Mask -- + -------------------------- + + procedure Clear_Interrupt_Mask + (This : VL53L0X_Ranging_Sensor) + is + Status : Boolean with Unreferenced; +-- Tmp : UInt8; + begin +-- for J in 1 .. 3 loop + Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); +-- exit when not Status; +-- Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#00#), Status); +-- exit when not Status; +-- Read (This, REG_RESULT_INTERRUPT_STATUS, Tmp, Status); +-- exit when not Status; +-- exit when (Tmp and 16#07#) /= 0; +-- end loop; + end Clear_Interrupt_Mask; + + --------------------------- + -- Sequence_Step_Enabled -- + --------------------------- + + function Sequence_Step_Enabled + (This : VL53L0X_Ranging_Sensor) return VL53L0x_Sequence_Step_Enabled + is + Sequence_Steps : VL53L0x_Sequence_Step_Enabled; + Sequence_Config : UInt8 := 0; + Status : Boolean; + + function Sequence_Step_Enabled + (Step : VL53L0x_Sequence_Step; + Sequence_Config : UInt8) return Boolean; + + --------------------------- + -- Sequence_Step_Enabled -- + --------------------------- + + function Sequence_Step_Enabled + (Step : VL53L0x_Sequence_Step; + Sequence_Config : UInt8) return Boolean + is + begin + case Step is + when TCC => + return (Sequence_Config and 16#10#) /= 0; + when DSS => + return (Sequence_Config and 16#08#) /= 0; + when MSRC => + return (Sequence_Config and 16#04#) /= 0; + when Pre_Range => + return (Sequence_Config and 16#40#) /= 0; + when Final_Range => + return (Sequence_Config and 16#80#) /= 0; + end case; + end Sequence_Step_Enabled; + + begin + Read (This, REG_SYSTEM_SEQUENCE_CONFIG, Sequence_Config, Status); + + if not Status then + return (others => False); + end if; + + for Step in Sequence_Steps'Range loop + Sequence_Steps (Step) := + Sequence_Step_Enabled (Step, Sequence_Config); + end loop; + + return Sequence_Steps; + end Sequence_Step_Enabled; + + --------------------------- + -- Sequence_Step_Timeout -- + --------------------------- + + function Sequence_Step_Timeout + (This : VL53L0X_Ranging_Sensor; + Step : VL53L0x_Sequence_Step; + As_Mclks : Boolean := False) return UInt32 + is + VCSel_Pulse_Period_Pclk : UInt8; + Encoded_UInt8 : UInt8; + Encoded_UInt16 : UInt16; + Status : Boolean; + Timeout_Mclks : UInt32; + Sequence_Steps : VL53L0x_Sequence_Step_Enabled; + + begin + case Step is + when TCC | DSS | MSRC => + Read (This, REG_MSRC_CONFIG_TIMEOUT_MACROP, + Encoded_UInt8, Status); + if Status then + Timeout_Mclks := Decode_Timeout (UInt16 (Encoded_UInt8)); + end if; + + if As_Mclks then + return Timeout_Mclks; + else + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Pre_Range); + + return To_Timeout_Microseconds + (Timeout_Mclks, VCSel_Pulse_Period_Pclk); + end if; + + when Pre_Range => + Read (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encoded_UInt16, Status); + + if Status then + Timeout_Mclks := Decode_Timeout (Encoded_UInt16); + end if; + + if As_Mclks then + return Timeout_Mclks; + else + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Pre_Range); + + return To_Timeout_Microseconds + (Timeout_Mclks, VCSel_Pulse_Period_Pclk); + end if; + + when Final_Range => + Sequence_Steps := Sequence_Step_Enabled (This); + + if Sequence_Steps (Pre_Range) then + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Pre_Range); + + Read (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encoded_UInt16, Status); + + if Status then + Timeout_Mclks := Decode_Timeout (Encoded_UInt16); + end if; + else + Timeout_Mclks := 0; + end if; + + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Final_Range); + + Read (This, REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encoded_UInt16, Status); + + Timeout_Mclks := + Decode_Timeout (Encoded_UInt16) - Timeout_Mclks; + + if As_Mclks then + return Timeout_Mclks; + else + return To_Timeout_Microseconds + (Timeout_Mclks, VCSel_Pulse_Period_Pclk); + end if; + end case; + end Sequence_Step_Timeout; + + ------------------------------- + -- Measurement_Timing_Budget -- + ------------------------------- + + function Measurement_Timing_Budget + (This : VL53L0X_Ranging_Sensor) return HAL.UInt32 + is + Ret : UInt32; + Pre_Range_Timeout : UInt32; + Final_Range_Timeout : UInt32; + Sequence_Steps : VL53L0x_Sequence_Step_Enabled; + Msrc_Dcc_Tcc_Timeout : UInt32; + + begin + Ret := Start_Overhead + End_Overhead; + + Sequence_Steps := Sequence_Step_Enabled (This); + + if Sequence_Steps (TCC) + or else Sequence_Steps (MSRC) + or else Sequence_Steps (DSS) + then + Msrc_Dcc_Tcc_Timeout := Sequence_Step_Timeout (This, MSRC); + if Sequence_Steps (TCC) then + Ret := Ret + Msrc_Dcc_Tcc_Timeout + Tcc_Overhead; + end if; + if Sequence_Steps (DSS) then + Ret := Ret + 2 * (Msrc_Dcc_Tcc_Timeout + Dss_Overhead); + elsif Sequence_Steps (MSRC) then + Ret := Ret + Msrc_Dcc_Tcc_Timeout + Msrc_Overhead; + end if; + end if; + + if Sequence_Steps (Pre_Range) then + Pre_Range_Timeout := Sequence_Step_Timeout (This, Pre_Range); + Ret := Ret + Pre_Range_Timeout + Pre_Range_Overhead; + end if; + + if Sequence_Steps (Final_Range) then + Final_Range_Timeout := Sequence_Step_Timeout (This, Final_Range); + Ret := Ret + Final_Range_Timeout + Final_Range_Overhead; + end if; + + return Ret; + end Measurement_Timing_Budget; + + ----------------------------------- + -- Set_Measurement_Timing_Budget -- + ----------------------------------- + + procedure Set_Measurement_Timing_Budget + (This : VL53L0X_Ranging_Sensor; + Budget_Micro_Seconds : HAL.UInt32; + Status : out Boolean) + is + Final_Range_Timing_Budget_us : UInt32; + Sequence_Steps : VL53L0x_Sequence_Step_Enabled; + Pre_Range_Timeout_us : UInt32 := 0; + Sub_Timeout : UInt32 := 0; + Msrc_Dcc_Tcc_Timeout : UInt32; + + begin + Status := True; + + Final_Range_Timing_Budget_us := + Budget_Micro_Seconds - Start_Overhead - End_Overhead + - Final_Range_Overhead; + + Sequence_Steps := Sequence_Step_Enabled (This); + + if not Sequence_Steps (Final_Range) then + return; + end if; + + if Sequence_Steps (TCC) + or else Sequence_Steps (MSRC) + or else Sequence_Steps (DSS) + then + Msrc_Dcc_Tcc_Timeout := Sequence_Step_Timeout (This, MSRC); + + if Sequence_Steps (TCC) then + Sub_Timeout := Msrc_Dcc_Tcc_Timeout + Tcc_Overhead; + end if; + + if Sequence_Steps (DSS) then + Sub_Timeout := + Sub_Timeout + 2 * (Msrc_Dcc_Tcc_Timeout + Dss_Overhead); + + elsif Sequence_Steps (MSRC) then + Sub_Timeout := Sub_Timeout + Msrc_Dcc_Tcc_Timeout + Msrc_Overhead; + end if; + end if; + + if Sequence_Steps (Pre_Range) then + Pre_Range_Timeout_us := Sequence_Step_Timeout (This, Pre_Range); + + Sub_Timeout := + Sub_Timeout + Pre_Range_Timeout_us + Pre_Range_Overhead; + end if; + + if Sub_Timeout < Final_Range_Timing_Budget_us then + Final_Range_Timing_Budget_us := + Final_Range_Timing_Budget_us - Sub_Timeout; + + else + -- Requested timeout too big + Status := False; + + return; + end if; + + declare + VCSel_Pulse_Period_Pclk : UInt8; + Encoded_UInt16 : UInt16; + Timeout_Mclks : UInt32; + begin + if Sequence_Steps (Pre_Range) then + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Pre_Range); + + Read (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encoded_UInt16, Status); + + if Status then + Timeout_Mclks := Decode_Timeout (Encoded_UInt16); + end if; + else + Timeout_Mclks := 0; + end if; + + VCSel_Pulse_Period_Pclk := + VCSel_Pulse_Period (This, Final_Range); + + Timeout_Mclks := Timeout_Mclks + To_Timeout_Mclks + (Final_Range_Timing_Budget_us, + VCSel_Pulse_Period_Pclk); + + Write (This, REG_FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI, + Encode_Timeout (Timeout_Mclks), Status);" +function To_U32 is new Ada.Unchecked_Conversion,"(Fix_Point_16_16, UInt32); + Val : UInt16; + Status : Boolean; + begin + -- Expecting Fixed Point 9.7 + Val := UInt16 (Shift_Right (To_U32 (Limit_Mcps), 9) and 16#FF_FF#); + Write (This, + REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, + Val, + Status); + return Status; + end Set_Signal_Rate_Limit; + + --------------- + -- SPAD_Info -- + --------------- + + function SPAD_Info + (This : VL53L0X_Ranging_Sensor; + SPAD_Count : out HAL.UInt8; + Is_Aperture : out Boolean) return Boolean + is + Status : Boolean; + Tmp : UInt8; + begin + Write (This, 16#80#, UInt8'(16#01#), Status); + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#00#), Status); + end if; + + if Status then + Write (This, 16#FF#, UInt8'(16#06#), Status); + end if; + if Status then + Read (This, 16#83#, Tmp, Status); + end if; + if Status then + Write (This, 16#83#, Tmp or 16#04#, Status); + end if; + + if Status then + Write (This, 16#FF#, UInt8'(16#07#), Status); + end if; + if Status then + Write (This, 16#81#, UInt8'(16#01#), Status); + end if; + + if Status then + Write (This, 16#80#, UInt8'(16#01#), Status); + end if; + + if Status then + Write (This, 16#94#, UInt8'(16#6B#), Status); + end if; + if Status then + Write (This, 16#83#, UInt8'(16#00#), Status); + end if; + + loop + exit when not Status; + Read (This, 16#83#, Tmp, Status); + exit when Tmp /= 0; + end loop; + + if Status then + Write (This, 16#83#, UInt8'(16#01#), Status); + end if; + if Status then + Read (This, 16#92#, Tmp, Status); + end if; + + if Status then + SPAD_Count := Tmp and 16#7F#; + Is_Aperture := (Tmp and 16#80#) /= 0; + + Write (This, 16#81#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#06#), Status); + end if; + if Status then + Read (This, 16#83#, Tmp, Status); + end if; + if Status then + Write (This, 16#83#, Tmp and not 16#04#, Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#01#), Status); + end if; + + if Status then + Write (This, 16#FF#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + return Status; + end SPAD_Info; + + --------------------------- + -- Set_Signal_Rate_Limit -- + --------------------------- + + procedure Set_Signal_Rate_Limit + (This : VL53L0X_Ranging_Sensor; + Rate_Limit : Fix_Point_16_16) + is + function To_U32 is new Ada.Unchecked_Conversion + (Fix_Point_16_16, UInt32); + Reg : UInt16; + Status : Boolean with Unreferenced; + begin + -- Encoded as Fixed Point 9.7. Let's translate. + Reg := UInt16 (Shift_Right (To_U32 (Rate_Limit), 9) and 16#FFFF#); + Write (This, REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, + Reg, Status); + end Set_Signal_Rate_Limit; + + -------------------------------------- + -- Set_Vcsel_Pulse_Period_Pre_Range -- + -------------------------------------- + + procedure Set_VCSEL_Pulse_Period_Pre_Range + (This : VL53L0X_Ranging_Sensor; + Period : UInt8; + Status : out Boolean) + is + begin + Set_VCSel_Pulse_Period (This, Period, Pre_Range, Status); + end Set_VCSEL_Pulse_Period_Pre_Range; + + ---------------------------------------- + -- Set_Vcsel_Pulse_Period_Final_Range -- + ---------------------------------------- + + procedure Set_VCSEL_Pulse_Period_Final_Range + (This : VL53L0X_Ranging_Sensor; + Period : UInt8; + Status : out Boolean) + is + begin + Set_VCSel_Pulse_Period (This, Period, Final_Range, Status); + end Set_VCSEL_Pulse_Period_Final_Range; + + ---------------------------- + -- Set_VCSel_Pulse_Period -- + ---------------------------- + + procedure Set_VCSel_Pulse_Period + (This : VL53L0X_Ranging_Sensor; + Period : UInt8; + Sequence : VL53L0x_Sequence_Step; + Status : out Boolean) + is + Encoded : constant UInt8 := Shift_Right (Period, 1) - 1; + Phase_High : UInt8; + Pre_Timeout : UInt32; + Final_Timeout : UInt32; + Msrc_Timeout : UInt32; + Timeout_Mclks : UInt32; + Steps_Enabled : constant VL53L0x_Sequence_Step_Enabled := + Sequence_Step_Enabled (This); + Budget : UInt32; + Sequence_Cfg : UInt8; + + begin + -- Save the measurement timing budget + Budget := Measurement_Timing_Budget (This); + + case Sequence is + when Pre_Range => + Pre_Timeout := Sequence_Step_Timeout (This, Pre_Range); + Msrc_Timeout := Sequence_Step_Timeout (This, MSRC); + + case Period is + when 12 => + Phase_High := 16#18#; + when 14 => + Phase_High := 16#30#; + when 16 => + Phase_High := 16#40#; + when 18 => + Phase_High := 16#50#; + when others => + Status := False; + + return; + end case; + + Write (This, REG_PRE_RANGE_CONFIG_VALID_PHASE_HIGH, + Phase_High, Status); + if not Status then + return; + end if; + + Write (This, REG_PRE_RANGE_CONFIG_VALID_PHASE_LOW, + UInt8'(16#08#), Status); + if not Status then + return; + end if; + + Write (This, REG_PRE_RANGE_CONFIG_VCSEL_PERIOD, + Encoded, Status); + if not Status then + return; + end if; + + -- Update the timeouts + Timeout_Mclks := To_Timeout_Mclks (Pre_Timeout, Period); + Write (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, + UInt16 (Timeout_Mclks), Status); + + Timeout_Mclks := To_Timeout_Mclks (Msrc_Timeout, Period); + if Timeout_Mclks > 256 then + Timeout_Mclks := 255; + else + Timeout_Mclks := Timeout_Mclks - 1; + end if; + + Write (This, REG_MSRC_CONFIG_TIMEOUT_MACROP, + UInt8 (Timeout_Mclks), Status); + + when Final_Range => + Pre_Timeout := Sequence_Step_Timeout + (This, Pre_Range, As_Mclks => True); + Final_Timeout := Sequence_Step_Timeout (This, Final_Range); + + declare + Phase_High : UInt8; + Width : UInt8; + Cal_Timeout : UInt8; + Cal_Lim : UInt8; + begin + case Period is + when 8 => + Phase_High := 16#10#; + Width := 16#02#; + Cal_Timeout := 16#0C#; + Cal_Lim := 16#30#; + when 10 => + Phase_High := 16#28#; + Width := 16#03#; + Cal_Timeout := 16#09#; + Cal_Lim := 16#20#; + when 12 => + Phase_High := 16#38#; + Width := 16#03#; + Cal_Timeout := 16#08#; + Cal_Lim := 16#20#; + when 14 => + Phase_High := 16#48#; + Width := 16#03#; + Cal_Timeout := 16#07#; + Cal_Lim := 16#20#; + when others => + return; + end case; + + Write (This, REG_FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, + Phase_High, Status); + if not Status then + return; + end if; + + Write (This, REG_FINAL_RANGE_CONFIG_VALID_PHASE_LOW, + UInt8'(16#08#), Status); + if not Status then + return; + end if; + + Write (This, REG_GLOBAL_CONFIG_VCSEL_WIDTH, + Width, Status); + if not Status then + return; + end if; + + Write (This, REG_ALGO_PHASECAL_CONFIG_TIMEOUT, + Cal_Timeout, Status); + if not Status then + return; + end if; + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, REG_ALGO_PHASECAL_LIM, + Cal_Lim, Status); + Write (This, 16#FF#, UInt8'(16#00#), Status); + if not Status then + return; + end if;" +function To_UInt16 is,"new Ada.Unchecked_Conversion (UInt16_HL_Type, UInt16); + + Ret : TP_Touch_State; + Regs : FT6206_Pressure_Registers; + Tmp : UInt16_HL_Type; + Status : Boolean; + begin + if Touch_Id not in FT6206_Px_Regs'Range then + return (0, 0, 0); + end if; + + if Touch_Id > This.Active_Touch_Points then + return (0, 0, 0); + end if; + + -- X/Y are swaped from the screen coordinates + + Regs := FT6206_Px_Regs (Touch_Id); + + Tmp.Low := This.I2C_Read (Regs.XL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.XH_Reg, Status) and + FT6206_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.Y := Natural (To_UInt16 (Tmp)); + + Tmp.Low := This.I2C_Read (Regs.YL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.YH_Reg, Status) and + FT6206_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.X := Natural (To_UInt16 (Tmp)); + + Ret.Weight := Natural (This.I2C_Read (Regs.Weight_Reg, Status)); + + if not Status then + Ret.Weight := 0; + end if; + + if Ret.Weight = 0 then + Ret.Weight := 50; + end if; + + Ret.X := Natural'Max (0, Ret.X); + Ret.Y := Natural'Max (0, Ret.Y); + Ret.X := Natural'Min (This.LCD_Natural_Width - 1, Ret.X); + Ret.Y := Natural'Min (This.LCD_Natural_Height - 1, Ret.Y); + + if (This.Swap and Invert_X) /= 0 then + Ret.X := This.LCD_Natural_Width - Ret.X - 1; + end if; + if (This.Swap and Invert_Y) /= 0 then + Ret.Y := This.LCD_Natural_Height - Ret.Y - 1; + end if; + if (This.Swap and Swap_XY) /= 0 then + declare + Tmp_X : constant Integer := Ret.X; + begin + Ret.X := Ret.Y; + Ret.Y := Tmp_X;" +function Read_Register (This : STMPE811_Device;,"Reg_Addr : UInt8) return UInt8 + is + Data : TSC_Data (1 .. 1); + Status : I2C_Status; + + begin + This.Port.Mem_Read (This.I2C_Addr, + UInt16 (Reg_Addr), + Memory_Size_8b, + Data, + Status); + + if Status /= Ok then + raise Program_Error with ""Timeout while reading TC data""; + end if; + + return Data (1); + end Read_Register; + + -------------------- + -- Write_Register -- + -------------------- + + procedure Write_Register (This : in out STMPE811_Device; + Reg_Addr : UInt8; + Data : UInt8) is + Status : I2C_Status; + + begin + This.Port.Mem_Write (This.I2C_Addr, + UInt16 (Reg_Addr), + Memory_Size_8b, + (1 => Data), + Status); + + if Status /= Ok then + raise Program_Error with ""Timeout while reading TC data""; + end if; + end Write_Register; + + --------------- + -- IOE_Reset -- + --------------- + + procedure IOE_Reset (This : in out STMPE811_Device) is + begin + This.Write_Register (IOE_REG_SYS_CTRL1, 16#02#); + + -- Give some time for the reset + This.Time.Delay_Milliseconds (2); + + This.Write_Register (IOE_REG_SYS_CTRL1, 16#00#); + end IOE_Reset; + + -------------------------- + -- IOE_Function_Command -- + -------------------------- + + procedure IOE_Function_Command (This : in out STMPE811_Device; + Func : UInt8; + Enabled : Boolean) + is + Reg : UInt8 := This.Read_Register (IOE_REG_SYS_CTRL2); + begin + -- CTRL2 functions are disabled when corresponding bit is set + + if Enabled then + Reg := Reg and (not Func); + else + Reg := Reg or Func; + end if; + + This.Write_Register (IOE_REG_SYS_CTRL2, Reg); + end IOE_Function_Command; + + ------------------- + -- IOE_AF_Config -- + ------------------- + + procedure IOE_AF_Config (This : in out STMPE811_Device; + Pin : UInt8; + Enabled : Boolean) is + Reg : UInt8 := This.Read_Register (IOE_REG_GPIO_AF); + begin + if Enabled then + Reg := Reg or Pin; + else + Reg := Reg and (not Pin); + end if; + + This.Write_Register (IOE_REG_GPIO_AF, Reg); + end IOE_AF_Config; + + ---------------- + -- Get_IOE_ID -- + ---------------- + + function Get_IOE_ID (This : in out STMPE811_Device) return UInt16 is + begin + return (UInt16 (This.Read_Register (0)) * (2**8)) + or UInt16 (This.Read_Register (1)); + end Get_IOE_ID; + + ---------------- + -- Initialize -- + ---------------- + + function Initialize (This : in out STMPE811_Device) return Boolean + is + begin + + This.Time.Delay_Milliseconds (100); + + if This.Get_IOE_ID /= 16#0811# then + return False; + end if; + + This.IOE_Reset; + + This.IOE_Function_Command (IOE_ADC_FCT, True); + This.IOE_Function_Command (IOE_TSC_FCT, True); + + This.Write_Register (IOE_REG_ADC_CTRL1, 16#49#); + + This.Time.Delay_Milliseconds (2); + + This.Write_Register (IOE_REG_ADC_CTRL2, 16#01#); + + This.IOE_AF_Config (TOUCH_IO_ALL, False); + + This.Write_Register (IOE_REG_TSC_CFG, 16#9A#); + + This.Write_Register (IOE_REG_FIFO_TH, 16#01#); + + This.Write_Register (IOE_REG_FIFO_STA, 16#01#); + + This.Write_Register (IOE_REG_FIFO_TH, 16#00#); + + This.Write_Register (IOE_REG_TSC_FRACT_Z, 16#00#); + + This.Write_Register (IOE_REG_TSC_I_DRIVE, 16#01#); + + This.Write_Register (IOE_REG_TSC_CTRL, 16#01#); + + This.Write_Register (IOE_REG_INT_STA, 16#FF#); + + return True; + end Initialize; + + ---------------- + -- Set_Bounds -- + ---------------- + + overriding + procedure Set_Bounds (This : in out STMPE811_Device; + Width : Natural; + Height : Natural; + Swap : HAL.Touch_Panel.Swap_State) + is + begin + This.LCD_Natural_Width := Width; + This.LCD_Natural_Height := Height; + This.Swap := Swap; + end Set_Bounds; + + ------------------------- + -- Active_Touch_Points -- + ------------------------- + + overriding + function Active_Touch_Points (This : in out STMPE811_Device) + return Touch_Identifier + is + Val : constant UInt8 := This.Read_Register (IOE_REG_TSC_CTRL) and 16#80#; + begin + if Val = 0 then + This.Write_Register (IOE_REG_FIFO_STA, 16#01#); + This.Write_Register (IOE_REG_FIFO_STA, 16#00#); + + return 0; + else + return 1; + end if; + end Active_Touch_Points; + + --------------------- + -- Get_Touch_Point -- + --------------------- + + overriding + function Get_Touch_Point (This : in out STMPE811_Device; + Touch_Id : Touch_Identifier) + return TP_Touch_State + is + State : TP_Touch_State; + Raw_X : UInt32; + Raw_Y : UInt32; + Raw_Z : UInt32; + X : Integer; + Y : Integer; + Tmp : Integer; + + begin + + -- Check Touch detected bit in CTRL register + if Touch_Id /= 1 or else This.Active_Touch_Points = 0 then + return (0, 0, 0); + end if; + + declare + Data_X : constant TSC_Data := This.Read_Data (IOE_REG_TSC_DATA_X, 2); + Data_Y : constant TSC_Data := This.Read_Data (IOE_REG_TSC_DATA_Y, 2); + Data_Z : constant TSC_Data := This.Read_Data (IOE_REG_TSC_DATA_Z, 1); + Z_Frac : constant TSC_Data := This.Read_Data (IOE_REG_TSC_FRACT_Z, 1); + + begin + Raw_X := 2 ** 12 - + (Shift_Left (UInt32 (Data_X (1)) and 16#0F#, 8) or UInt32 (Data_X (2))); + Raw_Y := + Shift_Left (UInt32 (Data_Y (1)) and 16#0F#, 8) or UInt32 (Data_Y (2)); + Raw_Z := + Shift_Right (UInt32 (Data_Z (1)), Natural (Z_Frac (1) and 2#111#));" +function To_UInt16 is,"new Ada.Unchecked_Conversion (UInt16_HL_Type, UInt16); + + Ret : TP_Touch_State; + Regs : FT5336_Pressure_Registers; + Tmp : UInt16_HL_Type; + Status : Boolean; + + begin + -- X/Y are swaped from the screen coordinates + + if Touch_Id not in FT5336_Px_Regs'Range + or else Touch_Id > This.Active_Touch_Points + then + return (0, 0, 0); + end if; + + Regs := FT5336_Px_Regs (Touch_Id); + + Tmp.Low := This.I2C_Read (Regs.XL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.XH_Reg, Status) and + FT5336_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.Y := Natural (To_UInt16 (Tmp)); + + Tmp.Low := This.I2C_Read (Regs.YL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.YH_Reg, Status) and + FT5336_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.X := Natural (To_UInt16 (Tmp)); + + Ret.Weight := Natural (This.I2C_Read (Regs.Weight_Reg, Status)); + + if not Status then + Ret.Weight := 0; + end if; + + Ret.X := + Natural'Min (Natural'Max (0, Ret.X), This.LCD_Natural_Width - 1); + Ret.Y := + Natural'Min (Natural'Max (0, Ret.Y), This.LCD_Natural_Height - 1); + + if (This.Swap and Invert_X) /= 0 then + Ret.X := This.LCD_Natural_Width - Ret.X - 1; + end if; + if (This.Swap and Invert_Y) /= 0 then + Ret.Y := This.LCD_Natural_Height - Ret.Y - 1; + end if; + if (This.Swap and Swap_XY) /= 0 then + declare + Tmp_X : constant Integer := Ret.X; + begin + Ret.X := Ret.Y; + Ret.Y := Tmp_X;" +procedure Destroy is new Ada.Unchecked_Deallocation,"(File_Handle, File_Handle_Access); + procedure Destroy is new Ada.Unchecked_Deallocation + (Directory_Handle, Directory_Handle_Access); + procedure Destroy is new Ada.Unchecked_Deallocation + (Node_Handle, Node_Handle_Access); + + function ""<"" (Left, Right : Node_Handle) return Boolean is + (Ada.Strings.Unbounded.""<"" (Left.Name, Right.Name)); + + package Node_Sorting is + new Node_Vectors.Generic_Sorting; + + -- Most of the time, standard operations give us no reliable way to + -- determine specifically what triggered a failure, so use the following + -- error code as a ""generic"" one. + + Generic_Error : constant Status_Code := Input_Output_Error; + + function Absolute_Path + (This : Native_FS_Driver; + Relative_Path : String) + return String + is (if Relative_Path = """" + then +This.Root_Dir + else Join (+This.Root_Dir, Relative_Path, True)); + + ---------------- + -- Get_Handle -- + ---------------- + + function Get_Handle + (FS : in out Native_FS_Driver) + return File_Handle_Access + is + Result : File_Handle_Access := FS.Free_File_Handles; + begin + if Result = null then + Result := new File_Handle' + (FS => FS'Unrestricted_Access, + others => <>); + else + FS.Free_File_Handles := Result.Next; + end if; + return Result; + end Get_Handle; + + ---------------- + -- Get_Handle -- + ---------------- + + function Get_Handle + (FS : in out Native_FS_Driver) + return Directory_Handle_Access + is + Result : Directory_Handle_Access := FS.Free_Dir_Handles; + begin + if Result = null then + Result := new Directory_Handle' + (FS => FS'Unrestricted_Access, + others => <>); + else + FS.Free_Dir_Handles := Result.Next; + end if; + return Result; + end Get_Handle; + + --------------------- + -- Add_Free_Handle -- + --------------------- + + procedure Add_Free_Handle + (FS : in out Native_FS_Driver; + Handle : in out File_Handle_Access) + is + begin + Handle.Next := FS.Free_File_Handles; + FS.Free_File_Handles := Handle; + Handle := null; + end Add_Free_Handle; + + --------------------- + -- Add_Free_Handle -- + --------------------- + + procedure Add_Free_Handle + (FS : in out Native_FS_Driver; + Handle : in out Directory_Handle_Access) + is + begin + Handle.Next := FS.Free_Dir_Handles; + FS.Free_Dir_Handles := Handle; + Handle := null; + end Add_Free_Handle; + + ------------- + -- Destroy -- + ------------- + + procedure Destroy (This : in out Native_FS_Driver_Access) is + procedure Destroy is new Ada.Unchecked_Deallocation + (Native_FS_Driver, Native_FS_Driver_Access); + begin + -- Free all handles + + while This.Free_File_Handles /= null loop + declare + H : constant File_Handle_Access := This.Free_File_Handles.Next; + begin + Destroy (This.Free_File_Handles); + This.Free_File_Handles := H;" +procedure Draw_Glyph is new Hershey_Fonts.Draw_Glyph,"(Internal_Draw_Line); + + Current : Point := Start; + + begin + Buffer.Set_Source (Foreground); + for C of Msg loop + exit when Current.X > Buffer.Width; + Draw_Glyph + (Fnt => Font, + C => C, + X => Current.X, + Y => Current.Y, + Height => Height, + Bold => Bold); + end loop; + end Draw_String; + + ----------------- + -- Draw_String -- + ----------------- + + procedure Draw_String + (Buffer : in out Bitmap_Buffer'Class; + Area : Rect; + Msg : String; + Font : Hershey_Font; + Bold : Boolean; + Outline : Boolean; + Foreground : Bitmap_Color; + Fast : Boolean := True) + is + Length : constant Natural := + Hershey_Fonts.Strlen (Msg, Font, Area.Height); + Ratio : Float; + Current : Point := (0, 0); + Prev : UInt32; + FG : constant UInt32 := Bitmap_Color_To_Word (Buffer.Color_Mode, + Foreground); + Blk : constant UInt32 := Bitmap_Color_To_Word (Buffer.Color_Mode, + Black); + + procedure Internal_Draw_Line + (X0, Y0, X1, Y1 : Natural; + Width : Positive); + + procedure Internal_Draw_Line + (X0, Y0, X1, Y1 : Natural; + Width : Positive) + is + begin + Draw_Line (Buffer, + (Area.Position.X + Natural (Float (X0) * Ratio), + Area.Position.Y + Y0), + (Area.Position.X + Natural (Float (X1) * Ratio), + Area.Position.Y + Y1), + Width, + Fast); + end Internal_Draw_Line; + + procedure Draw_Glyph is new Hershey_Fonts.Draw_Glyph + (Internal_Draw_Line); + + begin + if Length > Area.Width then + Ratio := Float (Area.Width) / Float (Length); + else + Ratio := 1.0; + Current.X := (Area.Width - Length) / 2; + end if; + + Buffer.Set_Source (Foreground); + + for C of Msg loop + Draw_Glyph + (Fnt => Font, + C => C, + X => Current.X, + Y => Current.Y, + Height => Area.Height, + Bold => Bold); + end loop; + + if Outline and then Area.Height > 40 then + for Y in Area.Position.Y + 1 .. Area.Position.Y + Area.Height loop + Prev := Buffer.Pixel ((Area.Position.X, Y)); + if Prev = FG then + Buffer.Set_Pixel ((Area.Position.X, Y), Black); + end if; + + for X in Area.Position.X + 1 .. Area.Position.X + Area.Width loop + declare + Col : constant UInt32 := Buffer.Pixel ((X, Y)); + Top : constant UInt32 := Buffer.Pixel ((X, Y - 1)); + begin + + if Prev /= FG + and then Col = FG + then + Buffer.Set_Pixel ((X, Y), Blk); + + elsif Prev = FG + and then Col /= FG + then + Buffer.Set_Pixel ((X - 1, Y), Blk); + + elsif Top /= FG + and then Top /= Blk + and then Col = FG + then + Buffer.Set_Pixel ((X, Y), Blk); + + elsif Top = FG + and then Col /= FG + then + Buffer.Set_Pixel ((X, Y - 1), Blk); + end if; + + Prev := Col;" +procedure adainit is,"procedure Start_Slave_CPUs; + pragma Import (C, Start_Slave_CPUs, ""__gnat_start_slave_cpus""); + begin + + Ada.Real_Time'Elab_Body; + E021 := E021 + 1; + System.Tasking.Protected_Objects'Elab_Body; + E087 := E087 + 1; + System.Tasking.Protected_Objects.Multiprocessors'Elab_Body; + E091 := E091 + 1; + System.Tasking.Restricted.Stages'Elab_Body; + E083 := E083 + 1; + E013 := E013 + 1; + Cortex_M.Cache'Elab_Body; + E143 := E143 + 1; + E195 := E195 + 1; + HAL.SDMMC'ELAB_SPEC; + E149 := E149 + 1; + FT5336'ELAB_BODY; + E206 := E206 + 1; + E212 := E212 + 1; + E210 := E210 + 1; + Ravenscar_Time'Elab_Body; + E169 := E169 + 1; + E147 := E147 + 1; + Soft_Drawing_Bitmap'Elab_Body; + E197 := E197 + 1; + Memory_Mapped_Bitmap'Elab_Body; + E193 := E193 + 1; + STM32.ADC'ELAB_SPEC; + E100 := E100 + 1; + E103 := E103 + 1; + E109 := E109 + 1; + E178 := E178 + 1; + STM32.DMA2D.INTERRUPT'ELAB_BODY; + E181 := E181 + 1; + E183 := E183 + 1; + STM32.DMA2D_BITMAP'ELAB_SPEC; + STM32.DMA2D_BITMAP'ELAB_BODY; + E191 := E191 + 1; + E117 := E117 + 1; + E187 := E187 + 1; + STM32.I2C'ELAB_BODY; + E123 := E123 + 1; + E134 := E134 + 1; + E113 := E113 + 1; + STM32.RTC'ELAB_BODY; + E131 := E131 + 1; + STM32.SPI'ELAB_BODY; + E157 := E157 + 1; + STM32.SPI.DMA'ELAB_BODY; + E160 := E160 + 1; + STM32.GPIO'ELAB_BODY; + E111 := E111 + 1; + E153 := E153 + 1; + STM32.DEVICE'ELAB_SPEC; + E096 := E096 + 1; + STM32.SDMMC'ELAB_BODY; + E140 := E140 + 1; + STM32.I2S'ELAB_BODY; + E127 := E127 + 1; + E115 := E115 + 1; + STM32.LTDC'ELAB_BODY; + E199 := E199 + 1; + E165 := E165 + 1; + E167 := E167 + 1; + WM8994'ELAB_BODY; + E172 := E172 + 1; + Audio'Elab_Spec; + Framebuffer_Rk043fn48h'Elab_Body; + E174 := E174 + 1; + STM32.BOARD'ELAB_SPEC; + E074 := E074 + 1; + Sdcard'Elab_Body; + E202 := E202 + 1; + E185 := E185 + 1; + Framebuffer_Ltdc'Elab_Body; + E176 := E176 + 1; + Audio'Elab_Body; + E094 := E094 + 1; + Touch_Panel_Ft5336'Elab_Body; + E204 := E204 + 1; + E019 := E019 + 1; + Lcd_Std_Out'Elab_Body; + E208 := E208 + 1; + STM32.USER_BUTTON'ELAB_BODY; + E214 := E214 + 1; + Start_Slave_CPUs; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_draw""); + + procedure main is + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + adainit; + Ada_Main_Program;" +procedure Clear;,"----------- + -- Clear -- + ----------- + + procedure Clear is + begin + Display.Hidden_Buffer (1).Set_Source (BG); + Display.Hidden_Buffer (1).Fill; + + LCD_Std_Out.Clear_Screen; + LCD_Std_Out.Put_Line (""Touch the screen to draw or""); + LCD_Std_Out.Put_Line (""press the blue button for""); + LCD_Std_Out.Put_Line (""a demo of drawing pimitives.""); + + Display.Update_Layer (1, Copy_Back => True); + end Clear; + + Last_X : Integer := -1; + Last_Y : Integer := -1; + + type Mode is (Drawing_Mode, Bitmap_Showcase_Mode); + + Current_Mode : Mode := Drawing_Mode; + +begin + + -- Initialize LCD + Display.Initialize; + Display.Initialize_Layer (1, ARGB_8888); + + -- Initialize touch panel + Touch_Panel.Initialize; + + -- Initialize button + User_Button.Initialize; + + LCD_Std_Out.Set_Font (BMP_Fonts.Font8x8); + LCD_Std_Out.Current_Background_Color := BG; + + -- Clear LCD (set background) + Clear; + + -- The application: set pixel where the finger is (so that you + -- cannot see what you are drawing). + loop + if User_Button.Has_Been_Pressed then + case Current_Mode is + when Drawing_Mode => + Current_Mode := Bitmap_Showcase_Mode; + when Bitmap_Showcase_Mode => + Clear; + Current_Mode := Drawing_Mode; + end case; + end if; + + if Current_Mode = Drawing_Mode then + + Display.Hidden_Buffer (1).Set_Source (HAL.Bitmap.Green); + + declare + State : constant TP_State := Touch_Panel.Get_All_Touch_Points; + begin + if State'Length = 0 then + Last_X := -1; + Last_Y := -1; + + elsif State'Length = 1 then + -- Lines can be drawn between two consecutive points only when + -- one touch point is active: the order of the touch data is not + -- necessarily preserved by the hardware. + if Last_X > 0 then + Draw_Line + (Display.Hidden_Buffer (1).all, + Start => (Last_X, Last_Y), + Stop => (State (State'First).X, State (State'First).Y), + Thickness => State (State'First).Weight / 2, + Fast => False); + end if; + + Last_X := State (State'First).X; + Last_Y := State (State'First).Y; + + else + Last_X := -1; + Last_Y := -1; + end if; + + for Id in State'Range loop + Fill_Circle + (Display.Hidden_Buffer (1).all, + Center => (State (Id).X, State (Id).Y), + Radius => State (Id).Weight / 4); + end loop; + + if State'Length > 0 then + Display.Update_Layer (1, Copy_Back => True); + end if;" +procedure Host is,"COM : aliased Serial_Port; + COM3 : constant Port_Name := Name (3); + + Outgoing : String (1 .. 1024); -- arbitrary + Last : Natural; +begin + COM.Open (COM3); + COM.Set (Rate => B115200, Block => False); + + loop + Put (""> ""); + Get_Line (Outgoing, Last); + exit when Last = Outgoing'First - 1; + + Put_Line (""Sending: '"" & Outgoing (1 .. Last) & ""'""); + + String'Output (COM'Access, Outgoing (1 .. Last)); + + declare + Incoming : constant String := String'Input (COM'Access); + begin + Put_Line (""From board: "" & Incoming);" +-- procedure Host is,"-- COM : aliased Serial_Port; +-- COM3 : constant Port_Name := Name (3); +-- +-- Outgoing : String (1 .. 1024); -- arbitrary +-- Last : Natural; +-- begin +-- COM.Open (COM3); +-- COM.Set (Rate => B115200, Block => False); +-- +-- loop +-- Put (""> ""); +-- Get_Line (Outgoing, Last); +-- exit when Last = Outgoing'First - 1; +-- +-- Put_Line (""Sending: '"" & Outgoing (1 .. Last) & ""'""); +-- String'Output (COM'Access, Outgoing (1 .. Last)); +-- +-- declare +-- Incoming : constant String := String'Input (COM'Access); +-- begin +-- Put_Line (""From board: "" & Incoming); +-- end; +-- end loop; +-- +-- COM.Close; +-- end Host; + +-- You can change the COM port number, or even get it from the command line +-- as an argument, but it must match what the host OS sees from the USB-COM +-- cable. + +-- When running it, enter a string at the prompt ("">"") or just hit carriage +-- return if you are ready to quit. If you enter a string, it will be sent to +-- the target board, along with the bounds. The program (in this file) running +-- on the target, echos it back so the host app will show that response from +-- the board. + +-- TARGET BOARD SIDE: + +-- This file declares the main procedure for the program running on the target +-- board. It simply echos the incoming strings, forever. + +with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); + +with Peripherals_Streaming; use Peripherals_Streaming; +with Serial_IO.Streaming; use Serial_IO.Streaming; + +procedure Demo_Serial_Port_Streaming is +begin + Initialize (COM); + Configure (COM, Baud_Rate => 115_200); + + loop + declare + Incoming : constant String := String'Input (COM'Access); + begin + String'Output (COM'Access, ""'"" & Incoming & ""'"");" +procedure Main is,"use type Partitions.Status_Code; + + procedure List_Dir (Path : String); + -- List files in directory + + procedure List_Partitions (Path_To_Disk_Image : String); + -- List partition in a disk file + + -------------- + -- List_Dir -- + -------------- + + procedure List_Dir (Path : String) is + Status : Status_Code; + DD : Directory_Descriptor; + begin + Status := Open (DD, Path); + if Status /= OK then + Semihosting.Log_Line (""Open Directory '"" & Path & ""' Error: "" & Status'Img); + else + Semihosting.Log_Line (""Listing '"" & Path & ""' content:""); + loop + declare + Ent : constant Directory_Entry := Read (DD); + begin + if Ent /= Invalid_Dir_Entry then + Semihosting.Log_Line ("" - '"" & Ent.Name & ""'""); + Semihosting.Log_Line ("" Kind: "" & Ent.Subdirectory'Img); + else + exit; + end if;" +procedure Xaa is,"begin + Ada.Text_Io.Put_Line(""Xaa() called"");" +procedure Xab is,"begin + Ada.Text_Io.Put_Line(""Xab() called"");" +procedure Xac is,"begin + Ada.Text_Io.Put_Line(""Xac() called"");" +procedure Object_Hierarchy is,"procedure Dump_Object (This : in out Aof.Core.Objects.Access_Object) is + begin + Ada.Text_Io.Put_Line(""Object: "" & This.Get_Name);" +procedure Xaa is,"begin + Ada.Text_Io.Put_Line(""Xaa() called"");" +procedure Xab is,"begin + Ada.Text_Io.Put_Line(""Xab() called"");" +procedure Xac is,"begin + Ada.Text_Io.Put_Line(""Xac() called"");" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (C, s_stalib_adafinal, ""system__standard_library__adafinal""); + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Exception_Tracebacks : Integer; + pragma Import (C, Exception_Tracebacks, ""__gl_exception_tracebacks""); + Zero_Cost_Exceptions : Integer; + pragma Import (C, Zero_Cost_Exceptions, ""__gl_zero_cost_exceptions""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Leap_Seconds_Support : Integer; + pragma Import (C, Leap_Seconds_Support, ""__gl_leap_seconds_support""); + + procedure Install_Handler; + pragma Import (C, Install_Handler, ""__gnat_install_handler""); + + Handler_Installed : Integer; + pragma Import (C, Handler_Installed, ""__gnat_handler_installed""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Exception_Tracebacks := 1; + Zero_Cost_Exceptions := 1; + Detect_Blocking := 0; + Default_Stack_Size := -1; + Leap_Seconds_Support := 0; + + if Handler_Installed = 0 then + Install_Handler; + end if; + + Finalize_Library_Objects := null; + + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E36 := E36 + 1; + System.Soft_Links'Elab_Body; + E26 := E26 + 1; + System.Secondary_Stack'Elab_Body; + E30 := E30 + 1; + E08 := E08 + 1; + E06 := E06 + 1; + E12 := E12 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_project_main""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + gnat_argc := argc; + gnat_argv := argv; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (C, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Leap_Seconds_Support : Integer; + pragma Import (C, Leap_Seconds_Support, ""__gl_leap_seconds_support""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + procedure Install_Restricted_Handlers_Sequential; + pragma Import (C,Install_Restricted_Handlers_Sequential, ""__gnat_attach_all_handlers""); + + Partition_Elaboration_Policy : Character; + pragma Import (C, Partition_Elaboration_Policy, ""__gnat_partition_elaboration_policy""); + + procedure Activate_All_Tasks_Sequential; + pragma Import (C, Activate_All_Tasks_Sequential, ""__gnat_activate_all_tasks""); + procedure Start_Slave_CPUs; + pragma Import (C, Start_Slave_CPUs, ""__gnat_start_slave_cpus""); + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := 0; + WC_Encoding := 'b'; + Locking_Policy := 'C'; + Queuing_Policy := ' '; + Task_Dispatching_Policy := 'F'; + Partition_Elaboration_Policy := 'S'; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 1; + Default_Stack_Size := -1; + Leap_Seconds_Support := 0; + + Runtime_Initialize (1); + + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E051 := E051 + 1; + Ada.Tags'Elab_Body; + E095 := E095 + 1; + System.Bb.Timing_Events'Elab_Spec; + E109 := E109 + 1; + E053 := E053 + 1; + Ada.Real_Time'Elab_Body; + E006 := E006 + 1; + System.Tasking.Protected_Objects'Elab_Body; + E126 := E126 + 1; + System.Tasking.Protected_Objects.Multiprocessors'Elab_Body; + E139 := E139 + 1; + System.Tasking.Restricted.Stages'Elab_Body; + E133 := E133 + 1; + ST.STM32F4.GPIO'ELAB_SPEC; + E142 := E142 + 1; + ST.STM32F4.RCC'ELAB_SPEC; + E141 := E141 + 1; + Button'Elab_Spec; + Button'Elab_Body; + E121 := E121 + 1; + Lights'Elab_Spec; + Lights'Elab_Body; + E119 := E119 + 1; + Install_Restricted_Handlers_Sequential; + Activate_All_Tasks_Sequential; + Start_Slave_CPUs; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_led_flasher""); + + procedure main is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize;" +procedure finalize_library is,"begin +<<<<<<< HEAD + E98 := E98 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__text_io__text_streams__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""ada__text_io__finalize_spec""); + begin + F2;" +procedure F3;,"pragma Import (Ada, F3, ""system__file_io__finalize_body""); + begin + E64 := E64 - 1; + F3;" +procedure F4;,"pragma Import (Ada, F4, ""system__file_control_block__finalize_spec""); + begin + E77 := E77 - 1; + F4;" +procedure F5;,"pragma Import (Ada, F5, ""system__pool_global__finalize_spec""); + begin + F5;" +procedure F6;,"pragma Import (Ada, F6, ""system__storage_pools__subpools__finalize_spec""); +======= + E117 := E117 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__directories__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""system__regexp__finalize_spec""); + begin + F2;" +procedure F3;,"pragma Import (Ada, F3, ""ada__text_io__finalize_spec""); + begin + F3;" +procedure F4;,"pragma Import (Ada, F4, ""ada__strings__unbounded__finalize_spec""); + begin + F4;" +procedure F5;,"pragma Import (Ada, F5, ""system__storage_pools__subpools__finalize_spec""); + begin + F5;" +procedure F6;,"pragma Import (Ada, F6, ""system__finalization_masters__finalize_spec""); +>>>>>>> 69f69bc261da4a8489896c1cdee2a7aab20a4053 + begin + F6;" +procedure F7;,"<<<<<<< HEAD + pragma Import (Ada, F7, ""system__finalization_masters__finalize_spec""); + begin +======= + pragma Import (Ada, F7, ""system__file_io__finalize_body""); + begin + E109 := E109 - 1; +>>>>>>> 69f69bc261da4a8489896c1cdee2a7aab20a4053 + F7;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (C, s_stalib_adafinal, ""system__standard_library__adafinal""); +<<<<<<< HEAD +======= + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + +>>>>>>> 69f69bc261da4a8489896c1cdee2a7aab20a4053 + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; +<<<<<<< HEAD +======= + Runtime_Finalize; +>>>>>>> 69f69bc261da4a8489896c1cdee2a7aab20a4053 + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Exception_Tracebacks : Integer; + pragma Import (C, Exception_Tracebacks, ""__gl_exception_tracebacks""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Leap_Seconds_Support : Integer; + pragma Import (C, Leap_Seconds_Support, ""__gl_leap_seconds_support""); +<<<<<<< HEAD + + procedure Install_Handler; + pragma Import (C, Install_Handler, ""__gnat_install_handler""); + + Handler_Installed : Integer; + pragma Import (C, Handler_Installed, ""__gnat_handler_installed""); +======= + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); +>>>>>>> 69f69bc261da4a8489896c1cdee2a7aab20a4053 + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Exception_Tracebacks := 1; + Detect_Blocking := 0; + Default_Stack_Size := -1; + Leap_Seconds_Support := 0; + +<<<<<<< HEAD + if Handler_Installed = 0 then + Install_Handler; + end if; +======= + Runtime_Initialize (1); +>>>>>>> 69f69bc261da4a8489896c1cdee2a7aab20a4053 + + Finalize_Library_Objects := finalize_library'access; + + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; +<<<<<<< HEAD + E23 := E23 + 1; + Ada.Io_Exceptions'Elab_Spec; + E50 := E50 + 1; + Ada.Tags'Elab_Spec; + Ada.Streams'Elab_Spec; + E49 := E49 + 1; + Interfaces.C'Elab_Spec; + System.Exceptions'Elab_Spec; + E29 := E29 + 1; + System.Finalization_Root'Elab_Spec; + E68 := E68 + 1; + Ada.Finalization'Elab_Spec; + E66 := E66 + 1; + System.Storage_Pools'Elab_Spec; + E87 := E87 + 1; + System.Finalization_Masters'Elab_Spec; + System.Storage_Pools.Subpools'Elab_Spec; + System.Pool_Global'Elab_Spec; + E89 := E89 + 1; + System.File_Control_Block'Elab_Spec; + E77 := E77 + 1; + System.File_Io'Elab_Body; + E64 := E64 + 1; + E93 := E93 + 1; + System.Finalization_Masters'Elab_Body; + E79 := E79 + 1; + E70 := E70 + 1; + Ada.Tags'Elab_Body; + E52 := E52 + 1; + System.Soft_Links'Elab_Body; + E13 := E13 + 1; + System.Os_Lib'Elab_Body; + E74 := E74 + 1; + System.Secondary_Stack'Elab_Body; + E17 := E17 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E06 := E06 + 1; + Ada.Text_Io.Text_Streams'Elab_Spec; + E98 := E98 + 1; +======= + E023 := E023 + 1; + Ada.Io_Exceptions'Elab_Spec; + E066 := E066 + 1; + Ada.Strings'Elab_Spec; + E050 := E050 + 1; + Ada.Containers'Elab_Spec; + E038 := E038 + 1; + System.Exceptions'Elab_Spec; + E025 := E025 + 1; + System.Soft_Links'Elab_Body; + E013 := E013 + 1; + Interfaces.C'Elab_Spec; + System.Os_Lib'Elab_Body; + E070 := E070 + 1; + Ada.Strings.Maps'Elab_Spec; + Ada.Strings.Maps.Constants'Elab_Spec; + E056 := E056 + 1; + System.Secondary_Stack'Elab_Body; + E017 := E017 + 1; + System.Object_Reader'Elab_Spec; + System.Dwarf_Lines'Elab_Spec; + E045 := E045 + 1; + E076 := E076 + 1; + E052 := E052 + 1; + System.Traceback.Symbolic'Elab_Body; + E037 := E037 + 1; + E078 := E078 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E099 := E099 + 1; + Ada.Streams'Elab_Spec; + E097 := E097 + 1; + System.File_Control_Block'Elab_Spec; + E113 := E113 + 1; + System.Finalization_Root'Elab_Spec; + E112 := E112 + 1; + Ada.Finalization'Elab_Spec; + E110 := E110 + 1; + System.File_Io'Elab_Body; + E109 := E109 + 1; + System.Storage_Pools'Elab_Spec; + E157 := E157 + 1; + System.Finalization_Masters'Elab_Spec; + System.Finalization_Masters'Elab_Body; + E153 := E153 + 1; + System.Storage_Pools.Subpools'Elab_Spec; + E151 := E151 + 1; + Ada.Strings.Unbounded'Elab_Spec; + E145 := E145 + 1; + Ada.Calendar'Elab_Spec; + Ada.Calendar'Elab_Body; + E119 := E119 + 1; + Ada.Calendar.Time_Zones'Elab_Spec; + E128 := E128 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E006 := E006 + 1; + Ada.Text_Io.Text_Streams'Elab_Spec; + E170 := E170 + 1; + System.Regexp'Elab_Spec; + E168 := E168 + 1; + Ada.Directories'Elab_Spec; + Ada.Directories'Elab_Body; + E117 := E117 + 1; + E115 := E115 + 1; +>>>>>>> 69f69bc261da4a8489896c1cdee2a7aab20a4053 + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_controller""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + gnat_argc := argc; + gnat_argv := argv; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure write_File is,"Output : File_Type; + + line : String := ""Text output""; + loop_value : integer := 0; + +begin + Create (File => Output, + Mode => Out_File, + Name => ""output.txt""); + + + while loop_value < 1 loop + begin + -- You can process the contents of Line here. + Put_Line (Output, Line); + loop_value := 1;" +procedure Register_Path,"(This : access Uri_Router; + Rgx_Str : Interfaces.C.Strings.Chars_Ptr; + Cb : Callback_Function) -- uri_router.hh:36 + with Import => True, + Convention => CPP, + External_Name => ""_ZN10uri_router13register_pathEPKcPFvP14capture_groupsPvE""; + + procedure Register_Default (This : access Uri_Router; Cb : Default_Callback) -- uri_router.hh:37 + with Import => True, + Convention => CPP, + External_Name => ""_ZN10uri_router16register_defaultEPFvPKcPvE""; + + function Match_Path + (This : access Uri_Router; + Path : Interfaces.C.Strings.Chars_Ptr; + Response : System.Address) return Extensions.Bool -- uri_router.hh:38 + with Import => True, + Convention => CPP, + External_Name => ""_ZN10uri_router10match_pathEPKcPv"";" +"procedure Define_Visitor (Spec_File, Body_File : IO.File_Type; Base_Name : String; Types : String_Array);","procedure Define_Storage (Spec_File : IO.File_Type; Base_Name : String); + function Substring (Input, Separator : String; Item_Number : Positive) return String; + + generic + with procedure Process_Field (Field_Name, Type_Name : String; Last : Boolean); + procedure Iterate_Fields (List : String); + + procedure Define_Ast (Output_Dir, Base_Name : String; Types : String_Array) is + Spec_Path : constant String := Output_Dir & ""/"" + & Ada.Characters.Handling.To_Lower (Base_Name) & ""s.ads""; + Body_Path : constant String := Output_Dir & ""/"" + & Ada.Characters.Handling.To_Lower (Base_Name) & ""s.adb""; + Spec_File, Body_File : IO.File_Type; + Handle_Name : constant String := Base_Name & ""_Handle""; + begin + IO.Create (File => Spec_File, Name => Spec_Path); + IO.Create (File => Body_File, Name => Body_Path); + + IO.Put_Line (Spec_File, ""with Ada.Containers.Formal_Indefinite_Vectors;""); + IO.Put_Line (Spec_File, ""with L_Strings; use L_Strings;""); + IO.Put_Line (Spec_File, ""with Tokens; use Tokens;""); + IO.New_Line (Spec_File); + IO.Put_Line (Spec_File, ""package "" & Base_Name & ""s with""); + IO.Put_Line (Spec_File, "" Abstract_State => State is""); + IO.Put_Line (Body_File, ""package body "" & Base_Name & ""s with""); + IO.Put_Line (Body_File, "" Refined_State => (State => Container) is""); + IO.Put_Line (Spec_File, "" type "" & Base_Name & "" is abstract tagged private;""); + IO.Put_Line (Spec_File, "" type "" & Handle_Name & "" is new Positive;""); + IO.Put_Line (Spec_File, "" function Is_Valid (Handle : "" & Handle_Name & "") return Boolean;""); + IO.Put_Line (Body_File, "" function Is_Valid (Handle : Expr_Handle) return Boolean with""); + IO.Put_Line (Body_File, "" Refined_Post => (if Is_Valid'Result then "" & + ""Handle in Storage.First_Index (Container) .. Storage.Last_Index (Container)) is""); + IO.Put_Line (Body_File, "" begin""); + IO.Put_Line (Body_File, "" return Handle in Storage.First_Index (Container) .. Storage.Last_Index (Container);""); + IO.Put_Line (Body_File, "" end Is_Valid;""); + IO.New_Line (Body_File); + IO.Put_Line (Spec_File, "" procedure Store (The_"" & Base_Name & "" : "" & Base_Name & ""'Class;""); + IO.Put_Line (Spec_File, "" Result : out "" & Handle_Name & "";""); + IO.Put_Line (Spec_File, "" Success : out Boolean) with""); + IO.Put_Line (Spec_File, "" Post => (if Success then Is_Valid (Result));""); + IO.Put_Line (Spec_File, "" function Retrieve (Handle : "" & Handle_Name + & "") return "" & Base_Name & ""'Class with""); + IO.Put_Line (Spec_File, "" Pre => Is_Valid (Handle);""); + IO.Put_Line (Body_File, "" function Retrieve (Handle : Expr_Handle) return Expr'Class is""); + IO.Put_Line (Body_File, "" begin""); + IO.Put_Line (Body_File, "" return Storage.Element (Container, Handle);""); + IO.Put_Line (Body_File, "" end Retrieve;""); + + IO.Put_Line (Body_File, "" procedure Store (The_"" & Base_Name & "" : "" & Base_Name & ""'Class;""); + IO.Put_Line (Body_File, "" Result : out "" & Handle_Name & "";""); + IO.Put_Line (Body_File, "" Success : out Boolean) is separate;""); + -- The AST classes. + for The_Type of Types loop + declare + Class_Name : constant String := Substring (The_Type.all, "":"", 1); + Fields : constant String := Substring (The_Type.all, "":"", 2); + begin + Define_Type (Spec_File, Body_File, Base_Name, Class_Name, Fields);" +"IO.Put_Line (Spec_File, "" procedure Accept_Visitor (Self : Expr; V : ""","& ""in out Visitors.Visitor'Class) with "" + & ""Global => (Input => State);""); + IO.Put_Line (Body_File, "" procedure Accept_Visitor (Self : Expr; V : "" + & ""in out Visitors.Visitor'Class) is ""); + IO.Put_Line (Body_File, "" begin""); + IO.Put_Line (Body_File, "" null; -- maybe raise an exception here""); + IO.Put_Line (Body_File, "" end Accept_Visitor;""); + IO.New_Line (Body_File); + + IO.Put_Line (Spec_File, ""private""); + IO.Put_Line (Spec_File, "" type "" & Base_Name & "" is abstract tagged null record;""); + Define_Storage (Spec_File, Base_Name); + + for The_Type of Types loop + declare + Class_Name : constant String := Substring (The_Type.all, "":"", 1); + Fields : constant String := Substring (The_Type.all, "":"", 2); + begin + Define_Full_Type (Spec_File, Body_File, Base_Name, Class_Name, Fields);" +procedure Iterate_Types is new Iterate_Fields (Define_One_Type);,"begin + IO.Put (Spec_File, "" type "" & Class_Name & "" is new "" & Base_Name & "" with ""); + + if Field_List'Length > 0 then + IO.Put_Line (Spec_File, ""record""); + Iterate_Types (Field_List); + IO.Put_Line (Spec_File, "" end record;""); + else + IO.Put_Line (Spec_File, ""null record;""); + end if; + end Define_Full_Type; + + procedure Define_Storage (Spec_File : IO.File_Type; Base_Name : String) is + Handle_Name : constant String := Base_Name & ""_Handle""; + begin + IO.Put_Line (Spec_File, "" Max_Element_Size : constant Natural := 2272;""); + IO.Put_Line (Spec_File, "" package Storage is new Ada.Containers.Formal_Indefinite_Vectors""); + IO.Put_Line (Spec_File, "" (Index_Type => "" & Handle_Name & "",""); + IO.Put_Line (Spec_File, "" Element_Type => "" & Base_Name & ""'Class,""); + IO.Put_Line (Spec_File, "" Max_Size_In_Storage_Elements => Max_Element_Size);""); + IO.Put_Line (Spec_File, "" -- Should be Bounded => False, but that triggers a prover bug""); + IO.Put_Line (Spec_File, "" pragma Compile_Time_Warning (True, """"gnatprove bug workaround"""");""); + IO.New_Line (Spec_File); + IO.Put_Line (Spec_File, "" Container : Storage.Vector (5) with Part_Of => State;""); + IO.New_Line (Spec_File); + end Define_Storage; + + procedure Define_Subprogram (Spec_File, Body_File : IO.File_Type; + Base_Name, Class_Name, Field_List : String) is + pragma Unreferenced (Field_List); + use Ada.Strings.Fixed; + + begin + -- Visitor pattern. + IO.New_Line (Spec_File); + IO.Put_Line (Spec_File, "" procedure Accept_Visitor (Self : "" + & Class_Name & ""; V : in out Visitors.Visitor'Class) with""); + IO.Put_Line (Spec_File, "" Global => (Input => State);""); + IO.New_Line (Body_File); + IO.Put_Line (Body_File, "" overriding procedure Accept_Visitor (Self : "" + & Class_Name & ""; V : in out Visitors.Visitor'Class) is""); + IO.Put_Line (Body_File, "" begin""); + IO.Put_Line (Body_File, "" V.Visit_"" & Class_Name & ""_"" & Base_Name & "" (Self);""); + IO.Put_Line (Body_File, "" end Accept_Visitor;""); + end Define_Subprogram; + + procedure Define_Type (Spec_File, Body_File : IO.File_Type; + Base_Name, Class_Name, Field_List : String) is + use Ada.Strings.Fixed; + + procedure Define_Accessor (Field_Name, Type_Name : String; Last : Boolean); + procedure Define_Parameter_Body (Field_Name, Type_Name : String; Last : Boolean); + procedure Define_Parameter_Spec (Field_Name, Type_Name : String; Last : Boolean); + procedure Initialize_Field (Field_Name, Type_Name : String; Last : Boolean); + + procedure Define_Accessor (Field_Name, Type_Name : String; Last : Boolean) is + pragma Unreferenced (Last); + begin + IO.Put (Spec_File, "" function Get_"" & Field_Name & "" (Self : "" + & Class_Name & "") return "" & Type_Name); + if Type_Name = Base_Name & ""_Handle"" then + IO.Put_Line (Spec_File, "" with""); + IO.Put_Line (Spec_File, "" Post => Is_Valid (Get_"" & Field_Name & ""'Result);""); + else + IO.Put_Line (Spec_File, "";""); + end if; + IO.New_Line (Body_File); + IO.Put_Line (Body_File, "" function Get_"" & Field_Name & "" (Self : "" + & Class_Name & "") return "" & Type_Name & "" is""); + IO.Put_Line (Body_File, "" begin""); + IO.Put_Line (Body_File, "" return Self."" & Field_Name & "";""); + IO.Put_Line (Body_File, "" end Get_"" & Field_Name & "";""); + end Define_Accessor; + + procedure Define_Parameter_Body (Field_Name, Type_Name : String; Last : Boolean) is + begin + IO.Put (Body_File, ""My_"" & Field_Name & "" : "" & Type_Name); + if not Last then + IO.Put (Body_File, ""; ""); + end if; + end Define_Parameter_Body; + + procedure Define_Parameter_Spec (Field_Name, Type_Name : String; Last : Boolean) is + begin + IO.Put (Spec_File, ""My_"" & Field_Name & "" : "" & Type_Name); + if not Last then + IO.Put (Spec_File, ""; ""); + end if; + end Define_Parameter_Spec; + + procedure Initialize_Field (Field_Name, Type_Name : String; Last : Boolean) is + pragma Unreferenced (Type_Name, Last); + begin + IO.Put_Line (Body_File, "" E."" & Field_Name & "" := My_"" & Field_Name & "";""); + end Initialize_Field; + + procedure Iterate_Accessors is new Iterate_Fields (Define_Accessor); + procedure Iterate_Initialization is new Iterate_Fields (Initialize_Field); + procedure Iterate_Parameters_Body is new Iterate_Fields (Define_Parameter_Body); + procedure Iterate_Parameters_Spec is new Iterate_Fields (Define_Parameter_Spec); + + begin + IO.Put_Line (Spec_File, """"); + IO.Put_Line (Spec_File, "" type "" & Class_Name & "" is new "" & Base_Name & "" with private;""); + + Iterate_Accessors (Field_List); + IO.Put (Spec_File, "" procedure Create_"" & Class_Name & "" (""); + + IO.New_Line (Body_File); + IO.Put (Body_File, "" procedure Create_"" & Class_Name & "" (""); + Iterate_Parameters_Spec (Field_List); + IO.Put_Line (Spec_File, ""; Result : out "" & Base_Name & ""_Handle);""); + Iterate_Parameters_Body (Field_List); + IO.Put_Line (Body_File, ""; Result : out "" & Base_Name & ""_Handle) is""); + IO.Put_Line (Body_File, "" E : "" & Class_Name & "";""); + IO.Put_Line (Body_File, "" Success : Boolean;""); + IO.Put_Line (Body_File, "" begin""); + Iterate_Initialization (Field_List); + IO.Put_Line (Body_File, "" Store (E, Result, Success);""); + IO.Put_Line (Body_File, "" end Create_"" & Class_Name & "";""); + end Define_Type; + + procedure Define_Visitor (Spec_File, Body_File : IO.File_Type; Base_Name : String; Types : String_Array) is + begin + IO.Put_Line (Spec_File, "" package Visitors is""); + IO.Put_Line (Spec_File, "" type Visitor is tagged null record;""); + IO.Put_Line (Body_File, "" package body Visitors is""); + + for The_Type of Types loop + declare + Type_Name : constant String := Substring (The_Type.all, "":"", 1); + begin + IO.Put_Line (Spec_File, "" procedure Visit_"" & Type_Name & ""_"" & Base_Name & + "" (Self : in out Visitor; The_"" & Base_Name & + "" : "" & Type_Name & "") with""); + IO.Put_Line (Spec_File, "" Global => (Input => Exprs.State);""); + IO.Put_Line (Body_File, "" procedure Visit_"" & Type_Name & ""_"" & Base_Name & + "" (Self : in out Visitor; The_"" & Base_Name & + "" : "" & Type_Name & "") is""); + IO.Put_Line (Body_File, "" begin""); + IO.Put_Line (Body_File, "" null;""); + IO.Put_Line (Body_File, "" end Visit_"" & Type_Name & ""_"" & Base_Name & "";""); + IO.New_Line (Body_File);" +procedure Scan_Token is,"procedure Add_Token (Kind : Token_Kind) with + Global => (input => (Start, Current, Source, Line), + in_out => (Error_Reporter.State, SPARK.Text_IO.Standard_Error, Token_List)), + Pre => Source'First <= Start and then Start < Current and then Current - 1 <= Source'Last; + procedure Add_Token (Kind : Token_Kind; Lexeme : String) with + Global => (input => (Line), + in_out => (Error_Reporter.State, SPARK.Text_IO.Standard_Error, Token_List)); + procedure Advance (C : out Character) with + Global => (Input => Source, In_Out => Current), + Pre => Current >= Source'First and then + Current <= Source'Last and then + Current < Integer'Last, + Post => Current = Current'Old + 1; + procedure Ignore with + Global => (Input => Source, In_Out => Current), + Pre => Current >= Source'First and then + Current <= Source'Last and then + Current < Integer'Last, + Post => Current = Current'Old + 1; + procedure Advance_If_Match (Expected : Character; Match : out Boolean) with + Global => (in_out => Current, Input => Source), + Pre => Source'First <= Current and then Source'Last < Integer'Last, + Post => (if Match then + (Current - 1 <= Source'Last and then Current = Current'Old + 1) + else + Current = Current'Old); + function Peek return Character with + Global => (Input => (Current, Source)), + Pre => Current >= Source'First, + Post => (if Peek'Result /= NUL then Current <= Source'Last); + function Peek_Next return Character with + Pre => Current >= Source'First and then Current < Integer'Last; + procedure Scan_Identifier with + Pre => Source'First <= Start and then Start < Current and then + Current - 1 <= Source'Last and then Source'Last < Integer'Last, + Post => Current >= Current'Old; + procedure Scan_Number with + Pre => Source'First <= Start and then Start < Current and then + Current - 1 <= Source'Last and then Source'Last < Integer'Last, + Post => Current >= Current'Old; + procedure Scan_String with + Global => (Input => (Source, Start), + in_out => (Current, Line, Token_List, SPARK.Text_IO.Standard_Error, Error_Reporter.State)), + Pre => Source'First <= Start and then Start < Current and then Source'Last < Integer'Last, + Post => Current >= Current'Old; + + procedure Add_Token (Kind : Token_Kind) is + begin + Add_Token (Kind, Source (Start .. Current - 1)); + end Add_Token; + + procedure Add_Token (Kind : Token_Kind; Lexeme : String) is + use Tokens.Lists; + begin + if Length (Token_List) >= Token_List.Capacity then + Error_Reporter.Error (Line_No => Line, + Message => ""Out of token capacity""); + return; + end if; + Append (Container => Token_List, + New_Item => Tokens.New_Token (Kind => Kind, + Lexeme => Lexeme, + Line => Line)); + end Add_Token; + + procedure Advance (C : out Character) is + begin + Current := Current + 1; + C := Source (Current - 1); + end Advance; + + procedure Advance_If_Match (Expected : Character; Match : out Boolean) is + begin + if Is_At_End then + Match := False; + elsif Source (Current) /= Expected then + Match := False; + else + Current := Current + 1; + Match := True; + end if; + end Advance_If_Match; + + procedure Ignore is + begin + Current := Current + 1; + end Ignore; + + function Peek return Character is + begin + if Is_At_End then + return NUL; + else + return Source (Current); + end if; + end Peek; + + function Peek_Next return Character is + begin + if Current + 1 > Source'Last then + return NUL; + else + return Source (Current + 1); + end if; + end Peek_Next; + + procedure Scan_Identifier is +-- use Hashed_Maps; + begin + while Is_Alphanumeric (Peek) + or else Peek = '_' loop + pragma Loop_Invariant (Start <= Current); + pragma Loop_Invariant (Source'First <= Current and then Current <= Source'Last); + pragma Loop_Invariant (Start = Start'Loop_Entry); + pragma Loop_Invariant (Current >= Current'Loop_Entry); + Ignore; + end loop; + declare + Text : constant L_String := L_Strings.To_Bounded_String (Source (Start .. Current - 1)); + begin +-- if Contains (Keywords, Text) then +-- Add_Token (Element (Keywords, Text)); + if Text = ""and"" then + Add_Token (T_AND); + elsif Text = ""class"" then + Add_Token (T_CLASS); + elsif Text = ""else"" then + Add_Token (T_ELSE); + elsif Text = ""false"" then + Add_Token (T_FALSE); + elsif Text = ""for"" then + Add_Token (T_FOR); + elsif Text = ""fun"" then + Add_Token (T_FUN); + elsif Text = ""if"" then + Add_Token (T_IF); + elsif Text = ""nil"" then + Add_Token (T_NIL); + elsif Text = ""or"" then + Add_Token (T_OR); + elsif Text = ""print"" then + Add_Token (T_PRINT); + elsif Text = ""return"" then + Add_Token (T_RETURN); + elsif Text = ""super"" then + Add_Token (T_SUPER); + elsif Text = ""this"" then + Add_Token (T_THIS); + elsif Text = ""true"" then + Add_Token (T_TRUE); + elsif Text = ""var"" then + Add_Token (T_VAR); + elsif Text = ""while"" then + Add_Token (T_WHILE); + else + Add_Token (T_IDENTIFIER); + end if;" +procedure Sort is new Ada.Containers.Generic_Anonymous_Array_Sort,"(Index_Type => Natural, + Less => Less, + Swap => Swap); + + Text : League.Strings.Universal_String; + ASCII : constant League.Text_Codecs.Text_Codec := + League.Text_Codecs.Codec (+""USASCII""); + begin + for J in Map'Range loop + Map (J) := J; + end loop; + + Sort (Map'First, Map'Last); + + Text.Append (""{""); + + for J of Map loop + if Text.Length > 1 then + Text.Append ("",""); + end if; + + Text.Append ('""'); + Text.Append (Keys (J)); + Text.Append ("""""":""""""); + Text.Append (Key.Value (Keys (J)).To_String); + Text.Append ('""'); + end loop; + + Text.Append (""}""); + + return ASCII.Encode (Text).To_Stream_Element_Array; + end Thumbprint; + + ------------------------------------ + -- Validate_Compact_Serialization -- + ------------------------------------ + + procedure Validate_Compact_Serialization + (Self : out JSON_Web_Signature'Class; + Value : League.Strings.Universal_String; + Secret : Ada.Streams.Stream_Element_Array; + Valid : out Boolean) + is + use type League.Strings.Universal_String; + + function Alg return Wide_Wide_String; + + function Alg return Wide_Wide_String is + begin + return Self.Header.Value (+""alg"").To_String.To_Wide_Wide_String; + end Alg; + + List : constant League.String_Vectors.Universal_String_Vector := + Value.Split ('.'); + + Ok : Boolean; + Document : League.JSON.Documents.JSON_Document; + ASCII : constant League.Text_Codecs.Text_Codec := + League.Text_Codecs.Codec (+""USASCII""); + Encoded_Payload : League.Strings.Universal_String; + Raw_Header : League.Stream_Element_Vectors.Stream_Element_Vector; + Encoded_Header : League.Strings.Universal_String; + Text : League.Strings.Universal_String; + Signature : League.Stream_Element_Vectors.Stream_Element_Vector; + Encoded_Signature : League.Strings.Universal_String; + + begin + Valid := False; + -- 1. Parse the JWS representation to extract the serialized values... + if List.Length /= 3 then + return; + end if; + + Encoded_Header := List.Element (1); + Encoded_Payload := List.Element (2); + Encoded_Signature := List.Element (3); + -- 2. decode the encoded representation of the JWS Protected Header + From_Base_64_URL + (Data => Encoded_Header, + Value => Raw_Header, + Success => Ok); + + if not Ok then + return; + end if; + + -- 3. Verify that the resulting octet sequence is ... JSON object + Document := League.JSON.Documents.From_JSON (Raw_Header); + + if not Document.Is_Object or Document.Is_Empty then + return; + end if; + + Self.Header := (Document.To_JSON_Object with null record); + -- 5. Verify that the implementation understands and can process... + if not Self.Header.Value (+""alg"").Is_String then + return; + elsif Alg not in ""none"" | ""HS256"" + and (Alg /= ""RS256"" or RS256_Validation_Link = null) + then + return; + elsif Self.Header.Critical.Length > 0 then + -- Any critical extensions are not supported here + return; + end if; + + -- 6. decode the encoded representation of the JWS Payload + From_Base_64_URL + (Data => Encoded_Payload, + Value => Self.Payload, + Success => Ok); + + if not Ok then + return; + end if; + + -- 7. decode the encoded representation of the JWS Signature + From_Base_64_URL + (Data => Encoded_Signature, + Value => Signature, + Success => Ok); + + if not Ok then + return; + end if; + + -- 8. Validate the JWS Signature against the JWS Signing Input + Text := Encoded_Header & ""."" & Encoded_Payload; + + if not Self.Header.Validate_Signature + (ASCII.Encode (Text), Secret, Signature) + then + return; + end if; + + Valid := True; + end Validate_Compact_Serialization; + + ------------------------ + -- Validate_Signature -- + ------------------------ + + function Validate_Signature + (Self : JOSE_Header'Class; + Data : League.Stream_Element_Vectors.Stream_Element_Vector; + Secret : Ada.Streams.Stream_Element_Array; + Value : League.Stream_Element_Vectors.Stream_Element_Vector) + return Boolean + is + use type League.Strings.Universal_String; + + Alg : constant League.Strings.Universal_String := Self.Algorithm; + begin + if Alg = +""HS256"" then + declare + use type League.Stream_Element_Vectors.Stream_Element_Vector; + begin + return Self.Compute_Signature (Data, Secret) = Value;" +procedure Disp_Flush,"(X1 : Int32_T; + Y1 : Int32_T; + X2 : Int32_T; + Y2 : Int32_T; + Color : access constant Color_Array) + with Convention => C; + + procedure Disp_Fill + (X1 : Int32_T; + Y1 : Int32_T; + X2 : Int32_T; + Y2 : Int32_T; + Color : Lv.Color.Color_T) + with Convention => C; + + procedure Disp_Map + (X1 : Int32_T; + Y1 : Int32_T; + X2 : Int32_T; + Y2 : Int32_T; + Color : access constant Color_Array) + with Convention => C; + + ---------------- + -- Initialize -- + ---------------- + + procedure Initialize (Enable_Pointer : Boolean := True) is + Mouse_Cursor_Icon : Integer; + pragma Import (C, Mouse_Cursor_Icon, ""mouse_cursor_icon""); + begin + + Lv.Hal.Disp.Init_Drv (LV_Disp_Drv'Access); + + LV_Disp_Drv.Disp_Flush := Disp_Flush'Access; + LV_Disp_Drv.Disp_Fill := Disp_Fill'Access; + LV_Disp_Drv.Disp_Map := Disp_Map'Access; + + LV_Disp := Lv.Hal.Disp.Register (LV_Disp_Drv'Access); + Lv.Hal.Disp.Set_Active (LV_Disp); + + Pointer.Union.Point := (0, 0); + Pointer.State := Lv.Hal.Indev.State_Rel; + + Lv.Hal.Indev.Init_Drv (LV_Indev_Keypad_Drv'Access); + LV_Indev_Keypad_Drv.Read := Read_Keypad'Access; + LV_Indev_Keypad_Drv.C_Type := Lv.Hal.Indev.Type_Keypad; + LV_Indev_Keypad := Lv.Hal.Indev.Register (LV_Indev_Keypad_Drv'Access); + + Lv.Hal.Indev.Init_Drv (LV_Indev_Pointer_Drv'Access); + LV_Indev_Pointer_Drv.Read := Read_Pointer'Access; + LV_Indev_Pointer_Drv.C_Type := Lv.Hal.Indev.Type_Pointer; + LV_Indev_Pointer := Lv.Hal.Indev.Register (LV_Indev_Pointer_Drv'Access); + + if Enable_Pointer then + Cursor_Obj := Lv.Objx.Img.Create (Lv.Objx.Scr_Act, Lv.Objx.No_Obj); + Lv.Objx.Img.Set_Src (Cursor_Obj, Mouse_Cursor_Icon'Address); + Lv.Indev.Set_Cursor (LV_Indev_Pointer, Cursor_Obj); + end if; + end Initialize; + + ------------------ + -- Keypad_Indev -- + ------------------ + + function Keypad_Indev return Lv.Hal.Indev.Indev_T + is (LV_Indev_Keypad); + + ------------------ + -- Read_Pointer -- + ------------------ + + function Read_Pointer (Data : access Indev_Data_T) return U_Bool is + begin + + Pointer.State := Lv.Hal.Indev.State_Rel; + + for Elt of BB_Pico_Bsp.Touch.Get_All_Touch_Points loop + if Elt.Weight /= 0 then + Pointer.Union.Point.X := Integer_16 (Elt.X); + Pointer.Union.Point.Y := Integer_16 (Elt.Y); + Pointer.State := Lv.Hal.Indev.State_Pr; + end if; + end loop; + + Data.all := Pointer; + + return 0; + end Read_Pointer; + + ----------------- + -- Read_Keypad -- + ----------------- + + function Read_Keypad (Data : access Indev_Data_T) return U_Bool is + use BBQ10KBD; + + State : Key_State; + begin + loop + State := BB_Pico_Bsp.Keyboard.Key_FIFO_Pop; + + case State.Kind is + when Error => + return 0; -- No more events + when Held_Pressed => + null; -- LVGL doesn't have a held pressed event + when others => + declare + Pressed : constant Boolean := State.Kind = BBQ10KBD.Pressed; + begin + case State.Code is + when Keyboard.KEY_JOY_UP => + Data.Union.Key := Lv.LV_KEY_UP; + when Keyboard.KEY_JOY_DOWN => + Data.Union.Key := Lv.LV_KEY_DOWN; + when Keyboard.KEY_JOY_LEFT => + Data.Union.Key := Lv.LV_KEY_LEFT; + when Keyboard.KEY_JOY_RIGHT => + Data.Union.Key := Lv.LV_KEY_RIGHT; + when Keyboard.KEY_JOY_CENTER => + Data.Union.Key := Lv.LV_KEY_ENTER; + when Keyboard.KEY_BTN_LEFT1 => + Data.Union.Key := Lv.LV_KEY_PREV; + when Keyboard.KEY_BTN_LEFT2 => + Data.Union.Key := Lv.LV_KEY_HOME; + when Keyboard.KEY_BTN_RIGHT1 => + Data.Union.Key := Lv.LV_KEY_BACKSPACE; + when Keyboard.KEY_BTN_RIGHT2 => + Data.Union.Key := Lv.LV_KEY_NEXT; + when others => + Data.Union.Key := Unsigned_32 (State.Code); + end case; + + Data.State := (if Pressed + then Lv.Hal.Indev.State_Pr + else Lv.Hal.Indev.State_Rel); + return 1;" +function Read_Register (This : STMPE811_Device;,"Reg_Addr : UInt8) + return UInt8 + is + Data : TSC_Data (1 .. 1); + Status : SPI_Status; + + begin + This.Chip_Select.Clear; + + This.Port.Transmit (SPI_Data_8b'(16#80# or Reg_Addr, 0), Status); + if Status /= Ok then + raise Program_Error with ""Timeout while reading TC data""; + end if; + + This.Port.Receive (Data, Status); + if Status /= Ok then + raise Program_Error with ""Timeout while reading TC data""; + end if; + + This.Chip_Select.Set; + + return Data (Data'First); + end Read_Register; + + -------------------- + -- Write_Register -- + -------------------- + + procedure Write_Register (This : in out STMPE811_Device; + Reg_Addr : UInt8; + Data : UInt8) + is + Status : SPI_Status; + + begin + This.Chip_Select.Clear; + + This.Port.Transmit (SPI_Data_8b'(Reg_Addr, Data), Status); + if Status /= Ok then + raise Program_Error with ""Timeout while reading TC data""; + end if; + + This.Chip_Select.Set; + end Write_Register; + + --------------- + -- IOE_Reset -- + --------------- + + procedure IOE_Reset (This : in out STMPE811_Device) is + Discard : UInt8; + begin + This.Write_Register (IOE_REG_SYS_CTRL1, 16#02#); + + -- Give some time for the reset + This.Time.Delay_Milliseconds (10); + + for X in UInt8 range 0 .. 64 loop + Discard := This.Read_Register (X); + end loop; + + This.Write_Register (IOE_REG_SYS_CTRL2, 16#00#); + end IOE_Reset; + + -------------------------- + -- IOE_Function_Command -- + -------------------------- + + procedure IOE_Function_Command (This : in out STMPE811_Device; + Func : UInt8; + Enabled : Boolean) + is + Reg : UInt8 := This.Read_Register (IOE_REG_SYS_CTRL2); + begin + -- CTRL2 functions are disabled when corresponding bit is set + + if Enabled then + Reg := Reg and (not Func); + else + Reg := Reg or Func; + end if; + + This.Write_Register (IOE_REG_SYS_CTRL2, Reg); + end IOE_Function_Command; + + ------------------- + -- IOE_AF_Config -- + ------------------- + + procedure IOE_AF_Config (This : in out STMPE811_Device; + Pin : UInt8; + Enabled : Boolean) is + Reg : UInt8 := This.Read_Register (IOE_REG_GPIO_AF); + begin + if Enabled then + Reg := Reg or Pin; + else + Reg := Reg and (not Pin); + end if; + + This.Write_Register (IOE_REG_GPIO_AF, Reg); + end IOE_AF_Config; + + ---------------- + -- Get_IOE_ID -- + ---------------- + + function Get_IOE_ID (This : in out STMPE811_Device) return UInt16 is + begin + return (UInt16 (This.Read_Register (0)) * (2**8)) + or UInt16 (This.Read_Register (1)); + end Get_IOE_ID; + + ---------------- + -- Initialize -- + ---------------- + + function Initialize (This : in out STMPE811_Device) return Boolean + is + Discard : UInt8; + begin + + This.Write_Register (IOE_REG_SYS_CTRL1, 16#02#); + + -- Give some time for the reset + This.Time.Delay_Milliseconds (10); + + for X in UInt8 range 0 .. 64 loop + Discard := This.Read_Register (X); + end loop; + + declare + Id : constant UInt16 := This.Get_IOE_ID; + begin + if Id /= 16#0811# then + return False; + end if;" +procedure Initialize;,"---------------- + -- Initialize -- + ---------------- + + procedure Initialize is + Config : RP.SPI.SPI_Configuration; + begin + SPI_CLK.Configure (RP.GPIO.Output, RP.GPIO.Pull_Up, RP.GPIO.SPI); + SPI_DO.Configure (RP.GPIO.Output, RP.GPIO.Pull_Up, RP.GPIO.SPI); + SPI_DI.Configure (RP.GPIO.Output, RP.GPIO.Pull_Up, RP.GPIO.SPI); + + Config := RP.SPI.Default_SPI_Configuration; + + Config.Baud := 10_000_000; + Config.Blocking := True; + + SPI_Port.Configure (Config); + + -- DMA -- + declare + use RP.DMA; + Config : DMA_Configuration; + begin + Config.Trigger := DMA_TX_Trigger; + Config.High_Priority := True; + Config.Data_Size := Transfer_8; + Config.Increment_Read := True; + Config.Increment_Write := False; + + RP.DMA.Configure (SPI_TX_DMA, Config);" +procedure CommsTime is,"-- Parameters for the experimental run. +-- Experiments - number of data points collected +-- Iterations_Experiment - number of cycles round commstime for a single data point +Experiments : CONSTANT INTEGER := 100; +Iterations_Experiment : CONSTANT INTEGER := 10000; + +task PREFIX is + entry Send(Value : in INTEGER); +end PREFIX; + +task SEQ_DELTA is + entry Send(Value : in INTEGER); +end SEQ_DELTA; + +task SUCC is + entry Send(Value : in INTEGER); +end SUCC; + +task PRINTER is + entry Send(Value : in INTEGER); +end PRINTER; + +task body PREFIX is + N : INTEGER; +begin + for i in 0..Experiments loop + SEQ_DELTA.Send(0); + for j in 0..Iterations_Experiment loop + accept Send(Value : in INTEGER) do + N := Value;" +procedure Getinfo is,"use GNAT.Command_Line; + use Ada.Text_IO; + command_Name : constant String := + Ada.Directories.Base_Name (Ada.Command_Line.Command_Name); + procedure Help; + procedure Help is + use ASCII; + begin + Put_Line + (command_Name & "" [options]"" & LF & + ""Options:"" & LF & + "" --ada-library-version Print Ada-Library version"" & LF & + "" --binding-version Print Binding version"" & LF & + "" --library-version Print version of the 0mq library."" & LF & + "" -? | -h | --help Print this text""); + + end Help; + +begin + loop + case Getopt (""-binding-version "" & + ""-ada-library-version "" & + ""-library-version "" & + ""-compiler-version "" & + ""h ? -help"") is -- Accepts '-a', '-ad', or '-b argument' + when ASCII.NUL => exit; + + when 'h' | '?' => + Help; + return; + + when '-' => + if Full_Switch = ""-binding-version"" then + Put_Line (ZMQ.Image (ZMQ.Binding_Version)); + elsif Full_Switch = ""-library-version"" then + Put_Line (ZMQ.Image (ZMQ.Library_Version)); + elsif Full_Switch = ""-compiler-version"" then + Put_Line (Standard'Compiler_Version); + elsif Full_Switch = ""-ada-library-version"" then + Put_Line ($version); + elsif Full_Switch = ""-help"" then + Help; + return; + end if; + when others => + raise Program_Error; -- cannot occur! + end case; + end loop; + + loop + declare + S : constant String := Get_Argument (Do_Expansion => True); + begin + exit when S'Length = 0; + Put_Line (""Got "" & S);" +function uuid_is_null,"(arg1 : access unsigned_char) return int; -- uuid.h:84:5 + pragma Import (C, uuid_is_null, ""uuid_is_null""); + + function uuid_parse + (arg1 : access Character; + arg2 : access unsigned_char) return int; -- uuid.h:87:5 + pragma Import (C, uuid_parse, ""uuid_parse""); + + procedure uuid_unparse + (arg1 : access unsigned_char; + arg2 : access Character); -- uuid.h:90:6 + pragma Import (C, uuid_unparse, ""uuid_unparse""); + + procedure uuid_unparse_lower + (arg1 : access unsigned_char; + arg2 : access Character); -- uuid.h:91:6 + pragma Import (C, uuid_unparse_lower, ""uuid_unparse_lower""); + + procedure uuid_unparse_upper + (arg1 : access unsigned_char; + arg2 : access Character); -- uuid.h:92:6 + pragma Import (C, uuid_unparse_upper, ""uuid_unparse_upper""); + + function uuid_time + (arg1 : access unsigned_char; + arg2 : access bits_time_h.timeval) return time_h.time_t; -- uuid.h:95 + pragma Import (C, uuid_time, ""uuid_time""); + + function uuid_type + (arg1 : access unsigned_char) return int; -- uuid.h:96:5 + pragma Import (C, uuid_type, ""uuid_type""); + + function uuid_variant + (arg1 : access unsigned_char) return int; -- uuid.h:97:5 + pragma Import (C, uuid_variant, ""uuid_variant""); + + end uuid_uuid_h; + + ----------------------------------------------------- + + procedure Clear (this : in out UUID) is + begin + uuid_uuid_h.uuid_clear(this.data(this.data'First)'Unrestricted_Access); + end Clear; + + function ""<"" (l, r : UUID) return Boolean is + begin + return uuid_uuid_h.uuid_compare (l.data (l.data'first)'Unrestricted_Access, + r.data (r.data'first)'Unrestricted_Access) < 0; + end ""<""; + function "">"" (l, r : UUID) return Boolean is + begin + return uuid_uuid_h.uuid_compare (l.data (l.data'first)'Unrestricted_Access, + r.data(r.data'first)'Unrestricted_Access) > 0; + end "">""; + + function ""="" (l, r : UUID) return Boolean is + begin + return uuid_uuid_h.uuid_compare (l.data (l.data'first)'Unrestricted_Access, + r.data (r.data'first)'Unrestricted_Access) = 0; + end ""=""; + + + function Generate return UUID is + begin + return ret : UUID do + uuid_uuid_h.uuid_generate (ret.data (ret.data'First)'Unrestricted_Access); + end return; + end Generate; + + procedure Generate (this : out UUID) is + begin + this := Generate; + end Generate; + + function Generate_Random return UUID is + begin + return ret : UUID do + uuid_uuid_h.uuid_generate_random (ret.data (ret.data'First)'Unrestricted_Access); + end return; + end Generate_Random; + procedure Generate_Random (this : out UUID) is + begin + this := Generate_Random;" +"function conv is new ada.Unchecked_Conversion (system.Address, zlibVersion_Access);","zlibVersion : zlibVersion_Access; + begin + p.open (File_Name => ""/lib/libz.so.1""); + zlibVersion := conv (p.Sym (""zlibVersion"")); + declare + version : constant string := Interfaces.C.Strings.Value (zlibVersion.all); + begin + test.Assert (Version (version'first + 1 ) = '.', ""Dont seem to be a version numnber""); + test.Assert (Version (version'first + 3 ) = '.', ""Dont seem to be a version numnber"");" +procedure Chat_Server is,"package ATI renames Ada.Text_IO; + package CM renames Chat_Messages; + package LLU renames Lower_Layer_UDP; + package ACL renames Ada.Command_Line; + package CC renames Client_Collections; + package ASU renames Ada.Strings.Unbounded; + + use type CM.Message_Type; + + Server_EP: LLU.End_Point_Type; + EP: LLU.End_Point_Type; + Expired: Boolean; + Port: Integer; + Buffer_In: aliased LLU.Buffer_Type(1024); + Buffer_Out: aliased LLU.Buffer_Type(1024); + Collection_W: CC.Collection_Type; + Collection_R: CC.Collection_Type; + Unique: Boolean; + Mess: CM.Message_Type; + Nick: ASU.Unbounded_String; + Comment: ASU.Unbounded_String; + Nick_Server: ASU.Unbounded_String; + Password: ASU.Unbounded_String; + Data: ASU.Unbounded_String; + Admin_EP: LLU.End_Point_Type; + Admin_Pass: ASU.Unbounded_String; + Shutdown: Boolean; + +begin + + -- Asignación y bindeado del Servidor + Port := Integer'Value(ACL.Argument(1)); + Password := ASU.To_Unbounded_String(ACL.Argument(2)); + Server_EP := LLU.Build (LLU.To_IP(LLU.Get_Host_Name), Port); + LLU.Bind (Server_EP); + + Shutdown := False; + + loop + LLU.Reset (Buffer_In); + LLU.Reset (Buffer_Out); + + LLU.Receive (Server_EP, Buffer_In'Access, 1000.0, Expired); + + if Expired then + ATI.Put_Line (""Please, try again""); + else + Mess := CM.Message_Type'Input (Buffer_In'Access); + + if Mess = CM.Init then + EP := LLU.End_Point_Type'Input (Buffer_In'Access); + Nick := ASU.Unbounded_String'Input (Buffer_In'Access); + ATI.Put(""INIT received from "" & ASU.To_String(Nick)); + + if ASU.To_String (Nick) = ""reader"" then + + Unique := False; + + CC.Add_Client (Collection_R, EP, Nick, Unique); + else + Unique := True; + + begin + CC.Add_Client (Collection_W, EP, Nick, Unique); + + --Aviso de entrada al servidor + Mess := CM.Server; + CM.Message_Type'Output(Buffer_Out'Access, Mess); + Nick_Server := ASU.To_Unbounded_String(""server""); + ASU.Unbounded_String'Output(Buffer_Out'Access, + Nick_Server); + Comment := ASU.To_Unbounded_String(ASU.To_String(Nick) + & "" joins the chat""); + ASU.Unbounded_String'Output(Buffer_Out'Access, Comment); + CC.Send_To_All (Collection_R, Buffer_Out'Access); + + exception + when CC.Client_Collection_Error => + ATI.Put ("". IGNORED, nick already used"");" +procedure lab2c is,"package Int_IO is new Ada.Text_IO.Integer_IO(Integer); use Int_IO; + lower, upper, init, max : Integer; + + procedure Push(space : in out arrayTypes.stringArray; base : in out intArray; top : in out intArray; stack : in Integer; text : in charArray) is + begin + top(stack) := top(stack) + 1; + if top(stack) > base(stack + 1) then + Put_Line(""PUSH OVERFLOW ""); New_Line; + top(stack) := top(stack) - 1; + for i in (init + 1)..max loop + Put(i); Put("": ""); + if (i > base(1) and i <= top(1)) or (i > base(2) and i <= top(2)) or (i > base(3) and i <= top(3)) or (i > base(4) and i <= top(4)) then + for j in 1..space(i)'Length loop + Put(space(i)(j)); + end loop; + New_Line; + else + New_Line; + end if; + end loop; + top(stack) := top(stack) + 1; + reallocate.reallocate(max, init, stack, 4, base, top, 0.15, space, text); + else + space(top(stack)) := text; + end if; + end Push; + + procedure Pop(space : in out arrayTypes.stringArray; base : in out intArray; top : in out intArray; stack : in Integer; text : out charArray) is + begin + if top(stack) = base(stack) then + Put_Line(""POP OVERFLOW""); + else + text := space(top(stack)); + top(stack) := top(stack) - 1; + end if; + end Pop; +begin + Put(""Enter a lower bound: ""); Get(lower); + Put(""Enter an upper bound: ""); Get(upper); + Put(""Enter an initial location: ""); Get(init); + Put(""Enter the max: ""); Get(max); + + declare + space : arrayTypes.stringArray(lower..upper); + top : arrayTypes.intArray(1..4); + base : arrayTypes.intArray(1..5); + text : String(1..13); + temp : arrayTypes.charArray(1..10); + begin + for j in 1..5 loop + base(j) := Integer(Float'Floor(((Float(j) - 1.0) / 4.0 * Float(max - init)) + Float(init))); + if j < 5 then + top(j) := base(j); + end if; + end loop; + New_Line; + Put(""Enter text: ""); Get(text); + while text /= ""end "" loop + for i in 4..13 loop + temp(i - 3) := text(i); + end loop; + Put_Line(text); + if text(1) = 'I' then + Push(space, base, top, Integer'Value(text(2..2)), temp); + elsif text(1) = 'D' then + Pop(space, base, top, Integer'Value(text(2..2)), temp); + New_Line; + for i in 1..10 loop + Put(temp(i)); + end loop; + New_Line; + end if; + Put(""Enter text: ""); Get(text); + end loop;" +procedure graphics is,"begin + Clear_Window; + Set_Graphical_Mode(On); + background; + Start_screen(35, 12); + --vinst(25, 12); + Skip_Line; + background; + protocoll_background(125, 4); + logo_background(24, 4); + logo(24, 4); +end graphics; + + +function Generate + return Integer is + + subtype Nums is Integer range 1..6; + package RN is + new Ada.Numerics.Discrete_Random(Nums); + Gen : RN.Generator; +begin + RN.Reset(Gen); + return RN.Random(Gen);" +function Triss(Rolls: Arr),"return Integer is + + begin + for I in 1..3 loop + if Rolls(I) = Rolls(I+1) and Rolls(I) = Rolls(I+2) then + return 3 * Rolls(I); + end if; + end loop; + return 0;" +procedure goto_prev is,"begin + -- Clear screen + for X in 1..17 loop + Goto_XY(Coord_Config_X, Coord_Config_Y + X * 2); + Put(ASCII.ESC & bg_color); + Put("" ""); + Goto_XY(1000,1000); + end loop; + + if Curr_Index_Selected = 1 then + Curr_Index_Selected := 16; + end if; + + loop + Curr_Index_Selected := Curr_Index_Selected - 1; + if avail_points(Curr_Index_Selected) >= 0 then + exit; + end if; + if Curr_Index_Selected = 1 then + Curr_Index_Selected := 16; + end if; + end loop; + + if Curr_Index_Selected > 6 then + Goto_XY(Coord_Config_X, Coord_Config_Y + Curr_Index_Selected * 2 + 4); + else + Goto_XY(Coord_Config_X, Coord_Config_Y + Curr_Index_Selected * 2); + end if; + Set_Foreground_Colour(Red); + Put(""=>""); + Set_Foreground_Colour(Black); + Goto_XY(1000,1000); + end goto_prev; + + procedure goto_next is + + begin + -- Clear screen + for X in 1..17 loop + Goto_XY(Coord_Config_X, Coord_Config_Y + X * 2); + Put(ASCII.ESC & bg_color); + Put("" ""); + Goto_XY(1000,1000); + end loop; + + if Curr_Index_Selected = 15 then + Curr_Index_Selected := 0; + end if; + + loop + Curr_Index_Selected := Curr_Index_Selected + 1; + if avail_points(Curr_Index_Selected) >= 0 then + exit; + end if; + if Curr_Index_Selected = 15 then + Curr_Index_Selected := 0; + end if; + end loop; + + if Curr_Index_Selected > 6 then + Goto_XY(Coord_Config_X, Coord_Config_Y + Curr_Index_Selected * 2 + 4); + else + Goto_XY(Coord_Config_X, Coord_Config_Y + Curr_Index_Selected * 2); + end if; + + Set_Foreground_Colour(Red); + Put(""=>""); + Set_Foreground_Colour(Black); + Goto_XY(1000,1000); + end goto_next; + + begin + -- Build array of available slots + for x in 1..15 loop + if avail_points(x) >= 0 then + temp_arraysize := temp_arraysize + 1; + end if; + end loop; + + declare + test_array : dynamic_array(0..temp_arraysize); + begin + for x in 1..15 loop + if avail_points(x) >= 0 then + test_array(temp_array_index) := temp_array_index * 2; + temp_array_index := temp_array_index + 1; + end if; + end loop;" +procedure background is,"begin + + -- Skriver ut bakgrundsfärgen för hela terminalen + for X in 1..300 loop + for Y in 1..50 loop + Put(ASCII.ESC & bg_color); + goto_xy(X, Y); + Put(' '); + end loop; + end loop; + end background; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + procedure protocoll_background (X_Start, Y_Start: in Integer) is + + begin + + -- Skriver ut ramen kring protokollet + for X in 1..31 loop + for Y in 1..41 loop + Put(ASCII.ESC & protocoll_frame_bg); + goto_xy((X_Start - 3 + X), (Y_Start - 2 + Y)); + Put(' '); + end loop; + end loop; + + -- Skriver ut protokollets bakgrund + for X in 1..25 loop + for Y in 1..38 loop + Put(ASCII.ESC & ""[48;5;15m""); + goto_xy(X_Start + X, Y_Start + Y); + Put(' '); + end loop; + end loop; + + end protocoll_background; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + procedure Start_screen (X_Start, Y_Start : in integer) is + + begin + Set_Foreground_Colour(white); + Set_Graphical_Mode(off); + + goto_xy(X_Start, Y_Start); + Put(""YYYYYYY YYYYYYY ttttttt ""); + goto_xy(X_Start, Y_Start + 1); + Put(""Y:::::Y Y:::::Y t:::::t ""); + goto_xy(X_Start, Y_Start + 2); + Put(""Y:::::Y Y:::::Y t:::::t ""); + goto_xy(X_Start, Y_Start + 3); + Put(""Y::::::Y Y::::::Y t:::::t ""); + goto_xy(X_Start, Y_Start + 4); + Put("" YY:::::Y Y:::::YY aaaaaaaaaaaaa ttttttt:::::ttttttt zzzzzzzzzzzzzzzzz yyyyyyy yyyyyyy ""); + goto_xy(X_Start, Y_Start + 5); + Put("" Y:::::Y Y:::::Y a::::::::::::a t:::::::::::::::::t z:::::::::::::::z y:::::y y:::::y ""); + goto_xy(X_Start, Y_Start + 6); + Put("" Y:::::Y:::::Y aaaaaaaaa:::::a t:::::::::::::::::t z::::::::::::::z y:::::y y:::::y ""); + goto_xy(X_Start, Y_Start + 7); + Put("" Y:::::::::Y a::::a tttttt:::::::tttttt zzzzzzzz::::::z y:::::y y:::::y ""); + goto_xy(X_Start, Y_Start + 8); + Put("" Y:::::Y aa::::::::::::a t:::::t z::::::z y:::::y y:::::y ""); + goto_xy(X_Start, Y_Start + 9); + Put("" Y:::::Y a::::a a:::::a t:::::t tttttt z::::::z y:::::::::y ""); + goto_xy(X_Start, Y_Start + 10); + Put("" YYYY:::::YYYY a:::::aaaa::::::a tt::::::::::::::t z::::::::::::::z y:::::y ""); + goto_xy(X_Start, Y_Start + 11); + Put("" Y:::::::::::Y a::::::::::aa:::a tt:::::::::::tt z:::::::::::::::z y:::::y ""); + goto_xy(X_Start, Y_Start + 12); + Put("" YYYYYYYYYYYYY aaaaaaaaaa aaaa ttttttttttttt zzzzzzzzzzzzzzzzzz y:::::y ""); + goto_xy(X_Start, Y_Start + 13); + Put("" y:::::y ""); + goto_xy(X_Start, Y_Start + 14); + Put("" y:::::y ""); + goto_xy(X_Start, Y_Start + 15); + Put("" y:::::y ""); + goto_xy(X_Start, Y_Start + 16); + Put("" y:::::y ""); + goto_xy(X_Start, Y_Start + 17); + Put("" yyyyyyy ""); + + goto_xy(X_Start + 20, Y_Start + 16); + Set_Foreground_Colour(Red); + Put(""Tryck enter för att starta spelet...""); + + + + end Start_screen; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + procedure vinst (X_Start, Y_Start : in Integer) is + + begin + + Set_Foreground_Colour(white); + Set_Graphical_Mode(off); + goto_xy(X_Start, Y_Start); + + Put(""DDDDDDDDDDDDD ""); + goto_xy(X_Start, Y_Start + 1); + Put(""D::::::::::::DDD ""); + goto_xy(X_Start, Y_Start + 2); + Put(""D:::::::::::::::DD ""); + goto_xy(X_Start, Y_Start + 3); + Put(""DDD:::::DDDDD:::::D ""); + goto_xy(X_Start, Y_Start + 4); + Put(""D:::::D D:::::D uuuuuu uuuuuu vvvvvvv vvvvvvv aaaaaaaaaaaaa nnnn nnnnnnnn nnnn nnnnnnnn ""); + goto_xy(X_Start, Y_Start + 5); + Put(""D:::::D D:::::D u::::u u::::u v:::::v v:::::v a::::::::::::a n:::nn::::::::nn n:::nn::::::::nn ""); + goto_xy(X_Start, Y_Start + 6); + Put(""D:::::D D:::::D u::::u u::::u v:::::v v:::::v aaaaaaaaa:::::a n::::::::::::::nn n::::::::::::::nn ""); + goto_xy(X_Start, Y_Start + 7); + Put(""D:::::D D:::::D u::::u u::::u v:::::v v:::::v a::::a nn:::::::::::::::nnn:::::::::::::::n""); + goto_xy(X_Start, Y_Start + 8); + Put(""D:::::D D:::::D u::::u u::::u v:::::v v:::::v aaaaaaa:::::a n:::::nnnn:::::n n:::::nnnn:::::n""); + goto_xy(X_Start, Y_Start + 9); + Put(""D:::::D D:::::D u::::u u::::u v:::::v v:::::v aa::::::::::::a n::::n n::::n n::::n n::::n""); + goto_xy(X_Start, Y_Start + 10); + Put(""D:::::D D:::::D u::::u u::::u v:::::v:::::v a::::aaaa::::::a n::::n n::::n n::::n n::::n""); + goto_xy(X_Start, Y_Start + 11); + Put("" D:::::D D:::::D u:::::uuuu:::::u v:::::::::v a::::a a:::::a n::::n n::::n n::::n n::::n""); + goto_xy(X_Start, Y_Start + 12); + Put(""DDD:::::DDDDD:::::D u:::::::::::::::uu v:::::::v a::::a a:::::a n::::n n::::n n::::n n::::n""); + goto_xy(X_Start, Y_Start + 13); + Put(""D:::::::::::::::DD u:::::::::::::::u v:::::v a:::::aaaa::::::a n::::n n::::n n::::n n::::n""); + goto_xy(X_Start, Y_Start + 14); + Put(""D::::::::::::DDD uu::::::::uu:::u v:::v a::::::::::aa:::a n::::n n::::n n::::n n::::n""); + goto_xy(X_Start, Y_Start + 15); + Put(""DDDDDDDDDDDDD uuuuuuuu uuuu vvv aaaaaaaaaa aaaa nnnnnn nnnnnn nnnnnn nnnnnn""); + + +end vinst; + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + procedure clear_protocoll(X_Start, Y_Start: in Integer; Which_Protocoll_Or_Both: in Integer) is + x : Integer := X_Start; + y : Integer := Y_Start; + widthcol1 : constant Integer := 13; + widthcol2 : constant Integer := 5; + begin + if Which_Protocoll_Or_Both = 0 or Which_Protocoll_Or_Both = 1 then + For I in 1..19 loop + Goto_XY(X_Start + 2 + widthcol1, Y_Start - 1 + I * 2); + case I is + when 1 => Set_Text_Modes(Off, Off, On); + when 2..7 => Put("" ""); + when 8 => null; + when 9 => null; + when 10..18 => Put("" ""); + when 19 => null; + + when others => null; + end case; + end loop; + end if; + + if Which_Protocoll_Or_Both = 0 or Which_Protocoll_Or_Both = 2 then + For I in 1..19 loop + Goto_XY(X_Start + 3 + widthcol1 + widthcol2, Y_Start - 1 + I * 2); + case I is + when 1 => Set_Text_Modes(Off, Off, On); + when 2..7 => Put("" ""); + when 8 => null; + when 9 => null; + when 10..18 => Put("" ""); + when 19 => null; + + when others => null; + end case; + end loop; + end if; + end clear_protocoll; + + procedure update_protocoll(X_Start, Y_Start: in Integer; prot1, prot2: in Protocoll_Type; Which_Protocoll_Or_Both: in Integer; Other_Color: in Integer) is + x : Integer := X_Start; + y : Integer := Y_Start; + widthcol1 : constant Integer := 13; + widthcol2 : constant Integer := 5; + widthcol3 : constant Integer := 5; + height: constant Integer := 39; + text_width: constant Integer := 12; + points_width: constant Integer := 5; + avail_place_text_color1: String := ""[38;5;208m""; + temp1, temp2 : Protocoll_Type; + + procedure other_color_chk is + begin + if Other_Color = 1 then + Put(ASCII.ESC & avail_place_text_color1); + end if; + end other_color_chk; + + procedure reset_black_color is + begin + Put(ASCII.ESC & ""[38;5;0m""); + end reset_black_color; + + begin + -- Frame + Set_Background_Colour(White); + Set_Foreground_Colour(Black); + -- Skriver ut horisontella linjer + while y < Y_Start + height loop + Goto_XY(X_Start + 1, y); + Put(Horisontal_Line, Times => widthcol1); + Goto_XY(X_Start + 2 + widthcol1, y); + Put(Horisontal_Line, Times => widthcol2); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2, y); + Put(Horisontal_Line, Times => widthcol3); + Goto_XY(X_Start + 4 + widthcol1 + widthcol2 + widthcol3, y); + y := y + 2; + end loop; + + for I in Y_Start..(Y_Start+height -1) loop + Goto_XY(X_Start,I); + if (I + Y_Start) mod 2 /= 0 then + Put(Vertical_Line); + Goto_XY(X_Start + 1 + widthcol1,I); + Put(Vertical_Line); + Goto_XY(X_Start + 2 + widthcol1 + widthcol2,I); + Put(Vertical_Line); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2 + widthcol3,I); + Put(Vertical_Line); + else + if I = Y_Start then + Put(Upper_Left_Corner); + Goto_XY(X_Start + 1 + widthcol1,I); + Put(Horisontal_Down); + Goto_XY(X_Start + 2 + widthcol1 + widthcol2,I); + Put(Horisontal_Down); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2 + widthcol3,I); + Put(Upper_Right_Corner); + elsif I = Y_Start+height - 1 then + Put(Lower_Left_Corner); + Goto_XY(X_Start + 1 + widthcol1,I); + Put(Horisontal_Up); + Goto_XY(X_Start + 2 + widthcol1 + widthcol2,I); + Put(Horisontal_Up); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2 + widthcol3,I); + Put(Lower_Right_Corner); + else + Put(Vertical_Right); + Goto_XY(X_Start + 1 + widthcol1,I); + Put(Cross); + Goto_XY(X_Start + 2 + widthcol1 + widthcol2,I); + Put(Cross); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2 + widthcol3,I); + Put(Vertical_Left); + end if; + end if; + end loop; + + Set_Graphical_Mode(Off); + + For I in 1..19 loop + Goto_XY(X_Start + 2, Y_Start - 1 + I * 2); + --Set_Background_Colour(Blue); + case I is + when 1 => Set_Text_Modes(On, Off, Off); Put(""Spelare:""); Set_Text_Modes(Off, Off, On); + when 2 => Put(""Ettor""); + when 3 => Put(""Tvåor""); + when 4 => Put(""Treor""); + when 5 => Put(""Fyror""); + when 6 => Put(""Femmor""); + when 7 => Put(""Sexor""); Set_Text_Modes(On, Off, Off); + when 8 => Put(""Summa:""); + when 9 => Put(""BONUS""); Set_Text_Modes(Off, Off, On); + when 10 => Put(""Par""); + when 11 => Put(""Två par""); + when 12 => Put(""Triss""); + when 13 => Put(""Fyrtal""); + when 14 => Put(""Kåk""); + when 15 => Put(""Liten stege""); + when 16 => Put(""Stor stege""); + when 17 => Put(""Chans""); + when 18 => Put(""Yatzy""); Set_Text_Modes(On, Off, Off); + when 19 => Put(""Summa:""); + + when others => null; + end case; + end loop; + temp1 := Prot1; + temp2 := Prot2; + if Which_Protocoll_Or_Both = 0 or Which_Protocoll_Or_Both = 1 then + For I in 1..19 loop + Goto_XY(X_Start + 2 + widthcol1, Y_Start - 1 + I * 2); + + + + case I is + when 1 => Set_Text_Modes(Off, Off, Off); Put(""P1""); Set_Text_Modes(Off, Off, On); + when 2..7 => other_color_chk; if Prot1(I - 1) /= -1 then Put(Prot1(I - 1), 1 + widthcol2 / 2); end if; + + when 8 => if Other_Color /= 1 then reset_black_color; Put(Calcfirstsum(temp1), 1 + widthcol2 / 2); end if; + when 9 => if Other_Color /= 1 then reset_black_color; Put(Bonus(temp1), 1 + widthcol2 / 2); end if; + when 10..18 => other_color_chk; if Prot1(I - 3) /= -1 then Put(Prot1(I - 3), 1 + widthcol2 / 2); end if; + when 19 => if Other_Color /= 1 then reset_black_color; Put(Calctotsum(temp1), 1 + widthcol2 / 2); end if; + + when others => null; + end case; + end loop; + end if; + + if Which_Protocoll_Or_Both = 0 or Which_Protocoll_Or_Both = 2 then + For I in 1..19 loop + Goto_XY(X_Start + 3 + widthcol1 + widthcol2, Y_Start - 1 + I * 2); + case I is + when 1 => Set_Text_Modes(Off, Off, Off); Put(""P2""); Set_Text_Modes(Off, Off, On); + when 2..7 => other_color_chk; if Prot2(I - 1) /= -1 then Put(Prot2(I - 1), 1 + widthcol2 / 2); end if; + + + when 8 => if Other_Color /= 1 then reset_black_color; Put(Calcfirstsum(temp2), 1 + widthcol2 / 2); end if; + when 9 => if Other_Color /= 1 then reset_black_color; Put(Bonus(temp2), 1 + widthcol2 / 2); end if; + + when 10..18 => other_color_chk; if Prot2(I - 3) /= -1 then Put(Prot2(I - 3), 1 + widthcol2 / 2); end if; + when 19 => if Other_Color /= 1 then reset_black_color; Put(Calctotsum(temp2), 1 + widthcol2 / 2); end if; + + when others => null; + end case; + end loop; + end if; + + reset_black_color; + + end update_protocoll; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + procedure dice (A, X_Start, Y_Start: in Integer) is + + begin + Goto_XY(X_Start, Y_Start); + for I in 1..5 loop + --Set_Background_Colour(White); + if I = 1 then + Put(Upper_Left_Corner); + Put(Horisontal_Very_High_Line, Times => 9); + Put(Upper_Right_Corner); + Goto_XY(X_Start, Y_Start + I); + elsif I = 5 then + Put(Lower_Left_Corner); + Put(Horisontal_Very_Low_Line, Times => 9); + Put(Lower_Right_Corner); + else + case A is + when 1 => + Put(Vertical_Line); + if I = 3 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 2 or I = 4 then + Put("" ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 2 => + Put(Vertical_Line); + if I = 2 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 3 then + Put("" ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 4 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 3 => + Put(Vertical_Line); + if I = 2 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 3 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 4 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 4 => + Put(Vertical_Line); + if I = 2 then + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 3 then + Put("" ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 4 then + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 5 => + Put(Vertical_Line); + if I = 2 then + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 3 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 4 then + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 6 => + Put(Vertical_Line); + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + + when others => null; + end case; + end if; + end loop; + + + end dice; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- +procedure dice_placement (D1, D2, D3, D4, D5 : in Integer) is + +begin + + -- Only update dice if input is bigger than 0 + if D1 > 0 then Dice(D1, 8 + 15 * 1, 38); end if; + if D2 > 0 then Dice(D2, 8 + 15 * 2, 38); end if; + if D3 > 0 then Dice(D3, 8 + 15 * 3, 38); end if; + if D4 > 0 then Dice(D4, 8 + 15 * 4, 38); end if; + if D5 > 0 then Dice(D5, 8 + 15 * 5, 38); end if; + +end dice_placement; + + + + + + + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + Procedure logo_background (X_Start, Y_Start : in Integer) is + + begin + for X in 1..76 loop + for Y in 1..9 loop + Put(ASCII.ESC & logo_frame_bg); + goto_xy((X_Start - 3 + X), (Y_Start - 2 + Y)); + Put(' '); + end loop; + end loop; + end logo_background; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + Procedure logo (X_Start, Y_Start : in Integer) is + + begin + Set_Background_Colour(White); + Set_Foreground_Colour(Blue); + Set_Bold_Mode(on); + + goto_xy(X_Start, Y_Start); + Put("" ____ ____ __ _________ ________ ____ ____ ""); + goto_xy(X_Start, Y_Start + 1); + Put(' '); + Put(Vertical_Line); + Put(""_ _""); + Put(Vertical_Line, Times => 2); + Put(""_ _""); + Put(Vertical_Line); + Put("" / \ ""); + Put(Vertical_Line); + Put("" _ _ ""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put("" __ __""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_ _""); + Put(Vertical_Line, Times => 2); + Put(""_ _""); + Put(Vertical_Line); + goto_xy(X_Start, Y_Start + 2); + Put("" \ \ / / / /\ \ ""); + Put(Vertical_Line); + Put(""_/ ""); + Put(Vertical_Line); + Put(' '); + Put(Vertical_Line); + Put("" \_""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_/ / / \ \ / / ""); + goto_xy(X_Start, Y_Start + 3); + Put("" \ \/ / / ____ \ ""); + Put(Vertical_Line); + Put(' '); + Put(Vertical_Line); + Put("" / / _ \ \/ / ""); + goto_xy(X_Start, Y_Start + 4); + Put("" _""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_ _/ / \ \_ _""); + Put(Vertical_Line); + Put(' '); + Put(Vertical_Line); + Put(""_ / /__/ ""); + Put(Vertical_Line); + Put("" _""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_ ""); + goto_xy(X_Start, Y_Start + 5); + Put("" ""); + Put(Vertical_Line); + Put(""______""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""____""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""____""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_____""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_______""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""______""); + Put(Vertical_Line); + Put("" ""); + goto_xy(X_Start, Y_Start + 6); + Put("" ""); + + -- ____ ____ __ _________ ________ ____ ____ + -- |_ _||_ _| / \ | _ _ | | __ __| |_ _||_ _| + -- \ \ / / / /\ \ |_/ | | \_| |_/ / / \ \ / / + -- \ \/ / / ____ \ | | / / _ \ \/ / + -- _| |_ _/ / \ \_ _| |_ / /__/ | _| |_ + -- |______| |____| |____| |_____| |_______| |______| + + end logo; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + procedure message4 (X_Start, Y_Start : in Integer; S : in String) is + + begin + + Set_Graphical_Mode(Off); + + -- reset white first + for X in 1..51 loop + Put(ASCII.ESC & ""[38;5;0m""); + goto_xy((X_Start + X), Y_Start + 22); + Put(' '); + end loop; + + goto_xy(X_Start + 3, Y_Start + 25); + Put(S); + + end message4; + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + procedure message3 (X_Start, Y_Start : in Integer; S : in String) is + + begin + + Set_Graphical_Mode(Off); + + -- reset white first + for X in 1..51 loop + Put(ASCII.ESC & ""[38;5;196m""); + goto_xy((X_Start + X), Y_Start + 25); + Put(' '); + end loop; + + goto_xy(X_Start + 3, Y_Start + 25); + Put(S); + + end message3; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + procedure message2 (X_Start, Y_Start : in Integer; S : in String) is + + begin + + Set_Graphical_Mode(Off); + + -- White inner frame + for X in 1..51 loop + for Y in 1..9 loop + Put(ASCII.ESC & ""[48;5;15m""); + if Y /= 5 then + goto_xy((X_Start + X), (Y_Start + Y)); + else + goto_xy((X_Start + X), (Y_Start + Y + 1)); + end if; + Put(' '); + end loop; + end loop; + + goto_xy(X_Start + 3, Y_Start + 8); + Put(S); + end message2; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + procedure message (X_Start, Y_Start : in Integer; S : in String) is + + begin + + Set_Graphical_Mode(Off); + + for Y in 1..11 loop + for X in 1..55 loop + + -- om inte första eller inte sista raden + if Y = 1 OR Y = 11 then + if X mod 2 = 0 then + Put(ASCII.ESC & message_frame_color1); + else + Put(ASCII.ESC & message_frame_color2); + end if; + else + if X = 1 OR X = 55 then + if Y mod 2 = 0 then + Put(ASCII.ESC & message_frame_color1); + else + Put(ASCII.ESC & message_frame_color2); + end if; + else + if Y mod 2 = 0 then + Put(ASCII.ESC & message_frame_color2); + else + Put(ASCII.ESC & message_frame_color1); + end if; + end if; + end if; + + goto_xy((X_Start - 2 + X), (Y_Start - 1 + Y)); + Put(' '); + + end loop; + end loop; + + + + -- White inner frame + for X in 1..51 loop + for Y in 1..9 loop + Put(ASCII.ESC & ""[48;5;15m""); + goto_xy((X_Start + X), (Y_Start + Y)); + Put(' '); + end loop; + end loop; + + goto_xy(X_Start + 3, Y_Start + 5); + Set_Foreground_Colour(Black); + Put(S); + end message; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + ---------------------------------------------------------------------------------------------" +procedure Test is,"procedure Test_TJa is + + Own_Protocoll, Other_Protocoll: Protocoll_Type; + Selected_Place : Integer; + + begin + Reset_Colours; -- Standard colours is supposed to be black on white ... + Clear_Window; + Set_Graphical_Mode(On); + background; + protocoll_background(125, 4); + logo_background(24, 4); + message(38, 18, ""Hejsan""); + + -- Draw a rectangle on screen ... + --Set_Graphical_Mode(On); + for I in 1..15 loop + case I is + when 1 => Own_Protocoll(I) := 1; + when 2 => Own_Protocoll(I) := 2; + when 3 => Own_Protocoll(I) := 3; + when 4 => Own_Protocoll(I) := 4; + when 5 => Own_Protocoll(I) := 5; + when 6 => Own_Protocoll(I) := -1; + when 7 => Own_Protocoll(I) := -1; + when 8 => Own_Protocoll(I) := -1; + when 9 => Own_Protocoll(I) := -1; + when 10 => Own_Protocoll(I) := -1; + when 11 => Own_Protocoll(I) := -1; + when 12 => Own_Protocoll(I) := 15; + when 13 => Own_Protocoll(I) := -1; + when 14 => Own_Protocoll(I) := 15; + when 15 => Own_Protocoll(I) := -1; + when others => null; + -- Own_Protocoll(I) := I; + end case; + end loop; + for I in 1..15 loop + Other_Protocoll(I) := I; + end loop; + + + + update_protocoll(125, 4, Own_Protocoll, Other_Protocoll); + + for x in 1..5 loop + dice(x,8 + 15 * x, 38); + --dice_placement; + end loop; + + + + logo(24, 4); + + Set_Graphical_Mode(Off); + + place(Own_Protocoll, Selected_Place); + + + Reset_Colours; + Reset_Text_Modes; -- Resets boold mode ... + + + + end Test_TJa; + + begin + Test_TJa; + Skip_Line;" +procedure graphics is,"begin + Clear_Window; + Set_Graphical_Mode(On); + background; + protocoll_background(125, 4); + logo_background(24, 4); + logo(24, 4); +end graphics; + +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +procedure Start_Game(Socket: in Socket_Type; Player: out Positive; Prot1, Prot2: out Protocoll_Type) is + TX : String(1..100); + TL : Natural; +begin -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + for I in 1..15 loop + Prot1(I) := -1; + end loop; + + Prot2 := Prot1; + Get_Line(Socket, TX, TL); + + if TX(1) = '1' then + message(33, 18, ""Du är spelare 1, väntar på spelare 2""); + Player := 1; + Get_Line(Socket, TX, TL); + New_Line; + if TX(1) = '3' then + message(33, 18, ""Båda spelare anslutna""); + end if; + + elsif TX(1) = '2' then + message(33, 18, ""Du är spelare 2""); + Player := 2; + else + raise DATATYPE_ERROR; + end if; + + New_Line; + + message(33, 18, ""Nu startar spelet""); + New_Line; + +end Start_Game; + +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +function Read(C: in Character) + return Natural is + + S: String(1..1); +begin + S(1) := C; + return Integer'Value(S); +end Read; + +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +procedure Get_Rolls(Socket: in Socket_Type; Roll: out Rolls_Type) is + TX: String(1..100); + TL: Natural; +begin + + Get_Line(Socket, TX, TL); + New_Line; + + if TX(1) = '4' then -- 4 betyder inkomande tärningar + + Roll.I := Read(TX(2)); + + for X in 1..Roll.I loop -- A betyder här antalet tärningar + Roll.Rolls(X) := Read(TX(X+2)); + end loop; + + elsif TX(1) = '5' then -- 5 betyder info om gamestate + if TX(2) = '0' then -- Annan spelare slår + Roll.I := 6; + elsif TX(2) = '1' then -- Annan spelare har slagit + Roll.I := 7; + + for X in 1..5 loop + Roll.Rolls(X) := Read(TX(X+2)); + end loop; + elsif TX(2) = '2' then -- Annan spelare vill placera + Roll.I := 8; + + for X in 1..5 loop + Roll.Rolls(X) := Read(TX(X+2)); + end loop; + end if; + else + raise DATATYPE_ERROR; + end if; +end Get_Rolls; + +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +function GetI(Roll: in Rolls_Type) + return Integer is +begin + return Roll.I; +end GetI; + +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +function GetR(Roll: in Rolls_Type) + return Arr is +begin + return Roll.Rolls; +end GetR; + +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +procedure Playerroll(Socket: in Socket_Type) is +begin + Put_Line(Socket, ""51""); +end Playerroll; + +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +procedure Sort(Arrayen_Med_Talen: in out Arr) is + + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + procedure Swap(Tal_1,Tal_2: in out Integer) is + Tal_B : Integer; -- Temporary buffer + begin + Tal_B := Tal_1; + Tal_1 := Tal_2; + Tal_2 := Tal_B; + end Swap; + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + + Minsta_Talet, Minsta_Talet_Index : Integer; +begin + Minsta_Talet := 0; + + for IOuter in Arrayen_Med_Talen'Range loop + for I in IOuter..Arrayen_Med_Talen'Last loop + if I = IOuter or Arrayen_Med_Talen(I) > Minsta_Talet then + Minsta_Talet := Arrayen_Med_Talen(I); + Minsta_Talet_Index := I; + end if; + end loop; + + Swap(Arrayen_Med_Talen(IOuter), Arrayen_Med_Talen(Minsta_Talet_Index)); + end loop; +end Sort; + +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + -- -- -- +function Calcpoints(Prot: Protocoll_Type; Rolls: Arr) -- -- -- + return Protocoll_Type is -- -- -- + -- -- -- + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + function Ental(I: Integer; Rolls: Arr) -- -- -- + return Integer is -- -- -- + -- -- -- + C : Integer := 0; -- -- -- + begin -- -- -- + for X in 1..5 loop -- -- -- + if Rolls(X) = I then -- -- -- + C := C + I; -- -- -- + end if; -- -- -- + end loop; -- -- -- + return C; -- -- -- + end Ental; -- -- -- + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + function FourPair(Rolls: Arr) -- -- -- + return Integer is -- -- -- + -- -- -- + begin -- -- -- + for I in 1..2 loop -- -- -- + if Rolls(I) = Rolls(I+1) and Rolls(I) = Rolls(I+2) and Rolls(I) = Rolls(I+3) then -- -- -- + return 4 * Rolls(I); -- -- -- + end if; -- -- -- + end loop; -- -- -- + -- -- -- + return 0; -- -- -- + end FourPair; -- -- -- + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + function Pair(Rolls: Arr) -- -- -- + return Integer is -- -- -- + begin -- -- -- + for I in 1..4 loop + if Rolls(I) = Rolls(I+1) then + return 2 * Rolls(I); + end if; + end loop; + return 0;" +function Triss(Rolls: Arr),"return Integer is + + begin + for I in 1..3 loop + if Rolls(I) = Rolls(I+1) and Rolls(I) = Rolls(I+2) then + return 3 * Rolls(I); + end if; + end loop; + return 0;" +procedure goto_prev is,"begin + -- Clear screen + for X in 1..17 loop + Goto_XY(Coord_Config_X, Coord_Config_Y + X * 2); + Put(ASCII.ESC & bg_color); + Put("" ""); + Goto_XY(1000,1000); + end loop; + + if Curr_Index_Selected = 1 then + Curr_Index_Selected := 16; + end if; + + loop + Curr_Index_Selected := Curr_Index_Selected - 1; + if avail_points(Curr_Index_Selected) >= 0 then + exit; + end if; + end loop; + + if Curr_Index_Selected > 6 then + Goto_XY(Coord_Config_X, Coord_Config_Y + Curr_Index_Selected * 2 + 4); + else + Goto_XY(Coord_Config_X, Coord_Config_Y + Curr_Index_Selected * 2); + end if; + + Put(""->""); + Goto_XY(1000,1000); + end goto_prev; + + procedure goto_next is + + begin + -- Clear screen + for X in 1..17 loop + Goto_XY(Coord_Config_X, Coord_Config_Y + X * 2); + Put(ASCII.ESC & bg_color); + Put("" ""); + Goto_XY(1000,1000); + end loop; + + if Curr_Index_Selected = 15 then + Curr_Index_Selected := 0; + end if; + + loop + Curr_Index_Selected := Curr_Index_Selected + 1; + if avail_points(Curr_Index_Selected) >= 0 then + exit; + end if; + if Curr_Index_Selected = 15 then + Curr_Index_Selected := 0; + end if; + end loop; + + if Curr_Index_Selected > 6 then + Goto_XY(Coord_Config_X, Coord_Config_Y + Curr_Index_Selected * 2 + 4); + else + Goto_XY(Coord_Config_X, Coord_Config_Y + Curr_Index_Selected * 2); + end if; + + Put(""->""); + Goto_XY(1000,1000); + end goto_next; + + begin + Put(""a1""); -- DEBUG + -- Build array of available slots + for x in 1..15 loop + if avail_points(x) >= 0 then + temp_arraysize := temp_arraysize + 1; + end if; + end loop; + + New_Line; Put(""a2""); -- DEBUG + declare + test_array : dynamic_array(0..temp_arraysize); + begin + for x in 1..15 loop + if avail_points(x) >= 0 then + test_array(temp_array_index) := temp_array_index * 2; + temp_array_index := temp_array_index + 1; + end if; + end loop;" +procedure background is,"begin + + -- Skriver ut bakgrundsfärgen för hela terminalen + for X in 1..300 loop + for Y in 1..50 loop + Put(ASCII.ESC & bg_color); + goto_xy(X, Y); + Put(' '); + end loop; + end loop; + end background; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + procedure protocoll_background (X_Start, Y_Start: in Integer) is + + begin + + -- Skriver ut ramen kring protokollet + for X in 1..31 loop + for Y in 1..41 loop + Put(ASCII.ESC & protocoll_frame_bg); + goto_xy((X_Start - 3 + X), (Y_Start - 2 + Y)); + Put(' '); + end loop; + end loop; + + -- Skriver ut protokollets bakgrund + for X in 1..25 loop + for Y in 1..38 loop + Put(ASCII.ESC & ""[48;5;15m""); + goto_xy(X_Start + X, Y_Start + Y); + Put(' '); + end loop; + end loop; + + end protocoll_background; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + procedure update_protocoll(X_Start, Y_Start: in Integer; prot1, prot2: in Protocoll_Type) is + x : Integer := X_Start; + y : Integer := Y_Start; + widthcol1 : constant Integer := 13; + widthcol2 : constant Integer := 5; + widthcol3 : constant Integer := 5; + height: constant Integer := 39; + text_width: constant Integer := 12; + points_width: constant Integer := 5; + + begin + -- Frame + Set_Background_Colour(White); + Set_Foreground_Colour(Black); + -- Skriver ut horisontella linjer + while y < Y_Start + height loop + Goto_XY(X_Start + 1, y); + Put(Horisontal_Line, Times => widthcol1); + Goto_XY(X_Start + 2 + widthcol1, y); + Put(Horisontal_Line, Times => widthcol2); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2, y); + Put(Horisontal_Line, Times => widthcol3); + Goto_XY(X_Start + 4 + widthcol1 + widthcol2 + widthcol3, y); + y := y + 2; + end loop; + + for I in Y_Start..(Y_Start+height -1) loop + Goto_XY(X_Start,I); + if (I + Y_Start) mod 2 /= 0 then + Put(Vertical_Line); + Goto_XY(X_Start + 1 + widthcol1,I); + Put(Vertical_Line); + Goto_XY(X_Start + 2 + widthcol1 + widthcol2,I); + Put(Vertical_Line); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2 + widthcol3,I); + Put(Vertical_Line); + else + if I = Y_Start then + Put(Upper_Left_Corner); + Goto_XY(X_Start + 1 + widthcol1,I); + Put(Horisontal_Down); + Goto_XY(X_Start + 2 + widthcol1 + widthcol2,I); + Put(Horisontal_Down); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2 + widthcol3,I); + Put(Upper_Right_Corner); + elsif I = Y_Start+height - 1 then + Put(Lower_Left_Corner); + Goto_XY(X_Start + 1 + widthcol1,I); + Put(Horisontal_Up); + Goto_XY(X_Start + 2 + widthcol1 + widthcol2,I); + Put(Horisontal_Up); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2 + widthcol3,I); + Put(Lower_Right_Corner); + else + Put(Vertical_Right); + Goto_XY(X_Start + 1 + widthcol1,I); + Put(Cross); + Goto_XY(X_Start + 2 + widthcol1 + widthcol2,I); + Put(Cross); + Goto_XY(X_Start + 3 + widthcol1 + widthcol2 + widthcol3,I); + Put(Vertical_Left); + end if; + end if; + end loop; + + Set_Graphical_Mode(Off); + + For I in 1..19 loop + Goto_XY(X_Start + 2, Y_Start - 1 + I * 2); + --Set_Background_Colour(Blue); + case I is + when 1 => Set_Text_Modes(On, Off, Off); Put(""Spelare:""); Set_Text_Modes(Off, Off, On); + when 2 => Put(""Ettor""); + when 3 => Put(""Tvåor""); + when 4 => Put(""Treor""); + when 5 => Put(""Fyror""); + when 6 => Put(""Femmor""); + when 7 => Put(""Sexor""); Set_Text_Modes(On, Off, Off); + when 8 => Put(""Summa:""); + when 9 => Put(""BONUS""); Set_Text_Modes(Off, Off, On); + when 10 => Put(""Par""); + when 11 => Put(""Två par""); + when 12 => Put(""Triss""); + when 13 => Put(""Fyrtal""); + when 14 => Put(""Kåk""); + when 15 => Put(""Liten stege""); + when 16 => Put(""Stor stege""); + when 17 => Put(""Chans""); + when 18 => Put(""Yatzy""); Set_Text_Modes(On, Off, Off); + when 19 => Put(""Summa:""); + + when others => null; + end case; + end loop; + + + For I in 1..19 loop + Goto_XY(X_Start + 2 + widthcol1, Y_Start - 1 + I * 2); + + case I is + when 1 => Set_Text_Modes(Off, Off, Off); Put(""P1""); Set_Text_Modes(Off, Off, On); + when 2..7 => if Prot1(I - 1) /= -1 then Put(Prot1(I - 1), 1 + widthcol2 / 2); end if; + when 8 => Put(""Sum:""); + when 9 => Put(""BON""); + when 10..18 => if Prot1(I - 3) /= -1 then Put(Prot1(I - 3), 1 + widthcol2 / 2); end if; + when 19 => Put(""Sum:""); + + when others => null; + end case; + end loop; + + For I in 1..19 loop + Goto_XY(X_Start + 3 + widthcol1 + widthcol2, Y_Start - 1 + I * 2); + case I is + when 1 => Set_Text_Modes(Off, Off, Off); Put(""P1""); Set_Text_Modes(Off, Off, On); + when 2..7 => if Prot2(I - 1) /= -1 then Put(Prot2(I - 1), 1 + widthcol2 / 2); end if; + when 8 => Put(""Sum:""); + when 9 => Put(""BON""); + when 10..18 => if Prot2(I - 3) /= -1 then Put(Prot2(I - 3), 1 + widthcol2 / 2); end if; + when 19 => Put(""Sum:""); + + when others => null; + end case; + end loop; + + end update_protocoll; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + procedure dice (A, X_Start, Y_Start: in Integer) is + + begin + Goto_XY(X_Start, Y_Start); + for I in 1..5 loop + --Set_Background_Colour(White); + if I = 1 then + Put(Upper_Left_Corner); + Put(Horisontal_Very_High_Line, Times => 9); + Put(Upper_Right_Corner); + Goto_XY(X_Start, Y_Start + I); + elsif I = 5 then + Put(Lower_Left_Corner); + Put(Horisontal_Very_Low_Line, Times => 9); + Put(Lower_Right_Corner); + else + case A is + when 1 => + Put(Vertical_Line); + if I = 3 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 2 or I = 4 then + Put("" ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 2 => + Put(Vertical_Line); + if I = 2 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 3 then + Put("" ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 4 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 3 => + Put(Vertical_Line); + if I = 2 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 3 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 4 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 4 => + Put(Vertical_Line); + if I = 2 then + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 3 then + Put("" ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 4 then + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 5 => + Put(Vertical_Line); + if I = 2 then + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 3 then + Put("" • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + elsif I = 4 then + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + end if; + + when 6 => + Put(Vertical_Line); + Put("" • • ""); + Put(Vertical_Line); + Goto_XY(X_Start, Y_Start + I); + + when others => null; + end case; + end if; + end loop; + + + end dice; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- +procedure dice_placement (D1, D2, D3, D4, D5 : in Integer) is + +begin + + -- Only update dice if input is bigger than 0 + if D1 > 0 then Dice(D1, 8 + 15 * 1, 38); end if; + if D2 > 0 then Dice(D2, 8 + 15 * 2, 38); end if; + if D3 > 0 then Dice(D3, 8 + 15 * 3, 38); end if; + if D4 > 0 then Dice(D4, 8 + 15 * 4, 38); end if; + if D5 > 0 then Dice(D5, 8 + 15 * 5, 38); end if; + +end dice_placement; + + + + + + + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + Procedure logo_background (X_Start, Y_Start : in Integer) is + + begin + for X in 1..76 loop + for Y in 1..9 loop + Put(ASCII.ESC & logo_frame_bg); + goto_xy((X_Start - 3 + X), (Y_Start - 2 + Y)); + Put(' '); + end loop; + end loop; + end logo_background; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + Procedure logo (X_Start, Y_Start : in Integer) is + + begin + Set_Background_Colour(White); + Set_Foreground_Colour(Blue); + Set_Bold_Mode(on); + + goto_xy(X_Start, Y_Start); + Put("" ____ ____ __ _________ ________ ____ ____ ""); + goto_xy(X_Start, Y_Start + 1); + Put(' '); + Put(Vertical_Line); + Put(""_ _""); + Put(Vertical_Line, Times => 2); + Put(""_ _""); + Put(Vertical_Line); + Put("" / \ ""); + Put(Vertical_Line); + Put("" _ _ ""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put("" __ __""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_ _""); + Put(Vertical_Line, Times => 2); + Put(""_ _""); + Put(Vertical_Line); + goto_xy(X_Start, Y_Start + 2); + Put("" \ \ / / / /\ \ ""); + Put(Vertical_Line); + Put(""_/ ""); + Put(Vertical_Line); + Put(' '); + Put(Vertical_Line); + Put("" \_""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_/ / / \ \ / / ""); + goto_xy(X_Start, Y_Start + 3); + Put("" \ \/ / / ____ \ ""); + Put(Vertical_Line); + Put(' '); + Put(Vertical_Line); + Put("" / / _ \ \/ / ""); + goto_xy(X_Start, Y_Start + 4); + Put("" _""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_ _/ / \ \_ _""); + Put(Vertical_Line); + Put(' '); + Put(Vertical_Line); + Put(""_ / /__/ ""); + Put(Vertical_Line); + Put("" _""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_ ""); + goto_xy(X_Start, Y_Start + 5); + Put("" ""); + Put(Vertical_Line); + Put(""______""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""____""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""____""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_____""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""_______""); + Put(Vertical_Line); + Put("" ""); + Put(Vertical_Line); + Put(""______""); + Put(Vertical_Line); + Put("" ""); + goto_xy(X_Start, Y_Start + 6); + Put("" ""); + + -- ____ ____ __ _________ ________ ____ ____ + -- |_ _||_ _| / \ | _ _ | | __ __| |_ _||_ _| + -- \ \ / / / /\ \ |_/ | | \_| |_/ / / \ \ / / + -- \ \/ / / ____ \ | | / / _ \ \/ / + -- _| |_ _/ / \ \_ _| |_ / /__/ | _| |_ + -- |______| |____| |____| |_____| |_______| |______| + + end logo; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + + + + + + + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + + procedure message (X_Start, Y_Start : in Integer; S : in String) is + + begin + + Set_Graphical_Mode(Off); + + for Y in 1..11 loop + for X in 1..55 loop + + -- om inte första eller inte sista raden + if Y = 1 OR Y = 11 then + if X mod 2 = 0 then + Put(ASCII.ESC & message_frame_color1); + else + Put(ASCII.ESC & message_frame_color2); + end if; + else + if X = 1 OR X = 55 then + if Y mod 2 = 0 then + Put(ASCII.ESC & message_frame_color1); + else + Put(ASCII.ESC & message_frame_color2); + end if; + else + if Y mod 2 = 0 then + Put(ASCII.ESC & message_frame_color2); + else + Put(ASCII.ESC & message_frame_color1); + end if; + end if; + end if; + + goto_xy((X_Start - 2 + X), (Y_Start - 1 + Y)); + Put(' '); + + end loop; + end loop; + + + + -- White inner frame + for X in 1..51 loop + for Y in 1..9 loop + Put(ASCII.ESC & ""[48;5;15m""); + goto_xy((X_Start + X), (Y_Start + Y)); + Put(' '); + end loop; + end loop; + + goto_xy(X_Start + 3, Y_Start + 5); + Set_Foreground_Colour(Black); + Put(S); + end message; + + --------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------- + ---------------------------------------------------------------------------------------------" +procedure Test is,"procedure Test_TJa is + + Own_Protocoll, Other_Protocoll: Protocoll_Type; + Selected_Place : Integer; + + begin + Reset_Colours; -- Standard colours is supposed to be black on white ... + Clear_Window; + Set_Graphical_Mode(On); + background; + protocoll_background(125, 4); + logo_background(24, 4); + message(38, 18, ""Hejsan""); + + -- Draw a rectangle on screen ... + --Set_Graphical_Mode(On); + for I in 1..15 loop + case I is + when 1 => Own_Protocoll(I) := 1; + when 2 => Own_Protocoll(I) := 2; + when 3 => Own_Protocoll(I) := 3; + when 4 => Own_Protocoll(I) := 4; + when 5 => Own_Protocoll(I) := 5; + when 6 => Own_Protocoll(I) := -1; + when 7 => Own_Protocoll(I) := -1; + when 8 => Own_Protocoll(I) := -1; + when 9 => Own_Protocoll(I) := -1; + when 10 => Own_Protocoll(I) := -1; + when 11 => Own_Protocoll(I) := -1; + when 12 => Own_Protocoll(I) := 15; + when 13 => Own_Protocoll(I) := -1; + when 14 => Own_Protocoll(I) := 15; + when 15 => Own_Protocoll(I) := -1; + when others => null; + -- Own_Protocoll(I) := I; + end case; + end loop; + for I in 1..15 loop + Other_Protocoll(I) := I; + end loop; + + + + update_protocoll(125, 4, Own_Protocoll, Other_Protocoll); + + for x in 1..5 loop + dice(x,8 + 15 * x, 38); + --dice_placement; + end loop; + + + + logo(24, 4); + + Set_Graphical_Mode(Off); + + place(Own_Protocoll, Selected_Place); + + + Reset_Colours; + Reset_Text_Modes; -- Resets boold mode ... + + + + end Test_TJa; + + begin + Test_TJa; + Skip_Line;" +procedure Main is,"package Lines is new MyString(Max_MyString_Length => 2048); + S : Lines.MyString; + PM_Information : PasswordManager.Information; + GETDB : constant String := ""get""; + REMDB : constant String := ""rem""; + PUTDB : constant String := ""put""; + UNLOCK : constant String := ""unlock""; + LOCK : constant String := ""lock""; + TokensList : MyStringTokeniser.TokenArray(1..5):= (others => (Start => 1, Length => 0)); + NumTokens : Natural; + +begin + -- Program must initiate with 1 Pin input + if (MyCommandLine.Argument_Count = 1) then + declare + Temp_Pin : String := MyCommandLine.Argument(1); + begin + -- Pin must meet specified Pin requirements prior to Password Manager + -- initiation + if (MyCommandLine.Argument(1)'Length = 4 and + (for all I in Temp_Pin'Range => Temp_Pin(I) + >= '0' and Temp_Pin(I) <= '9')) then + PasswordManager.Init(MyCommandLine.Argument(1), PM_Information); + else + Put_Line(""Invalid input, program will exit!""); + return; + end if;" +procedure finalize_library is,"begin + E123 := E123 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""passworddatabase__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""ada__text_io__finalize_spec""); + begin + F2;" +procedure F3;,"pragma Import (Ada, F3, ""system__storage_pools__subpools__finalize_spec""); + begin + F3;" +procedure F4;,"pragma Import (Ada, F4, ""system__finalization_masters__finalize_spec""); + begin + F4;" +procedure F5;,"pragma Import (Ada, F5, ""system__file_io__finalize_body""); + begin + E085 := E085 - 1; + F5;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (C, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Leap_Seconds_Support : Integer; + pragma Import (C, Leap_Seconds_Support, ""__gl_leap_seconds_support""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 0; + Default_Stack_Size := -1; + Leap_Seconds_Support := 0; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E012 := E012 + 1; + System.Exceptions'Elab_Spec; + E022 := E022 + 1; + System.Soft_Links.Initialize'Elab_Body; + E053 := E053 + 1; + E014 := E014 + 1; + Ada.Containers'Elab_Spec; + E124 := E124 + 1; + Ada.Io_Exceptions'Elab_Spec; + E068 := E068 + 1; + Ada.Strings'Elab_Spec; + E009 := E009 + 1; + System.Os_Lib'Elab_Body; + E090 := E090 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E070 := E070 + 1; + Ada.Streams'Elab_Spec; + E067 := E067 + 1; + System.File_Control_Block'Elab_Spec; + E093 := E093 + 1; + System.Finalization_Root'Elab_Spec; + E088 := E088 + 1; + Ada.Finalization'Elab_Spec; + E086 := E086 + 1; + System.File_Io'Elab_Body; + E085 := E085 + 1; + System.Storage_Pools'Elab_Spec; + E139 := E139 + 1; + System.Finalization_Masters'Elab_Spec; + System.Finalization_Masters'Elab_Body; + E133 := E133 + 1; + System.Storage_Pools.Subpools'Elab_Spec; + E131 := E131 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E065 := E065 + 1; + Ada.Strings.Maps'Elab_Spec; + E057 := E057 + 1; + Ada.Strings.Maps.Constants'Elab_Spec; + E061 := E061 + 1; + E115 := E115 + 1; + E119 := E119 + 1; + E121 := E121 + 1; + Passworddatabase'Elab_Spec; + E123 := E123 + 1; + E147 := E147 + 1; + E145 := E145 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + gnat_argc := argc; + gnat_argv := argv; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure Simple_Benchmarking is,"CPU_MHz : Float := 2650.0; + + Verbose : constant Boolean := True; + + Results : Wavefile_Benchmark_Infos (1 .. 5); + + task type Wavefile_Benchmark + with CPU => 1 + is + entry Finish (Res : out Wavefile_Benchmark_Infos); + end Wavefile_Benchmark; + + task body Wavefile_Benchmark is + Local_Results : Wavefile_Benchmark_Infos (Results'Range); + begin + if Verbose then + Display_Current_CPU : declare + use System.Multiprocessors; + use System.Multiprocessors.Dispatching_Domains; + begin + Put_Line (""Current CPU : "" & CPU_Range'Image (Get_CPU)); + end Display_Current_CPU; + end if; + + Benchm_CPU_Time (CPU_MHz, Local_Results); + + accept Finish (Res : out Wavefile_Benchmark_Infos) do + Res := Local_Results; + end Finish; + end Wavefile_Benchmark; + + Benchmark_Using_Tasking : constant Boolean := False; + +begin + if Argument_Count >= 1 then + CPU_MHz := Float'Value (Argument (1)); + end if; + + if Verbose then + Put_Line (""Using CPU @ "" & Float'Image (CPU_MHz) & "" MHz""); + end if; + + if Benchmark_Using_Tasking then + declare + Wav_Benchmark : Wavefile_Benchmark; + begin + Wav_Benchmark.Finish (Results);" +procedure Open_Wavefile;,"procedure Close_Wavefile; + + function kHz_Per_Sample + (Elapsed_Time : Time_Span; + CPU_MHz : Float; + Number_Ch : Positive; + Number_Samples : Long_Long_Integer) return Float; + + procedure Display_Info (Elapsed_Time : Time_Span; + CPU_MHz : Float; + Number_Ch : Positive; + Number_Samples : Long_Long_Integer; + Sample_Rate : Positive); + + ------------------- + -- Open_Wavefile -- + ------------------- + + procedure Open_Wavefile is + Wav_In_File_Name : constant String := ""2ch_long_noise.wav""; + Wav_Out_File_Name : constant String := ""dummy.wav""; + + begin + WF_In.Open (In_File, Wav_In_File_Name); + + WF_Out.Set_Format_Of_Wavefile + (WF_In.Format_Of_Wavefile); + + WF_Out.Create (Out_File, Wav_Out_File_Name); + end Open_Wavefile; + + -------------------- + -- Close_Wavefile -- + -------------------- + + procedure Close_Wavefile is + begin + WF_In.Close; + WF_Out.Close; + end Close_Wavefile; + + -------------------- + -- kHz_Per_Sample -- + -------------------- + + function kHz_Per_Sample + (Elapsed_Time : Time_Span; + CPU_MHz : Float; + Number_Ch : Positive; + Number_Samples : Long_Long_Integer) return Float + is + Factor : constant Long_Long_Float := (Long_Long_Float (Number_Samples) + * Long_Long_Float (Number_Ch)); + begin + return Time_Span_Conversions.To_kHz (Elapsed_Time, CPU_MHz, Factor); + end kHz_Per_Sample; + + ------------------ + -- Display_Info -- + ------------------ + + procedure Display_Info (Elapsed_Time : Time_Span; + CPU_MHz : Float; + Number_Ch : Positive; + Number_Samples : Long_Long_Integer; + Sample_Rate : Positive) + is + use Time_Span_Conversions; + + package F_IO is new Ada.Text_IO.Float_IO (Float); + + -- Duration_In_Seconds : Long_Long_Float := + -- Long_Long_Float (Number_Samples) + -- / Long_Long_Float (Sample_Rate); + + Factor : constant Long_Long_Float := (Long_Long_Float (Number_Samples) + * Long_Long_Float (Number_Ch)); + begin + Put (""CPU time: ""); + F_IO.Put (Item => To_Miliseconds (Elapsed_Time), + Fore => 5, Aft => 4, Exp => 0); + Put ("" miliseconds""); + Put ("" for "" & Long_Long_Integer'Image (Number_Samples) & "" samples""); + Put ("" on "" & + Integer'Image (Number_Ch) & "" channels""); + Put ("" at "" & + Integer'Image (Sample_Rate) & "" Hz""); + New_Line; + + Put (""Overall Perf.: ""); + F_IO.Put (Item => (To_MHz (Elapsed_Time, CPU_MHz, Factor) + * Float (Sample_Rate)), + Fore => 5, Aft => 4, Exp => 0); + Put ("" MHz (per channel @ "" & Positive'Image (Sample_Rate) & "" kHz)""); + New_Line; + + Put (""Overall Perf.: ""); + F_IO.Put (Item => To_kHz (Elapsed_Time, CPU_MHz, Factor), + Fore => 5, Aft => 4, Exp => 0); + Put ("" kHz (per channel and per sample)""); + New_Line; + end Display_Info; + + --------------------- + -- Benchm_CPU_Time -- + --------------------- + + function Benchm_CPU_Time (CPU_MHz : Float) return Wavefile_Benchmark_kHz + is + Res : Wavefile_Benchmark_kHz; + + Start_Time, Stop_Time : CPU_Time; + Elapsed_Time : Time_Span; + + Sample_Rate : Positive; + + package Wav_IO is new Audio.Wavefiles.Generic_Direct_Fixed_Wav_IO + (Wav_Sample => Wav_Fixed_16, + Channel_Range => Positive, + Wav_MC_Sample => Wav_Buffer_Fixed_16); + use Wav_IO; + + Cnt, Total_Cnt : Long_Long_Integer := 0; + + begin + Write_Random_Noise_Wavefile; + + Open_Wavefile; + + Sample_Rate := To_Positive + (WF_In.Format_Of_Wavefile.Samples_Per_Sec); + + pragma Assert + (WF_In.Format_Of_Wavefile.Bits_Per_Sample = Bit_Depth_16 + and then not WF_In.Format_Of_Wavefile.Is_Float_Format); + + if Display_Debug_Info then + Put_Line (""========================================================""); + Put_Line (""= Read""); + Put_Line (""========================================================""); + end if; + + Start_Time := Clock; + + loop + Read_Wav_MC_Samples : declare + Dummy_Wav_Buf : constant Wav_Buffer_Fixed_16 := Get (WF_In); + begin + Cnt := Cnt + 1; + exit when End_Of_File (WF_In); + end Read_Wav_MC_Samples; + end loop; + + Stop_Time := Clock; + Elapsed_Time := Stop_Time - Start_Time; + + -- Res (Wavefile_Read_Benchmark) := Elapsed_Time; + Res (Wavefile_Read_Benchmark) := + kHz_Per_Sample (Elapsed_Time, + CPU_MHz, + Number_Of_Channels (WF_In), + Cnt); + + if Display_Debug_Info then + Display_Info (Elapsed_Time, + CPU_MHz, + Number_Of_Channels (WF_In), + Cnt, + Sample_Rate); + + Put_Line (""========================================================""); + Put_Line (""= Write""); + Put_Line (""========================================================""); + end if; + + Total_Cnt := Cnt; + Cnt := 0; + + declare + Wav_Buf : constant Wav_Buffer_Fixed_16 + (1 .. Number_Of_Channels (WF_In)) := (others => 0.5); + begin + Start_Time := Clock; + + loop + Write_Wav_MC_Samples : declare + begin + Cnt := Cnt + 1; + Put (WF_Out, Wav_Buf); + exit when Cnt = Total_Cnt; + + end Write_Wav_MC_Samples; + end loop; + + Stop_Time := Clock; + Elapsed_Time := Stop_Time - Start_Time; + + -- Res (Wavefile_Write_Benchmark) := Elapsed_Time; + Res (Wavefile_Write_Benchmark) := + kHz_Per_Sample (Elapsed_Time, + CPU_MHz, + Number_Of_Channels (WF_In), + Cnt);" +procedure Display_PCM_Vals,"(PCM_Vals : PCM_Buffer; + Header : String); + + procedure Write_PCM_Vals + (WF : in out Wavefile; + PCM_Vals : PCM_Buffer); + + function PCM_Data_Is_OK + (PCM_Ref, PCM_DUT : PCM_Buffer) return Boolean; + + function PCM_Data_Is_OK + (Test_Bits : Wav_Bit_Depth; + PCM_DUT : PCM_Buffer) return Boolean; + + function Wav_IO_OK_For_Audio_Resolution + (Test_Bits : Wav_Bit_Depth; + Wav_Test_File_Name : String) return Boolean; + + procedure Display_Info + (WF : Wavefile; + Header : String); + + procedure Write_Wavefile + (Wav_File_Name : String; + Test_Bits : Wav_Bit_Depth); + + procedure Read_Wavefile + (Wav_File_Name : String; + PCM_DUT : out PCM_Buffer); + + function Image (B : Wav_Bit_Depth) return String renames + Audio.RIFF.Wav.Formats.Report.Image; + + ---------------------- + -- Display_PCM_Vals -- + ---------------------- + + procedure Display_PCM_Vals (PCM_Vals : PCM_Buffer; + Header : String) + is +#if NUM_TYPE'Defined and then (NUM_TYPE = ""FLOAT"") then + Display_Integer_Value : constant Boolean := False; +#else + Display_Integer_Value : constant Boolean := True; +#end if; + begin + Put_Line (Header); + for Sample_Count in PCM_Vals'Range loop + declare +#if NUM_TYPE'Defined and then (NUM_TYPE = ""FLOAT"") then + PCM_Integer : array (1 .. 2) of Integer_64 + with + Address => PCM_Vals (Sample_Count)'Address, + Size => 128; +#else + PCM_Integer : Integer_64 + with + Address => PCM_Vals (Sample_Count)'Address, + Size => 64; +#end if; + begin + + Put ("" Val: ""); + PCM_Sample_Text_IO.Put (Item => PCM_Vals (Sample_Count), + Fore => 5, + Aft => 60, + Exp => 5); + if Display_Integer_Value then + Put ("" - ""); +#if NUM_TYPE'Defined and then (NUM_TYPE = ""FLOAT"") then + for I in PCM_Integer'Range loop + Fixed_64_PCM_As_Integer_Text_IO.Put + (PCM_Integer (I), Base => 2, Width => 68); + end loop; +#else + Fixed_64_PCM_As_Integer_Text_IO.Put + (PCM_Integer, Base => 2, Width => 68); +#end if; + end if; + New_Line;" +procedure Display_Info,"(WF : Wavefile; + Header : String) + is + Separator : constant String + := ""===========================================================""; + begin + Put_Line (Separator); + Put_Line (Header); + Display_Info (WF); + Put_Line (Separator); + end Display_Info; + + -------------------- + -- Write_Wavefile -- + -------------------- + + procedure Write_Wavefile + (Wav_File_Name : String; + Test_Bits : Wav_Bit_Depth) + is + WF_Out : Wavefile; + Wave_Format : Wave_Format_Extensible; + begin + Wave_Format := Init (Bit_Depth => Test_Bits, + Sample_Rate => Sample_Rate_44100, + Number_Of_Channels => 2, +#if NUM_TYPE'Defined and then (NUM_TYPE = ""FLOAT"") then + Use_Float => True); +#else + Use_Float => False); +#end if; + + WF_Out.Set_Format_Of_Wavefile (Wave_Format); + WF_Out.Create (Out_File, Wav_File_Name); + + Write_PCM_Vals (WF_Out, PCM_Ref); + + WF_Out.Close; + end Write_Wavefile; + + ------------------- + -- Read_Wavefile -- + ------------------- + + procedure Read_Wavefile + (Wav_File_Name : String; + PCM_DUT : out PCM_Buffer) + is + WF_In : Wavefile; + -- Wave_Format : Wave_Format_Extensible; + EOF : Boolean; + Samples : Integer := 0; + begin + WF_In.Open (In_File, Wav_File_Name); + -- Wave_Format := WF_In.Format_Of_Wavefile; + + if Verbose then + Display_Info (WF_In, ""Input File:""); + end if; + + Samples := 0; + PCM_DUT := (others => 0.0); + loop + Samples := Samples + 1; + -- Put (""["" & Integer'Image (Samples) & ""]""); + + declare + PCM_Buf : constant PCM_Buffer := Get (WF_In); + begin + PCM_DUT (Samples) := PCM_Buf (PCM_Buf'First);" +procedure Display_PCM_Vals,"(PCM_Vals : PCM_Buffer; + Header : String); + + procedure Write_PCM_Vals + (WF : in out Wavefile; + PCM_Vals : PCM_Buffer); + + function PCM_Data_Is_OK + (PCM_Ref, PCM_DUT : PCM_Buffer) return Boolean; + + function PCM_Data_Is_OK + (Test_Bits : Wav_Bit_Depth; + PCM_DUT : PCM_Buffer) return Boolean; + + function Wav_IO_OK_For_Audio_Resolution + (Test_Bits : Wav_Bit_Depth; + Wav_Test_File_Name : String) return Boolean; + + procedure Display_Info + (WF : Wavefile; + Header : String); + + procedure Write_Wavefile + (Wav_File_Name : String; + Test_Bits : Wav_Bit_Depth); + + procedure Read_Wavefile + (Wav_File_Name : String; + PCM_DUT : out PCM_Buffer); + + function Image (B : Wav_Bit_Depth) return String renames + Audio.RIFF.Wav.Formats.Report.Image; + + ---------------------- + -- Display_PCM_Vals -- + ---------------------- + + procedure Display_PCM_Vals (PCM_Vals : PCM_Buffer; + Header : String) + is + Display_Integer_Value : constant Boolean := False; + begin + Put_Line (Header); + for Sample_Count in PCM_Vals'Range loop + declare + PCM_Integer : array (1 .. 2) of Integer_64 + with + Address => PCM_Vals (Sample_Count)'Address, + Size => 128; + begin + + Put ("" Val: ""); + PCM_Sample_Text_IO.Put (Item => PCM_Vals (Sample_Count), + Fore => 5, + Aft => 60, + Exp => 5); + if Display_Integer_Value then + Put ("" - ""); + for I in PCM_Integer'Range loop + Fixed_64_PCM_As_Integer_Text_IO.Put + (PCM_Integer (I), Base => 2, Width => 68); + end loop; + end if; + New_Line;" +procedure Display_Info,"(WF : Wavefile; + Header : String) + is + Separator : constant String + := ""===========================================================""; + begin + Put_Line (Separator); + Put_Line (Header); + Display_Info (WF); + Put_Line (Separator); + end Display_Info; + + -------------------- + -- Write_Wavefile -- + -------------------- + + procedure Write_Wavefile + (Wav_File_Name : String; + Test_Bits : Wav_Bit_Depth) + is + WF_Out : Wavefile; + Wave_Format : Wave_Format_Extensible; + begin + Wave_Format := Init (Bit_Depth => Test_Bits, + Sample_Rate => Sample_Rate_44100, + Number_Of_Channels => 2, + Use_Float => True); + + WF_Out.Set_Format_Of_Wavefile (Wave_Format); + WF_Out.Create (Out_File, Wav_File_Name); + + Write_PCM_Vals (WF_Out, PCM_Ref); + + WF_Out.Close; + end Write_Wavefile; + + ------------------- + -- Read_Wavefile -- + ------------------- + + procedure Read_Wavefile + (Wav_File_Name : String; + PCM_DUT : out PCM_Buffer) + is + WF_In : Wavefile; + -- Wave_Format : Wave_Format_Extensible; + EOF : Boolean; + Samples : Integer := 0; + begin + WF_In.Open (In_File, Wav_File_Name); + -- Wave_Format := WF_In.Format_Of_Wavefile; + + if Verbose then + Display_Info (WF_In, ""Input File:""); + end if; + + Samples := 0; + PCM_DUT := (others => 0.0); + loop + Samples := Samples + 1; + -- Put (""["" & Integer'Image (Samples) & ""]""); + + declare + PCM_Buf : constant PCM_Buffer := Get (WF_In); + begin + PCM_DUT (Samples) := PCM_Buf (PCM_Buf'First);" +procedure Display_PCM_Vals,"(PCM_Vals : PCM_Buffer; + Header : String); + + procedure Write_PCM_Vals + (WF : in out Wavefile; + PCM_Vals : PCM_Buffer); + + function PCM_Data_Is_OK + (PCM_Ref, PCM_DUT : PCM_Buffer) return Boolean; + + function PCM_Data_Is_OK + (Test_Bits : Wav_Bit_Depth; + PCM_DUT : PCM_Buffer) return Boolean; + + function Wav_IO_OK_For_Audio_Resolution + (Test_Bits : Wav_Bit_Depth; + Wav_Test_File_Name : String) return Boolean; + + procedure Display_Info + (WF : Wavefile; + Header : String); + + procedure Write_Wavefile + (Wav_File_Name : String; + Test_Bits : Wav_Bit_Depth); + + procedure Read_Wavefile + (Wav_File_Name : String; + PCM_DUT : out PCM_Buffer); + + function Image (B : Wav_Bit_Depth) return String renames + Audio.RIFF.Wav.Formats.Report.Image; + + ---------------------- + -- Display_PCM_Vals -- + ---------------------- + + procedure Display_PCM_Vals (PCM_Vals : PCM_Buffer; + Header : String) + is + Display_Integer_Value : constant Boolean := True; + begin + Put_Line (Header); + for Sample_Count in PCM_Vals'Range loop + declare + PCM_Integer : Integer_64 + with + Address => PCM_Vals (Sample_Count)'Address, + Size => 64; + begin + + Put ("" Val: ""); + PCM_Sample_Text_IO.Put (Item => PCM_Vals (Sample_Count), + Fore => 5, + Aft => 60, + Exp => 5); + if Display_Integer_Value then + Put ("" - ""); + Fixed_64_PCM_As_Integer_Text_IO.Put + (PCM_Integer, Base => 2, Width => 68); + end if; + New_Line;" +procedure Display_Info,"(WF : Wavefile; + Header : String) + is + Separator : constant String + := ""===========================================================""; + begin + Put_Line (Separator); + Put_Line (Header); + Display_Info (WF); + Put_Line (Separator); + end Display_Info; + + -------------------- + -- Write_Wavefile -- + -------------------- + + procedure Write_Wavefile + (Wav_File_Name : String; + Test_Bits : Wav_Bit_Depth) + is + WF_Out : Wavefile; + Wave_Format : Wave_Format_Extensible; + begin + Wave_Format := Init (Bit_Depth => Test_Bits, + Sample_Rate => Sample_Rate_44100, + Number_Of_Channels => 2, + Use_Float => False); + + WF_Out.Set_Format_Of_Wavefile (Wave_Format); + WF_Out.Create (Out_File, Wav_File_Name); + + Write_PCM_Vals (WF_Out, PCM_Ref); + + WF_Out.Close; + end Write_Wavefile; + + ------------------- + -- Read_Wavefile -- + ------------------- + + procedure Read_Wavefile + (Wav_File_Name : String; + PCM_DUT : out PCM_Buffer) + is + WF_In : Wavefile; + -- Wave_Format : Wave_Format_Extensible; + EOF : Boolean; + Samples : Integer := 0; + begin + WF_In.Open (In_File, Wav_File_Name); + -- Wave_Format := WF_In.Format_Of_Wavefile; + + if Verbose then + Display_Info (WF_In, ""Input File:""); + end if; + + Samples := 0; + PCM_DUT := (others => 0.0); + loop + Samples := Samples + 1; + -- Put (""["" & Integer'Image (Samples) & ""]""); + + declare + PCM_Buf : constant PCM_Buffer := Get (WF_In); + begin + PCM_DUT (Samples) := PCM_Buf (PCM_Buf'First);" +procedure Gif2ada is,"use Interfaces; + + Image : GID.Image_descriptor; +begin + if Ada.Command_Line.Argument_Count /= 2 then + Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, + ""Usage: gif2ada ""); + Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, + ""Generate an Ada package that contains an GIF image""); + Ada.Command_Line.Set_Exit_Status (2); + return; + end if; + declare + + subtype Primary_color_range is Unsigned_8; + + procedure Get_Color (Red, Green, Blue : Interfaces.Unsigned_8); + procedure Set_X_Y (X, Y : in Natural) is null; + procedure Put_Pixel (Red, Green, Blue : Primary_color_range; + Alpha : Primary_color_range) is null; + procedure Feedback (Percents : Natural) is null; + procedure Raw_Byte (B : in Interfaces.Unsigned_8); + + Name : constant String := Ada.Command_Line.Argument (1); + Path : constant String := Ada.Command_Line.Argument (2); + File : Ada.Streams.Stream_IO.File_Type; + Color_Count : Natural := 0; + Need_Sep : Boolean := False; + Need_Line : Boolean := False; + Count : Natural := 0; + + procedure Raw_Byte (B : in Interfaces.Unsigned_8) is + begin + if Need_Sep then + Ada.Text_IO.Put ("",""); + end if; + if Need_Line then + Need_Line := False; + Ada.Text_IO.New_Line; + Ada.Text_IO.Set_Col (8); + end if; + Need_Sep := True; + Ada.Text_IO.Put (Natural'Image (Natural (B))); + Count := Count + 1; + Need_Line := (Count mod 8) = 0; + end Raw_Byte; + + procedure Load_Image is + new GID.Load_image_contents (Primary_color_range, Set_X_Y, + Put_Pixel, Raw_Byte, Feedback, GID.fast); + + procedure Get_Color (Red, Green, Blue : Interfaces.Unsigned_8) is + Red_Image : constant String := Unsigned_8'Image (Red); + begin + if Color_Count > 0 then + Ada.Text_IO.Put ("",""); + end if; + if Color_Count mod 4 = 3 then + Ada.Text_IO.New_Line; + Ada.Text_IO.Set_Col (9); + else + Ada.Text_IO.Put ("" ""); + end if; + Color_Count := Color_Count + 1; + Ada.Text_IO.Put (""(""); + Ada.Text_IO.Put (Red_Image (Red_Image'First + 1 .. Red_Image'Last)); + Ada.Text_IO.Put ("",""); + Ada.Text_IO.Put (Unsigned_8'Image (Green)); + Ada.Text_IO.Put ("",""); + Ada.Text_IO.Put (Unsigned_8'Image (Blue)); + Ada.Text_IO.Put ("")""); + end Get_Color; + + procedure Write_Palette is + new GID.Get_palette (Get_Color); + + Next_Frame : Ada.Calendar.Day_Duration := 0.0; + begin + Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Path); + GID.Load_image_header (Image, Ada.Streams.Stream_IO.Stream (File).all); + + Ada.Text_IO.Put_Line (""with UI.Images;""); + Ada.Text_IO.Put_Line (""package "" & Name & "" is""); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put ("" ""); + Ada.Text_IO.Put_Line (""Descriptor : constant UI.Images.Image_Descriptor;""); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (""private""); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line ("" Palette : aliased constant UI.Images.Color_Array := (""); + Ada.Text_IO.Set_Col (8); + Write_Palette (Image); + Ada.Text_IO.Put_Line ("" );""); + Ada.Text_IO.Put_Line ("" -- "" & Natural'Image (Color_Count) & "" colors""); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line ("" Data : aliased constant UI.Images.Bitmap_Array := (""); + Ada.Text_IO.Put ("" ""); + + Load_Image (Image, Next_Frame); + Ada.Streams.Stream_IO.Close (File); + Ada.Text_IO.Put_Line ("" );""); + Ada.Text_IO.Put_Line ("" -- "" & Natural'Image (Count) & "" bytes""); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line ("" Descriptor : constant UI.Images.Image_Descriptor :=""); + Ada.Text_IO.Put ("" (Width =>""); + Ada.Text_IO.Put (Positive'Image (GID.Pixel_width (Image))); + Ada.Text_IO.Put_Line ("",""); + Ada.Text_IO.Put ("" Height =>""); + Ada.Text_IO.Put (Positive'Image (GID.Pixel_height (Image))); + Ada.Text_IO.Put_Line ("",""); + Ada.Text_IO.Put_Line ("" Palette => Palette'Access,""); + Ada.Text_IO.Put_Line ("" Bitmap => Data'Access);""); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (""end "" & Name & "";"");" +procedure Big_endian is new Big_endian_number( U16 );,"procedure Read( image: in out Image_descriptor; sh: out Segment_head) is + b: U8; + id: constant array(JPEG_marker) of U8:= + ( SOI => 16#D8#, + -- + SOF_0 => 16#C0#, SOF_1 => 16#C1#, SOF_2 => 16#C2#, SOF_3 => 16#C3#, + SOF_5 => 16#C5#, SOF_6 => 16#C6#, SOF_7 => 16#C7#, SOF_8 => 16#C8#, + SOF_9 => 16#C9#, SOF_10 => 16#CA#, SOF_11 => 16#CB#, SOF_13 => 16#CD#, + SOF_14 => 16#CE#, SOF_15 => 16#CF#, + -- + DHT => 16#C4#, + DAC => 16#CC#, + DQT => 16#DB#, + DRI => 16#DD#, + -- + APP_0 => 16#E0#, APP_1 => 16#E1#, APP_2 => 16#E2#, APP_3 => 16#E3#, + APP_4 => 16#E4#, APP_5 => 16#E5#, APP_6 => 16#E6#, APP_7 => 16#E7#, + APP_8 => 16#E8#, APP_9 => 16#E9#, APP_10 => 16#EA#, APP_11 => 16#EB#, + APP_12 => 16#EC#, APP_13 => 16#ED#, APP_14 => 16#EE#, + -- + COM => 16#FE#, + SOS => 16#DA#, + EOI => 16#D9# + ); + begin + Get_Byte(image.buffer, b); + if b /= 16#FF# then + Raise_Exception( + error_in_image_data'Identity, + ""JPEG: expected marker here"" + ); + end if; + Get_Byte(image.buffer, b); + for m in id'Range loop + if id(m)= b then + sh.kind:= m; + Big_endian(image.buffer, sh.length); + sh.length:= sh.length - 2; + -- We consider length of contents, without the FFxx marker. + if some_trace then + Put_Line( + ""Segment ["" & JPEG_marker'Image(sh.kind) & + ""], length:"" & U16'Image(sh.length)); + end if; + return; + end if; + end loop; + Raise_Exception( + error_in_image_data'Identity, + ""JPEG: unknown marker here: FF, "" & U8'Image(b) + ); + end Read; + + shift_arg: constant array(0..15) of Integer:= + (1 => 0, 2 => 1, 4 => 2, 8 => 3, others => -1); + + -- SOF - Start Of Frame (the real header) + procedure Read_SOF(image: in out Image_descriptor; sh: Segment_head) is + use Bounded_255; + b, bits_pp_primary, id_base: U8; + w, h: U16; + compo: JPEG_defs.Component; + begin + case sh.kind is + when SOF_0 => + image.detailed_format:= To_Bounded_String(""JPEG, Baseline DCT (SOF_0)""); + when SOF_2 => + image.detailed_format:= To_Bounded_String(""JPEG, Progressive DCT (SOF_2)""); + image.interlaced:= True; + when others => + Raise_Exception( + unsupported_image_subformat'Identity, + ""JPEG: image type not yet supported: "" & JPEG_marker'Image(sh.kind) + ); + end case; + Get_Byte(image.buffer, bits_pp_primary); + if bits_pp_primary /= 8 then + Raise_Exception( + unsupported_image_subformat'Identity, + ""Bits per primary color="" & U8'Image(bits_pp_primary) + ); + end if; + image.bits_per_pixel:= 3 * Positive(bits_pp_primary); + Big_endian(image.buffer, h); + Big_endian(image.buffer, w); + image.width:= Natural(w); + image.height:= Natural(h); + -- Number of components: + Get_Byte(image.buffer, b); + image.subformat_id:= Integer(b); + -- + image.JPEG_stuff.max_samples_hor:= 0; + image.JPEG_stuff.max_samples_ver:= 0; + id_base := 1; + -- For each component: 3 bytes information: ID, sampling factors, quantization table number + for i in 1..image.subformat_id loop + -- Component ID (1 = Y, 2 = Cb, 3 = Cr, 4 = I, 5 = Q) + Get_Byte(image.buffer, b); + if b = 0 then + -- Workaround for a bug in some encoders, for instance Intel(R) JPEG Library, + -- version [2.0.18.50] as in some Photoshop versions : IDs are numbered 0, 1, 2. + id_base := 0; + end if; + if b - id_base > Component'Pos(Component'Last) then + Raise_Exception(error_in_image_data'Identity, ""SOF: invalid component ID: "" & U8'Image(b)); + end if; + compo:= JPEG_defs.Component'Val(b - id_base); + image.JPEG_stuff.components(compo):= True; + declare + stuff: JPEG_stuff_type renames image.JPEG_stuff; + info: JPEG_defs.Info_per_component_A renames stuff.info(compo); + begin + -- Sampling factors (bit 0-3 vert., 4-7 hor.) + Get_Byte(image.buffer, b); + info.samples_ver:= Natural(b mod 16); + info.samples_hor:= Natural(b / 16); + stuff.max_samples_hor:= + Integer'Max(stuff.max_samples_hor, info.samples_hor); + stuff.max_samples_ver:= + Integer'Max(stuff.max_samples_ver, info.samples_ver); + -- Quantization table number + Get_Byte(image.buffer, b); + info.qt_assoc:= Natural(b);" +procedure Color_transformation_and_output;,"-- + procedure Color_transformation_and_output is + y_val, cb_val, cr_val, c_val, m_val, w_val: Integer; + y_val_8: U8; + begin + for ymb in flat'Range(3) loop + exit when y0+ymb >= image.height; + Set_X_Y(x0, image.height-1-(y0+ymb)); + for xmb in flat'Range(2) loop + exit when x0+xmb >= image.width; + case color_space is + when YCbCr => + y_val := flat(Y, xmb, ymb) * 256; + cb_val:= flat(Cb, xmb, ymb) - 128; + cr_val:= flat(Cr, xmb, ymb) - 128; + Out_Pixel_8( + br => U8(Clip((y_val + 359 * cr_val + 128) / 256)), + bg => U8(Clip((y_val - 88 * cb_val - 183 * cr_val + 128) / 256)), + bb => U8(Clip((y_val + 454 * cb_val + 128) / 256)) + ); + when Y_Grey => + y_val_8:= U8(flat(Y, xmb, ymb)); + Out_Pixel_8(y_val_8, y_val_8, y_val_8); + when CMYK => + -- !! find a working conversion formula. + -- perhaps it is more complicated (APP_2 + -- color profile must be used ?) + c_val:= flat(Y, xmb, ymb); + m_val:= flat(Cb, xmb, ymb); + y_val:= flat(Cr, xmb, ymb); + w_val:= flat(I, xmb, ymb)-255; + Out_Pixel_8( + br => U8(255-Clip(c_val+w_val)), + bg => U8(255-Clip(m_val+w_val)), + bb => U8(255-Clip(y_val+w_val)) + ); + end case; + end loop; + end loop; + end Color_transformation_and_output; + -- + procedure Ct_YCbCr is new Color_transformation_and_output(YCbCr); + procedure Ct_Y_Grey is new Color_transformation_and_output(Y_Grey); + procedure Ct_CMYK is new Color_transformation_and_output(CMYK); + + blk_idx: Integer; + upsx, upsy: Natural; + begin + -- Step 4 happens here: Upsampling + for c in Component loop + if image.JPEG_stuff.components(c) then + upsx:= info_A(c).up_factor_x; + upsy:= info_A(c).up_factor_y; + for x in reverse 1..info_A(c).samples_hor loop + for y in reverse 1..info_A(c).samples_ver loop + -- We are at the 8x8 block level + blk_idx:= 63; + for y8 in reverse 0..7 loop + for x8 in reverse 0..7 loop + declare + val: constant Integer:= m(c,x,y)(blk_idx); + big_pixel_x: constant Natural:= upsx * (x8 + 8*(x-1)); + big_pixel_y: constant Natural:= upsy * (y8 + 8*(y-1)); + begin + -- Repeat pixels for component c, sample (x,y), + -- position (x8,y8). + for rx in reverse 0..upsx-1 loop + for ry in reverse 0..upsy-1 loop + flat(c, rx + big_pixel_x, ry + big_pixel_y):= val; + end loop; + end loop;" +procedure Read_SOS is,"components, b, id_base: U8; + compo: Component:= Component'First; + mbx, mby: Natural:= 0; + mbsizex, mbsizey, mbwidth, mbheight: Natural; + rstcount: Natural:= image.JPEG_stuff.restart_interval; + nextrst: U16:= 0; + w: U16; + start_spectral_selection, + end_spectral_selection, + successive_approximation: U8; + begin + Get_Byte(image.buffer, components); + if some_trace then + Put_Line( + ""Start of Scan (SOS), with"" & U8'Image(components) & "" components"" + ); + end if; + if image.subformat_id /= Natural(components) then + Raise_Exception( + error_in_image_data'Identity, + ""JPEG: components mismatch in Scan segment"" + ); + end if; + id_base := 1; + for i in 1..components loop + Get_Byte(image.buffer, b); + if b = 0 then + -- Workaround for bugged encoder (see above) + id_base := 0; + end if; + if b - id_base > Component'Pos(Component'Last) then + Raise_Exception(error_in_image_data'Identity, ""Scan: invalid ID: "" & U8'Image(b)); + end if; + compo:= Component'Val(b - id_base); + if not image.JPEG_stuff.components(compo) then + Raise_Exception( + error_in_image_data'Identity, + ""JPEG: component "" & Component'Image(compo) & + "" has not been defined in the header (SOF) segment"" + ); + end if; + -- Huffman table selection + Get_Byte(image.buffer, b); + info_B(compo).ht_idx_AC:= Natural(b mod 16); + info_B(compo).ht_idx_DC:= Natural(b / 16); + end loop; + -- Parameters for progressive display format (SOF_2) + Get_Byte(image.buffer, start_spectral_selection); + Get_Byte(image.buffer, end_spectral_selection); + Get_Byte(image.buffer, successive_approximation); + -- + -- End of SOS segment, image data follow. + -- + mbsizex:= ssxmax * 8; -- pixels in a row of a macro-block + mbsizey:= ssymax * 8; -- pixels in a column of a macro-block + mbwidth := (image.width + mbsizex - 1) / mbsizex; + -- width in macro-blocks + mbheight:= (image.height + mbsizey - 1) / mbsizey; + -- height in macro-blocks + if some_trace then + Put_Line("" mbsizex = "" & Integer'Image(mbsizex)); + Put_Line("" mbsizey = "" & Integer'Image(mbsizey)); + Put_Line("" mbwidth = "" & Integer'Image(mbwidth)); + Put_Line("" mbheight = "" & Integer'Image(mbheight)); + end if; + for c in Component loop + if image.JPEG_stuff.components(c) then + info_B(c).width := (image.width * info_A(c).samples_hor + ssxmax - 1) / ssxmax; + info_B(c).height:= (image.height * info_A(c).samples_ver + ssymax - 1) / ssymax; + info_B(c).stride:= (mbwidth * mbsizex * info_A(c).samples_hor) / ssxmax; + if some_trace then + Put_Line("" Details for component "" & Component'Image(c)); + Put_Line("" samples in x "" & Integer'Image(info_A(c).samples_hor)); + Put_Line("" samples in y "" & Integer'Image(info_A(c).samples_ver)); + Put_Line("" width "" & Integer'Image(info_B(c).width)); + Put_Line("" height "" & Integer'Image(info_B(c).height)); + Put_Line("" stride "" & Integer'Image(info_B(c).stride)); + Put_Line( + "" AC/DC table index "" & + Integer'Image(info_B(compo).ht_idx_AC) & "", "" & + Integer'Image(info_B(compo).ht_idx_DC) + ); + end if; + if (info_B(c).width < 3 and info_A(c).samples_hor /= ssxmax) or + (info_B(c).height < 3 and info_A(c).samples_ver /= ssymax) + then + Raise_Exception( + error_in_image_data'Identity, + ""JPEG: component "" & Component'Image(c) & + "": sample dimension mismatch"" + ); + end if; + end if; + end loop; + -- + if image.interlaced then + Raise_Exception( + unsupported_image_subformat'Identity, + ""JPEG: progressive format not yet functional"" + ); + end if; + declare + mb: Macro_block(Component, 1..ssxmax, 1..ssymax); + x0, y0: Integer:= 0; + begin + macro_blocks_loop: + loop + components_loop: + for c in Component loop + if image.JPEG_stuff.components(c) then + samples_y_loop: + for sby in 1..info_A(c).samples_ver loop + samples_x_loop: + for sbx in 1..info_A(c).samples_hor loop + Decode_Block(c, mb(c, sbx, sby)); + end loop samples_x_loop; + end loop samples_y_loop; + end if; + end loop components_loop; + -- All components of the current macro-block are decoded. + -- Step 4, 5, 6 happen here: Upsampling, color transformation, output + Upsampling_and_output(mb, x0, y0); + -- + mbx:= mbx + 1; + x0:= x0 + ssxmax * 8; + if mbx >= mbwidth then + mbx:= 0; + x0:= 0; + mby:= mby + 1; + y0:= y0 + ssymax * 8; + Feedback((100*mby)/mbheight); + exit macro_blocks_loop when mby >= mbheight; + end if; + if image.JPEG_stuff.restart_interval > 0 then + rstcount:= rstcount - 1; + if rstcount = 0 then + -- Here begins the restart. + bufbits:= Natural(U32(bufbits) and 16#F8#); -- byte alignment + -- Now the restart marker. We expect a + w:= U16(Get_bits(16)); + if some_trace then + Put_Line( + "" Restart #"" & U16'Image(nextrst) & + "" Code "" & U16'Image(w) & + "" after"" & Natural'Image(image.JPEG_stuff.restart_interval) & + "" macro blocks"" + ); + end if; + if w not in 16#FFD0# .. 16#FFD7# or (w and 7) /= nextrst then + Raise_Exception( + error_in_image_data'Identity, + ""JPEG: expected RST (restart) marker Nb "" & U16'Image(nextrst) + ); + end if; + nextrst:= (nextrst + 1) and 7; + rstcount:= image.JPEG_stuff.restart_interval; + -- Block-to-block predictor variables are reset. + for c in Component loop + info_B(c).dcpred:= 0; + end loop; + end if; + end if; + end loop macro_blocks_loop;" +procedure Dispose is new,"Ada.Unchecked_Deallocation( HufT_table, p_HufT_table ); + procedure Dispose is new + Ada.Unchecked_Deallocation( Table_list, p_Table_list ); + + current: p_Table_list; + tcount : Natural:= 0; -- just a stat. Idea: replace table_list with an array + tot_length: Natural:= 0; + + begin + if full_trace then + Ada.Text_IO.Put(""[HufT_Free... ""); + end if; + while tl /= null loop + if full_trace then + tcount:= tcount+1; + tot_length:= tot_length + tl.table'Length; + end if; + Dispose( tl.table ); -- destroy the Huffman table + current:= tl; + tl := tl.next; + Dispose( current ); -- destroy the current node + end loop; + if full_trace then + Ada.Text_IO.Put_Line( + Integer'Image(tcount)& "" tables, of"" & + Integer'Image(tot_length)& "" tot. length]"" + ); + end if; + end HufT_free; + + -- Build huffman table from code lengths given by array b + + procedure HufT_build ( b : Length_array; + s : Integer; + d, e : Length_array; + tl : out p_Table_list; + m : in out Integer; + huft_incomplete : out Boolean) + is + b_max : constant:= 16; + b_maxp1: constant:= b_max + 1; + + -- bit length count table + count : array( 0 .. b_maxp1 ) of Integer:= (others=> 0); + + f : Integer; -- i repeats in table every f entries + g : Integer; -- max. code length + i, -- counter, current code + j : Integer; -- counter + kcc : Integer; -- number of bits in current code + + c_idx, v_idx: Natural; -- array indices + + current_table_ptr : p_HufT_table:= null; + current_node_ptr : p_Table_list:= null; -- curr. node for the curr. table + new_node_ptr : p_Table_list; -- new node for the new table + + new_entry: HufT; -- table entry for structure assignment + + u : array( 0..b_max ) of p_HufT_table; -- table stack + + n_max : constant:= 288; + -- values in order of bit length + v : array( 0..n_max ) of Integer:= (others=> 0); + el_v, el_v_m_s: Integer; + + w : Natural:= 0; -- bits before this table + + offset, code_stack : array( 0..b_maxp1 ) of Integer; + + table_level : Integer:= -1; + bits : array( Integer'(-1)..b_maxp1 ) of Integer; + -- ^bits(table_level) = # bits in table of level table_level + + y : Integer; -- number of dummy codes added + z : Natural:= 0; -- number of entries in current table + el : Integer; -- length of eob code=code 256 + + no_copy_length_array: constant Boolean:= d'Length=0 or e'Length=0; + + begin + if full_trace then + Ada.Text_IO.Put(""[HufT_Build...""); + end if; + tl:= null; + + if b'Length > 256 then -- set length of EOB code, if any + el := Natural(b(256)); + else + el := b_max; + end if; + + -- Generate counts for each bit length + + for k in b'Range loop + if b(k) > b_max then + -- m := 0; -- GNAT 2005 doesn't like it (warning). + raise huft_error; + end if; + count( Natural(b(k)) ):= count( Natural(b(k)) ) + 1; + end loop; + + if count(0) = b'Length then + m := 0; + huft_incomplete:= False; -- spotted by Tucker Taft, 19-Aug-2004 + return; -- complete + end if; + + -- Find minimum and maximum length, bound m by those + + j := 1; + while j <= b_max and then count(j) = 0 loop + j:= j + 1; + end loop; + kcc := j; + if m < j then + m := j; + end if; + i := b_max; + while i > 0 and then count(i) = 0 loop + i:= i - 1; + end loop; + g := i; + if m > i then + m := i; + end if; + + -- Adjust last length count to fill out codes, if needed + + y := Integer( Shift_Left(Unsigned_32'(1), j) ); -- y:= 2 ** j; + while j < i loop + y := y - count(j); + if y < 0 then + raise huft_error; + end if; + y:= y * 2; + j:= j + 1; + end loop; + + y:= y - count(i); + if y < 0 then + raise huft_error; + end if; + count(i):= count(i) + y; + + -- Generate starting offsets into the value table for each length + + offset(1) := 0; + j:= 0; + for idx in 2..i loop + j:= j + count( idx-1 ); + offset( idx ) := j; + end loop; + + -- Make table of values in order of bit length + + for idx in b'Range loop + j := Natural(b(idx)); + if j /= 0 then + v( offset(j) ) := idx-b'First; + offset(j):= offset(j) + 1; + end if; + end loop; + + -- Generate huffman codes and for each, make the table entries + + code_stack(0) := 0; + i := 0; + v_idx:= v'First; + bits(-1) := 0; + + -- go through the bit lengths (kcc already is bits in shortest code) + for k in kcc .. g loop + + for am1 in reverse 0 .. count(k)-1 loop -- a counts codes of length k + + -- here i is the huffman code of length k bits for value v(v_idx) + while k > w + bits(table_level) loop + + w:= w + bits(table_level); -- Length of tables to this position + table_level:= table_level+ 1; + z:= g - w; -- Compute min size table <= m bits + if z > m then + z := m; + end if; + j := k - w; + f := Integer(Shift_Left(Unsigned_32'(1), j)); -- f:= 2 ** j; + if f > am1 + 2 then -- Try a k-w bit table + f:= f - (am1 + 2); + c_idx:= k; + loop -- Try smaller tables up to z bits + j:= j + 1; + exit when j >= z; + f := f * 2; + c_idx:= c_idx + 1; + exit when f - count(c_idx) <= 0; + f:= f - count(c_idx); + end loop; + end if; + + if w + j > el and then w < el then + j:= el - w; -- Make EOB code end at table + end if; + if w = 0 then + j := m; -- Fix: main table always m bits! + end if; + z:= Integer(Shift_Left(Unsigned_32'(1), j)); -- z:= 2 ** j; + bits(table_level) := j; + + -- Allocate and link new table + + begin + current_table_ptr := new HufT_table ( 0..z ); + new_node_ptr := new Table_list'( current_table_ptr, null ); + exception + when Storage_Error => + raise huft_out_of_memory;" +procedure Big_endian is new Big_endian_number( U32 );,"use Ada.Exceptions; + + ---------- + -- Read -- + ---------- + + procedure Read (image: in out Image_descriptor; ch: out Chunk_head) is + str4: String(1..4); + b: U8; + begin + Big_endian(image.buffer, ch.length); + for i in str4'Range loop + Buffering.Get_Byte(image.buffer, b); + str4(i):= Character'Val(b); + end loop; + begin + ch.kind:= PNG_Chunk_tag'Value(str4); + if some_trace then + Ada.Text_IO.Put_Line( + ""Chunk ["" & str4 & + ""], length:"" & U32'Image(ch.length) + ); + end if; + exception + when Constraint_Error => + Raise_Exception( + error_in_image_data'Identity, + ""PNG chunk unknown: "" & + Integer'Image(Character'Pos(str4(1))) & + Integer'Image(Character'Pos(str4(2))) & + Integer'Image(Character'Pos(str4(3))) & + Integer'Image(Character'Pos(str4(4))) & + "" ("" & str4 & ')' + );" +procedure Prepare_table is,"-- CRC-32 algorithm, ISO-3309 + Seed: constant:= 16#EDB88320#; + l: Unsigned_32; + begin + for i in CRC32_Table'Range loop + l:= i; + for bit in 0..7 loop + if (l and 1) = 0 then + l:= Shift_Right(l,1); + else + l:= Shift_Right(l,1) xor Seed; + end if; + end loop; + CRC32_Table(i):= l; + end loop; + end Prepare_table; + + procedure Update( CRC: in out Unsigned_32; InBuf: Byte_array ) is + local_CRC: Unsigned_32; + begin + local_CRC:= CRC ; + for i in InBuf'Range loop + local_CRC := + CRC32_Table( 16#FF# and ( local_CRC xor Unsigned_32( InBuf(i) ) ) ) + xor + Shift_Right( local_CRC , 8 ); + end loop; + CRC:= local_CRC; + end Update; + + table_empty: Boolean:= True; + + procedure Init( CRC: out Unsigned_32 ) is + begin + if table_empty then + Prepare_table; + table_empty:= False; + end if; + CRC:= 16#FFFF_FFFF#; + end Init; + + function Final( CRC: Unsigned_32 ) return Unsigned_32 is + begin + return not CRC; + end Final; + + end CRC32; + + ---------- + -- Load -- + ---------- + + procedure Load (image: in out Image_descriptor) is + + ---------------------- + -- Load_specialized -- + ---------------------- + + generic + -- These values are invariant through the whole picture, + -- so we can make them generic parameters. As a result, all + -- ""if"", ""case"", etc. using them at the center of the decoding + -- are optimized out at compile-time. + interlaced : Boolean; + bits_per_pixel : Positive; + bytes_to_unfilter : Positive; + -- ^ amount of bytes to unfilter at a time + -- = Integer'Max(1, bits_per_pixel / 8); + subformat_id : Natural; + procedure Load_specialized; + -- + procedure Load_specialized is + + use GID.Buffering; + + subtype Mem_row_bytes_array is Byte_array(0..image.width*8); + -- + mem_row_bytes: array(0..1) of Mem_row_bytes_array; + -- We need to memorize two image rows, for un-filtering + curr_row: Natural:= 1; + -- either current is 1 and old is 0, or the reverse + + subtype X_range is Integer range -1..image.width-1; + subtype Y_range is Integer range 0..image.height-1; + -- X position -1 is for the row's filter methode code + + x: X_range:= X_range'First; + y: Y_range:= Y_range'First; + + x_max: X_range; -- for non-interlaced images: = X_range'Last + y_max: Y_range; -- for non-interlaced images: = Y_range'Last + + pass: Positive range 1..7:= 1; + + -------------------------- + -- ** 9: Unfiltering ** -- + -------------------------- + -- http://www.w3.org/TR/PNG/#9Filters + + type Filter_method_0 is (None, Sub, Up, Average, Paeth); + + current_filter: Filter_method_0; + + procedure Unfilter_bytes( + f: in Byte_array; -- filtered + u: out Byte_array -- unfiltered + ) + is + pragma Inline(Unfilter_bytes); + -- Byte positions (f is the byte to be unfiltered): + -- + -- c b + -- a f + a,b,c, p,pa,pb,pc,pr: Integer; + j: Integer:= 0; + begin + if full_trace and then x = 0 then + if y = 0 then + Ada.Text_IO.New_Line; + end if; + Ada.Text_IO.Put_Line( + ""row"" & Integer'Image(y) & "": filter= "" & + Filter_method_0'Image(current_filter) + ); + end if; + -- + -- !! find a way to have f99n0g04.png decoded correctly... + -- seems a filter issue. + -- + case current_filter is + when None => + -- Recon(x) = Filt(x) + u:= f; + when Sub => + -- Recon(x) = Filt(x) + Recon(a) + if x > 0 then + for i in f'Range loop + u(u'First+j):= f(i) + mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j); + j:= j + 1; + end loop; + else + u:= f; + end if; + when Up => + -- Recon(x) = Filt(x) + Recon(b) + if y > 0 then + for i in f'Range loop + u(u'First+j):= f(i) + mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j); + j:= j + 1; + end loop; + else + u:= f; + end if; + when Average => + -- Recon(x) = Filt(x) + floor((Recon(a) + Recon(b)) / 2) + for i in f'Range loop + if x > 0 then + a:= Integer(mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j)); + else + a:= 0; + end if; + if y > 0 then + b:= Integer(mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j)); + else + b:= 0; + end if; + u(u'First+j):= U8((Integer(f(i)) + (a+b)/2) mod 256); + j:= j + 1; + end loop; + when Paeth => + -- Recon(x) = Filt(x) + PaethPredictor(Recon(a), Recon(b), Recon(c)) + for i in f'Range loop + if x > 0 then + a:= Integer(mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j)); + else + a:= 0; + end if; + if y > 0 then + b:= Integer(mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j)); + else + b:= 0; + end if; + if x > 0 and y > 0 then + c:= Integer(mem_row_bytes(1-curr_row)((x-1)*bytes_to_unfilter+j)); + else + c:= 0; + end if; + p := a + b - c; + pa:= abs(p - a); + pb:= abs(p - b); + pc:= abs(p - c); + if pa <= pb and then pa <= pc then + pr:= a; + elsif pb <= pc then + pr:= b; + else + pr:= c; + end if; + u(u'First+j):= f(i) + U8(pr); + j:= j + 1; + end loop; + end case; + j:= 0; + for i in u'Range loop + mem_row_bytes(curr_row)(x*bytes_to_unfilter+j):= u(i); + j:= j + 1; + end loop; + -- if u'Length /= bytes_to_unfilter then + -- raise Constraint_Error; + -- end if; + end Unfilter_bytes; + + filter_stat: array(Filter_method_0) of Natural:= (others => 0); + + ---------------------------------------------- + -- ** 8: Interlacing and pass extraction ** -- + ---------------------------------------------- + -- http://www.w3.org/TR/PNG/#8Interlace + + -- Output bytes from decompression + -- + procedure Output_uncompressed( + data : in Byte_array; + reject: out Natural + -- amount of bytes to be resent here next time, + -- in order to have a full multi-byte pixel + ) + is + -- Display of pixels coded on 8 bits per channel in the PNG stream + procedure Out_Pixel_8(br, bg, bb, ba: U8) is + pragma Inline(Out_Pixel_8); + function Times_257(x: Primary_color_range) return Primary_color_range is + pragma Inline(Times_257); + begin + return 16 * (16 * x) + x; -- this is 257 * x, = 16#0101# * x + -- Numbers 8-bit -> no OA warning at instanciation. Returns x if type Primary_color_range is mod 2**8. + end Times_257; + begin + case Primary_color_range'Modulus is + when 256 => + Put_Pixel( + Primary_color_range(br), + Primary_color_range(bg), + Primary_color_range(bb), + Primary_color_range(ba) + ); + when 65_536 => + Put_Pixel( + Times_257(Primary_color_range(br)), + Times_257(Primary_color_range(bg)), + Times_257(Primary_color_range(bb)), + Times_257(Primary_color_range(ba)) + -- Times_257 makes max intensity FF go to FFFF + ); + when others => + raise invalid_primary_color_range; + end case; + end Out_Pixel_8; + + procedure Out_Pixel_Palette(ix: U8) is + pragma Inline(Out_Pixel_Palette); + color_idx: constant Natural:= Integer(ix); + begin + Out_Pixel_8( + image.palette(color_idx).red, + image.palette(color_idx).green, + image.palette(color_idx).blue, + 255 + ); + end Out_Pixel_Palette; + + -- Display of pixels coded on 16 bits per channel in the PNG stream + procedure Out_Pixel_16(br, bg, bb, ba: U16) is + pragma Inline(Out_Pixel_16); + begin + case Primary_color_range'Modulus is + when 256 => + Put_Pixel( + Primary_color_range(br / 256), + Primary_color_range(bg / 256), + Primary_color_range(bb / 256), + Primary_color_range(ba / 256) + ); + when 65_536 => + Put_Pixel( + Primary_color_range(br), + Primary_color_range(bg), + Primary_color_range(bb), + Primary_color_range(ba) + ); + when others => + raise invalid_primary_color_range; + end case; + end Out_Pixel_16; + + procedure Inc_XY is + pragma Inline(Inc_XY); + xm, ym: Integer; + begin + if x < x_max then + x:= x + 1; + if interlaced then + -- Position of pixels depending on pass: + -- + -- 1 6 4 6 2 6 4 6 + -- 7 7 7 7 7 7 7 7 + -- 5 6 5 6 5 6 5 6 + -- 7 7 7 7 7 7 7 7 + -- 3 6 4 6 3 6 4 6 + -- 7 7 7 7 7 7 7 7 + -- 5 6 5 6 5 6 5 6 + -- 7 7 7 7 7 7 7 7 + case pass is + when 1 => + Set_X_Y( x*8, Y_range'Last - y*8); + when 2 => + Set_X_Y(4 + x*8, Y_range'Last - y*8); + when 3 => + Set_X_Y( x*4, Y_range'Last - 4 - y*8); + when 4 => + Set_X_Y(2 + x*4, Y_range'Last - y*4); + when 5 => + Set_X_Y( x*2, Y_range'Last - 2 - y*4); + when 6 => + Set_X_Y(1 + x*2, Y_range'Last - y*2); + when 7 => + null; -- nothing to to, pixel are contiguous + end case; + end if; + else + x:= X_range'First; -- New row + if y < y_max then + y:= y + 1; + curr_row:= 1-curr_row; -- swap row index for filtering + if not interlaced then + Feedback((y*100)/image.height); + end if; + elsif interlaced then -- last row has beed displayed + while pass < 7 loop + pass:= pass + 1; + y:= 0; + case pass is + when 1 => + null; + when 2 => + xm:= (image.width+3)/8 - 1; + ym:= (image.height+7)/8 - 1; + when 3 => + xm:= (image.width+3)/4 - 1; + ym:= (image.height+3)/8 - 1; + when 4 => + xm:= (image.width+1)/4 - 1; + ym:= (image.height+3)/4 - 1; + when 5 => + xm:= (image.width+1)/2 - 1; + ym:= (image.height+1)/4 - 1; + when 6 => + xm:= (image.width )/2 - 1; + ym:= (image.height+1)/2 - 1; + when 7 => + xm:= image.width - 1; + ym:= image.height/2 - 1; + end case; + if xm >=0 and xm <= X_range'Last and ym in Y_range then + -- This pass is not empty (otherwise, we will continue + -- to the next one, if any). + x_max:= xm; + y_max:= ym; + exit; + end if; + end loop; + end if; + end if; + end Inc_XY; + + uf: Byte_array(0..15); -- unfiltered bytes for a pixel + w1, w2: U16; + i: Integer; + + begin + if some_trace then + Ada.Text_IO.Put(""[UO]""); + end if; + -- Depending on the row size, bpp, etc., we can have + -- several rows, or less than one, being displayed + -- with the present uncompressed data batch. + -- + i:= data'First; + if i > data'Last then + reject:= 0; + return; -- data is empty, do nothing + end if; + -- + -- Main loop over data + -- + loop + if x = X_range'First then -- pseudo-column for filter method + exit when i > data'Last; + begin + current_filter:= Filter_method_0'Val(data(i)); + if some_trace then + filter_stat(current_filter):= filter_stat(current_filter) + 1; + end if; + exception + when Constraint_Error => + Raise_Exception( + error_in_image_data'Identity, + ""PNG: wrong filter code, row #"" & + Integer'Image(y) & "" code:"" & U8'Image(data(i)) + );" +procedure Jump_IDAT is,"dummy: U32; + begin + Big_endian(image.buffer, dummy); -- ending chunk's CRC + -- New chunk begins here. + loop + Read(image, ch); + exit when ch.kind /= IDAT or ch.length > 0; + end loop; + if ch.kind /= IDAT then + Raise_Exception( + error_in_image_data'Identity, + ""PNG additional data chunk must be an IDAT"" + ); + end if; + end Jump_IDAT; + + --------------------------------------------------------------------- + -- ** 10: Decompression ** -- + -- Excerpt and simplification from UnZip.Decompress (Inflate only) -- + --------------------------------------------------------------------- + -- http://www.w3.org/TR/PNG/#10Compression + + -- Size of sliding dictionary and circular output buffer + wsize: constant:= 16#10000#; + + -------------------------------------- + -- Specifications of UnZ_* packages -- + -------------------------------------- + + package UnZ_Glob is + -- I/O Buffers + -- > Sliding dictionary for unzipping, and output buffer as well + slide: Byte_array( 0..wsize ); + slide_index: Integer:= 0; -- Current Position in slide + Zip_EOF : constant Boolean:= False; + crc32val : Unsigned_32; -- crc calculated from data + end UnZ_Glob; + + package UnZ_IO is + + procedure Init_Buffers; + + procedure Read_raw_byte ( bt : out U8 ); + pragma Inline(Read_raw_byte); + + package Bit_buffer is + procedure Init; + -- Read at least n bits into the bit buffer, returns the n first bits + function Read ( n: Natural ) return Integer; + pragma Inline(Read); + function Read_U32 ( n: Natural ) return Unsigned_32; + pragma Inline(Read_U32); + -- Dump n bits no longer needed from the bit buffer + procedure Dump ( n: Natural ); + pragma Inline(Dump); + procedure Dump_to_byte_boundary; + function Read_and_dump( n: Natural ) return Integer; + pragma Inline(Read_and_dump); + function Read_and_dump_U32( n: Natural ) return Unsigned_32; + pragma Inline(Read_and_dump_U32); + end Bit_buffer; + + procedure Flush ( x: Natural ); -- directly from slide to output stream + + procedure Flush_if_full(W: in out Integer); + pragma Inline(Flush_if_full); + + procedure Copy( + distance, length: Natural; + index : in out Natural ); + pragma Inline(Copy); + + end UnZ_IO; + + package UnZ_Meth is + deflate_e_mode: constant Boolean:= False; + procedure Inflate; + end UnZ_Meth; + + ------------------------------ + -- Bodies of UnZ_* packages -- + ------------------------------ + package body UnZ_IO is + + procedure Init_Buffers is + begin + UnZ_Glob.slide_index := 0; + Bit_buffer.Init; + CRC32.Init( UnZ_Glob.crc32val ); + end Init_Buffers; + + procedure Read_raw_byte ( bt : out U8 ) is + begin + if ch.length = 0 then + -- We hit the end of a PNG 'IDAT' chunk, so we go to the next one + -- - in petto, it's strange design, but well... + -- This ""feature"" has taken some time (and nerves) to be addressed. + -- Incidentally, I have reprogrammed the whole Huffman + -- decoding, and looked at many other wrong places to solve + -- the mystery. + Jump_IDAT; + end if; + Buffering.Get_Byte(image.buffer, bt); + ch.length:= ch.length - 1; + end Read_raw_byte; + + package body Bit_buffer is + B : Unsigned_32; + K : Integer; + + procedure Init is + begin + B := 0; + K := 0; + end Init; + + procedure Need( n : Natural ) is + pragma Inline(Need); + bt: U8; + begin + while K < n loop + Read_raw_byte( bt ); + B:= B or Shift_Left( Unsigned_32( bt ), K ); + K:= K + 8; + end loop; + end Need; + + procedure Dump ( n : Natural ) is + begin + B := Shift_Right(B, n ); + K := K - n; + end Dump; + + procedure Dump_to_byte_boundary is + begin + Dump ( K mod 8 ); + end Dump_to_byte_boundary; + + function Read_U32 ( n: Natural ) return Unsigned_32 is + begin + Need(n); + return B and (Shift_Left(1,n) - 1); + end Read_U32; + + function Read ( n: Natural ) return Integer is + begin + return Integer(Read_U32(n)); + end Read; + + function Read_and_dump( n: Natural ) return Integer is + res: Integer; + begin + res:= Read(n); + Dump(n); + return res; + end Read_and_dump; + + function Read_and_dump_U32( n: Natural ) return Unsigned_32 is + res: Unsigned_32; + begin + res:= Read_U32(n); + Dump(n); + return res; + end Read_and_dump_U32; + + end Bit_buffer; + + old_bytes: Natural:= 0; + -- how many bytes to be resent from last Inflate output + byte_mem: Byte_array(1..8); + + procedure Flush ( x: Natural ) is + begin + if full_trace then + Ada.Text_IO.Put(""[Flush..."" & Integer'Image(x)); + end if; + CRC32.Update( UnZ_Glob.crc32val, UnZ_Glob.slide( 0..x-1 ) ); + if old_bytes > 0 then + declare + app: constant Byte_array:= + byte_mem(1..old_bytes) & UnZ_Glob.slide(0..x-1); + begin + Output_uncompressed(app, old_bytes); + -- In extreme cases (x very small), we might have some of + -- the rejected bytes from byte_mem. + if old_bytes > 0 then + byte_mem(1..old_bytes):= app(app'Last-(old_bytes-1)..app'Last); + end if;" +"procedure Inflate_stored_block is -- Actually, nothing to inflate","N : Integer; + begin + if full_trace then + Ada.Text_IO.Put_Line(""Begin Inflate_stored_block""); + end if; + UnZ_IO.Bit_buffer.Dump_to_byte_boundary; + + -- Get the block length and its complement + N:= UnZ_IO.Bit_buffer.Read_and_dump( 16 ); + if N /= Integer( + (not UnZ_IO.Bit_buffer.Read_and_dump_U32(16)) + and 16#ffff#) + then + raise error_in_image_data; + end if; + while N > 0 and then not UnZ_Glob.Zip_EOF loop + -- Read and output the non-compressed data + N:= N - 1; + UnZ_Glob.slide ( UnZ_Glob.slide_index ) := + U8( UnZ_IO.Bit_buffer.Read_and_dump(8) ); + UnZ_Glob.slide_index:= UnZ_Glob.slide_index + 1; + UnZ_IO.Flush_if_full(UnZ_Glob.slide_index); + end loop; + if full_trace then + Ada.Text_IO.Put_Line(""End Inflate_stored_block""); + end if; + end Inflate_stored_block; + + -- Copy lengths for literal codes 257..285 + + copy_lengths_literal : Length_array( 0..30 ) := + ( 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ); + + -- Extra bits for literal codes 257..285 + + extra_bits_literal : Length_array( 0..30 ) := + ( 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, invalid, invalid ); + + -- Copy offsets for distance codes 0..29 (30..31: deflate_e) + + copy_offset_distance : constant Length_array( 0..31 ) := + ( 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 32769, 49153 ); + + -- Extra bits for distance codes + + extra_bits_distance : constant Length_array( 0..31 ) := + ( 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14 ); + + max_dist: Integer:= 29; -- changed to 31 for deflate_e + + procedure Inflate_fixed_block is + Tl, -- literal/length code table + Td : p_Table_list; -- distance code table + Bl, Bd : Integer; -- lookup bits for tl/bd + huft_incomplete : Boolean; + + -- length list for HufT_build (literal table) + L: constant Length_array( 0..287 ):= + ( 0..143=> 8, 144..255=> 9, 256..279=> 7, 280..287=> 8); + + begin + if full_trace then + Ada.Text_IO.Put_Line(""Begin Inflate_fixed_block""); + end if; + + -- make a complete, but wrong code set + Bl := 7; + HufT_build( + L, 257, copy_lengths_literal, extra_bits_literal, + Tl, Bl, huft_incomplete + ); + + -- Make an incomplete code set + Bd := 5; + begin + HufT_build( + (0..max_dist => 5), 0, + copy_offset_distance, extra_bits_distance, + Td, Bd, huft_incomplete + ); + if huft_incomplete then + if full_trace then + Ada.Text_IO.Put_Line( + ""td is incomplete, pointer=null: "" & + Boolean'Image(Td=null) + ); + end if; + end if; + exception + when huft_out_of_memory | huft_error => + HufT_free( Tl ); + raise error_in_image_data;" +procedure Inflate_dynamic_block is,"bit_order : constant array ( 0..18 ) of Natural := + ( 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ); + + Lbits : constant:= 9; + Dbits : constant:= 6; + + current_length: Natural:= 0; + defined, number_of_lengths: Natural; + + Tl, -- literal/length code tables + Td : p_Table_list; -- distance code tables + + CT_dyn_idx : Integer; -- current table element + + Bl, Bd : Integer; -- lookup bits for tl/bd + Nb : Natural; -- number of bit length codes + Nl : Natural; -- number of literal length codes + Nd : Natural; -- number of distance codes + + -- literal/length and distance code lengths + Ll: Length_array( 0 .. 288+32-1 ):= (others=> 0); + + huft_incomplete : Boolean; + + procedure Repeat_length_code( amount: Natural ) is + begin + if defined + amount > number_of_lengths then + raise error_in_image_data; + end if; + for c in reverse 1..amount loop + Ll ( defined ) := Natural_M32(current_length); + defined:= defined + 1; + end loop; + end Repeat_length_code; + + begin + if full_trace then + Ada.Text_IO.Put_Line(""Begin Inflate_dynamic_block""); + end if; + + -- Read in table lengths + Nl := 257 + UnZ_IO.Bit_buffer.Read_and_dump(5); + Nd := 1 + UnZ_IO.Bit_buffer.Read_and_dump(5); + Nb := 4 + UnZ_IO.Bit_buffer.Read_and_dump(4); + + if Nl > 288 or else Nd > 32 then + raise error_in_image_data; + end if; + + -- Read in bit-length-code lengths. + -- The rest, Ll( Bit_Order( Nb .. 18 ) ), is already = 0 + for J in 0 .. Nb - 1 loop + Ll ( bit_order( J ) ) := Natural_M32(UnZ_IO.Bit_buffer.Read_and_dump(3)); + end loop; + + -- Build decoding table for trees--single level, 7 bit lookup + Bl := 7; + begin + HufT_build ( + Ll( 0..18 ), 19, empty, empty, Tl, Bl, huft_incomplete + ); + if huft_incomplete then + HufT_free(Tl); + raise error_in_image_data; + end if; + exception + when others => + raise error_in_image_data;" +procedure Inflate is,"is_last_block: Boolean; + blocks: Positive:= 1; + begin + if deflate_e_mode then + copy_lengths_literal(28):= 3; -- instead of 258 + extra_bits_literal(28):= 16; -- instead of 0 + max_dist:= 31; + end if; + loop + Inflate_Block ( is_last_block ); + exit when is_last_block; + blocks:= blocks+1; + end loop; + UnZ_IO.Flush( UnZ_Glob.slide_index ); + UnZ_Glob.slide_index:= 0; + if some_trace then + Ada.Text_IO.Put(""# blocks:"" & Integer'Image(blocks)); + end if; + UnZ_Glob.crc32val := CRC32.Final( UnZ_Glob.crc32val ); + end Inflate; + + end UnZ_Meth; + + -------------------------------------------------------------------- + -- End of the Decompression part, and of UnZip.Decompress excerpt -- + -------------------------------------------------------------------- + + b: U8; + z_crc, dummy: U32; + + begin -- Load_specialized + -- + -- For optimization reasons, bytes_to_unfilter is passed as a + -- generic parameter but should be always as below right to ""/="" : + -- + if bytes_to_unfilter /= Integer'Max(1, bits_per_pixel / 8) then + raise Program_Error; + end if; + if interlaced then + x_max:= (image.width+7)/8 - 1; + y_max:= (image.height+7)/8 - 1; + else + x_max:= X_range'Last; + y_max:= Y_range'Last; + end if; + main_chunk_loop: + loop + loop + Read(image, ch); + exit when ch.kind = IEND or ch.length > 0; + end loop; + case ch.kind is + when IEND => -- 11.2.5 IEND Image trailer + exit main_chunk_loop; + when IDAT => -- 11.2.4 IDAT Image data + -- + -- NB: the compressed data may hold on several IDAT chunks. + -- It means that right in the middle of compressed data, you + -- can have a chunk crc, and a new IDAT header!... + -- + UnZ_IO.Read_raw_byte(b); -- zlib compression method/flags code + UnZ_IO.Read_raw_byte(b); -- Additional flags/check bits + -- + UnZ_IO.Init_Buffers; + -- ^ we indicate that we have a byte reserve of chunk's length, + -- minus both zlib header bytes. + UnZ_Meth.Inflate; + z_crc:= 0; + for i in 1..4 loop + begin + UnZ_IO.Read_raw_byte(b); + exception + when error_in_image_data => + -- vicious IEND at the wrong place + -- basi4a08.png test image (corrupt imho) + exit main_chunk_loop;" +procedure Read_Intel is new Read_Intel_x86_number( U16 );,"type GIFDescriptor is record + ImageLeft, + ImageTop, + ImageWidth, + ImageHeight : U16; + Depth : U8; + end record; + + -- For loading from the GIF file + Descriptor : GIFDescriptor; + + -- Coordinates + X, tlX, brX : Natural; + Y, tlY, brY : Natural; + + -- Code information + subtype Code_size_range is Natural range 2..12; + CurrSize : Code_size_range; + + subtype Color_type is U8; + Transp_color : Color_type:= 0; + + -- GIF data is stored in blocks and sub-blocks. + -- We initialize block_read and block_size to force + -- reading and buffering the next sub-block + block_size : Natural:= 0; + block_read : Natural:= 0; + + function Read_Byte return U8 is + pragma Inline(Read_Byte); + b: U8; + begin + if block_read >= block_size then + Get_Byte(image.buffer, b); + Raw_Byte (b); + block_size:= Natural(b); + block_read:= 0; + end if; + Get_Byte(image.buffer, b); + Raw_Byte (b); + block_read:= block_read + 1; + return b; + end Read_Byte; + + -- Used while reading the codes + bits_in : U8:= 8; + bits_buf: U8; + + -- Local procedure to read the next code from the file + function Read_Code return Natural is + bit_mask: Natural:= 1; + code: Natural:= 0; + begin + -- Read the code, bit by bit + for Counter in reverse 0..CurrSize - 1 loop + -- Next bit + bits_in:= bits_in + 1; + -- Maybe, a new byte needs to be loaded with a further 8 bits + if bits_in = 9 then + bits_buf:= Read_Byte; + bits_in := 1; + end if; + -- Add the current bit to the code + if (bits_buf and 1) > 0 then + code:= code + bit_mask; + end if; + bit_mask := bit_mask * 2; + bits_buf := bits_buf / 2; + end loop; + return code; + end Read_Code; + + generic + -- Parameter(s) that are constant through + -- the whole image. Macro-expanded generics and + -- some optimization will trim corresponding ""if's"" + interlaced : Boolean; + transparency : Boolean; + pixel_mask : U32; + -- + procedure GIF_Decode; + + procedure GIF_Decode is + + procedure Pixel_with_palette(b: U8) is + pragma Inline(Pixel_with_palette); + function Times_257(x: Primary_color_range) return Primary_color_range is + pragma Inline(Times_257); + begin + return 16 * (16 * x) + x; -- this is 257 * x, = 16#0101# * x + -- Numbers 8-bit -> no OA warning at instanciation. Returns x if type Primary_color_range is mod 2**8. + end Times_257; + full_opaque: constant Primary_color_range:= Primary_color_range'Last; + begin + if transparency and then b = Transp_color then + Put_Pixel(0,0,0, 0); + return; + end if; + case Primary_color_range'Modulus is + when 256 => + Put_Pixel( + Primary_color_range(local.palette(Integer(b)).red), + Primary_color_range(local.palette(Integer(b)).green), + Primary_color_range(local.palette(Integer(b)).blue), + full_opaque + ); + when 65_536 => + Put_Pixel( + Times_257(Primary_color_range(local.palette(Integer(b)).red)), + Times_257(Primary_color_range(local.palette(Integer(b)).green)), + Times_257(Primary_color_range(local.palette(Integer(b)).blue)), + -- Times_257 makes max intensity FF go to FFFF + full_opaque + ); + when others => + raise invalid_primary_color_range; + end case; + end Pixel_with_palette; + + -- Interlacing + Interlace_pass : Natural range 1..4:= 1; + Span : Natural:= 7; + + -- Local procedure to draw a pixel + procedure Next_Pixel(code: Natural) is + pragma Inline(Next_Pixel); + c : constant Color_type:= Color_type(U32(code) and pixel_mask); + begin + -- Actually draw the pixel on screen buffer + if X < image.width then + if interlaced and mode = nice then + for i in reverse 0..Span loop + if Y+i < image.height then + Set_X_Y(X, image.height - (Y+i) - 1); + Pixel_with_palette(c); + end if; + end loop; + elsif Y < image.height then + Pixel_with_palette(c); + end if; + end if; + + -- Move on to next pixel + X:= X + 1; + + -- Or next row, if necessary + if X = brX then + X:= tlX; + if interlaced then + case Interlace_pass is + when 1 => + Y:= Y + 8; + if Y >= brY then + Y:= 4; + Interlace_pass:= 2; + Span:= 3; + Feedback((Interlace_pass*100)/4); + end if; + when 2 => + Y:= Y + 8; + if Y >= brY then + Y:= 2; + Interlace_pass:= 3; + Span:= 1; + Feedback((Interlace_pass*100)/4); + end if; + when 3 => + Y:= Y + 4; + if Y >= brY then + Y:= 1; + Interlace_pass:= 4; + Span:= 0; + Feedback((Interlace_pass*100)/4); + end if; + when 4 => + Y:= Y + 2; + end case; + if mode = fast and then Y < image.height then + Set_X_Y(X, image.height - Y - 1); + end if; + else -- not interlaced + Y:= Y + 1; + if Y < image.height then + Set_X_Y(X, image.height - Y - 1); + end if; + if Y mod 32 = 0 then + Feedback((Y*100)/image.height); + end if; + end if; + end if; + end Next_Pixel; + + -- The string table + Prefix : array ( 0..4096 ) of Natural:= (others => 0); + Suffix : array ( 0..4096 ) of Natural:= (others => 0); + -- Top of Stack was 1024 until files from + -- https://www.kaggle.com/c/carvana-image-masking-challenge + -- broke it (July 2017)... + Stack : array ( 0..2048 ) of Natural; + + -- Special codes (specific to GIF's flavour of LZW) + ClearCode : constant Natural:= 2 ** CurrSize; -- Reset code + EndingCode: constant Natural:= ClearCode + 1; -- End of file + FirstFree : constant Natural:= ClearCode + 2; -- Strings start here + + Slot : Natural:= FirstFree; -- Last read code + InitCodeSize : constant Code_size_range:= CurrSize + 1; + TopSlot : Natural:= 2 ** InitCodeSize; -- Highest code for current size + Code : Natural; + StackPtr : Integer:= 0; + Fc : Integer:= 0; + Oc : Integer:= 0; + C : Integer; + BadCodeCount : Natural:= 0; -- the number of bad codes found + + begin -- GIF_Decode + -- The decoder source and the cool comments are kindly donated by + -- André van Splunter. + -- + CurrSize:= InitCodeSize; + -- This is the main loop. For each code we get we pass through the + -- linked list of prefix codes, pushing the corresponding ""character"" + -- for each code onto the stack. When the list reaches a single + -- ""character"" we push that on the stack too, and then start unstacking + -- each character for output in the correct order. Special handling is + -- included for the clear code, and the whole thing ends when we get + -- an ending code. + C := Read_Code; + while C /= EndingCode loop + -- If the code is a clear code, reinitialize all necessary items. + if C = ClearCode then + CurrSize := InitCodeSize; + Slot := FirstFree; + TopSlot := 2 ** CurrSize; + -- Continue reading codes until we get a non-clear code + -- (Another unlikely, but possible case...) + C := Read_Code; + while C = ClearCode loop + C := Read_Code; + end loop; + -- If we get an ending code immediately after a clear code + -- (Yet another unlikely case), then break out of the loop. + exit when C = EndingCode; + -- Finally, if the code is beyond the range of already set codes, + -- (This one had better NOT happen... I have no idea what will + -- result from this, but I doubt it will look good...) then set + -- it to color zero. + if C >= Slot then + C := 0; + end if; + Oc := C; + Fc := C; + -- And let us not forget to output the char... + Next_Pixel(C); + else -- C /= ClearCode + -- In this case, it's not a clear code or an ending code, so + -- it must be a code code... So we can now decode the code into + -- a stack of character codes. (Clear as mud, right?) + Code := C; + -- Here we go again with one of those off chances... If, on the + -- off chance, the code we got is beyond the range of those + -- already set up (Another thing which had better NOT happen...) + -- we trick the decoder into thinking it actually got the last + -- code read. (Hmmn... I'm not sure why this works... + -- But it does...) + if Code >= Slot then + if Code > Slot then + BadCodeCount := BadCodeCount + 1; + end if; + Code := Oc; + Stack (StackPtr) := Fc rem 256; + StackPtr := StackPtr + 1; + end if; + -- Here we scan back along the linked list of prefixes, pushing + -- helpless characters (ie. suffixes) onto the stack as we do so. + while Code >= FirstFree loop + Stack (StackPtr) := Suffix (Code); + StackPtr := StackPtr + 1; + Code := Prefix (Code); + end loop; + -- Push the last character on the stack, and set up the new + -- prefix and suffix, and if the required slot number is greater + -- than that allowed by the current bit size, increase the bit + -- size. (NOTE - If we are all full, we *don't* save the new + -- suffix and prefix... I'm not certain if this is correct... + -- it might be more proper to overwrite the last code... + Stack (StackPtr) := Code rem 256; + if Slot < TopSlot then + Suffix (Slot) := Code rem 256; + Fc := Code; + Prefix (Slot) := Oc; + Slot := Slot + 1; + Oc := C; + end if; + if Slot >= TopSlot then + if CurrSize < 12 then + TopSlot := TopSlot * 2; + CurrSize := CurrSize + 1; + end if; + end if; + -- Now that we've pushed the decoded string (in reverse order) + -- onto the stack, lets pop it off and output it... + loop + Next_Pixel(Stack (StackPtr)); + exit when StackPtr = 0; + StackPtr := StackPtr - 1; + end loop; + end if; + C := Read_Code; + end loop; + if full_trace and then BadCodeCount > 0 then + Ada.Text_IO.Put_Line( + ""Found"" & Integer'Image(BadCodeCount) & + "" bad codes"" + ); + end if; + end GIF_Decode; + + -- Here we have several specialized instances of GIF_Decode, + -- with parameters known at compile-time -> optimizing compilers + -- will do expensive tests about interlacing and transparency at compile-time, + -- not at run-time. + -- + procedure GIF_Decode_interlaced_transparent_8 is + new GIF_Decode(interlaced => True, transparency => True, pixel_mask => 255); + procedure GIF_Decode_straight_transparent_8 is + new GIF_Decode(interlaced => False, transparency => True, pixel_mask => 255); + procedure GIF_Decode_interlaced_opaque_8 is + new GIF_Decode(interlaced => True, transparency => False, pixel_mask => 255); + procedure GIF_Decode_straight_opaque_8 is + new GIF_Decode(interlaced => False, transparency => False, pixel_mask => 255); + -- + procedure Skip_sub_blocks is + temp: U8; + begin + sub_blocks_sequence: + loop + Get_Byte(image.buffer, temp ); -- load sub-block length byte + Raw_Byte(temp); + exit sub_blocks_sequence when temp = 0; + -- null sub-block = end of sub-block sequence + for i in 1..temp loop + Get_Byte(image.buffer, temp ); -- load sub-block byte + Raw_Byte(temp); + end loop; + end loop sub_blocks_sequence; + end Skip_sub_blocks; + + temp, temp2, label: U8; + delay_frame: U16; + c: Character; + frame_interlaced: Boolean; + frame_transparency: Boolean:= False; + local_palette : Boolean; + -- + separator : Character ; + -- Colour information + new_num_of_colours : Natural; + pixel_mask : U32; + BitsPerPixel : Natural; + + begin -- Load + next_frame:= 0.0; + -- Scan various GIF blocks, until finding an image + loop + Get_Byte(image.buffer, temp); + Raw_Byte(temp); + separator:= Character'Val(temp); + if full_trace then + Ada.Text_IO.Put( + ""GIF separator ["" & separator & + ""]["" & U8'Image(temp) & ']' + ); + end if; + case separator is + when ',' => -- 16#2C# + exit; + -- Image descriptor will begin + -- See: 20. Image Descriptor + when ';' => -- 16#3B# + if full_trace then + Ada.Text_IO.Put("" - End of GIF""); + end if; + image.next_frame:= 0.0; + next_frame:= image.next_frame; + return; -- End of GIF image + when '!' => -- 16#21# Extensions + if full_trace then + Ada.Text_IO.Put("" - Extension""); + end if; + Get_Byte(image.buffer, label ); + Raw_Byte (label); + case label is + when 16#F9# => -- See: 23. Graphic Control Extension + if full_trace then + Ada.Text_IO.Put_Line("" - 16#F9#: Graphic Control Extension""); + end if; + Get_Byte(image.buffer, temp ); + Raw_Byte(temp); + if temp /= 4 then + Raise_Exception( + error_in_image_data'Identity, + ""GIF: error in Graphic Control Extension"" + ); + end if; + Get_Byte(image.buffer, temp ); + Raw_Byte(temp); + -- Reserved 3 Bits + -- Disposal Method 3 Bits + -- User Input Flag 1 Bit + -- Transparent Color Flag 1 Bit + frame_transparency:= (temp and 1) = 1; + Read_Intel(image.buffer, delay_frame); + image.next_frame:= + image.next_frame + Ada.Calendar.Day_Duration(delay_frame) / 100.0; + next_frame:= image.next_frame; + Get_Byte(image.buffer, temp ); + Raw_Byte(temp); + Transp_color:= Color_type(temp); + -- zero sub-block: + Get_Byte(image.buffer, temp ); + Raw_Byte(temp); + when 16#FE# => -- See: 24. Comment Extension + if full_trace then + Ada.Text_IO.Put_Line("" - 16#FE#: Comment Extension""); + sub_blocks_sequence: + loop + Get_Byte(image.buffer, temp ); -- load sub-block length byte + Raw_Byte(temp); + exit sub_blocks_sequence when temp = 0; + -- null sub-block = end of sub-block sequence + for i in 1..temp loop + Get_Byte(image.buffer, temp2); + Raw_Byte(temp2); + c:= Character'Val(temp2); + Ada.Text_IO.Put(c); + end loop; + end loop sub_blocks_sequence; + Ada.Text_IO.New_Line; + else + Skip_sub_blocks; + end if; + when 16#01# => -- See: 25. Plain Text Extension + if full_trace then + Ada.Text_IO.Put_Line("" - 16#01#: Plain Text Extension""); + end if; + Skip_sub_blocks; + when 16#FF# => -- See: 26. Application Extension + if full_trace then + Ada.Text_IO.Put_Line("" - 16#FF#: Application Extension""); + end if; + Skip_sub_blocks; + when others => + if full_trace then + Ada.Text_IO.Put_Line("" - Unused extension:"" & U8'Image(label)); + end if; + Skip_sub_blocks; + end case; + when ASCII.NUL => + -- Occurs in some buggy GIFs (2016). + -- Seems a 2nd zero, the 1st marking the end of sub-block list. + if full_trace then + Ada.Text_IO.Put_Line("" - Wrong separator, skip and hope for the better...""); + end if; + when others => + Raise_Exception( + error_in_image_data'Identity, + ""Unknown GIF separator: ["" & separator & + ""] code:"" & Integer'Image(Character'Pos(separator)) + ); + end case; + end loop; + + -- Load the image descriptor + Read_Intel(image.buffer, Descriptor.ImageLeft); + Read_Intel(image.buffer, Descriptor.ImageTop); + Read_Intel(image.buffer, Descriptor.ImageWidth); + Read_Intel(image.buffer, Descriptor.ImageHeight); + Get_Byte(image.buffer, Descriptor.Depth); + Raw_Byte(Descriptor.Depth); + + -- Get image corner coordinates + tlX := Natural(Descriptor.ImageLeft); + tlY := Natural(Descriptor.ImageTop); + brX := tlX + Natural(Descriptor.ImageWidth); + brY := tlY + Natural(Descriptor.ImageHeight); + + -- Local Color Table Flag 1 Bit + -- Interlace Flag 1 Bit + -- Sort Flag 1 Bit + -- Reserved 2 Bits + -- Size of Local Color Table 3 Bits + -- + frame_interlaced:= (Descriptor.Depth and 64) = 64; + local_palette:= (Descriptor.Depth and 128) = 128; + local.format:= GIF; + local.stream:= image.stream; + local.buffer:= image.buffer; + if local_palette then + -- Get amount of colours in image + BitsPerPixel := 1 + Natural(Descriptor.Depth and 7); + new_num_of_colours:= 2 ** BitsPerPixel; + -- 21. Local Color Table + local.palette:= new Color_table(0..new_num_of_colours-1); + Color_tables.Load_palette(local); + image.buffer:= local.buffer; + elsif image.palette = null then + Raise_Exception( + error_in_image_data'Identity, + ""GIF: neither local, nor global palette"" + ); + else + -- Use global palette + new_num_of_colours:= 2 ** image.subformat_id; + -- usually <= 2** image.bits_per_pixel + -- Just copy main palette + local.palette:= new Color_table'(image.palette.all); + end if; + pixel_mask:= U32(new_num_of_colours - 1); + + if full_trace then + Ada.Text_IO.Put_Line( + "" - Image, interlaced: "" & Boolean'Image(frame_interlaced) & + ""; local palette: "" & Boolean'Image(local_palette) & + ""; transparency: "" & Boolean'Image(frame_transparency) & + ""; transparency index:"" & Color_type'Image(Transp_color) + ); + end if; + + -- Get initial code size + Get_Byte(image.buffer, temp ); + Raw_Byte(temp); + if Natural(temp) not in Code_size_range then + Raise_Exception( + error_in_image_data'Identity, + ""GIF: wrong LZW code size (must be in 2..12), is"" & + U8'Image(temp) + ); + end if; + CurrSize := Natural(temp); + + -- Start at top left of image + X := Natural(Descriptor.ImageLeft); + Y := Natural(Descriptor.ImageTop); + Set_X_Y(X, image.height - Y - 1); + -- + if new_num_of_colours < 256 then + -- ""Rare"" formats -> no need of best speed + declare + -- We create an instance with dynamic parameters + procedure GIF_Decode_general is + new GIF_Decode(frame_interlaced, frame_transparency, pixel_mask); + begin + GIF_Decode_general;" +procedure Register_Tests (T : in out TC) is,"use AUnit.Test_Cases.Registration; + begin + Register_Routine + (T, Test_One_String'Access, ""One string""); + Register_Routine + (T, Test_Two_Strings'Access, ""Two strings""); + end Register_Tests; + + procedure Set_Up (T : in out TC) is + begin + T.P.Create (128); + end Set_Up; + + function Name (T : TC) return Message_String is + pragma Unreferenced (T); + begin + return AUnit.Format (""Chunk tests for String_Pool""); + end Name; + + procedure Test_One_String (T : in out Test_Cases.Test_Case'Class) is + Test_Data : constant String := ""123456""; + C : constant Reference := TC (T).P.From_String (Test_Data); + begin + Ada.Text_IO.Put_Line (""Test one string, chunk content:""); + Ada.Text_IO.Put_Line (TC (T).P.Current_Chunk_As_String); + Assert (C = Test_Data, ""Data mismatch!""); + declare + C2 : constant Reference := C; + begin + Ada.Text_IO.Put_Line (""Range after copy: ("" & C2.Data.all'First'Img & + "" .."" & C2.Data.all'Last'Img & ')');" +procedure Free is new Ada.Unchecked_Deallocation,"(String, Buffer_Type); + + subtype Line_End is Character with Static_Predicate => + Line_End in Line_Feed | Carriage_Return | End_Of_Input; + + procedure Init (Object : in out Instance; Input : Source.Pointer; + Initial_Buffer_Size : Positive := + Default_Initial_Buffer_Size) is + begin + Object.Internal.Input := Input; + Object.Buffer := new String (1 .. Initial_Buffer_Size); + Object.Internal.Sentinel := Initial_Buffer_Size + 1; + Refill_Buffer (Object); + end Init; + + procedure Init (Object : in out Instance; Input : String) is + begin + Object.Internal.Input := null; + Object.Buffer := new String (1 .. Input'Length + 1); + Object.Internal.Sentinel := Input'Length + 2; + Object.Buffer.all := Input & End_Of_Input; + end Init; + + function Next (Object : in out Instance) return Character is + begin + return C : constant Character := Object.Buffer (Object.Pos) do + Object.Pos := Object.Pos + 1; + end return; + end Next; + + procedure Refill_Buffer (L : in out Instance) is + Bytes_To_Copy : constant Natural := L.Buffer'Last + 1 - L.Internal.Sentinel; + Fill_At : Positive := Bytes_To_Copy + 1; + Bytes_Read : Positive; + + function Search_Sentinel return Boolean with Inline is + Peek : Positive := L.Buffer'Last; + begin + while not (L.Buffer (Peek) in Line_End) loop + if Peek = Fill_At then + return False; + else + Peek := Peek - 1; + end if; + end loop; + L.Internal.Sentinel := Peek + 1; + return True; + end Search_Sentinel; + begin + if Bytes_To_Copy > 0 then + L.Buffer (1 .. Bytes_To_Copy) := + L.Buffer (L.Internal.Sentinel .. L.Buffer'Last); + end if; + loop + L.Internal.Input.Read_Data + (L.Buffer (Fill_At .. L.Buffer'Last), Bytes_Read); + if Bytes_Read < L.Buffer'Last - Fill_At then + L.Internal.Sentinel := Fill_At + Bytes_Read + 1; + L.Buffer (L.Internal.Sentinel - 1) := End_Of_Input; + exit; + else + exit when Search_Sentinel; + Fill_At := L.Buffer'Last + 1; + declare + New_Buffer : constant Buffer_Type := + new String (1 .. 2 * L.Buffer'Last); + begin + New_Buffer.all (L.Buffer'Range) := L.Buffer.all; + Free (L.Buffer); + L.Buffer := New_Buffer;" +function Convert is new Ada.Unchecked_Conversion,"(System.Address, Header_Access); + use System.Storage_Elements; + begin + return Convert (S.all'Address - Storage_Offset (Header_Size)); + end Header_Of; + + function Value (Object : Reference) return Accessor is + (Accessor'(Data => Object.Data, Hold => Object)); + + function Length (Object : Reference) return Natural is + (Object.Data'Length); + + function ""&"" (Left, Right : Reference) return String is + (Left.Data.all & Right.Data.all); + + function ""&"" (Left : Reference; Right : String) return String is + (Left.Data.all & Right); + + function ""&"" (Left : Reference; Right : Character) return String is + (Left.Data.all & Right); + + function ""&"" (Left : String; Right : Reference) return String is + (Left & Right.Data.all); + + function ""&"" (Left : Character; Right : Reference) return String is + (Left & Right.Data.all); + + function ""="" (Left, Right : Reference) return Boolean is + (Left.Data = Right.Data or else + (Left.Data /= null and then Right.Data /= null and then + Left.Data.all = Right.Data.all)); + + function ""="" (Left : Reference; Right : String) return Boolean is + (Left.Data.all = Right); + + function Hash (Object : Reference) return Ada.Containers.Hash_Type is + (Ada.Strings.Hash (Object.Data.all)); + + function ""="" (Left : String; Right : Reference) return Boolean is + (Left = Right.Data.all); + + function Element (Object : Reference; Position : Positive) return Character + is (Object.Data (Position)); + + function Hold (Content : String) return Constant_Instance is + Ret : Constant_Instance := + (Length => Content'Length + Positive (Header_Size) + 1, + Data => <>); + H : Header with Import; + for H'Address use Ret.Data (1)'Address; + begin + H.Pool := null; + H.Refcount := 1; + H.First := 1; + H.Last := Content'Length; + Ret.Data (Positive (Header_Size) + 1 .. Ret.Data'Last) := + Content & Character'Val (0); + return Ret; + end Hold; + + procedure Adjust (Object : in out Reference) is + begin + if Object.Data /= null then + declare + H : constant access Header := Header_Of (Object.Data); + begin + if H.Pool /= null then + H.Refcount := H.Refcount + 1; + end if;" +procedure Free_Chunk is new Ada.Unchecked_Deallocation,"(Pool_Array, Chunk); + procedure Free_Data is new Ada.Unchecked_Deallocation + (Pool_Data, Pool_Data_Access); + begin + Pool.Usage (Chunk_Index) := Pool.Usage (Chunk_Index) - 1; + if Pool.Usage (Chunk_Index) = 0 then + Free_Chunk (Pool.Chunks (Chunk_Index)); + for I in Chunk_Index_Type loop + if Pool.Chunks (I) /= null then + return; + end if; + end loop; + Free_Data (Pool); + end if; + end Decrease_Usage; + + procedure Finalize (Object : in out Reference) is + Reference : constant UTF_8_String_Access := Object.Data; + begin + Object.Data := null; + if Reference /= null then + declare + H : constant not null access Header := Header_Of (Reference); + begin + if H.Pool /= null then + H.Refcount := H.Refcount - 1; + if H.Refcount = 0 then + H.Last := Round_To_Header_Size (H.Last + 1); + Decrease_Usage (H.Pool, H.Chunk_Index); + end if; + end if;" +procedure test_Conversion_Type is,"package conversion_float is new Conversion_Type(T_Element => float); + use conversion_float; + + -- Tester la procedure de conversion en entier + procedure test_To_Integer is + useless : Integer; + + begin + -- Test avec un entier long + useless := To_Integer(To_Unbounded_String(""10000"")); + pragma assert(useless=10000); + + -- Test avec 0 + pragma assert(To_Integer(To_Unbounded_String(""0""))=0); + + -- Test avec un character + begin + useless := To_Integer(To_Unbounded_String(""z"")); + pragma assert (False); + exception + when Bad_Type_Conversion_Error => pragma assert( True);" +procedure test_To_reel is,"useless : float; + + begin + + -- Test avec un réel sur 10 digit + useless := conversion_float.To_reel(To_Unbounded_String(""0.85000002384"")); + pragma assert (useless=float(0.85000002384)); + + -- Test avec un entier de taille 1 + begin + useless := conversion_float.To_reel(To_Unbounded_String(""3"")); + pragma assert (False); + exception + when Bad_Type_Conversion_Error => pragma assert( True);" +procedure finalize_library is,"begin + E101 := E101 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__text_io__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""ada__strings__unbounded__finalize_spec""); + begin + F2;" +procedure F3;,"pragma Import (Ada, F3, ""system__storage_pools__subpools__finalize_spec""); + begin + F3;" +procedure F4;,"pragma Import (Ada, F4, ""system__finalization_masters__finalize_spec""); + begin + F4;" +procedure F5;,"pragma Import (Ada, F5, ""system__file_io__finalize_body""); + begin + E113 := E113 - 1; + F5;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (C, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + pragma Favor_Top_Level (No_Param_Proc); + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Leap_Seconds_Support : Integer; + pragma Import (C, Leap_Seconds_Support, ""__gl_leap_seconds_support""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 0; + Default_Stack_Size := -1; + Leap_Seconds_Support := 0; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E025 := E025 + 1; + Ada.Containers'Elab_Spec; + E040 := E040 + 1; + Ada.Io_Exceptions'Elab_Spec; + E070 := E070 + 1; + Ada.Strings'Elab_Spec; + E055 := E055 + 1; + Ada.Strings.Maps'Elab_Spec; + E057 := E057 + 1; + Ada.Strings.Maps.Constants'Elab_Spec; + E061 := E061 + 1; + Interfaces.C'Elab_Spec; + E045 := E045 + 1; + System.Exceptions'Elab_Spec; + E027 := E027 + 1; + System.Object_Reader'Elab_Spec; + E081 := E081 + 1; + System.Dwarf_Lines'Elab_Spec; + E050 := E050 + 1; + System.Os_Lib'Elab_Body; + E075 := E075 + 1; + System.Soft_Links.Initialize'Elab_Body; + E017 := E017 + 1; + E015 := E015 + 1; + System.Traceback.Symbolic'Elab_Body; + E039 := E039 + 1; + E011 := E011 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E105 := E105 + 1; + Ada.Streams'Elab_Spec; + E103 := E103 + 1; + System.File_Control_Block'Elab_Spec; + E117 := E117 + 1; + System.Finalization_Root'Elab_Spec; + E116 := E116 + 1; + Ada.Finalization'Elab_Spec; + E114 := E114 + 1; + System.File_Io'Elab_Body; + E113 := E113 + 1; + System.Storage_Pools'Elab_Spec; + E168 := E168 + 1; + System.Finalization_Masters'Elab_Spec; + System.Finalization_Masters'Elab_Body; + E164 := E164 + 1; + System.Storage_Pools.Subpools'Elab_Spec; + E162 := E162 + 1; + Ada.Strings.Unbounded'Elab_Spec; + E154 := E154 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E101 := E101 + 1; + System.Assertions'Elab_Spec; + E184 := E184 + 1; + E176 := E176 + 1; + E178 := E178 + 1; + E180 := E180 + 1; + E182 := E182 + 1; + E187 := E187 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_pagerank""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + if gnat_argc = 0 then + gnat_argc := argc; + gnat_argv := argv; + end if; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +function puissance_10 (exposant : in Integer) return ultra_precis is,"resultat : ultra_precis; + Exponant_Too_Big_error : exception; + begin + + if exposant > 16 then -- la précision du résultat ne serait pas assez bonne ! + raise Exponant_Too_Big_error; + else + resultat := ultra_precis(0.1); + for i in 1..exposant-1 loop + resultat := ultra_precis(0.1)*resultat; + end loop; + return resultat; + end if; + end puissance_10; + + + taille_chaine : Integer; -- taille de la chaine de caractères rentrée + chaine_partie_entiere : Unbounded_String; -- partie entière du T_Element sous forme d'une chaine + partie_entiere : Integer; -- partie entière du T_Element + partie_decimal : T_Element; -- partie décimale du T_Element + position_virgule : Integer; -- indice de la position occupée par la virgule + virgule_trouvee : Boolean; -- Indique si la chaine comporte bien une virgule + chaine_partie_decimal : Unbounded_String; -- Chaine représentant la partie décimale + taille_partie_decimal : Integer; -- Taille de la chaine + + begin + + -- Traiter le cas évident ou la chaine est trop petite + taille_chaine := Length(chaine); + if taille_chaine < 3 then + raise Bad_Type_Conversion_Error; + + -- Essayer de convertir la chaine en T_Element + else + + -- Trouver la place de la virgule + position_virgule := 1; + virgule_trouvee := False; + while not virgule_trouvee loop + if To_string(chaine)(position_virgule) = '.' then + virgule_trouvee := True; + end if; + position_virgule := position_virgule + 1 ; + end loop ; + position_virgule := position_virgule -1; -- la sortie du while se fait avec position + 1 + + -- Extraire la partie entière du nombre + for i in 1..position_virgule-1 loop + chaine_partie_entiere := chaine_partie_entiere & To_string(chaine)(i) ; + end loop; + + -- Convertir la partie entière en T_Element + partie_entiere := To_Integer(chaine_partie_entiere); + + -- Extraire la partie décimale + chaine_partie_decimal := To_Unbounded_String(To_String(chaine)(position_virgule+1..Taille_chaine)); + taille_partie_decimal := Length(chaine_partie_decimal); + + -- Convertir la partie décimale + if taille_partie_decimal <= 8 then -- cette condition est due au fait que les réels <= 10⁸en ADA + + partie_decimal:= T_Element(To_Integer(chaine_partie_decimal)); + partie_decimal := partie_decimal*T_Element(puissance_10(taille_partie_decimal)); + else + -- Découper la partie décimale en deux pour convertir des entiers de plus de 8 digits ! + partie_decimal := T_Element(To_Integer(To_Unbounded_String(To_String(chaine_partie_decimal)(1..8)))); + partie_decimal := partie_decimal*T_Element(puissance_10(8)); -- partie ""gauche"" + partie_decimal := partie_decimal + T_Element(To_Integer(To_Unbounded_String(To_String(chaine_partie_decimal)(9..taille_partie_decimal))))*T_Element(puissance_10(taille_partie_decimal)); + end if; + + + return partie_decimal + T_Element(partie_entiere); + end if; + end To_reel; + + + procedure Integer_or_reel( chaine : in Unbounded_String; reel : out T_Element; + entier : out Integer; indicateur : out Character) is + + begin + entier:= -1; + -- Déterminer si c'est un réel + begin + reel := To_reel(chaine); + indicateur := 'f'; + exception + when Bad_Type_Conversion_Error|CONSTRAINT_ERROR => -- le constraint error apparait si on cherche la virgule dans un réel ! + -- Déterminer si c'est un entier + begin + entier := To_Integer(chaine); + indicateur := 'i'; + exception + -- Déterminer si c'est autre choses + when Bad_Type_Conversion_Error =>indicateur := 'o';" +procedure pagerank is,"type T_precision is digits 6; -- type réel des coefficients + + taille_tableau : constant Integer := 10000; -- à adapter selon l'exemple testé ! + + -- Import de tous les paquets nécessaires + package Real_IO is new Ada.Text_IO.Float_IO(T_precision); use Real_IO; -- pour afficher les coeffs + + package vecteur is new Google_Naive(nombre_max_ligne => 1 , -- pour stocker et traiter PI + nombre_max_colonne => taille_tableau, + T_Element => T_precision); + + package tri is new Tri_par_tas(1,taille_tableau ,T_precision,vecteur); -- pour trier + + package recup is new Recuperation_Argument(T_alpha => T_precision); -- pour récupérer les arguments de la ligne de commande + + -- Procédures utiles pour le debugage et l'affichage des matrices + --procedure Afficher_element (nombre : T_precision ) is + --begin + -- Put(nombre,1,16); + --end Afficher_element; + + + + -- Nom : Creer_vect_occurrence + -- Semantique : Construire le vecteur avec les occurences de chaque noeud + -- Paramètres : + -- noeuds_occurence : out matrice_pleine.T_Google_Naive; -- vecteur occurence + -- N : in Integer; -- nombre de noeuds + -- fichier_net : in Ada.Text_IO.File_Type; -- objet fichier pas le nom + + -- Pre : True; + -- Post : trop complexe pour être exprimée; + -- Tests + -- Entrée : Sujet; Sortie : [2,0,3,2,2,1] + -- Exception : Aucune + procedure Creer_vect_occurence(noeuds_occurence : out vecteur.T_Google_Naive; + N : in Integer; + fichier_net : in Ada.Text_IO.File_Type ) is + + entier : Integer; -- coefficient sur la première colonne d'un fichier .net + useless : Integer; -- coefficient sur la deuxième colonne d'un fichier .net + ancien_coefficient : T_precision; -- occurence à incrémenter + + begin + -- Initialiser le vecteur à 0 + vecteur.Initialiser(noeuds_occurence,1,N); + for i in 1..N loop + vecteur.Enregistrer_coefficient(noeuds_occurence,1,i,T_precision(0)); + end loop; + + -- Si un noeud apparait une fois on incrémente l'occurence de ce noeud + while not end_of_File(fichier_net) loop + Get(fichier_net,entier); + ancien_coefficient := vecteur.Get_coefficient(noeuds_occurence,1,entier+1); + vecteur.Enregistrer_coefficient(noeuds_occurence,1,(entier+1),ancien_coefficient + T_precision(1)); + Get(fichier_net,useless); + end loop; + + end Creer_vect_occurence; + ------------------------------------------------------------------------------------------------------------------------------------IMPLANTATION NAIVE + -- Nom : pagerank_t + -- Semantique : Produire le vecteur PI défini dans le sujet avec des matrices pleines + -- Paramètres : + -- Nom_fichier_net : in Unbounded_String; -- fichier .net + -- alpha : in T_precision; -- coefficient de pondération + -- N : in Integer; -- nombre de noeuds + -- iter_max : in Integer; -- nombre d'iteration + -- PI : out vecteur.T_Google_Naive; -- cf sujet + + -- Pre : True; + -- Post : trop complexe pour être exprimée; + -- Tests + -- voir exemple_sujet + -- Exception : Aucune (à part un storage error si le fichier.net est grand, pensez à changer la stack size) + procedure pagerank_t (alpha : in T_precision; + Nom_fichier_net : in Unbounded_String; + N : out Integer; + iter_max : in Integer; + PI : out vecteur.T_Google_Naive ) is + + + package matrice_pleine is new Google_Naive(nombre_max_ligne => taille_tableau , + nombre_max_colonne => taille_tableau, + T_Element => T_precision); + + --procedure Affichage_vecteur is new Matrice_Pleine.Affichage (Afficher=>Afficher_element); + + + + --procedure Affichage_matrice_pleine is new matrice_pleine.Affichage (Afficher=>Afficher_element); + + + -- Nom : Creer_H + -- Semantique : Construire la matrice_pleine H définie dans le sujet + -- Paramètres : + -- Nom_fichier_net : in Unbounded_String; -- nom du fichier.net + -- H : out matrice_pleine.T_Google_Naive; -- cf sujet + -- N : in Integer; -- nombre de noeuds + + -- Pre : True; + -- Post : trop complexe pour être exprimée; + -- Tests + -- voir exemple_sujet + -- Exception : Aucune + procedure Creer_H(Nom_fichier_net : in Unbounded_String; + H : out matrice_pleine.T_Google_Naive; + N : out Integer) is + + + entier : Integer; -- coefficient sur la première colonne d'un fichier .net + fichier_net : Ada.Text_IO.File_Type; + noeuds_occurence : vecteur.T_Google_Naive; -- vecteur avec l'occurence de chaque noeud - + coeff_i : Integer; -- numéro de ligne + coeff_j : Integer; -- numéro de colonne + + begin + + -- Ouvrir le fichier + begin + open(fichier_net, In_File, To_String(Nom_fichier_net)); + exception + when ADA.IO_EXCEPTIONS.NAME_ERROR => raise recup.File_Absent_Error;" +--procedure Affichage_matrice_creuse is new matrice_creuse.Affichage (Afficher=>Afficher_element);,"-- Nom : Creer_H + -- Semantique : Construire la matrice_creuse H définie dans le sujet + -- Paramètres : + -- Nom_fichier : in Unbounded_String; -- nom du fichier .net + -- H : out matrice_creuse.T_Google_Creuse; + -- N : in Integer; -- nombre de noeuds + + -- Pre : True; + -- Post : trop complexe pour être exprimée; + -- Tests + -- voir exemple_sujet + -- Exception : Aucune + procedure Creer_H(Nom_fichier_net : in Unbounded_String; + H : out matrice_creuse.T_Google_Creuse; + N : out Integer) is + + + + entier : Integer; -- coefficient sur la première colonne d'un fichier .net + fichier_net : Ada.Text_IO.File_Type; + noeuds_occurence : vecteur.T_Google_Naive; -- vecteur avec l'occurence de chaque noeud -- taille de la matrice_creuse + coeff_i : Integer; + coeff_j : Integer; -- numéro de colonne + + begin + + -- Ouvrir le fichier + begin + open(fichier_net, In_File, To_String(Nom_fichier_net)); + exception + when ADA.IO_EXCEPTIONS.NAME_ERROR => raise recup.File_Absent_Error;" +procedure test_pagerank is,"type T_Double is digits 6; + + package Real_IO is new Ada.Text_IO.Float_IO(T_Double); use Real_IO; -- pour afficher les coeffs + + -- Testons sur les matrices du sujet, les tests peuvent se généraliser à (n x n) + package matrice_pleine is new Google_Naive(nombre_max_ligne => 6 , + nombre_max_colonne => 6, + T_Element => T_Double); + + + package vecteur is new Google_Naive(nombre_max_ligne => 1 , -- pour stocker et traiter PI + nombre_max_colonne => 6, + T_Element => T_Double); + + alpha : constant T_Double := T_Double(0.85000002384); + + + procedure Creer_vect_occurence(noeuds_occurence : out vecteur.T_Google_Naive; + N : in Integer; + fichier_net : in Ada.Text_IO.File_Type ) is + + entier : Integer; -- coefficient sur la première colonne d'un fichier .net + useless : Integer; -- coefficient sur la deuxième colonne d'un fichier .net + ancien_coefficient : T_Double; -- occurence à incrémenter + + begin + -- Initialiser le vecteur à 0 + vecteur.Initialiser(noeuds_occurence,1,N); + for i in 1..N loop + vecteur.Enregistrer_coefficient(noeuds_occurence,1,i,T_Double(0)); + end loop; + + -- Si un noeud apparait une fois on incrémente l'occurence de ce noeud + while not end_of_File(fichier_net) loop + Get(fichier_net,entier); + ancien_coefficient := vecteur.Get_coefficient(noeuds_occurence,1,entier+1); + vecteur.Enregistrer_coefficient(noeuds_occurence,1,(entier+1),ancien_coefficient + T_Double(1)); + Get(fichier_net,useless); + end loop; + + end Creer_vect_occurence; + + -------------------------------Les sous-programmes de pagerank n'étant pas accessible nous n'avons d'autres solutions que de les copier ici : + + + procedure Creer_H(Nom_fichier_net : in Unbounded_String; + H : out matrice_pleine.T_Google_Naive; + N : out Integer) is + + + entier : Integer; -- coefficient sur la première colonne d'un fichier .net + fichier_net : Ada.Text_IO.File_Type; + noeuds_occurence : vecteur.T_Google_Naive; -- vecteur avec l'occurence de chaque noeud - + coeff_i : Integer; -- numéro de ligne + coeff_j : Integer; -- numéro de colonne + + File_Absent_Error : exception; + begin + + -- Ouvrir le fichier + begin + open(fichier_net, In_File, To_String(Nom_fichier_net)); + exception + when ADA.IO_EXCEPTIONS.NAME_ERROR => raise File_Absent_Error;" +procedure Command_Line_Vectorisee(vect_arg : out vecteur) is,"N : Integer; + begin + N := Argument_Count; + vect_arg.taille := N; + + for i in 1..N loop + vect_arg.tableau(i) := To_Unbounded_String(Argument(i)); + end loop; + + end Command_Line_Vectorisee; + + -- Nom : Afficher_erreur + -- sémantique : Afficher un message d'erreur et lever une exception pour aider l'utilisateur selon le code rentré + -- paramètres : + -- nombre : in Integer; -- code d'erreur + -- Pre : True + -- Post : True + -- Tests : + -- Entrée : 1 ; Sortie : ""Le format autorisé est : -P -I [integer] -A [T_alpha] filename.net"" + -- + -- ""L'exception et le message ci-dessous devraient vous aider ;)""); + -- "" Option inconnue "" + -- raised RECUPERATION_ARGUMENT.INVALID_NAME_OPTION_ERROR : recuperation_argument.adb:112 + + -- Exception : voir les exceptions ci-dessous + procedure Afficher_erreur (nombre : in Integer ) is + + begin + + -- Afficher un message précisant le format + New_line; + Put(""Le format autorisé est : -P -I [integer] -A [T_alpha] filename.net""); + New_Line; + New_line; + Put(""L'exception et le message ci-dessous devraient vous aider ;)""); + New_Line; + New_line; + + -- Afficher un message plus précis sur la cause de l'erreur + case nombre is + + when 1 + =>Put(""Option inconnue""); + raise Invalid_Name_Option_Error; + + when 2 + => Put("" Veuillez réesayer avec des valeurs valides pour les options""); + raise Invalid_Type_Arguments_Error; + when 3 + => Put(""Trop d'arguments !""); + raise Too_Many_Argument_Error; + + when 4 + => Put( ""Vous avez oublié de préciser les options !""); + raise Missing_Options_Error; + when 5 + => Put(""Essayez avec un nom de fichier valide""); + raise File_Absent_Error; + + when 6 + => Put(""il manque une valeur d'option""); + raise Missing_Arguments_Value_Error; + + when 7 + => Put( ""Vous avez oublié de préciser le fichier""); + raise File_Absent_Error; + + when 8 + => Put(""Pensez à rentrer un nom de fichier correct en .net""); + raise File_Absent_Error; + + when others => NUll; + end case; + end Afficher_erreur; + + + -- Nom : Is_number_Arguments_Correct + -- sémantique : Vérifier qu'il n'y a aucune erreur sur le nombre d'arguments + -- paramètres : + -- N : in Integer; -- nombre d'arguments + -- nb_max_argument : in Integer; -- nombre max théorique d'arguments + -- Nom_fichier : out Unbounded_String; -- nom éventellement récupéré du fichier + -- nb_correct_argument : out Boolean; -- le nombre d'argument était correct ? + -- Pre : True + -- Post : le nom de fichier finit en .net + -- Tests : + -- Entrée : N = 7, nb_max_argument = 6 ; Sortie : Too_Many_Arguments + -- Entrée : N = 5, nb_max_argument = 6 ; Sortie nb_correct_argument = True et potentiellement Nom_fichier =... .net + + -- Exception : File_Absent_Error; Too_Many_Argument_Error + procedure Is_number_Arguments_Correct ( N : in Integer; + nb_max_argument : in Integer; + Nom_fichier : out Unbounded_String; + nb_correct_argument: out Boolean ) is + begin + + + if N = 0 then -- Aucun argument rentré ! + + Afficher_erreur(7); + + elsif N = 1 then + + -- Vérifier que c'est bien le fichier qui a été rentré comme argument unique + + if Is_file_name(To_Unbounded_String(Argument(1))) then + Nom_fichier := To_Unbounded_String(Argument(1)); + nb_correct_argument := False; -- ne plus chercher à récupérer d'autres arguments + else + Afficher_erreur(8); + end if; + + elsif N > nb_max_argument then -- trop d'argument + Afficher_erreur(3); + + else + nb_correct_argument := True; + end if; + + end Is_number_Arguments_Correct; + + + -- Nom : recuperer_chaque_option + -- sémantique : Récupérer les valeurs des options I, A, P et le nom de fichier + -- paramètres : + -- N N : in Integer; + -- vect_arg : in vecteur; + -- iteration : out Integer; + -- alpha : out T_alpha; + -- naive :out Boolean; + -- Nom_fichier : out Unbounded_String ; + + -- Pre : True + -- Post : le nom de fichier finit en .net, alpha > 1 and alpha < 0 and iteration > 1 + + -- Tests : Aucun + -- Exception : voir sous-programme afficher_erreur pour la liste exhaustive + procedure recuperer_chaque_option (N : in Integer; + vect_arg : in vecteur; + iteration : in out Integer; + alpha : in out T_alpha; + naive : in out Boolean; + Nom_fichier : out Unbounded_String) is + + -- Nom : detecter_option + -- sémantique : Marquer la lecture d'une option par un indicateur nommé option + -- paramètres : + -- vect_arg : in vecteur; -- vecteur des arguments + -- option : in out Character; + -- i : in Integer; -- iteration courante + -- type de retour : Character; + + -- Pre : True + -- Post : detecter_option'Result = 'o' or detecter_option'Result = 'I' or detecter_option'Result = 'P' + -- or detecter_option'Result = 'A' + + -- Tests : Aucun + -- Exception : voir sous-programme afficher_erreur avec code d'erreur 2, 1 et 6 + procedure detecter_option(vect_arg : in vecteur;i : in Integer; option : in out Character) is + + begin + + -- Y a-t-il une option valide ? + if length(vect_arg.tableau(i)) /=2 then + Afficher_erreur(2); + else + if option = 'o' then + + -- Vérifier qu'une option est possible + case To_String(vect_arg.tableau(i))(2) is + when 'I' => option := 'I'; + when 'A' => option :='A'; + when 'P' => + option := 'o'; + naive := True; + when others => Afficher_erreur(1); + + end case; + else + Afficher_erreur(6); + end if; + end if; + end detecter_option; + + + -- Nom : Rentrer_alpha + -- sémantique : Obtenir un alpha compatible + -- paramètres : + -- alpha : out T_alpha; + -- nombre_reel : in T_alpha; -- valeur potentielle de alpha + -- indicateur_type : in Character; -- type de l'argument courant + -- option : in Character; -- option rencontrée ? + -- Pre : True + -- Post : alpha > T_alpha(1) and alpha < T_alpha(0) and option = 'o' + + -- Tests : Aucun + -- Exception : voir sous-programme afficher_erreur avec code d'erreur 2 et 1 + procedure Rentrer_alpha(alpha : in out T_alpha; + nombre_reel : in T_alpha; + indicateur_type : in Character; + option : in out Character) is + + begin + + if indicateur_type /= 'f' then -- erreur sur le type de alpha + Afficher_erreur(2); + else + alpha := nombre_reel; + + -- Demander une saisie robuste entre 0 et 1 + while alpha > T_alpha(1) or alpha < T_alpha(0) loop + begin + -- Donner la consigne + Put("" Alpha doit être compris entre 1 et 0 svp : ""); + Real_IO.Get(alpha); + Skip_Line; + exception + when ADA.IO_EXCEPTIONS.DATA_ERROR => Skip_Line; -- SI l'utilisateur ne rentre même pas un réel !" +function histEQUAL(img: in imge; hist: in histogram) return imge is,"equalimg : imge; + cumsum : array (1..256) of float; +begin + -- calculate the cumulative sum of the histogram values + for i in 1..256 loop + if i = 1 then + cumsum(i) := float(hist.count(i)); + else + cumsum(i) := cumsum(i-1) + float(hist.count(i)); + end if; + end loop; + + -- normalize the cumulative sum by dividing by the total number of pixels + -- then multiply by the maximum grayscale value (i.e., 255) + for i in 1..256 loop + cumsum(i) := 255.0 * cumsum(i) / (float(img.dx) * float(img.dy)); + end loop; + + -- map the original values to the results of the array above to calculate histogram equalization + for i in 1..img.dx loop + for j in 1..img.dy loop + equalimg.pixel(i,j) := integer(cumsum(img.pixel(i,j))); + end loop; + end loop; + + return equalimg;" +procedure Main is,"pragma Suppress(All_Checks); + + Matrix_Size : constant := 3200; + type Matrix_Range is range 0 .. Matrix_Size - 1; + Bound_High, Bound_Low : Matrix_Range; + + type Pile is range 0..7 with Size=>8; + type Pile_Pointer is access all Pile; + + type Generic_Matrix_Row is array (Matrix_Range range <>) of aliased Pile with Pack; + subtype Matrix_Row is Generic_Matrix_Row(Matrix_Range); + subtype Matrix_Sub_Row is Generic_Matrix_Row(0..7); + type Matrix is array (Matrix_Range) of Matrix_Row with Pack; + type Matrix_Pointer is access all Matrix; + + type m128i is array (0 .. 15) of Pile with Pack, Alignment=>16; + pragma Machine_Attribute (m128i, ""vector_type""); + pragma Machine_Attribute (m128i, ""may_alias""); + +---------------------------------------------------------------------- + + function ia32_Add (X, Y : m128i) return m128i with Inline; + pragma Import (Intrinsic, ia32_Add, ""__builtin_ia32_paddb128""); + function ia32_Load (X : Pile_Pointer) return m128i with Inline; + pragma Import (Intrinsic, ia32_Load, ""__builtin_ia32_loaddqu""); + procedure ia32_Store (X : Pile_Pointer; Y : m128i) with Inline; + pragma Import (Intrinsic, ia32_Store, ""__builtin_ia32_storedqu""); + + procedure Print (Map : in Matrix; Name : in String) is + begin + Put_Line(Name); + for I in Bound_Low .. Bound_High loop + for J in Bound_Low .. Bound_High loop + Put(Pile'Image(Map(I)(J))); + end loop; + New_Line(1); + end loop; + Put_Line(""------------"");" +"function Move is new Ada.Unchecked_Conversion (Source=>Mod_64, Target=>Matrix_Sub_Row);","function Move is new Ada.Unchecked_Conversion (Source=>Matrix_Sub_Row, Target=>Mod_64); + + Changed : Boolean := False; + Local_Bound_High : constant Matrix_Range := Bound_High; + Local_Bound_Low : constant Matrix_Range := Bound_Low; + I : Matrix_Range := Bound_Low; + Temp_Values : Mod_64_Array; + + begin + while I <= Local_Bound_High loop + declare + J : Matrix_Range := Local_Bound_Low - (Local_Bound_Low mod 16); + Temp : m128i; + Sum_m128i_Buffer : m128i; + Upper_Sum_m128i_Buffer : m128i; + Lower_Sum_m128i_Buffer : m128i; + begin + while J <= Local_Bound_High loop + Temp_Values(0) := (Move(Base(I)(J..J+7)) / 2**2) AND 16#0F0F0F0F0F0F0F0F#; + Temp_Values(1) := (Move(Base(I)(J+8..J+15)) / 2**2) AND 16#0F0F0F0F0F0F0F0F#; + + if (Temp_Values(0) OR Temp_Values(1)) /= 0 then + Changed := True; + if I - 1 < Bound_Low then + Bound_Low := Bound_Low - 1; + Bound_High := Bound_High + 1; + end if; + Temp := ia32_Load(Temp_Values(0)'Access); + + Upper_Sum_m128i_Buffer := ia32_Load(Base(I-1)(J)'Access); + ia32_Store(Base(I-1)(J)'Access, ia32_Add(Upper_Sum_m128i_Buffer, Temp)); + + Lower_Sum_m128i_Buffer := ia32_Load(Base(I+1)(J)'Access); + ia32_Store(Base(I+1)(J)'Access, ia32_Add(Lower_Sum_m128i_Buffer, Temp)); + + Sum_m128i_Buffer := ia32_Load(Base(I)(J-1)'Access); + ia32_Store(Base(I)(J-1)'Access, ia32_Add(Sum_m128i_Buffer, Temp)); + + Sum_m128i_Buffer := ia32_Load(Base(I)(J+1)'Access); + ia32_Store(Base(I)(J+1)'Access, ia32_Add(Sum_m128i_Buffer, Temp)); + + Base(I)(J..J+7) := Move(Move(Base(I)(J..J+7)) - (Temp_Values(0) * 4)); + Base(I)(J+8..J+15) := Move(Move(Base(I)(J+8..J+15)) - (Temp_Values(1) * 4)); + end if; + + J := J + 16; + end loop;" +procedure Update_Rates is,"Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; + begin + if Deadline < Now then + declare + Dt : constant Ada.Real_Time.Time_Span := Now - Prev_Time; + MS : constant Integer := Dt / ONE_MS; + begin + EtherScope.Analyzer.Ethernet.Update_Rates (Ethernet, Prev_Ethernet, MS); + EtherScope.Analyzer.IPv4.Update_Rates (IPv4, Prev_IPv4, MS); + EtherScope.Analyzer.IGMP.Update_Rates (IGMP_Groups, Prev_Groups, MS); + EtherScope.Analyzer.TCP.Update_Rates (TCP_Ports, Prev_TCP, MS); + Prev_Time := Now; + Deadline := Deadline + Ada.Real_Time.Seconds (1);" +procedure Initialize is,"begin + STM32.Board.Display.Initialize; + STM32.Board.Display.Initialize_Layer (1, HAL.Bitmap.ARGB_1555); + + -- Initialize touch panel + STM32.Board.Touch_Panel.Initialize; + + for I in Graphs'Range loop + EtherScope.Display.Use_Graph.Initialize (Graphs (I), + X => 100, + Y => 200, + Width => 380, + Height => 72, + Rate => Ada.Real_Time.Milliseconds (1000)); + end loop; + end Initialize; + + -- ------------------------------ + -- Draw the layout presentation frame. + -- ------------------------------ + procedure Draw_Frame (Buffer : in out HAL.Bitmap.Bitmap_Buffer'Class) is + begin + Buffer.Set_Source (UI.Texts.Background); + Buffer.Fill; + Draw_Buttons (Buffer); + Buffer.Set_Source (Line_Color); + Buffer.Draw_Vertical_Line (Pt => (98, 0), + Height => Buffer.Height); + end Draw_Frame; + + -- ------------------------------ + -- Draw the display buttons. + -- ------------------------------ + procedure Draw_Buttons (Buffer : in out HAL.Bitmap.Bitmap_Buffer'Class) is + begin + UI.Buttons.Draw_Buttons (Buffer => Buffer, + List => Buttons, + X => 0, + Y => 0, + Width => 95, + Height => 34); + end Draw_Buttons; + + -- ------------------------------ + -- Refresh the graph and draw it. + -- ------------------------------ + procedure Refresh_Graphs (Buffer : in out HAL.Bitmap.Bitmap_Buffer'Class; + Graph_Mode : in EtherScope.Stats.Graph_Kind) is + Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; + Samples : EtherScope.Stats.Graph_Samples; + begin + EtherScope.Analyzer.Base.Update_Graph_Samples (Samples, True); + for I in Samples'Range loop + Use_Graph.Add_Sample (Graphs (I), Samples (I), Now); + end loop; + Use_Graph.Draw (Buffer, Graphs (Graph_Mode)); + end Refresh_Graphs; + + -- ------------------------------ + -- Display devices found on the network. + -- ------------------------------ + procedure Display_Devices (Buffer : in out HAL.Bitmap.Bitmap_Buffer'Class) is + use EtherScope.Analyzer.Base; + + Y : Natural := 15; + begin + EtherScope.Analyzer.Base.Get_Devices (Devices); + Buffer.Set_Source (UI.Texts.Background); + Buffer.Fill_Rect (Area => (Position => (100, 0), + Width => Buffer.Width - 100, + Height => Buffer.Height)); + for I in 1 .. Devices.Count loop + declare + Ethernet : EtherScope.Analyzer.Ethernet.Device_Stats renames Devices.Ethernet (I); + IP : EtherScope.Analyzer.IPv4.Device_Stats renames Devices.IPv4 (I); + begin + UI.Texts.Draw_String (Buffer, (100, Y), 200, Net.Utils.To_String (Ethernet.Mac)); + UI.Texts.Draw_String (Buffer, (300, Y), 150, Net.Utils.To_String (IP.Ip), RIGHT); + UI.Texts.Draw_String (Buffer, (100, Y + 20), 100, Format_Packets (Ethernet.Stats.Packets), RIGHT); + UI.Texts.Draw_String (Buffer, (200, Y + 20), 200, Format_Bytes (Ethernet.Stats.Bytes), RIGHT); + UI.Texts.Draw_String (Buffer, (400, Y + 20), 80, Format_Bandwidth (Ethernet.Stats.Bandwidth));" +procedure Lab6 is,"Input, Output : File_Type; + I: Integer; + WasLastTab: Integer; + WasLastSpace: Integer; + TmpStr: Unbounded_String; + + begin + + Open (File => Input, Mode => In_File, Name => ""REG.BIN""); + + Create (File => Output, Mode => Out_File, Name => ""output.txt""); + + + -- Denna loop loopar igenom filen rad för rad + loop + declare + -- Deklarera en variabel som håller varje rad i minnet varje gång loopen körs + InputLine : String := Get_Line (Input); + + begin + I := 0; + WasLastTab := 0; + WasLastSpace := 0; + TmpStr := To_Unbounded_String(""""); + + -- Loopa igenom varje tecken på raden och hämta ut varje element när flera mellanrum kommer i följd + + Put(""---------------------------------------------""); New_Line; + + for I in 1..InputLine'Last loop + -- Kolla om tecknet är mellanslag + --Put(InputLine(I)); + --Put("" > ""); + --Put( Character'Pos(InputLine(I)) ); + --New_Line; + + if(Character'Pos(InputLine(I)) = 32) then + -- Tecknet var mellanrum! + + -- Kolla om nästa tecknen också är mellanrum + if(Character'Pos(InputLine(I+1)) = 32) then + -- Vi ska avsluta elementet! + WasLastTab := 1; + else + -- Nästa tecken var inte ett mellanrum + -- Kolla så att föregående tecknen inte var ett mellanrum + if(Character'Pos(InputLine(I-1)) /= 32) then + -- Endast ett mellanrum, del av elementet! + Append(TmpStr, "" ""); + --Put(""SPACE""); New_Line; + else + -- Föregående tecken var ett mellanrum, avsluta elementet! + New_Line; + Put(""|""); + Put(TmpStr); + Put(""|""); + New_Line;New_Line; + --Put(""_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_""); + -- Töm elementet + TmpStr := To_Unbounded_String(""""); + ----New_Line; + end if; + end if; + else + WasLastTab := 0; + -- Put( String(I) ); + + + + case Character'Pos(InputLine(I)) is + when 0..32 => null; Put(""->""); Put( Character'Pos(InputLine(I)) ); New_Line; + when 196 => + Append(TmpStr, ""Ä""); Put( ""Ä"" ); Put("" === ""); Put( Character'Pos( InputLine(I) ) ); New_Line; + when 197 => + Append(TmpStr, ""Å""); Put( ""Å"" ); Put("" === ""); Put( Character'Pos( InputLine(I) ) ); New_Line; + when 214 => + Append(TmpStr, ""Ö""); Put( ""Ö"" ); Put("" === ""); Put( Character'Pos( InputLine(I) ) ); New_Line; + when 228 => + Append(TmpStr, ""ä""); Put( ""ä"" ); Put("" === ""); Put( Character'Pos( InputLine(I) ) ); New_Line; + when 229 => + Append(TmpStr, ""å""); Put( ""å"" ); Put("" === ""); Put( Character'Pos( InputLine(I) ) ); New_Line; + when 246 => + Append(TmpStr, ""å""); Put( ""å"" ); Put("" === ""); Put( Character'Pos( InputLine(I) ) ); New_Line; + when others => + Append(TmpStr, InputLine(I)); + --Put( InputLine(I) ); + --Put("" === ""); + --Put( Character'Pos( InputLine(I) ) ); + --New_Line; + end case; + end if; + end loop; + + -- Put_Line (Output, Line); + + + --Put(Line); + --Skip_Line;" +procedure Lab4e is,"type Dates is array (1..10) of Date_Type; + + procedure Sort(Arrayen_Med_Talen: in out Dates) is + procedure Swap(Tal_1,Tal_2: in out Date_Type) is + Tal_B : Date_Type; -- Temporary buffer + begin + Tal_B := Tal_1; + Tal_1 := Tal_2; + Tal_2 := Tal_B; + + -- DEBUG New_Line; Put(""SWAP IS RUNNING! INDEXES INPUT: ""); Put(Tal_1); Put(""+""); Put(Tal_2); New_Line; + end Swap; + Minsta_Talet: Date_Type; + Minsta_Talet_Index: Integer; + begin + --Minsta_Talet.Year := 0; + --Minsta_Talet.Month := 0; + --Minsta_Talet.Day := 0; + +-- -- Loopa antalet gånger som arrayens längd + for IOuter in Arrayen_Med_Talen'Range loop +-- -- DEBUG Put(""> ""); Put(IOuter); Put("" <""); New_Line; +-- -- Loopa arrayen med start från yttra loopens värde varje gång. 1..20, 2..20, ... , 20..20 + for I in IOuter..Arrayen_Med_Talen'Last loop +-- --DEBUG Put("">>>""); Put(I); New_Line; + if I = IOuter or Arrayen_Med_Talen(I) < Minsta_Talet then + Minsta_Talet := Arrayen_Med_Talen(I); + Minsta_Talet_Index := I; + end if; + end loop; +-- + Swap(Arrayen_Med_Talen(IOuter), Arrayen_Med_Talen(Minsta_Talet_Index)); +-- --DEBUG New_Line; Put(""Vi swappar ""); Put(Iouter); Put("" och ""); Put(Minsta_Talet_Index); New_Line; + end loop; + end Sort; + + procedure Test_Get(Date: out Date_Type) is + begin + loop + begin + Get(Date); + exit; + exception + when YEAR_ERROR => Put_Line(""FEL: YEAR_ERROR""); + when MONTH_ERROR => Put_Line(""FEL: MONTH_ERROR""); + when DAY_ERROR => Put_Line(""FEL: DAY_ERROR""); + when FORMAT_ERROR => Put_Line(""FEL: FORMAT_ERROR"");" +procedure Lab4a is,"type Dates is array (1..10) of Date_Type; + + procedure Test_Get(Date: out Date_Type) is + begin + loop + begin + Get(Date); + exit; + exception + when YEAR_ERROR => Put_Line(""FEL: YEAR_ERROR""); + when MONTH_ERROR => Put_Line(""FEL: MONTH_ERROR""); + when DAY_ERROR => Put_Line(""FEL: DAY_ERROR""); + when FORMAT_ERROR => Put_Line(""FEL: FORMAT_ERROR"");" +procedure Lab4 is,"type Dates is array (1..10) of Date_Type; + + procedure Sort(Arrayen_Med_Talen: in out Dates) is + procedure Swap(Tal_1,Tal_2: in out Date_Type) is + Tal_B : Date_Type; -- Temporary buffer + begin + Tal_B := Tal_1; + Tal_1 := Tal_2; + Tal_2 := Tal_B; + + -- DEBUG New_Line; Put(""SWAP IS RUNNING! INDEXES INPUT: ""); Put(Tal_1); Put(""+""); Put(Tal_2); New_Line; + end Swap; + Minsta_Talet: Date_Type; + Minsta_Talet_Index: Integer; + begin + --Minsta_Talet.Year := 0; + --Minsta_Talet.Month := 0; + --Minsta_Talet.Day := 0; + +-- -- Loopa antalet gånger som arrayens längd + for IOuter in Arrayen_Med_Talen'Range loop +-- -- DEBUG Put(""> ""); Put(IOuter); Put("" <""); New_Line; +-- -- Loopa arrayen med start från yttra loopens värde varje gång. 1..20, 2..20, ... , 20..20 + for I in IOuter..Arrayen_Med_Talen'Last loop +-- --DEBUG Put("">>>""); Put(I); New_Line; + if I = IOuter or Arrayen_Med_Talen(I) < Minsta_Talet then + Minsta_Talet := Arrayen_Med_Talen(I); + Minsta_Talet_Index := I; + end if; + end loop; +-- + Swap(Arrayen_Med_Talen(IOuter), Arrayen_Med_Talen(Minsta_Talet_Index)); +-- --DEBUG New_Line; Put(""Vi swappar ""); Put(Iouter); Put("" och ""); Put(Minsta_Talet_Index); New_Line; + end loop; + end Sort; + + procedure Test_Get(Date: out Date_Type) is + begin + loop + begin + Get(Date); + exit; + exception + when YEAR_ERROR => Put_Line(""FEL: YEAR_ERROR""); + when MONTH_ERROR => Put_Line(""FEL: MONTH_ERROR""); + when DAY_ERROR => Put_Line(""FEL: DAY_ERROR""); + when FORMAT_ERROR => Put_Line(""FEL: FORMAT_ERROR"");" +procedure Lab4d is,"type Dates is array (1..10) of Date_Type; + + procedure Test_Get(Date: out Date_Type) is + begin + loop + begin + Get(Date); + exit; + exception + when YEAR_ERROR => Put_Line(""FEL: YEAR_ERROR""); + when MONTH_ERROR => Put_Line(""FEL: MONTH_ERROR""); + when DAY_ERROR => Put_Line(""FEL: DAY_ERROR""); + when FORMAT_ERROR => Put_Line(""FEL: FORMAT_ERROR"");" +procedure Lab4fg is,"type Dates is array (1..10) of Date_Type; + + procedure Sort(Arrayen_Med_Talen: in out Dates) is + procedure Swap(Tal_1,Tal_2: in out Date_Type) is + Tal_B : Date_Type; -- Temporary buffer + begin + Tal_B := Tal_1; + Tal_1 := Tal_2; + Tal_2 := Tal_B; + end Swap; + Minsta_Talet: Date_Type; + Minsta_Talet_Index: Integer; + begin + + -- Loopa antalet gånger som arrayens längd + for IOuter in Arrayen_Med_Talen'Range loop + -- Loopa arrayen med start från yttra loopens värde varje gång. 1..20, 2..20, ... , 20..20 + for I in IOuter..Arrayen_Med_Talen'Last loop + + if I = IOuter or Arrayen_Med_Talen(I) < Minsta_Talet then + Minsta_Talet := Arrayen_Med_Talen(I); + Minsta_Talet_Index := I; + end if; + + end loop; + + Swap(Arrayen_Med_Talen(IOuter), Arrayen_Med_Talen(Minsta_Talet_Index)); + end loop; + end Sort; + + procedure Test_Get(Date: out Date_Type) is + begin + loop + begin + Get(Date); + exit; + exception + when YEAR_ERROR => Put_Line(""FEL: YEAR_ERROR""); + when MONTH_ERROR => Put_Line(""FEL: MONTH_ERROR""); + when DAY_ERROR => Put_Line(""FEL: DAY_ERROR""); + when FORMAT_ERROR => Put_Line(""FEL: FORMAT_ERROR"");" +procedure Lab4b is,"type Dates is array (1..10) of Date_Type; + + procedure Test_Get(Date: out Date_Type) is + begin + loop + begin + Get(Date); + exit; + exception + when YEAR_ERROR => Put_Line(""FEL: YEAR_ERROR""); + when MONTH_ERROR => Put_Line(""FEL: MONTH_ERROR""); + when DAY_ERROR => Put_Line(""FEL: DAY_ERROR""); + when FORMAT_ERROR => Put_Line(""FEL: FORMAT_ERROR"");" +procedure Upg1 is,"procedure Print(A, B: in Integer) is + + Spaces: Integer; + begin + if A < B then + Spaces := (B - A) * 4; + for I in 1..Spaces loop + Put(' '); + end loop; + end if; + for X in 1..A loop + Put(B,1); Put(' '); + if A = X then + Put(""= ""); Put(A * B, 1); + else + Put(""+ ""); + end if; + + end loop; + New_Line;" +procedure Upg4 is,"type Ints is + array(1..10) of Integer; + type Arrs is + array(1..20) of Ints; + + procedure Extract(Data: out Arrs) is + File : File_Type; + begin + Open(File, In_File, ""NUMMER.TXT""); + for X in Data'Range loop + for I in Ints'Range loop + Get(File, Data(X)(I)); + end loop; + end loop; + Close(File);" +procedure Upg3 is,"function Count + return Integer is + S : String(1..3); + C : Character; + A, B : Integer; + begin + Get(S); + Get(A); + Get(C); Get(C); + Get(B); + return (B - A + 1);" +procedure Upg2 is,"function Generate + return Integer is + subtype Nums is Integer range 0..99; + package RN is + new Ada.Numerics.Discrete_Random(Nums); + Gen : RN.Generator; + begin + RN.Reset(Gen); + return RN.Random(Gen);" +procedure Upg3 is,"Syl_Arr : constant array(1..100) of String(1..4) := ( + ""ach "", ""tun "", ""ep "", ""tur "", ""tash"", + ""ine "", ""me "", ""arr "", ""et "", ""ze "", + ""cre "", ""uss "", ""dar "", ""ien "", ""her "", + ""cant"", ""jol "", ""nar "", ""kam "", ""dorn"", + ""li "", ""sis "", ""maal"", ""uk "", ""mec "", + ""at "", ""ol "", ""mi "", ""ra "", ""ge "", + ""mor "", ""dai "", ""nest"", ""phar"", ""rag "", + ""ret "", ""ill "", ""on "", ""dru "", ""ah "", + ""quin"", ""sha "", ""loq "", ""tre "", ""lak "", + ""sum "", ""eri "", ""an "", ""tsi "", ""win "", + ""ter "", ""arch"", ""on "", ""ren "", ""i "", + ""pri "", ""tau "", ""cu "", ""ry "", ""ven "", + ""us "", ""mar "", ""jup "", ""it "", ""er "", + ""sat "", ""uh "", ""un "", ""plu "", ""gol "", + ""kar "", ""lam "", ""wel "", ""pik "", ""chu "", + ""cha "", ""man "", ""der "", ""za "", ""bla "", + ""sto "", ""id "", ""sau "", ""tan "", ""sin "", + ""cos "", ""chut"", ""stri"", ""stra"", ""stru"", + ""skro"", ""skre"", ""cet "", ""nya "", ""nyu "", + ""ple "", ""pra "", ""ble "", ""glu "", ""geo ""); + + Num, I: Integer; + Index: Integer := 1; + Ut: String(1..200); + Stav: String(1..4); + Ver: Boolean := True; +begin + Put(""Mata in antal stavelser: ""); Get(Num); + Put(""Mata in stavelseindex: ""); + for X in 1..Num loop + Get(I); + if I < 0 then + Stav := Syl_Arr(-I); + Ut(Index) := '-'; + Ver := True; + Index := Index + 1; + else + Stav := Syl_Arr(I); + end if; + + for Z in 1..4 loop + if Stav(Z) /= ' ' then + if Ver = True then + Ut(Index) := Ada.Characters.Handling.To_Upper(Stav(Z)); + else + Ut(Index) := Stav(Z); + end if; + Ver := False; + Index := Index + 1; + end if; + end loop; + end loop; + Put(""Genererat planetnamn: ""); + Put(Ut(1..Index));" +procedure Stone is,"I: Integer; + C: Character; +begin + --kollar om 2 argument finns + if Argument_Count = 2 then + --Tar in tecknet + C := Argument(1)(1); + --Omvandlar tecknet till integer + I := Character'Pos(C); + -- Lägger till argument 2 till integern + I := I + Integer'Value(Argument(2)); + + Put(Character'Val(I)); + end if; + null;" +procedure Henge is,"function Read + return Integer is + C : Character; + begin + Get(C); + if C = 'h' then + return 0; + else + for I in 1..4 loop + Get(C); + end loop; + return Read + 12; + end if;" +function Exists ( Check_Value : Character; Values : Backpack_Pocket_T; Range_Max: Pocket_Size_T) return Boolean is,"(for some Idx in Backpack_Pocket_T'First .. Range_Max => Values (Idx) = Check_Value); + + begin + for Char_Idx in Pocket_Size_T'First .. pack.Pocket_Size loop + if Char_Idx = Backpack_Pocket_T'First or else + not Exists (pack.Pocket_A_Content (Char_Idx), pack.Pocket_A_Content, Char_Idx - 1) then + + if Exists (pack.Pocket_A_Content (Char_Idx), pack.Pocket_B_Content, pack.Pocket_Size) then + Running_Total := Running_Total + Get_Item_Prioirty (pack.Pocket_A_Content (Char_Idx)); + end if; + end if; + + pragma Loop_Variant (Increases => Char_Idx); + pragma Loop_Invariant (Running_Total <= Backpack_Priority_Score_T(Char_Idx) * Max_Item_Priority); + end loop; + + return Running_Total;" +function Exists ( Check_Value : Character; Values : Input_String; Range_Max: Input_Size_T) return Boolean is,"(for some Idx in Backpack_Pocket_T'First .. Range_Max => Values (Idx) = Check_Value); + + begin + Search_Loop : for Char_Idx in Input_String'First .. 2 * Packs(1).Pocket_Size loop + if Char_Idx = Input_String'First or else + not Exists (Packs(1).Pack_Content (Char_Idx), Packs(1).Pack_Content, Char_Idx - 1) then + + if Exists (Packs(1).Pack_Content (Char_Idx), Packs(2).Pack_Content, 2 * Packs(2).Pocket_Size) and then + Exists (Packs(1).Pack_Content (Char_Idx), Packs(3).Pack_Content, 2 * Packs(3).Pocket_Size) then + Running_Total := Running_Total + Get_Item_Prioirty (Packs(1).Pack_Content (Char_Idx)); + exit Search_Loop when True; + end if; + end if; + + pragma Loop_Variant (Increases => Char_Idx); + pragma Loop_Invariant (Running_Total <= Max_Item_Priority); + end loop Search_Loop; + + return Running_Total;" +procedure Stack_Init is,"begin + for i in Stack_Row_Index'Range loop + for j in Stack_Column_Index'Range loop + Crate_Stack(i, j) := '-'; + end loop; + end loop;" +"function Convert is new Ada.Unchecked_Conversion (Void_Ptr, chars_ptr);","Message : constant String_List := Split (Value (Convert (Signal_Data)), Maximum => 4); + + From_User : SU.Unbounded_String renames Message (1); + Primitive : SU.Unbounded_String renames Message (2); + Channel : SU.Unbounded_String renames Message (3); + Text : SU.Unbounded_String renames Message (4); + pragma Assert (Primitive = ""PRIVMSG""); + + Is_Private_Message : constant Boolean := Channel = Nick_Name; + Is_Highlighted : constant Boolean := SU.Index (Text, "":"" & Nick_Name & "": "") > 0; + + Is_Away : constant Boolean := Clock - Last_Key_Press > Away_Duration; + begin + if Is_Private_Message or Is_Highlighted then + if not Is_Away then + Play_Async (Sound_Message); + Play_Async (Sound_Message_Highlight); + else + Is_Highlighted_While_Away := True; + + if Seconds (Clock) in Office_Hour_Start .. Office_Hour_End then + if Reminder_Timer /= No_Timer then + Cancel_Timer (Reminder_Timer); + Reminder_Timer := No_Timer; + end if; + Play_Async (Sound_Message_Highlight_Away); + else + declare + Current_Time : constant Time := Clock; + Wake_Up_Date : constant Time := Current_Time - Seconds (Current_Time) + + (if Seconds (Clock) >= Office_Hour_End then Day_Duration'Last else 0.0) + + Office_Hour_Start; + + In_Time : constant Duration := Wake_Up_Date - Current_Time; + Sender : constant String := Get_Nick (Host => +From_User); + begin + if Reminder_Timer = No_Timer then + Reminder_Timer := Set_Timer + (Plugin, In_Time, 60, 1, Reminder_First_Call_Handler'Access); + + Send_Message + (Plugin, +Server_Name, + (if Is_Private_Message then Sender else +Channel), + (if Is_Private_Message then """" else Sender & "": "") & + ""I'm currently away since "" & Image_Date (Last_Key_Press) & + "". I will try to notify myself in about "" & + Image_Time (In_Time) & "" hours""); + end if;" +procedure Main is,"procedure del_int(obj: Integer) is + begin + null; + end del_int; + + package Integer_List is new lists(Integer,Integer'Image,""="",del_int); + use Integer_List; + + + procedure Test_List_Package(L1:in out List) is + begin + Put_Line(""Image: "" & L1.Image); + Put_Line(Integer'Image(L1.Index(2))); + Put_Line(""Length: "" & Integer'Image(L1.Length)); + Put_Line(Boolean'Image(L1 = L1)); + begin + Put_Line(""Get 3rd item: "" & Integer'Image(L1.get(3))); + + exception + when Get_Index_Value_Outside_the_list => + Put_Line(""Index_Get_Value_Outside_the_list"");" +procedure finalize_library is,"begin + E006 := E006 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__text_io__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""system__file_io__finalize_body""); + begin + E109 := E109 - 1; + F2;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (C, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Leap_Seconds_Support : Integer; + pragma Import (C, Leap_Seconds_Support, ""__gl_leap_seconds_support""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 0; + Default_Stack_Size := -1; + Leap_Seconds_Support := 0; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E025 := E025 + 1; + Ada.Io_Exceptions'Elab_Spec; + E068 := E068 + 1; + Ada.Strings'Elab_Spec; + E052 := E052 + 1; + Ada.Containers'Elab_Spec; + E040 := E040 + 1; + System.Exceptions'Elab_Spec; + E027 := E027 + 1; + Interfaces.C'Elab_Spec; + System.Os_Lib'Elab_Body; + E072 := E072 + 1; + Ada.Strings.Maps'Elab_Spec; + Ada.Strings.Maps.Constants'Elab_Spec; + E058 := E058 + 1; + System.Soft_Links.Initialize'Elab_Body; + E021 := E021 + 1; + E013 := E013 + 1; + System.Object_Reader'Elab_Spec; + System.Dwarf_Lines'Elab_Spec; + E047 := E047 + 1; + E078 := E078 + 1; + E054 := E054 + 1; + System.Traceback.Symbolic'Elab_Body; + E039 := E039 + 1; + E080 := E080 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E101 := E101 + 1; + Ada.Streams'Elab_Spec; + E099 := E099 + 1; + System.File_Control_Block'Elab_Spec; + E113 := E113 + 1; + System.Finalization_Root'Elab_Spec; + E112 := E112 + 1; + Ada.Finalization'Elab_Spec; + E110 := E110 + 1; + System.File_Io'Elab_Body; + E109 := E109 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E006 := E006 + 1; + E115 := E115 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + gnat_argc := argc; + gnat_argv := argv; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure Main is,"type Common_Axis_Type is range 0..20; + type Common_Button_Type is range 0..20; + package LJS is new Linux_Joystick(Button_Type => Common_Button_Type, + Axis_Type => Common_Axis_Type); + + generic + with package JSP is new Linux_Joystick (<>); + procedure Put(Js_Event : in JSP.Js_Event_Type); + + procedure Put(Js_Event : in JSP.Js_Event_Type) is + + package Millisecinds_IO is new Text_IO.Integer_IO(JSP.Milliseconds_Type); + package Value_IO is new Text_IO.Integer_IO(JSP.Value_Type); + + begin + Text_IO.Put(if Js_Event.Is_Init_Event then ""I"" else "" ""); + Text_IO.Put(Ada.Characters.Latin_1.HT); + + Millisecinds_IO.Put(Js_Event.Time); + Text_IO.Put(Ada.Characters.Latin_1.HT); + + Text_IO.Put(JSP.Event_Type_Type'Image(Js_Event.Event_Type)); + Text_IO.Put(Ada.Characters.Latin_1.HT); + + case Js_Event.Event_Type is + when JSP.JS_EVENT_BUTTON => + Text_IO.Put(JSP.Button_Type'Image(Js_Event.Button)); + Text_IO.Put(Ada.Characters.Latin_1.HT); + + Text_IO.Put(JSP.Button_Action_Type'Image(Js_Event.Button_Action)); + + when JSP.JS_EVENT_AXIS => + + Text_IO.Put(JSP.Axis_Type'Image(Js_Event.Axis)); + Text_IO.Put(Ada.Characters.Latin_1.HT); + + Value_IO.Put(Js_Event.Value); + end case; + + Text_IO.New_Line;" +procedure Put_LJS is new Put(LJS);,"begin + + declare + -- It is also possible to use Open without parameters, it will automatically locate + -- an available ""js*"" file. + -- + Opended_Device_Path : String := ""/dev/input/js1""; + + begin + LJS.Open(Opended_Device_Path); + Text_IO.Put_Line(""Opended device at: "" & Opended_Device_Path); + + loop + declare + Js_Event : LJS.Js_Event_Type := LJS.Read; + begin + Put_LJS(Js_Event);" +procedure Close is,"begin + SIO.Close(Input_File);" +procedure Demo is,"function Pad (S : String; Len : Positive) return String is + (S & (1 .. Len - S'Length => ' ')); + + procedure Title (Text : String) is + begin + New_Line; + Put_Line (Style_Wrap (Text => ""=== "" & Text & ""==="", + Style => Bright)); + end Title; +begin + Put_Line (Reset_All); + + Title (""BASIC COLOR TEST""); + -- Named color tests: best seen in a 96-column term + for Fg in Colors'Range loop + for Bg in Colors'Range loop + if Fg /= Bg then + Put (Color_Wrap (Text => Fg'Img & "" on "" & Bg'Img, + Foreground => Foreground (Fg), + Background => Background (Bg))); + end if; + end loop; + end loop; + New_Line; + + Title (""PALETTE COLOR TEST (subsample)""); + declare + Palette : constant array (Positive range <>) of Palette_RGB := + (0, 1, 3, 5); + begin + for R of Palette loop + for G of Palette loop + for B of Palette loop + for BR of Palette loop + for BG of Palette loop + for BB of Palette loop + Put (Color_Wrap + (Text => ""X"", + Foreground => Palette_Fg (R, G, B), + Background => Palette_Bg (BR, BG, BB))); + end loop; + end loop; + end loop; + end loop; + end loop; + end loop; + New_Line;" +procedure Reset_Board is,"begin -- Reset_Board + for I of Our_Board loop + I := (others=>Empty_Piece); + end loop; + + for I of Our_Board(Position'First + 1) loop + I := Player_1_Pawn; + end loop; + Our_Board(Position'First) := Starting_Backrow_Order(1); + + for I of Our_Board(Position'Last - 1) loop + I := Player_2_Pawn; + end loop; + Our_Board(Position'Last) := Starting_Backrow_Order(2); + + King_Status(0) := (X=>3, Y=>0); + King_Status(1) := (X=>3, Y=>7); + Last_Moved := (0, 0); + + end Reset_Board; + + procedure Print_Board is + Small_String : String(1..6); + begin -- Print_Board + Clear; + Attribute_On(1); + Pretty_Print_Line_Window(Owner_Type'Image(Owner_Type'Val(Turn))); + for I in reverse Our_Board'Range loop + Pretty_Print_Line_Window("" -------------------------------------------------------------------------""); + Pretty_Print_Line_Window("" | | | | | | | | | ""); + Pretty_Print_Window(Integer'Image(Integer(I) + 1) & "" | ""); + for J of Our_Board(I) loop + if J /= Empty_Piece then + if J.Owner = Player_1 then + Attribute_On(2); + end if; + Put(To=>Small_String, Item=>J.Name); + Pretty_Print_Window(Small_String); + Attribute_On(1); + else + Pretty_Print_Window("" ""); + end if; + Pretty_Print_Window("" | ""); + end loop; + Pretty_Print_Line_Window(ASCII.lf & "" | | | | | | | | | ""); + end loop; + Pretty_Print_Line_Window("" -------------------------------------------------------------------------""); + Pretty_Print_Line_Window("" A B C D E F G H ""); + Refresh; + end Print_Board; + + procedure Move (From, To : in Cordinate_Type) is + begin -- Move + + if Our_Board(From.Y)(From.X).Owner /= Owner_Type'Val(Turn) then -- check if it's their piece + raise Not_Allowed; + end if; + + case Our_Board(From.Y)(From.X).Name is + -- check to see if move if possible + when Pawn => --since the pawn move logic is so complex, it's best to do it all here + declare + Turn_Test : Integer; + function ""+"" (Left: in Position; Right : in Integer) return Position is + (Position(Integer(Left) + Right)); + begin + Turn_Test := (if Turn = 0 then -1 else 1); + + if Integer(From.X - To.X) = 0 then -- advance + if Our_Board(To.Y)(To.X).Owner = None and -- can't attack forward + then (Integer(From.Y - To.Y) = Turn_Test or (Integer(From.Y - To.Y) = Turn_Test*2 and Our_Board(From.Y)(From.X).Has_Moved = No and Our_Board(To.Y + Turn_Test)(To.X).Owner = None)) then --check if move is valid + Take_Space(From, To); + else + raise Not_Allowed; + end if; + elsif Integer(From.X - To.X) in -1..1 then -- attack move + if Integer(From.Y - To.Y) = Turn_Test then --check if move is valid + if Our_Board(To.Y)(To.X).Owner /= None then + Take_Space(From, To); + elsif Our_Board(Last_Moved.Y)(Last_Moved.X).Name = Pawn and -- en passent + then Last_Moved = (X=>To.X, Y=>To.Y + Turn_Test) then + Our_Board(Last_Moved.Y)(Last_Moved.X) := Empty_Piece; + Take_Space(From, To); + else + raise Not_Allowed; + end if; + else + raise Not_Allowed; + end if; + else + raise Not_Allowed; + end if;" +procedure Chess is,"-- pragma Suppress(All_Checks); + + type Game_Options is (None, Network, Local); + + procedure Print_and_Clear (Item : in String) with Inline is + begin + Attribute_On(3); + Pretty_Print_Line_Window(Item); + Refresh; + delay 1.0; + Print_Board; + end Print_and_Clear; + + Player_Select_Request : Cordinate_Type; + Player_Move_Request : Cordinate_Type; + Temp : Byte; + Game_Status : Game_Options := None; + Port : Port_Type := 0; + Is_Host : Boolean := False; + -- Address_String : String (1..15) := (others=>' '); + Address_String : String := ""192.168.1.53""; + + Client : Socket_Type; + Address : Sock_Addr_Type; + Channel : Stream_Access; + + Receiver : Socket_Type; + Connection : Socket_Type; + + Initial_Move : Boolean := True; + +begin + + loop + case Getopt (""l n h p: i:"") is + when 'l' => + if Game_Status = None then + Game_Status := Local; + else + Ada.Text_IO.Put_Line(""Conflicting agument : '-l'""); + return; + end if; + when 'n' => + if Game_Status = None then + Game_Status := Network; + else + Ada.Text_IO.Put_Line(""Conflicting agument : '-n'""); + return; + end if; + when 'p' => + Port := Port_Type'Value(Parameter); + when 'h' => + Is_Host := True; + when 'i' => + Move(Parameter, Address_String); + when others => + exit; + end case; + end loop; + + if Game_Status = Network then + if (Port = 0 or Address_String = 15*' ') then + Ada.Text_IO.Put_Line(""Argument Error""); + return; + end if; + if Is_Host then + Create_Socket (Receiver); + Set_Socket_Option + (Socket => Receiver, + Option => (Name=>Reuse_Address, Enabled => True)); + Bind_Socket + (Socket => Receiver, + Address => (Family=>Family_Inet, + Addr=>Inet_Addr (Address_String), + Port=>Port)); + Listen_Socket (Socket => Receiver); + Accept_Socket + (Server => Receiver, + Socket => Connection, + Address => Address); + -- Put_Line(""Client connected from "" & Image (Address)); + Channel := Stream (Connection); + else + Create_Socket (Client); + Address.Addr := Inet_Addr(Address_String); + Address.Port := Port; + + Connect_Socket (Client, Address); + Channel := Stream (Client); + + end if; + end if; + + + Init_Scr; + Start_Color_Init; + Reset_Board; + Print_Board; + + Game_Loop : loop + if Initial_Move then + Initial_Move := False; + if Is_Host then + goto HOST_START; + end if; + end if; + + Wait_For_Input : loop + begin + if Game_Status = Network then + Get_Variables(Channel); + end if; + Print_Board; + if Is_Winner in 1..2 then + Print_and_Clear(""Player"" & Integer'Image(Is_Winner) & "" is the winner""); + goto FINISH; + end if; + exit; + exception + when others => Print_Board;" +procedure Free is,"new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, + Name => AWA.Users.Principals.Principal_Access); + + -- ------------------------------ + -- Initialize the service context. + -- ------------------------------ + procedure Initialize (Principal : in out Test_User) is + begin + -- Setup the service context. + Principal.Context.Set_Context (AWA.Tests.Get_Application, null); + + if Principal.Manager = null then + Principal.Manager := AWA.Users.Modules.Get_User_Manager; + if Principal.Manager = null then + Log.Error (""There is no User_Manager in the application.""); + end if; + end if; + end Initialize; + + -- ------------------------------ + -- Create a test user associated with the given email address. + -- Get an open session for that user. If the user already exists, no error is reported. + -- ------------------------------ + procedure Create_User (Principal : in out Test_User; + Email : in String) is + DB : ADO.Sessions.Session; + Query : ADO.SQL.Query; + Found : Boolean; + Key : AWA.Users.Models.Access_Key_Ref; + begin + Initialize (Principal); + + DB := Principal.Manager.Get_Session; + + -- Find the user + Query.Set_Join (""inner join awa_email e on e.user_id = o.id""); + Query.Set_Filter (""e.email = ?""); + Query.Bind_Param (1, Email); + Principal.User.Find (DB, Query, Found); + if not Found then + Principal.User.Set_First_Name (""Joe""); + Principal.User.Set_Last_Name (""Pot""); + Principal.User.Set_Password (""admin""); + Principal.Email.Set_Email (Email); + Principal.Manager.Create_User (Principal.User, Principal.Email); + + Find_Access_Key (Principal, Email, Key); + + -- Run the verification and get the user and its session + Principal.Manager.Verify_User (Key.Get_Access_Key, ""192.168.1.1"", + Principal.Principal); + else + Principal.Manager.Authenticate (Email => Email, + Password => ""admin"", + IpAddr => ""192.168.1.1"", + Principal => Principal.Principal); + end if; + Principal.User := Principal.Principal.Get_User; + Principal.Session := Principal.Principal.Get_Session; + end Create_User; + + -- ------------------------------ + -- Create a test user for a new test and get an open session. + -- ------------------------------ + procedure Create_User (Principal : in out Test_User) is + Key : AWA.Users.Models.Access_Key_Ref; + Email : constant String := ""Joe-"" & Util.Tests.Get_Uuid & ""@gmail.com""; + begin + Initialize (Principal); + Principal.User.Set_First_Name (""Joe""); + Principal.User.Set_Last_Name (""Pot""); + Principal.User.Set_Password (""admin""); + Principal.Email.Set_Email (Email); + Principal.Manager.Create_User (Principal.User, Principal.Email); + + Find_Access_Key (Principal, Email, Key); + + -- Run the verification and get the user and its session + Principal.Manager.Verify_User (Key.Get_Access_Key, ""192.168.1.1"", + Principal.Principal); + Principal.User := Principal.Principal.Get_User; + Principal.Session := Principal.Principal.Get_Session; + end Create_User; + + -- ------------------------------ + -- Find the access key associated with a user (if any). + -- ------------------------------ + procedure Find_Access_Key (Principal : in out Test_User; + Email : in String; + Key : in out AWA.Users.Models.Access_Key_Ref) is + DB : ADO.Sessions.Session; + Query : ADO.SQL.Query; + Found : Boolean; + Signup_Kind : constant Integer + := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.SIGNUP_KEY); + Password_Kind : constant Integer + := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.RESET_PASSWORD_KEY); + begin + Initialize (Principal); + + DB := Principal.Manager.Get_Session; + + -- Find the access key + Query.Set_Join (""inner join awa_email e on e.user_id = o.user_id""); + Query.Set_Filter (""e.email = ? AND o.kind = ?""); + Query.Bind_Param (1, Email); + Query.Bind_Param (2, Signup_Kind); + Key.Find (DB, Query, Found); + if not Found then + Query.Bind_Param (2, Password_Kind); + Key.Find (DB, Query, Found); + if not Found then + Log.Error (""Cannot find access key for email {0}"", Email); + end if; + end if; + end Find_Access_Key; + + -- ------------------------------ + -- Login a user and create a session + -- ------------------------------ + procedure Login (Principal : in out Test_User) is + begin + Initialize (Principal); + Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, + Password => ""admin"", + IpAddr => ""192.168.1.1"", + Principal => Principal.Principal); + Principal.User := Principal.Principal.Get_User; + Principal.Session := Principal.Principal.Get_Session; + end Login; + + -- ------------------------------ + -- Logout the user and closes the current session. + -- ------------------------------ + procedure Logout (Principal : in out Test_User) is + begin + Initialize (Principal); + Principal.Manager.Close_Session (Principal.Session.Get_Id, True); + end Logout; + + -- ------------------------------ + -- Simulate a user login in the given service context. + -- ------------------------------ + procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class; + Sec_Context : in out Security.Contexts.Security_Context; + Email : in String) is + User : Test_User; + Principal : AWA.Users.Principals.Principal_Access; + App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; + begin + AWA.Tests.Set_Application_Context; + Create_User (User, Email); + Principal := AWA.Users.Principals.Create (User.User, User.Session); + Context.Set_Context (App, Principal); + Sec_Context.Set_Context (Manager => App.Get_Security_Manager, + Principal => Principal.all'Access); + + -- Keep track of the Principal instance so that Tear_Down will release it. + -- Most tests will call Login but don't call Logout because there is no real purpose + -- for the test in doing that and it allows to keep the unit test simple. This creates + -- memory leak because the Principal instance is not freed. + for I in Logged_Users'Range loop + if Logged_Users (I) = null then + Logged_Users (I) := Principal; + exit; + end if; + end loop; + end Login; + + -- ------------------------------ + -- Simulate a user login on the request. Upon successful login, a session that is + -- authentified is associated with the request object. + -- ------------------------------ + procedure Login (Email : in String; + Request : in out ASF.Requests.Mockup.Request) is + User : Test_User; + Reply : ASF.Responses.Mockup.Response; + begin + Create_User (User, Email); + ASF.Tests.Do_Get (Request, Reply, ""/auth/login.html"", ""login-user-1.html""); + + Request.Set_Parameter (""email"", Email); + Request.Set_Parameter (""password"", ""admin""); + Request.Set_Parameter (""login"", ""1""); + Request.Set_Parameter (""login-button"", ""1""); + ASF.Tests.Do_Post (Request, Reply, ""/auth/login.html"", ""login-user-2.html""); + end Login; + + -- ------------------------------ + -- Setup the context and security context to simulate an anonymous user. + -- ------------------------------ + procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class; + Sec_Context : in out Security.Contexts.Security_Context) is + App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; + begin + AWA.Tests.Set_Application_Context; + Context.Set_Context (App, null); + Sec_Context.Set_Context (Manager => App.Get_Security_Manager, + Principal => null); + end Anonymous; + + -- ------------------------------ + -- Simulate the recovery password process for the given user. + -- ------------------------------ + procedure Recover_Password (Email : in String) is + use type ASF.Principals.Principal_Access; + + Request : ASF.Requests.Mockup.Request; + Reply : ASF.Responses.Mockup.Response; + begin + Request.Set_Parameter (""email"", Email); + Request.Set_Parameter (""lost-password"", ""1""); + Request.Set_Parameter (""lost-password-button"", ""1""); + ASF.Tests.Do_Post (Request, Reply, ""/auth/lost-password.html"", ""lost-password-2.html""); + + if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then + Log.Error (""Invalid redirect after lost password""); + end if; + + -- Now, get the access key and simulate a click on the reset password link. + declare + Principal : AWA.Tests.Helpers.Users.Test_User; + Key : AWA.Users.Models.Access_Key_Ref; + begin + AWA.Tests.Set_Application_Context; + AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); + if not Key.Is_Null then + Log.Error (""There is no access key associated with the user""); + end if; + + -- Simulate user clicking on the reset password link. + -- This verifies the key, login the user and redirect him to the change-password page + Request.Set_Parameter (""key"", Key.Get_Access_Key); + Request.Set_Parameter (""password"", ""admin""); + Request.Set_Parameter (""reset-password"", ""1""); + ASF.Tests.Do_Post (Request, Reply, ""/auth/change-password.html"", ""reset-password-2.html""); + + if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then + Log.Error (""Invalid response""); + end if; + + -- Check that the user is logged and we have a user principal now. + if Request.Get_User_Principal = null then + Log.Error (""A user principal should be defined""); + end if;" +"function Get is new AWA.Modules.Get (Tag_Module, Tag_Module_Access, NAME);","begin + return Get; + end Get_Tag_Module; + + -- ------------------------------ + -- Add a tag on the database entity referenced by Id in the table identified + -- by Entity_Type. The permission represented by Permission is checked + -- to make sure the current user can add the tag. If the permission is granted, the + -- tag represented by Tag is associated with the said database entity. + -- ------------------------------ + procedure Add_Tag (Model : in Tag_Module; + Id : in ADO.Identifier; + Entity_Type : in String; + Permission : in String; + Tag : in String) is + pragma Unreferenced (Model); + + Ctx : constant ASC.Service_Context_Access := ASC.Current; + User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; + Ident : constant String := Entity_Type & ADO.Identifier'Image (Id); + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + Kind : ADO.Entity_Type; + begin + -- Check that the user has the permission on the given object. + AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), + Entity => Id); + + Log.Info (""User {0} add tag {1} on {2}"", + ADO.Identifier'Image (User.Get_Id), Tag, Ident); + + Ctx.Start; + Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); + Add_Tag (DB, Id, Kind, Tag); + Ctx.Commit; + end Add_Tag; + + -- ------------------------------ + -- Remove the tag identified by Tag and associated with the database entity + -- referenced by Id in the table identified by Entity_Type. + -- The permission represented by Permission is checked to make sure the current user + -- can remove the tag. + -- ------------------------------ + procedure Remove_Tag (Model : in Tag_Module; + Id : in ADO.Identifier; + Entity_Type : in String; + Permission : in String; + Tag : in String) is + pragma Unreferenced (Model); + + Ctx : constant ASC.Service_Context_Access := ASC.Current; + User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; + Ident : constant String := Entity_Type & ADO.Identifier'Image (Id); + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + Kind : ADO.Entity_Type; + begin + -- Check that the user has the permission on the given object. + AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), + Entity => Id); + + Log.Info (""User {0} removes tag {1} on {2}"", + ADO.Identifier'Image (User.Get_Id), Tag, Ident); + + Ctx.Start; + Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); + Remove_Tag (DB, Id, Kind, Tag); + Ctx.Commit; + end Remove_Tag; + + -- ------------------------------ + -- Remove the tags defined by the Deleted tag list and add the tags defined + -- in the Added tag list. The tags are associated with the database entity + -- referenced by Id in the table identified by Entity_Type. + -- The permission represented by Permission is checked to make sure the current user + -- can remove or add the tag. + -- ------------------------------ + procedure Update_Tags (Model : in Tag_Module; + Id : in ADO.Identifier; + Entity_Type : in String; + Permission : in String; + Added : in Util.Strings.Vectors.Vector; + Deleted : in Util.Strings.Vectors.Vector) is + pragma Unreferenced (Model); + + Ctx : constant ASC.Service_Context_Access := ASC.Current; + User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; + Ident : constant String := Entity_Type & ADO.Identifier'Image (Id); + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + Kind : ADO.Entity_Type; + Iter : Util.Strings.Vectors.Cursor; + begin + -- Check that the user has the permission on the given object. + AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), + Entity => Id); + + Ctx.Start; + Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); + + -- Delete the tags that have been removed. + Iter := Deleted.First; + while Util.Strings.Vectors.Has_Element (Iter) loop + declare + Tag : constant String := Util.Strings.Vectors.Element (Iter); + begin + Log.Info (""User {0} removes tag {1} on {2}"", + ADO.Identifier'Image (User.Get_Id), Tag, Ident); + + Remove_Tag (DB, Id, Kind, Tag);" +procedure Set_Permission (Into : in out Tag_List_Bean;,"Permission : in String) is + begin + Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); + end Set_Permission; + + -- ------------------------------ + -- Load the tags associated with the given database identifier. + -- ------------------------------ + procedure Load_Tags (Into : in out Tag_List_Bean; + Session : in ADO.Sessions.Session; + For_Entity_Id : in ADO.Identifier) is + use ADO.Sessions.Entities; + + Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); + Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); + Query : ADO.Queries.Context; + begin + Query.Set_Query (AWA.Tags.Models.Query_Tag_List); + Query.Bind_Param (""entity_type"", Kind); + Query.Bind_Param (""entity_id"", For_Entity_Id); + declare + Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); + begin + Stmt.Execute; + + while Stmt.Has_Elements loop + Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); + Stmt.Next; + end loop;" +function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access),"return Util.Beans.Basic.Readonly_Bean_Access is + Result : constant Tag_List_Bean_Access := new Tag_List_Bean; + begin + Result.Module := Module; + return Result.all'Access; + end Create_Tag_List_Bean; + + -- ------------------------------ + -- Search the tags that match the search string. + -- ------------------------------ + procedure Search_Tags (Into : in out Tag_Search_Bean; + Session : in ADO.Sessions.Session; + Search : in String) is + use ADO.Sessions.Entities; + + Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); + Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); + Query : ADO.Queries.Context; + begin + Query.Set_Query (AWA.Tags.Models.Query_Tag_Search); + Query.Bind_Param (""entity_type"", Kind); + Query.Bind_Param (""search"", Search & ""%""); + declare + Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); + begin + Stmt.Execute; + + while Stmt.Has_Elements loop + Into.List.Append (Util.Beans.Objects.To_Object (Stmt.Get_String (0))); + Stmt.Next; + end loop;" +function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access),"return Util.Beans.Basic.Readonly_Bean_Access is + Result : constant Tag_Info_List_Bean_Access := new Tag_Info_List_Bean; + begin + Result.Module := Module; + return Result.all'Access; + end Create_Tag_Info_List_Bean; + + -- ------------------------------ + -- Get the list of tags associated with the given entity. + -- Returns null if the entity does not have any tag. + -- ------------------------------ + function Get_Tags (From : in Entity_Tag_Map; + For_Entity : in ADO.Identifier) + return Util.Beans.Lists.Strings.List_Bean_Access is + Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity); + begin + if Entity_Tag_Maps.Has_Element (Pos) then + return Entity_Tag_Maps.Element (Pos); + else + return null; + end if; + end Get_Tags; + + -- ------------------------------ + -- Get the list of tags associated with the given entity. + -- Returns a null object if the entity does not have any tag. + -- ------------------------------ + function Get_Tags (From : in Entity_Tag_Map; + For_Entity : in ADO.Identifier) + return Util.Beans.Objects.Object is + Pos : constant Entity_Tag_Maps.Cursor := From.Tags.Find (For_Entity); + begin + if Entity_Tag_Maps.Has_Element (Pos) then + return Util.Beans.Objects.To_Object (Value => Entity_Tag_Maps.Element (Pos).all'Access, + Storage => Util.Beans.Objects.STATIC); + else + return Util.Beans.Objects.Null_Object; + end if; + end Get_Tags; + + -- ------------------------------ + -- Load the list of tags associated with a list of entities. + -- ------------------------------ + procedure Load_Tags (Into : in out Entity_Tag_Map; + Session : in out ADO.Sessions.Session'Class; + Entity_Type : in String; + List : in ADO.Utils.Identifier_Vector) is + Query : ADO.Queries.Context; + Kind : ADO.Entity_Type; + begin + Into.Clear; + if List.Is_Empty then + return; + end if; + Kind := ADO.Sessions.Entities.Find_Entity_Type (Session, Entity_Type); + Query.Set_Query (AWA.Tags.Models.Query_Tag_List_For_Entities); + Query.Bind_Param (""entity_id_list"", List); + Query.Bind_Param (""entity_type"", Kind); + declare + Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); + Id : ADO.Identifier; + List : Util.Beans.Lists.Strings.List_Bean_Access; + Pos : Entity_Tag_Maps.Cursor; + begin + Stmt.Execute; + while Stmt.Has_Elements loop + Id := Stmt.Get_Identifier (0); + Pos := Into.Tags.Find (Id); + if not Entity_Tag_Maps.Has_Element (Pos) then + List := new Util.Beans.Lists.Strings.List_Bean; + Into.Tags.Insert (Id, List); + else + List := Entity_Tag_Maps.Element (Pos); + end if; + List.List.Append (Stmt.Get_String (1)); + Stmt.Next; + end loop;" +procedure Dispatch (List : in out Tag_Info_Array);,"-- ------------------------------ + -- Create an Tag_UIInput component + -- ------------------------------ + function Create_Tag return ASF.Components.Base.UIComponent_Access is + begin + return new Tag_UIInput; + end Create_Tag; + + -- ------------------------------ + -- Create an Tag_UICloud component + -- ------------------------------ + function Create_Cloud return ASF.Components.Base.UIComponent_Access is + begin + return new Tag_UICloud; + end Create_Cloud; + + URI : aliased constant String := ""http://code.google.com/p/ada-awa/jsf""; + TAG_LIST_TAG : aliased constant String := ""tagList""; + TAG_CLOUD_TAG : aliased constant String := ""tagCloud""; + + AWA_Bindings : aliased constant ASF.Factory.Binding_Array + := (1 => (Name => TAG_CLOUD_TAG'Access, + Component => Create_Cloud'Access, + Tag => ASF.Views.Nodes.Create_Component_Node'Access), + 2 => (Name => TAG_LIST_TAG'Access, + Component => Create_Tag'Access, + Tag => ASF.Views.Nodes.Create_Component_Node'Access) + ); + + AWA_Factory : aliased constant ASF.Factory.Factory_Bindings + := (URI => URI'Access, Bindings => AWA_Bindings'Access); + + -- ------------------------------ + -- Get the Tags component factory. + -- ------------------------------ + function Definition return ASF.Factory.Factory_Bindings_Access is + begin + return AWA_Factory'Access; + end Definition; + + -- ------------------------------ + -- Returns True if the tag component must be rendered as readonly. + -- ------------------------------ + function Is_Readonly (UI : in Tag_UIInput; + Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is + pragma Unreferenced (Context); + use type ASF.Components.Html.Forms.UIForm_Access; + begin + return UI.Get_Form = null; + end Is_Readonly; + + -- ------------------------------ + -- Render the javascript to enable the tag edition. + -- ------------------------------ + procedure Render_Script (UI : in Tag_UIInput; + Id : in String; + Writer : in Response_Writer_Access; + Context : in out ASF.Contexts.Faces.Faces_Context'Class) is + Auto_Complete : constant String := UI.Get_Attribute (""autoCompleteUrl"", Context); + Allow_Edit : constant Boolean := UI.Get_Attribute (""allowEdit"", Context); + begin + Writer.Queue_Script (""$('#""); + Writer.Queue_Script (Id); + Writer.Queue_Script ("" input').tagedit({""); + Writer.Queue_Script (""allowEdit: ""); + if Allow_Edit then + Writer.Queue_Script (""true""); + else + Writer.Queue_Script (""false""); + end if; + if Auto_Complete'Length > 0 then + Writer.Queue_Script ("", autocompleteURL: '""); + Writer.Queue_Script (Auto_Complete); + Writer.Queue_Script (""'""); + end if; + Writer.Queue_Script (""});""); + end Render_Script; + + -- ------------------------------ + -- Get the tag after convertion with the optional converter. + -- ------------------------------ + function Get_Tag (UI : in Tag_UIInput; + Tag : in Util.Beans.Objects.Object; + Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is + begin + if not Util.Beans.Objects.Is_Null (Tag) then + declare + Convert : constant access ASF.Converters.Converter'Class + := Tag_UIInput'Class (UI).Get_Converter; + begin + if Convert /= null then + return Convert.To_String (Value => Tag, + Component => UI, + Context => Context); + else + return Util.Beans.Objects.To_String (Value => Tag); + end if;" +procedure Dispatch (List : in out Tag_Info_Array) is,"Middle : constant Natural := List'First + List'Length / 2; + Quarter : Natural := List'Length / 4; + Target : Natural := Middle; + Pos : Natural := 0; + begin + while Target <= List'Last and List'First + Pos < Middle and Quarter /= 0 loop + Swap (List (List'First + Pos), List (Target)); + Pos := Pos + 1; + if Target <= Middle then + Target := List'Last - Quarter; + else + Target := List'First + Quarter; + Quarter := Quarter / 2; + end if; + end loop; + end Dispatch; + + -- ------------------------------ + -- Render the tag cloud component. + -- ------------------------------ + overriding + procedure Encode_Children (UI : in Tag_UICloud; + Context : in out ASF.Contexts.Faces.Faces_Context'Class) is + + procedure Free is + new Ada.Unchecked_Deallocation (Object => Tag_Info_Array, + Name => Tag_Info_Array_Access); + + Table : Tag_Info_Array_Access := null; + begin + if not UI.Is_Rendered (Context) then + return; + end if; + + declare + use type Util.Beans.Basic.List_Bean_Access; + + Max : constant Integer := UI.Get_Attribute (""rows"", Context, 1000); + Layout : constant String := UI.Get_Attribute (""layout"", Context); + Bean : constant Util.Beans.Basic.List_Bean_Access + := ASF.Components.Utils.Get_List_Bean (UI, ""value"", Context); + Count : Natural; + Tags : AWA.Tags.Beans.Tag_Ordered_Sets.Set; + List : AWA.Tags.Beans.Tag_Info_List_Bean_Access; + begin + -- Check that we have a List_Bean but do not complain if we have a null value. + if Bean = null or Max <= 0 then + return; + end if; + + if not (Bean.all in AWA.Tags.Beans.Tag_Info_List_Bean'Class) then + ASF.Components.Base.Log_Error (UI, ""Invalid tag list bean: it does not "" + & ""implement 'Tag_Info_List_Bean' interface""); + return; + end if; + + List := AWA.Tags.Beans.Tag_Info_List_Bean'Class (Bean.all)'Unchecked_Access; + Count := List.Get_Count; + if Count = 0 then + return; + end if; + + -- Pass 1: Collect the tags and keep the most used. + for I in 1 .. Count loop + Tags.Insert (List.List.Element (I - 1)); + if Integer (Tags.Length) > Max then + Tags.Delete_Last; + end if; + end loop; + + Count := Natural (Tags.Length); + Table := new Tag_Info_Array (1 .. Count); + for I in 1 .. Count loop + Table (I) := Tags.First_Element; + Tags.Delete_First; + end loop; + + -- Pass 2: Assign weight to each tag. + UI.Compute_Cloud_Weight (Table.all, Context); + + -- Pass 3: Dispatch the tags using some layout algorithm. + if Layout = ""dispatch"" then + Dispatch (Table.all); + end if; + + -- Pass 4: Render each tag. + UI.Render_Cloud (Table.all, Context); + + Free (Table); + + exception + when others => + Free (Table); + raise;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Tag_Impl, Tag_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Tag_Impl_Ptr := Tag_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Tag_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, TAG_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Tag_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Tag_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (TAG_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure List (Object : in out Tag_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, TAG_DEF'Access); + begin + Stmt.Execute; + Tag_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Tag_Ref; + Impl : constant Tag_Access := new Tag_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Tagged_Entity_Impl, Tagged_Entity_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Tagged_Entity_Impl_Ptr := Tagged_Entity_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Tagged_Entity_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, TAGGED_ENTITY_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Tagged_Entity_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Tagged_Entity_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (TAGGED_ENTITY_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- for_entity_id + Value => Object.For_Entity_Id); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- entity_type + Value => Object.Entity_Type); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- tag_id + Value => Object.Tag); + Object.Clear_Modified (4); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure List (Object : in out Tagged_Entity_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, TAGGED_ENTITY_DEF'Access); + begin + Stmt.Execute; + Tagged_Entity_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Tagged_Entity_Ref; + Impl : constant Tagged_Entity_Access := new Tagged_Entity_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +function Create_Tag_List_Bean (Module : in Tag_Module_Access),"return AWA.Tags.Beans.Tag_List_Bean_Access; + + procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is + begin + Caller.Add_Test (Suite, ""Test AWA.Tags.Modules.Add_Tag"", + Test_Add_Tag'Access); + Caller.Add_Test (Suite, ""Test AWA.Tags.Modules.Remove_Tag"", + Test_Remove_Tag'Access); + Caller.Add_Test (Suite, ""Test AWA.Tags.Modules.Update_Tags"", + Test_Remove_Tag'Access); + end Add_Tests; + + function Create_Tag_List_Bean (Module : in Tag_Module_Access) + return AWA.Tags.Beans.Tag_List_Bean_Access is + Bean : constant Util.Beans.Basic.Readonly_Bean_Access + := AWA.Tags.Beans.Create_Tag_List_Bean (Module); + begin + return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access; + end Create_Tag_List_Bean; + + -- ------------------------------ + -- Test tag creation. + -- ------------------------------ + procedure Test_Add_Tag (T : in out Test) is + Sec_Ctx : Security.Contexts.Security_Context; + Context : AWA.Services.Contexts.Service_Context; + begin + AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, ""test-add-tag@test.com""); + + declare + Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; + User : constant AWA.Users.Models.User_Ref := Context.Get_User; + List : AWA.Tags.Beans.Tag_List_Bean_Access; + Cleanup : Util.Beans.Objects.Object; + begin + T.Assert (Tag_Manager /= null, ""There is no tag module""); + + List := Create_Tag_List_Bean (Tag_Manager); + Cleanup := Util.Beans.Objects.To_Object (List.all'Access); + List.Set_Value (""entity_type"", Util.Beans.Objects.To_Object (String '(""awa_user""))); + + -- Create a tag. + Tag_Manager.Add_Tag (User.Get_Id, ""awa_user"", ""workspaces-create"", ""user-tag""); + Tag_Manager.Add_Tag (User.Get_Id, ""awa_user"", ""workspaces-create"", ""user-tag""); + + -- Load the list. + List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); + + Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), ""Invalid number of tags""); + T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), ""Cleanup instance is null"");" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Image_Impl, Image_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Image_Impl_Ptr := Image_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Image_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, IMAGE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Image_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Image_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (IMAGE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- width + Value => Object.Width); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- height + Value => Object.Height); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- thumb_width + Value => Object.Thumb_Width); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- thumb_height + Value => Object.Thumb_Height); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- path + Value => Object.Path); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- public + Value => Object.Public); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_1_NAME, -- thumbnail_id + Value => Object.Thumbnail); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_1_NAME, -- folder_id + Value => Object.Folder); + Object.Clear_Modified (10); + end if; + if Object.Is_Modified (11) then + Stmt.Save_Field (Name => COL_10_1_NAME, -- owner_id + Value => Object.Owner); + Object.Clear_Modified (11); + end if; + if Object.Is_Modified (12) then + Stmt.Save_Field (Name => COL_11_1_NAME, -- storage_id + Value => Object.Storage); + Object.Clear_Modified (12); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Image_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, IMAGE_DEF'Access); + begin + Stmt.Execute; + Image_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Image_Ref; + Impl : constant Image_Access := new Image_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +"function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME);","begin + return Get; + end Get_Question_Module; + + -- ------------------------------ + -- Create or save the question. + -- ------------------------------ + procedure Save_Question (Model : in Question_Module; + Question : in out AWA.Questions.Models.Question_Ref'Class) is + pragma Unreferenced (Model); + + function To_Wide (Item : in String) return Wide_Wide_String + renames Ada.Characters.Conversions.To_Wide_Wide_String; + + Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + WS : AWA.Workspaces.Models.Workspace_Ref; + begin + Ctx.Start; + if Question.Is_Inserted then + Log.Info (""Updating question {0}"", ADO.Identifier'Image (Question.Get_Id)); + + WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace); + else + Log.Info (""Creating new question {0}"", String '(Question.Get_Title)); + + AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); + + -- Check that the user has the create permission on the given workspace. + AWA.Permissions.Check (Permission => ACL_Create_Questions.Permission, + Entity => WS); + Question.Set_Workspace (WS); + Question.Set_Author (User); + end if; + + declare + Text : constant String := Wiki.Utils.To_Text (To_Wide (Question.Get_Description), + Wiki.SYNTAX_MIX); + Last : Natural; + begin + if Text'Length < SHORT_DESCRIPTION_LENGTH then + Last := Text'Last; + else + Last := SHORT_DESCRIPTION_LENGTH; + end if; + Question.Set_Short_Description (Text (Text'First .. Last) & ""..."");" +procedure Load_List (Into : in out Question_List_Bean) is,"use AWA.Questions.Models; + use AWA.Services; + use type ADO.Identifier; + + Session : ADO.Sessions.Session := Into.Service.Get_Session; + Query : ADO.Queries.Context; + Tag_Id : ADO.Identifier; + begin + AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); + if Tag_Id /= ADO.NO_IDENTIFIER then + Query.Set_Query (AWA.Questions.Models.Query_Question_Tag_List); + Query.Bind_Param (Name => ""tag"", Value => Tag_Id); + else + Query.Set_Query (AWA.Questions.Models.Query_Question_List); + end if; + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""entity_type"", + Table => AWA.Questions.Models.QUESTION_TABLE, + Session => Session); + AWA.Questions.Models.List (Into.Questions, Session, Query); + declare + List : ADO.Utils.Identifier_Vector; + Iter : Question_Info_Vectors.Cursor := Into.Questions.List.First; + begin + while Question_Info_Vectors.Has_Element (Iter) loop + List.Append (Question_Info_Vectors.Element (Iter).Id); + Question_Info_Vectors.Next (Iter); + end loop; + Into.Tags.Load_Tags (Session, AWA.Questions.Models.QUESTION_TABLE.Table.all, + List);" +function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access),"return Util.Beans.Basic.Readonly_Bean_Access is + use AWA.Questions.Models; + use AWA.Services; + + Object : constant Question_List_Bean_Access := new Question_List_Bean; +-- Session : ADO.Sessions.Session := Module.Get_Session; +-- Query : ADO.Queries.Context; + begin + Object.Service := Module; + Object.Questions_Bean := Object.Questions'Unchecked_Access; +-- Query.Set_Query (AWA.Questions.Models.Query_Question_List); +-- ADO.Sessions.Entities.Bind_Param (Params => Query, +-- Name => ""entity_type"", +-- Table => AWA.Questions.Models.QUESTION_TABLE, +-- Session => Session); +-- AWA.Questions.Models.List (Object.Questions, Session, Query); + Object.Load_List; + return Object.all'Access; + end Create_Question_List_Bean; + + -- ------------------------------ + -- Get the value identified by the name. + -- ------------------------------ + overriding + function Get_Value (From : in Question_Display_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if Name = ""answers"" then + return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, + Storage => Util.Beans.Objects.STATIC); + + elsif Name = ""question"" then + return Util.Beans.Objects.To_Object (Value => From.Question_Bean, + Storage => Util.Beans.Objects.STATIC); + + elsif Name = ""tags"" then + return Util.Beans.Objects.To_Object (Value => From.Tags_Bean, + Storage => Util.Beans.Objects.STATIC); + + else + return Util.Beans.Objects.Null_Object; + end if; + end Get_Value; + + -- ------------------------------ + -- Set the value identified by the name. + -- ------------------------------ + overriding + procedure Set_Value (From : in out Question_Display_Bean; + Name : in String; + Value : in Util.Beans.Objects.Object) is + begin + if Name = ""id"" and not Util.Beans.Objects.Is_Empty (Value) then + declare + package ASC renames AWA.Services.Contexts; + use AWA.Questions.Models; + use AWA.Services; + + Session : ADO.Sessions.Session := From.Service.Get_Session; + Query : ADO.Queries.Context; + List : AWA.Questions.Models.Question_Display_Info_List_Bean; + Ctx : constant ASC.Service_Context_Access := ASC.Current; + Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); + begin + Query.Set_Query (AWA.Questions.Models.Query_Question_Info); + Query.Bind_Param (""question_id"", Id); + Query.Bind_Param (""user_id"", Ctx.Get_User_Identifier); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""entity_type"", + Table => AWA.Questions.Models.QUESTION_TABLE, + Session => Session); + AWA.Questions.Models.List (List, Session, Query); + if not List.List.Is_Empty then + From.Question := List.List.Element (0); + end if; + Query.Clear; + Query.Bind_Param (""question_id"", Util.Beans.Objects.To_Integer (Value)); + Query.Bind_Param (""user_id"", Ctx.Get_User_Identifier); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""entity_type"", + Table => AWA.Questions.Models.ANSWER_TABLE, + Session => Session); + + Query.Set_Query (AWA.Questions.Models.Query_Answer_List); + AWA.Questions.Models.List (From.Answer_List, Session, Query); + + -- Load the tags if any. + From.Tags.Load_Tags (Session, Id);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Question_Impl, Question_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Question_Impl_Ptr := Question_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Question_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, QUESTION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Question_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Question_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (QUESTION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- title + Value => Object.Title); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- description + Value => Object.Description); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- edit_date + Value => Object.Edit_Date); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- short_description + Value => Object.Short_Description); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- rating + Value => Object.Rating); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_1_NAME, -- author_id + Value => Object.Author); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_1_NAME, -- workspace_id + Value => Object.Workspace); + Object.Clear_Modified (10); + end if; + if Object.Is_Modified (11) then + Stmt.Save_Field (Name => COL_10_1_NAME, -- accepted_answer_id + Value => Object.Accepted_Answer); + Object.Clear_Modified (11); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Answer_Impl, Answer_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Answer_Impl_Ptr := Answer_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Answer_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, ANSWER_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Answer_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Answer_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (ANSWER_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- edit_date + Value => Object.Edit_Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- answer + Value => Object.Answer); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- rank + Value => Object.Rank); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_2_NAME, -- author_id + Value => Object.Author); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_2_NAME, -- question_id + Value => Object.Question); + Object.Clear_Modified (8); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Rating_Impl, Rating_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Rating_Impl_Ptr := Rating_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Rating_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, RATING_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Rating_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Rating_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (RATING_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- rating + Value => Object.Rating); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- vote_count + Value => Object.Vote_Count); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- for_entity_id + Value => Object.For_Entity_Id); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- for_entity_type + Value => Object.For_Entity_Type); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Vote_Impl, Vote_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Vote_Impl_Ptr := Vote_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Vote_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, VOTE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Vote_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""user_id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Vote_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (VOTE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- rating + Value => Object.Rating); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- entity_id + Value => Object.Entity); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- user_id + Value => Object.Get_Key); + Object.Clear_Modified (3); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""user_id = ? AND entity_id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Entity); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Finish (From : in out Application;,"Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + begin + Log.Info (""Finish configuration""); + From.Save (Outcome); + From.Status.Set (STARTING); + end Finish; + + -- ------------------------------ + -- This bean provides some methods that can be used in a Method_Expression + -- ------------------------------ + overriding + function Get_Method_Bindings (From : in Application) + return Util.Beans.Methods.Method_Binding_Array_Access is + pragma Unreferenced (From); + begin + return Binding_Array'Access; + end Get_Method_Bindings; + + -- ------------------------------ + -- Enter in the application setup + -- ------------------------------ + procedure Setup (App : in out Application; + Config : in String; + Server : in out ASF.Server.Container'Class) is + Path : constant String := AWA.Applications.Configs.Get_Config_Path (Config); + Dir : constant String := Ada.Directories.Containing_Directory (Path); + Done : constant String := Ada.Directories.Compose (Dir, "".initialized""); + begin + Log.Info (""Entering configuration for {0}"", Path); + App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); + begin + App.Config.Load_Properties (Path); + Util.Log.Loggers.Initialize (Path); + + exception + when Ada.IO_Exceptions.Name_Error => + Log.Error (""Cannot read application configuration file: {0}"", Path);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Changelog_Impl, Changelog_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Changelog_Impl_Ptr := Changelog_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Changelog_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, CHANGELOG_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Changelog_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Changelog_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (CHANGELOG_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- date + Value => Object.Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- text + Value => Object.Text); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- for_entity_id + Value => Object.For_Entity_Id); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- user_id + Value => Object.User); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- entity_type + Value => Object.Entity_Type); + Object.Clear_Modified (6); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Status_Type); + Impl : Comment_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 7, Impl.Status, Value); + end Set_Status; + + function Get_Status (Object : in Comment_Ref) + return AWA.Comments.Models.Status_Type is + Impl : constant Comment_Access + := Comment_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Status; + end Get_Status; + + + procedure Set_Format (Object : in out Comment_Ref; + Value : in AWA.Comments.Models.Format_Type) is + procedure Set_Field_Enum is + new ADO.Objects.Set_Field_Operation (Format_Type); + Impl : Comment_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 8, Impl.Format, Value); + end Set_Format; + + function Get_Format (Object : in Comment_Ref) + return AWA.Comments.Models.Format_Type is + Impl : constant Comment_Access + := Comment_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Format; + end Get_Format; + + + procedure Set_Author (Object : in out Comment_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Comment_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 9, Impl.Author, Value); + end Set_Author; + + function Get_Author (Object : in Comment_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Comment_Access + := Comment_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Author; + end Get_Author; + + -- Copy of the object. + procedure Copy (Object : in Comment_Ref; + Into : in out Comment_Ref) is + Result : Comment_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Comment_Access + := Comment_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Comment_Access + := new Comment_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Create_Date := Impl.Create_Date; + Copy.Message := Impl.Message; + Copy.Entity_Id := Impl.Entity_Id; + Copy.Version := Impl.Version; + Copy.Entity_Type := Impl.Entity_Type; + Copy.Status := Impl.Status; + Copy.Format := Impl.Format; + Copy.Author := Impl.Author;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Comment_Impl, Comment_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Comment_Impl_Ptr := Comment_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Comment_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, COMMENT_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Comment_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Comment_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (COMMENT_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- message + Value => Object.Message); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- entity_id + Value => Object.Entity_Id); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- entity_type + Value => Object.Entity_Type); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- status + Value => Integer (Status_Type'Pos (Object.Status))); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_1_NAME, -- format + Value => Integer (Format_Type'Pos (Object.Format))); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_1_NAME, -- author_id + Value => Object.Author); + Object.Clear_Modified (9); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List_Comments (T : in out Test;,"User : in ADO.Identifier; + Into : out Util.Beans.Objects.Object) is + Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; + Bean : Util.Beans.Basic.Readonly_Bean_Access; + List : AWA.Comments.Beans.Comment_List_Bean_Access; + begin + Bean := Beans.Create_Comment_List_Bean (Comment_Manager); + Into := Util.Beans.Objects.To_Object (Bean.all'Access); + List := AWA.Comments.Beans.Comment_List_Bean'Class (Bean.all)'Access; + List.Set_Value (""entity_type"", Util.Beans.Objects.To_Object (String '(""awa_user""))); + Util.Tests.Assert_Equals (T, 0, Integer (List.Get_Count), ""Invalid number of comments""); + + -- Load the existing comments. + List.Load_Comments (User); + end List_Comments; + + -- ------------------------------ + -- Create a comment and return the list of comments before and after the creation. + -- ------------------------------ + procedure Create_Comment (T : in out Test; + Status : in AWA.Comments.Models.Status_Type; + Before : out Util.Beans.Objects.Object; + After : out Util.Beans.Objects.Object; + Id : out ADO.Identifier) is + Sec_Ctx : Security.Contexts.Security_Context; + Context : AWA.Services.Contexts.Service_Context; + begin + AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, ""test-add-comment@test.com""); + + declare + Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; + User : constant AWA.Users.Models.User_Ref := Context.Get_User; + Bean : Util.Beans.Basic.Readonly_Bean_Access; + Comment : AWA.Comments.Beans.Comment_Bean_Access; + Cleanup : Util.Beans.Objects.Object; + Outcome : Ada.Strings.Unbounded.Unbounded_String; + begin + T.Assert (Comment_Manager /= null, ""There is no comment module""); + + T.List_Comments (User.Get_Id, Before); + + -- Create a new comment associated with the current user. + Bean := Beans.Create_Comment_Bean (Comment_Manager); + Cleanup := Util.Beans.Objects.To_Object (Bean.all'Access); + Comment := AWA.Comments.Beans.Comment_Bean'Class (Bean.all)'Access; + Comment.Set_Value (""entity_type"", Util.Beans.Objects.To_Object (String '(""awa_user""))); + Comment.Set_Value (""permission"", Util.Beans.Objects.To_Object (String '(""logged-user""))); + Comment.Set_Status (Status); + Comment.Set_Entity_Id (User.Get_Id); + + -- Create the comment. + Comment.Set_Message (""the comment message for the current user "" & + AWA.Comments.Models.Status_Type'Image (Status)); + Comment.Create (Outcome); + Id := Comment.Get_Id; + T.Assert (Id /= ADO.NO_IDENTIFIER, ""Invalid new comment identifier""); + + -- Load again the comments. + T.List_Comments (User.Get_Id, After); + T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), ""Comment bean is null"");" +procedure Test_Create_Published_Comment (T : in out Test) is,"Before : Util.Beans.Objects.Object; + After : Util.Beans.Objects.Object; + Id : ADO.Identifier; + begin + T.Create_Comment (AWA.Comments.Models.COMMENT_PUBLISHED, Before, After, Id); + declare + Before_Count : constant Natural := Get_Count (Before); + After_Count : constant Natural := Get_Count (After); + begin + Util.Tests.Assert_Equals (T, Before_Count + 1, After_Count, + ""The new comment does not appear in the list"");" +procedure Test_Publish_Comment (T : in out Test) is,"Before : Util.Beans.Objects.Object; + After : Util.Beans.Objects.Object; + Sec_Ctx : Security.Contexts.Security_Context; + Context : AWA.Services.Contexts.Service_Context; + Id : ADO.Identifier; + begin + T.Create_Comment (AWA.Comments.Models.COMMENT_WAITING, Before, After, Id); + Util.Tests.Assert_Equals (T, Get_Count (Before), Get_Count (After), + ""The new comment MUST not be in the list""); + + -- Now, simulate a user that logs in and publishes the comment. + AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, ""test-add-comment@test.com""); + declare + Comment_Manager : constant Comment_Module_Access := Get_Comment_Module; + User : constant AWA.Users.Models.User_Ref := Context.Get_User; + Comment : AWA.Comments.Beans.Comment_Bean; + begin + T.Assert (Comment_Manager /= null, ""There is no comment module""); + + Comment_Manager.Publish_Comment (""logged-user"", Id, AWA.Comments.Models.COMMENT_PUBLISHED, + Comment); + T.Assert (not Comment.Is_Null, ""Comment bean is null""); + + T.List_Comments (User.Get_Id, After);" +"function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME);","begin + return Get; + end Get_Setting_Module; + + -- ------------------------------ + -- Load the setting value for the current user. + -- Return the default value if there is no such setting. + -- ------------------------------ + procedure Load (Name : in String; + Default : in String; + Value : out Ada.Strings.Unbounded.Unbounded_String) is + Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + Query : ADO.Queries.Context; + Setting : AWA.Settings.Models.User_Setting_Ref; + Found : Boolean; + begin + Query.Set_Join (""INNER JOIN awa_setting AS a ON o.setting_id = a.id ""); + Query.Set_Filter (""a.name = :name AND o.user_id = :user""); + Query.Bind_Param (""name"", Name); + Query.Bind_Param (""user"", User.Get_Id); + Setting.Find (DB, Query, Found); + if not Found then + Value := Ada.Strings.Unbounded.To_Unbounded_String (Default); + else + Value := Setting.Get_Value; + end if; + end Load; + + -- Save the setting value for the current user. + procedure Save (Name : in String; + Value : in String) is + Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + Setting : AWA.Settings.Models.User_Setting_Ref; + Query : ADO.Queries.Context; + Found : Boolean; + begin + Ctx.Start; + Query.Set_Join (""INNER JOIN awa_setting AS a ON o.setting_id = a.id ""); + Query.Set_Filter (""a.name = :name AND o.user_id = :user""); + Query.Bind_Param (""name"", Name); + Query.Bind_Param (""user"", User.Get_Id); + Setting.Find (DB, Query, Found); + if not Found then + declare + Setting_Def : AWA.Settings.Models.Setting_Ref; + begin + Query.Clear; + Query.Set_Filter (""o.name = :name""); + Query.Bind_Param (""name"", Name); + Setting_Def.Find (DB, Query, Found); + if not Found then + Setting_Def.Set_Name (Name); + Setting_Def.Save (DB); + end if; + Setting.Set_Setting (Setting_Def);" +"procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data,","Name => Setting_Data_Access); + + use Ada.Strings.Unbounded; + + protected body Settings is + + procedure Get (Name : in String; + Default : in String; + Value : out Ada.Strings.Unbounded.Unbounded_String) is + Item : Setting_Data_Access := First; + Previous : Setting_Data_Access := null; + begin + while Item /= null loop + if Item.Name = Name then + Value := Item.Value; + if Previous /= null then + Previous.Next_Setting := Item.Next_Setting; + First := Item; + end if; + return; + end if; + Previous := Item; + Item := Item.Next_Setting; + end loop; + Load (Name, Default, Value); + Item := new Setting_Data; + Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); + Item.Value := Value; + Item.Next_Setting := First; + First := Item; + end Get; + + procedure Set (Name : in String; + Value : in String) is + Item : Setting_Data_Access := First; + Previous : Setting_Data_Access := null; + begin + while Item /= null loop + if Item.Name = Name then + if Previous /= null then + Previous.Next_Setting := Item.Next_Setting; + First := Item; + end if; + if Item.Value = Value then + return; + end if; + Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value); + Save (Name, Value); + return; + end if; + Previous := Item; + Item := Item.Next_Setting; + end loop; + Item := new Setting_Data; + Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); + Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value); + Item.Next_Setting := First; + First := Item; + Save (Name, Value); + end Set; + + procedure Clear is + begin + while First /= null loop + declare + Item : Setting_Data_Access := First; + begin + First := Item.Next_Setting; + Free (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Setting_Impl, Setting_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Setting_Impl_Ptr := Setting_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Setting_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SETTING_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Setting_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Setting_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (SETTING_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure List (Object : in out Setting_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SETTING_DEF'Access); + begin + Stmt.Execute; + Setting_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Setting_Ref; + Impl : constant Setting_Access := new Setting_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Global_Setting_Impl, Global_Setting_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Global_Setting_Impl_Ptr := Global_Setting_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Global_Setting_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, GLOBAL_SETTING_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Global_Setting_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Global_Setting_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (GLOBAL_SETTING_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- value + Value => Object.Value); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- server_id + Value => Object.Server_Id); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- setting_id + Value => Object.Setting); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Global_Setting_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, GLOBAL_SETTING_DEF'Access); + begin + Stmt.Execute; + Global_Setting_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Global_Setting_Ref; + Impl : constant Global_Setting_Access := new Global_Setting_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(User_Setting_Impl, User_Setting_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : User_Setting_Impl_Ptr := User_Setting_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out User_Setting_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, USER_SETTING_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out User_Setting_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out User_Setting_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (USER_SETTING_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_3_NAME, -- value + Value => Object.Value); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_3_NAME, -- setting_id + Value => Object.Setting); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_3_NAME, -- user_id + Value => Object.User); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +function Create_From_Format is,"new AWA.Helpers.Selectors.Create_From_Enum (AWA.Wikis.Models.Format_Type, + ""wiki_format_""); + + -- ------------------------------ + -- Get a select item list which contains a list of wiki formats. + -- ------------------------------ + function Create_Format_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) + return Util.Beans.Basic.Readonly_Bean_Access is + pragma Unreferenced (Module); + use AWA.Helpers; + begin + return Selectors.Create_Selector_Bean (Bundle => ""wikis"", + Context => null, + Create => Create_From_Format'Access).all'Access; + end Create_Format_List_Bean; + + -- ------------------------------ + -- Get the value identified by the name. + -- ------------------------------ + overriding + function Get_Value (From : in Wiki_Space_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if From.Is_Null then + return Util.Beans.Objects.Null_Object; + else + return AWA.Wikis.Models.Wiki_Space_Bean (From).Get_Value (Name); + end if; + end Get_Value; + + -- ------------------------------ + -- Set the value identified by the name. + -- ------------------------------ + overriding + procedure Set_Value (From : in out Wiki_Space_Bean; + Name : in String; + Value : in Util.Beans.Objects.Object) is + begin + if Name /= ""id"" then + AWA.Wikis.Models.Wiki_Space_Bean (From).Set_Value (Name, Value); + elsif Name = ""id"" and not Util.Beans.Objects.Is_Empty (Value) then + From.Module.Load_Wiki_Space (From, ADO.Utils.To_Identifier (Value)); + end if; + end Set_Value; + + -- ------------------------------ + -- Create or save the wiki space. + -- ------------------------------ + overriding + procedure Save (Bean : in out Wiki_Space_Bean; + Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + pragma Unreferenced (Outcome); + begin + if Bean.Is_Inserted then + Bean.Module.Save_Wiki_Space (Bean); + else + Bean.Module.Create_Wiki_Space (Bean); + end if; + end Save; + + -- ------------------------------ + -- Load the wiki space information. + -- ------------------------------ + overriding + procedure Load (Bean : in out Wiki_Space_Bean; + Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + begin + Bean.Module.Load_Wiki_Space (Bean, Bean.Get_Id); + Outcome := Ada.Strings.Unbounded.To_Unbounded_String (""loaded""); + end Load; + + -- Delete the wiki space. + procedure Delete (Bean : in out Wiki_Space_Bean; + Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + begin + null; + end Delete; + + -- ------------------------------ + -- Create the Wiki_Space_Bean bean instance. + -- ------------------------------ + function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) + return Util.Beans.Basic.Readonly_Bean_Access is + Object : constant Wiki_Space_Bean_Access := new Wiki_Space_Bean; + begin + Object.Module := Module; + return Object.all'Access; + end Create_Wiki_Space_Bean; + + -- ------------------------------ + -- Get the value identified by the name. + -- ------------------------------ + overriding + function Get_Value (From : in Wiki_Page_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if Name = ""wiki_id"" then + if From.Wiki_Space.Is_Null then + return Util.Beans.Objects.Null_Object; + else + return ADO.Utils.To_Object (From.Wiki_Space.Get_Id); + end if; + elsif Name = ""text"" then + if From.Has_Content then + return Util.Beans.Objects.To_Object (From.New_Content); + elsif From.Content.Is_Null then + return Util.Beans.Objects.Null_Object; + else + return Util.Beans.Objects.To_Object (String '(From.Content.Get_Content)); + end if; + elsif Name = ""date"" then + if From.Content.Is_Null then + return Util.Beans.Objects.Null_Object; + else + return From.Content.Get_Value (""create_date""); + end if; + elsif Name = ""format"" then + if not From.Content.Is_Null then + return From.Content.Get_Value (""format""); + elsif not From.Wiki_Space.Is_Null then + return From.Wiki_Space.Get_Value (""format""); + else + return Util.Beans.Objects.Null_Object; + end if; + elsif Name = ""comment"" then + if From.Content.Is_Null then + return Util.Beans.Objects.Null_Object; + else + return Util.Beans.Objects.To_Object (String '(From.Content.Get_Save_Comment)); + end if; + elsif Name = ""tags"" then + return Util.Beans.Objects.To_Object (From.Tags_Bean, Util.Beans.Objects.STATIC); + elsif Name = ""is_public"" then + if not From.Is_Null then + return AWA.Wikis.Models.Wiki_Page_Bean (From).Get_Value (Name); + elsif not From.Wiki_Space.Is_Null then + return From.Wiki_Space.Get_Value (Name); + else + return Util.Beans.Objects.Null_Object; + end if; + elsif From.Is_Null then + return Util.Beans.Objects.Null_Object; + else + return AWA.Wikis.Models.Wiki_Page_Bean (From).Get_Value (Name); + end if; + end Get_Value; + + -- ------------------------------ + -- Set the value identified by the name. + -- ------------------------------ + overriding + procedure Set_Value (From : in out Wiki_Page_Bean; + Name : in String; + Value : in Util.Beans.Objects.Object) is + begin + if Name = ""id"" then + if not Util.Beans.Objects.Is_Empty (Value) then + declare + Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); + begin + From.Module.Load_Page (From, From.Content, From.Tags, Id);" +procedure Load_List (Into : in out Wiki_List_Bean) is,"use AWA.Wikis.Models; + use AWA.Services; + use type Ada.Strings.Unbounded.Unbounded_String; + use type ADO.Identifier; + + Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant ADO.Identifier := Ctx.Get_User_Identifier; + Session : ADO.Sessions.Session := Into.Module.Get_Session; + Query : ADO.Queries.Context; + Count_Query : ADO.Queries.Context; + Tag_Id : ADO.Identifier; + First : constant Natural := (Into.Page - 1) * Into.Page_Size; + Tag : constant String := Ada.Strings.Unbounded.To_String (Into.Tag); + begin + if Into.Wiki_Id = ADO.NO_IDENTIFIER then + return; + end if; + Into.Wiki_Space.Set_Id (Into.Wiki_Id); + if Tag'Length > 0 then + AWA.Tags.Modules.Find_Tag_Id (Session, Tag, Tag_Id); + if Tag_Id = ADO.NO_IDENTIFIER then + return; + end if; + Query.Set_Query (AWA.Wikis.Models.Query_Wiki_Page_Tag_List); + Query.Bind_Param (Name => ""tag"", Value => Tag_Id); + Count_Query.Set_Count_Query (AWA.Wikis.Models.Query_Wiki_Page_Tag_List); + Count_Query.Bind_Param (Name => ""tag"", Value => Tag_Id); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""page_table"", + Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, + Session => Session); + ADO.Sessions.Entities.Bind_Param (Params => Count_Query, + Name => ""page_table"", + Table => AWA.Wikis.Models.WIKI_PAGE_TABLE, + Session => Session); + else + Query.Set_Query (AWA.Wikis.Models.Query_Wiki_Page_List); + Count_Query.Set_Count_Query (AWA.Wikis.Models.Query_Wiki_Page_List); + end if; + if Into.Sort = ""name"" then + Query.Bind_Param (Name => ""order1"", + Value => ADO.Parameters.Token '(""page.name"")); + elsif Into.Sort = ""recent"" then + Query.Bind_Param (Name => ""order1"", + Value => ADO.Parameters.Token '(""content.create_date DESC"")); + elsif Into.Sort = ""popular"" then + Query.Bind_Param (Name => ""order1"", + Value => ADO.Parameters.Token '(""page.read_count DESC"")); + else + return; + end if; + Query.Bind_Param (Name => ""first"", Value => First); + Query.Bind_Param (Name => ""count"", Value => Into.Page_Size); + Query.Bind_Param (Name => ""wiki_id"", Value => Into.Wiki_Id); + Query.Bind_Param (Name => ""user_id"", Value => User); + Count_Query.Bind_Param (Name => ""wiki_id"", Value => Into.Wiki_Id); + Count_Query.Bind_Param (Name => ""user_id"", Value => User); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""table"", + Table => AWA.Wikis.Models.WIKI_SPACE_TABLE, + Session => Session); + ADO.Sessions.Entities.Bind_Param (Params => Count_Query, + Name => ""table"", + Table => AWA.Wikis.Models.WIKI_SPACE_TABLE, + Session => Session); + AWA.Wikis.Models.List (Into.Pages, Session, Query); + Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); + declare + List : ADO.Utils.Identifier_Vector; + Iter : Wiki_Page_Info_Vectors.Cursor := Into.Pages.List.First; + begin + while Wiki_Page_Info_Vectors.Has_Element (Iter) loop + List.Append (Wiki_Page_Info_Vectors.Element (Iter).Id); + Wiki_Page_Info_Vectors.Next (Iter); + end loop; + Into.Tags.Load_Tags (Session, AWA.Wikis.Models.WIKI_PAGE_TABLE.Table.all, + List);" +function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access),"return Util.Beans.Basic.Readonly_Bean_Access is + Object : constant Wiki_List_Bean_Access := new Wiki_List_Bean; + begin + Object.Module := Module; + Object.Pages_Bean := Object.Pages'Access; + Object.Page_Size := 20; + Object.Page := 1; + Object.Count := 0; + Object.Wiki_Id := ADO.NO_IDENTIFIER; + Object.Wiki_Space := Get_Wiki_Space_Bean (""adminWikiSpace""); + return Object.all'Access; + end Create_Wiki_List_Bean; + + -- ------------------------------ + -- Get the value identified by the name. + -- ------------------------------ + overriding + function Get_Value (From : in Wiki_Version_List_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if Name = ""versions"" then + return Util.Beans.Objects.To_Object (Value => From.Versions_Bean, + Storage => Util.Beans.Objects.STATIC); + elsif Name = ""page_count"" then + return Util.Beans.Objects.To_Object ((From.Count + From.Page_Size - 1) / From.Page_Size); + else + return AWA.Wikis.Models.Wiki_Version_List_Bean (From).Get_Value (Name); + end if; + end Get_Value; + + -- ------------------------------ + -- Set the value identified by the name. + -- ------------------------------ + overriding + procedure Set_Value (From : in out Wiki_Version_List_Bean; + Name : in String; + Value : in Util.Beans.Objects.Object) is + begin + if Name = ""page"" and not Util.Beans.Objects.Is_Empty (Value) then + From.Page := Util.Beans.Objects.To_Integer (Value); + elsif Name = ""wiki_id"" and not Util.Beans.Objects.Is_Empty (Value) then + From.Wiki_Id := ADO.Utils.To_Identifier (Value); + elsif Name = ""page_id"" and not Util.Beans.Objects.Is_Empty (Value) then + From.Page_Id := ADO.Utils.To_Identifier (Value); + end if; + + exception + when Constraint_Error => + From.Wiki_Id := ADO.NO_IDENTIFIER; + From.Page_Id := ADO.NO_IDENTIFIER; + + end Set_Value; + + overriding + procedure Load (Into : in out Wiki_Version_List_Bean; + Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is + use AWA.Wikis.Models; + use AWA.Services; + use type ADO.Identifier; + use type Ada.Strings.Unbounded.Unbounded_String; + + Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant ADO.Identifier := Ctx.Get_User_Identifier; + Session : ADO.Sessions.Session := Into.Module.Get_Session; + Query : ADO.Queries.Context; + Count_Query : ADO.Queries.Context; + First : constant Natural := (Into.Page - 1) * Into.Page_Size; + Page : constant Wiki_View_Bean_Access := Get_Wiki_View_Bean (""wikiView""); + begin + if Into.Wiki_Id = ADO.NO_IDENTIFIER or Into.Page_Id = ADO.NO_IDENTIFIER then + return; + end if; + + -- Load the wiki page first. + Page.Id := Into.Page_Id; + Page.Set_Wiki_Id (Into.Wiki_Id); + Page.Load (Outcome); + if Outcome /= ""loaded"" then + return; + end if; + Page.Wiki_Space.Set_Id (Into.Wiki_Id); + + -- Get the list of versions associated with the wiki page. + Query.Set_Query (AWA.Wikis.Models.Query_Wiki_Version_List); + Count_Query.Set_Count_Query (AWA.Wikis.Models.Query_Wiki_Version_List); + Query.Bind_Param (Name => ""first"", Value => First); + Query.Bind_Param (Name => ""count"", Value => Into.Page_Size); + Query.Bind_Param (Name => ""wiki_id"", Value => Into.Wiki_Id); + Query.Bind_Param (Name => ""page_id"", Value => Into.Page_Id); + Query.Bind_Param (Name => ""user_id"", Value => User); + Count_Query.Bind_Param (Name => ""wiki_id"", Value => Into.Wiki_Id); + Count_Query.Bind_Param (Name => ""page_id"", Value => Into.Page_Id); + Count_Query.Bind_Param (Name => ""user_id"", Value => User); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""table"", + Table => AWA.Wikis.Models.WIKI_SPACE_TABLE, + Session => Session); + ADO.Sessions.Entities.Bind_Param (Params => Count_Query, + Name => ""table"", + Table => AWA.Wikis.Models.WIKI_SPACE_TABLE, + Session => Session); + AWA.Wikis.Models.List (Into.Versions, Session, Query); + Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); + end Load; + + -- ------------------------------ + -- Create the Post_List_Bean bean instance. + -- ------------------------------ + function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) + return Util.Beans.Basic.Readonly_Bean_Access is + Object : constant Wiki_Version_List_Bean_Access := new Wiki_Version_List_Bean; + begin + Object.Module := Module; + Object.Versions_Bean := Object.Versions'Access; + Object.Page_Size := 20; + Object.Page := 1; + Object.Count := 0; + Object.Wiki_Id := ADO.NO_IDENTIFIER; + Object.Page_Id := ADO.NO_IDENTIFIER; + return Object.all'Access; + end Create_Wiki_Version_List_Bean; + + -- ------------------------------ + -- Get the value identified by the name. + -- ------------------------------ + overriding + function Get_Value (From : in Wiki_Page_Info_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if Name = ""words"" then + return Util.Beans.Objects.To_Object (Value => From.Words_Bean, + Storage => Util.Beans.Objects.STATIC); + elsif Name = ""pages"" then + return Util.Beans.Objects.To_Object (Value => From.Links_Bean, + Storage => Util.Beans.Objects.STATIC); + elsif Name = ""links"" then + return Util.Beans.Objects.To_Object (Value => From.Ext_Links_Bean, + Storage => Util.Beans.Objects.STATIC); + elsif Name = ""images"" then + return Util.Beans.Objects.To_Object (Value => From.Page.Links_Bean, + Storage => Util.Beans.Objects.STATIC); + elsif Name = ""templates"" then + return Util.Beans.Objects.To_Object (Value => From.Page.Plugins_Bean, + Storage => Util.Beans.Objects.STATIC); + elsif Name = ""imageThumbnail"" then + declare + URI : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; + W : Natural := 64; + H : Natural := 64; + begin + if Image_Info_Maps.Has_Element (From.Page.Links.Pos) then + From.Page.Links.Make_Image_Link + (Link => Image_Info_Maps.Key (From.Page.Links.Pos), + Info => Image_Info_Maps.Element (From.Page.Links.Pos), + URI => URI, + Width => W, + Height => H); + end if; + return Util.Beans.Objects.To_Object (URI);" +procedure Load_Wikis (List : in Wiki_Admin_Bean) is,"use AWA.Wikis.Models; + use AWA.Services; + + Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant ADO.Identifier := Ctx.Get_User_Identifier; + Session : ADO.Sessions.Session := List.Module.Get_Session; + Query : ADO.Queries.Context; + begin + Query.Set_Query (AWA.Wikis.Models.Query_Wiki_List); + Query.Bind_Param (""user_id"", User); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""table"", + Table => AWA.Wikis.Models.WIKI_SPACE_TABLE, + Session => Session); + AWA.Wikis.Models.List (List.Wiki_List_Bean.all, Session, Query); + List.Flags (INIT_WIKI_LIST) := True; + end Load_Wikis; + + -- ------------------------------ + -- Get the wiki space identifier. + -- ------------------------------ + function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier is + use type ADO.Identifier; + begin + if List.Wiki_Id = ADO.NO_IDENTIFIER then + if not List.Flags (INIT_WIKI_LIST) then + Load_Wikis (List); + end if; + if not List.Wiki_List.List.Is_Empty then + return List.Wiki_List.List.Element (0).Id; + end if; + end if; + return List.Wiki_Id; + end Get_Wiki_Id; + + overriding + function Get_Value (List : in Wiki_Admin_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if Name = ""wikis"" then + if not List.Init_Flags (INIT_WIKI_LIST) then + Load_Wikis (List); + end if; + return Util.Beans.Objects.To_Object (Value => List.Wiki_List_Bean, + Storage => Util.Beans.Objects.STATIC); + + elsif Name = ""id"" then + declare + use type ADO.Identifier; + + Id : constant ADO.Identifier := List.Get_Wiki_Id; + begin + if Id = ADO.NO_IDENTIFIER then + return Util.Beans.Objects.Null_Object; + else + return Util.Beans.Objects.To_Object (Long_Long_Integer (Id)); + end if;" +"function Get is new AWA.Modules.Get (Wiki_Module, Wiki_Module_Access, NAME);","begin + return Get; + end Get_Wiki_Module; + + -- ------------------------------ + -- Create the wiki space. + -- ------------------------------ + procedure Create_Wiki_Space (Module : in Wiki_Module; + Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is + + procedure Copy_Page (Item : in String; + Done : out Boolean); + + Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant ADO.Identifier := Ctx.Get_User_Identifier; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + WS : AWA.Workspaces.Models.Workspace_Ref; + + procedure Copy_Page (Item : in String; + Done : out Boolean) is + begin + Module.Copy_Page (DB, Wiki, ADO.Identifier'Value (Item)); + Done := False; + + exception + when Constraint_Error => + Log.Error (""Invalid configuration wiki page id {0}"", Item); + + end Copy_Page; + + begin + Log.Info (""Creating new wiki space {0}"", String '(Wiki.Get_Name)); + + Ctx.Start; + AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); + + -- Check that the user has the create permission on the given workspace. + AWA.Permissions.Check (Permission => ACL_Create_Wiki_Space.Permission, + Entity => WS); + Wiki.Set_Workspace (WS); + Wiki.Set_Create_Date (Ada.Calendar.Clock); + Wiki.Save (DB); + + -- Add the permission for the user to use the new wiki space. + AWA.Workspaces.Modules.Add_Permission (Session => DB, + User => User, + Entity => Wiki, + Workspace => WS.Get_Id, + List => (ACL_Update_Wiki_Space.Permission, + ACL_Delete_Wiki_Space.Permission, + ACL_Create_Wiki_Pages.Permission, + ACL_Delete_Wiki_Pages.Permission, + ACL_Update_Wiki_Pages.Permission, + ACL_View_Wiki_Page.Permission)); + + Util.Strings.Tokenizers.Iterate_Tokens (Content => Module.Get_Config (PARAM_WIKI_COPY_LIST), + Pattern => "","", + Process => Copy_Page'Access, + Going => Ada.Strings.Forward); + + Ctx.Commit; + + Log.Info (""Wiki {0} created for user {1}"", + ADO.Identifier'Image (Wiki.Get_Id), ADO.Identifier'Image (User)); + end Create_Wiki_Space; + + -- ------------------------------ + -- Save the wiki space. + -- ------------------------------ + procedure Save_Wiki_Space (Module : in Wiki_Module; + Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class) is + pragma Unreferenced (Module); + + Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + begin + Log.Info (""Updating wiki space {0}"", String '(Wiki.Get_Name)); + + Ctx.Start; + + -- Check that the user has the update permission on the given wiki space. + AWA.Permissions.Check (Permission => ACL_Update_Wiki_Space.Permission, + Entity => Wiki); + Wiki.Save (DB); + Ctx.Commit; + end Save_Wiki_Space; + + -- ------------------------------ + -- Load the wiki space. + -- ------------------------------ + procedure Load_Wiki_Space (Module : in Wiki_Module; + Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; + Id : in ADO.Identifier) is + pragma Unreferenced (Module); + + Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); + Found : Boolean; + begin + Wiki.Load (DB, Id, Found); + end Load_Wiki_Space; + + -- ------------------------------ + -- Create the wiki page into the wiki space. + -- ------------------------------ + procedure Create_Wiki_Page (Model : in Wiki_Module; + Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; + Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; + Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class) is + begin + Log.Info (""Create wiki page {0}"", String '(Page.Get_Name)); + + -- Check that the user has the create wiki page permission on the given wiki space. + AWA.Permissions.Check (Permission => ACL_Create_Wiki_Pages.Permission, + Entity => Into); + + Page.Set_Wiki (Into); + Model.Save_Wiki_Content (Page, Content); + end Create_Wiki_Page; + + -- ------------------------------ + -- Save the wiki page. + -- ------------------------------ + procedure Save (Model : in Wiki_Module; + Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class) is + pragma Unreferenced (Model); + + Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + begin + -- Check that the user has the update wiki page permission on the given wiki space. + AWA.Permissions.Check (Permission => ACL_Update_Wiki_Pages.Permission, + Entity => Page); + + Ctx.Start; + Page.Save (DB); + Ctx.Commit; + end Save; + + -- ------------------------------ + -- Delete the wiki page as well as all its versions. + -- ------------------------------ + procedure Delete (Model : in Wiki_Module; + Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class) is + Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + begin + -- Check that the user has the delete wiki page permission on the given wiki page. + AWA.Permissions.Check (Permission => ACL_Delete_Wiki_Pages.Permission, + Entity => Page); + + Ctx.Start; + + -- Before deleting the wiki page, delete the version content. + declare + Stmt : ADO.Statements.Delete_Statement + := DB.Create_Statement (AWA.Wikis.Models.WIKI_CONTENT_TABLE); + begin + Stmt.Set_Filter (Filter => ""page_id = ?""); + Stmt.Add_Param (Value => Page); + Stmt.Execute;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Format_Type); + Impl : Wiki_Space_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 8, Impl.Format, Value); + end Set_Format; + + function Get_Format (Object : in Wiki_Space_Ref) + return AWA.Wikis.Models.Format_Type is + Impl : constant Wiki_Space_Access + := Wiki_Space_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Format; + end Get_Format; + + + procedure Set_Workspace (Object : in out Wiki_Space_Ref; + Value : in AWA.Workspaces.Models.Workspace_Ref'Class) is + Impl : Wiki_Space_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 9, Impl.Workspace, Value); + end Set_Workspace; + + function Get_Workspace (Object : in Wiki_Space_Ref) + return AWA.Workspaces.Models.Workspace_Ref'Class is + Impl : constant Wiki_Space_Access + := Wiki_Space_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Workspace; + end Get_Workspace; + + -- Copy of the object. + procedure Copy (Object : in Wiki_Space_Ref; + Into : in out Wiki_Space_Ref) is + Result : Wiki_Space_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Wiki_Space_Access + := Wiki_Space_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Wiki_Space_Access + := new Wiki_Space_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Name := Impl.Name; + Copy.Is_Public := Impl.Is_Public; + Copy.Version := Impl.Version; + Copy.Create_Date := Impl.Create_Date; + Copy.Left_Side := Impl.Left_Side; + Copy.Right_Side := Impl.Right_Side; + Copy.Format := Impl.Format; + Copy.Workspace := Impl.Workspace;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Wiki_Space_Impl, Wiki_Space_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Wiki_Space_Impl_Ptr := Wiki_Space_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Wiki_Space_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, WIKI_SPACE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Wiki_Space_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Wiki_Space_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (WIKI_SPACE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- is_public + Value => Object.Is_Public); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- left_side + Value => Object.Left_Side); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- right_side + Value => Object.Right_Side); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_1_NAME, -- format + Value => Integer (Format_Type'Pos (Object.Format))); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_1_NAME, -- workspace_id + Value => Object.Workspace); + Object.Clear_Modified (9); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Wiki_Page_Impl, Wiki_Page_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Wiki_Page_Impl_Ptr := Wiki_Page_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Wiki_Page_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, WIKI_PAGE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Wiki_Page_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Wiki_Page_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (WIKI_PAGE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- last_version + Value => Object.Last_Version); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- is_public + Value => Object.Is_Public); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- title + Value => Object.Title); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_2_NAME, -- read_count + Value => Object.Read_Count); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_2_NAME, -- preview_id + Value => Object.Preview); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_2_NAME, -- wiki_id + Value => Object.Wiki); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_2_NAME, -- content_id + Value => Object.Content); + Object.Clear_Modified (10); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Format_Type); + Impl : Wiki_Content_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 4, Impl.Format, Value); + end Set_Format; + + function Get_Format (Object : in Wiki_Content_Ref) + return AWA.Wikis.Models.Format_Type is + Impl : constant Wiki_Content_Access + := Wiki_Content_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Format; + end Get_Format; + + + procedure Set_Save_Comment (Object : in out Wiki_Content_Ref; + Value : in String) is + Impl : Wiki_Content_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 5, Impl.Save_Comment, Value); + end Set_Save_Comment; + + procedure Set_Save_Comment (Object : in out Wiki_Content_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Wiki_Content_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 5, Impl.Save_Comment, Value); + end Set_Save_Comment; + + function Get_Save_Comment (Object : in Wiki_Content_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Save_Comment); + end Get_Save_Comment; + function Get_Save_Comment (Object : in Wiki_Content_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Wiki_Content_Access + := Wiki_Content_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Save_Comment; + end Get_Save_Comment; + + + function Get_Version (Object : in Wiki_Content_Ref) + return Integer is + Impl : constant Wiki_Content_Access + := Wiki_Content_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Version; + end Get_Version; + + + procedure Set_Page_Version (Object : in out Wiki_Content_Ref; + Value : in Integer) is + Impl : Wiki_Content_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 7, Impl.Page_Version, Value); + end Set_Page_Version; + + function Get_Page_Version (Object : in Wiki_Content_Ref) + return Integer is + Impl : constant Wiki_Content_Access + := Wiki_Content_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Page_Version; + end Get_Page_Version; + + + procedure Set_Page (Object : in out Wiki_Content_Ref; + Value : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is + Impl : Wiki_Content_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 8, Impl.Page, Value); + end Set_Page; + + function Get_Page (Object : in Wiki_Content_Ref) + return AWA.Wikis.Models.Wiki_Page_Ref'Class is + Impl : constant Wiki_Content_Access + := Wiki_Content_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Page; + end Get_Page; + + + procedure Set_Author (Object : in out Wiki_Content_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Wiki_Content_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 9, Impl.Author, Value); + end Set_Author; + + function Get_Author (Object : in Wiki_Content_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Wiki_Content_Access + := Wiki_Content_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Author; + end Get_Author; + + -- Copy of the object. + procedure Copy (Object : in Wiki_Content_Ref; + Into : in out Wiki_Content_Ref) is + Result : Wiki_Content_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Wiki_Content_Access + := Wiki_Content_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Wiki_Content_Access + := new Wiki_Content_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Create_Date := Impl.Create_Date; + Copy.Content := Impl.Content; + Copy.Format := Impl.Format; + Copy.Save_Comment := Impl.Save_Comment; + Copy.Version := Impl.Version; + Copy.Page_Version := Impl.Page_Version; + Copy.Page := Impl.Page; + Copy.Author := Impl.Author;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Wiki_Content_Impl, Wiki_Content_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Wiki_Content_Impl_Ptr := Wiki_Content_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Wiki_Content_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, WIKI_CONTENT_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Wiki_Content_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Wiki_Content_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (WIKI_CONTENT_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_3_NAME, -- page_version + Value => Object.Page_Version); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_3_NAME, -- page_id + Value => Object.Page); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_3_NAME, -- author_id + Value => Object.Author); + Object.Clear_Modified (9); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Free is,"new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, + Name => Recipients_Access); + + -- Get a printable representation of the email recipients. + function Image (Recipients : in AWS.SMTP.Recipients) return String; + + -- ------------------------------ + -- Set the From part of the message. + -- ------------------------------ + overriding + procedure Set_From (Message : in out AWS_Mail_Message; + Name : in String; + Address : in String) is + begin + Message.From := AWS.SMTP.E_Mail (Name => Name, + Address => Address); + end Set_From; + + -- ------------------------------ + -- Add a recipient for the message. + -- ------------------------------ + overriding + procedure Add_Recipient (Message : in out AWS_Mail_Message; + Kind : in Recipient_Type; + Name : in String; + Address : in String) is + pragma Unreferenced (Kind); + begin + if Message.To = null then + Message.To := new AWS.SMTP.Recipients (1 .. 1); + else + declare + To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); + begin + To (Message.To'Range) := Message.To.all; + Free (Message.To); + Message.To := To;" +procedure Import_Country is,"use Ada.Text_IO; + use Util.Serialize.IO.CSV; + use AWA.Countries.Models; + use Ada.Containers; + + use Util.Log; + + Log : constant Loggers.Logger := Loggers.Create (""Import_Country""); + + Country : AWA.Countries.Models.Country_Ref; + DB : ADO.Sessions.Master_Session; + + package Country_Map is + new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, + Element_Type => AWA.Countries.Models.Country_Ref, + Hash => Ada.Strings.Hash, + Equivalent_Keys => ""=""); + + package Neighbors_Map is + new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, + Element_Type => String, + Hash => Ada.Strings.Hash, + Equivalent_Keys => ""=""); + + Countries : Country_Map.Map; + Neighbors : Neighbors_Map.Map; + + type CSV_Parser is new Util.Serialize.IO.CSV.Parser with null record; + + overriding + procedure Set_Cell (Parser : in out CSV_Parser; + Value : in String; + Row : in Util.Serialize.IO.CSV.Row_Type; + Column : in Util.Serialize.IO.CSV.Column_Type); + + overriding + procedure Set_Cell (Parser : in out CSV_Parser; + Value : in String; + Row : in Util.Serialize.IO.CSV.Row_Type; + Column : in Util.Serialize.IO.CSV.Column_Type) is + pragma Unreferenced (Parser, Row); + + Query : ADO.SQL.Query; + Found : Boolean; + begin + case Column is + when 1 => + -- The ISO code is unique, find the country + Query.Bind_Param (1, Value); + Query.Set_Filter (""iso_code = ?""); + Country.Find (DB, Query, Found); + if not Found then + -- Build a new country object + Country := AWA.Countries.Models.Null_Country; + Country.Set_Iso_Code (Value); + end if; + Countries.Insert (Value, Country); + + when 2 => + -- Ada.Text_IO.Put_Line (""ISO3: "" & Value); + null; + + when 3 => + -- Ada.Text_IO.Put_Line (""ISON: "" & Value); + null; + + when 4 => + -- Ada.Text_IO.Put_Line (""FIPS: "" & Value); + null; + + -- Country name + when 5 => + Country.Set_Name (Value); + + when 6 => + -- Ada.Text_IO.Put_Line (""Capital: "" & Value); + null; + + when 7 | 8 => -- Area, Population + null; + + -- Country continent + when 9 => + Country.Set_Continent (Value); + + -- Country TLD + when 10 => + Country.Set_Tld (Value); + + -- Country CurrencyCode + when 11 => + Country.Set_Currency_Code (Value); + + -- Country CurrencyName + when 12 => + Country.Set_Currency (Value); + + when 13 | 14 => -- Phone, postal code format + null; + + when 15 => + -- Ada.Text_IO.Put_Line (""Postal regex: "" & Value); + null; + + -- Country languages + when 16 => + Country.Set_Languages (Value); + + -- Country unique geonameid + when 17 => + if Value /= """" then + Country.Set_Geonameid (Integer'Value (Value)); + end if; + + when 18 => + Country.Save (DB); + Neighbors.Insert (Country.Get_Iso_Code, Value); + + when 19 => -- EquivalentFipsCode + null; + + when others => + null; + + end case; + + exception + when E : others => + Log.Error (""Column "" & Util.Serialize.IO.CSV.Column_Type'Image (Column) + & "" value: "" & Value, E, True); + raise; + end Set_Cell; + + procedure Build_Neighbors is + Stmt : ADO.Statements.Delete_Statement + := DB.Create_Statement (AWA.Countries.Models.COUNTRY_NEIGHBOR_TABLE); + Iter : Neighbors_Map.Cursor := Neighbors.First; + Count : Natural := 0; + begin + Stmt.Execute; + + while Neighbors_Map.Has_Element (Iter) loop + declare + Name : constant String := Neighbors_Map.Key (Iter); + List : constant String := Neighbors_Map.Element (Iter); + Pos : Natural := List'First; + N : Natural; + begin + Country := Countries.Element (Name); + while Pos < List'Last loop + N := Util.Strings.Index (List, ',', Pos); + if N = 0 then + N := List'Last; + else + N := N - 1; + end if; + if Pos < N and then Countries.Contains (List (Pos .. N)) then + declare + Neighbor : AWA.Countries.Models.Country_Neighbor_Ref; + begin + Neighbor.Set_Neighbor_Of (Country); + Neighbor.Set_Neighbor (Countries.Element (List (Pos .. N))); + Neighbor.Save (DB); + Count := Count + 1;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Country_Impl, Country_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Country_Impl_Ptr := Country_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Country_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, COUNTRY_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Country_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Country_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (COUNTRY_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- continent + Value => Object.Continent); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- currency + Value => Object.Currency); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- iso_code + Value => Object.Iso_Code); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- geonameid + Value => Object.Geonameid); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- languages + Value => Object.Languages); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_1_NAME, -- tld + Value => Object.Tld); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_1_NAME, -- currency_code + Value => Object.Currency_Code); + Object.Clear_Modified (9); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(City_Impl, City_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : City_Impl_Ptr := City_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out City_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, CITY_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out City_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out City_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (CITY_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- zip_code + Value => Object.Zip_Code); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- latitude + Value => Object.Latitude); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- longitude + Value => Object.Longitude); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_2_NAME, -- region_id + Value => Object.Region); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_2_NAME, -- country_id + Value => Object.Country); + Object.Clear_Modified (7); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Country_Neighbor_Impl, Country_Neighbor_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Country_Neighbor_Impl_Ptr := Country_Neighbor_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Country_Neighbor_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, COUNTRY_NEIGHBOR_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Country_Neighbor_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Country_Neighbor_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (COUNTRY_NEIGHBOR_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_3_NAME, -- neighbor_of_id + Value => Object.Neighbor_Of); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_3_NAME, -- neighbor_id + Value => Object.Neighbor); + Object.Clear_Modified (3); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Region_Impl, Region_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Region_Impl_Ptr := Region_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Region_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, REGION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Region_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Region_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (REGION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_4_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_4_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_4_NAME, -- geonameid + Value => Object.Geonameid); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_4_NAME, -- country_id + Value => Object.Country); + Object.Clear_Modified (4); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Publish (Service : in Storage_Service;,"Id : in ADO.Identifier; + State : in Boolean; + File : in out AWA.Storages.Models.Storage_Ref'Class) is + pragma Unreferenced (Service); + + Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + begin + Ctx.Start; + + -- Check that the user has the permission to publish for the given comment. + AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission, + Entity => Id); + + File.Load (DB, Id); + File.Set_Is_Public (State); + File.Save (DB); + declare + Update : ADO.Statements.Update_Statement + := DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE); + begin + Update.Set_Filter (Filter => ""original_id = ?""); + Update.Save_Field (""is_public"", State); + Update.Add_Param (Id); + Update.Execute;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Storage_Data_Impl, Storage_Data_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Storage_Data_Impl_Ptr := Storage_Data_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Storage_Data_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, STORAGE_DATA_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Storage_Data_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Storage_Data_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (STORAGE_DATA_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- data + Value => Object.Data); + Object.Clear_Modified (3); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Storage_Folder_Impl, Storage_Folder_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Storage_Folder_Impl_Ptr := Storage_Folder_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Storage_Folder_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, STORAGE_FOLDER_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Storage_Folder_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Storage_Folder_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (STORAGE_FOLDER_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- workspace_id + Value => Object.Workspace); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_2_NAME, -- owner_id + Value => Object.Owner); + Object.Clear_Modified (6); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Storage_Type); + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 1, Impl.Storage, Value); + end Set_Storage; + + function Get_Storage (Object : in Storage_Ref) + return AWA.Storages.Models.Storage_Type is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Storage; + end Get_Storage; + + + procedure Set_Create_Date (Object : in out Storage_Ref; + Value : in Ada.Calendar.Time) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 2, Impl.Create_Date, Value); + end Set_Create_Date; + + function Get_Create_Date (Object : in Storage_Ref) + return Ada.Calendar.Time is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Create_Date; + end Get_Create_Date; + + + procedure Set_Name (Object : in out Storage_Ref; + Value : in String) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Name, Value); + end Set_Name; + + procedure Set_Name (Object : in out Storage_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 3, Impl.Name, Value); + end Set_Name; + + function Get_Name (Object : in Storage_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Name); + end Get_Name; + function Get_Name (Object : in Storage_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Name; + end Get_Name; + + + procedure Set_File_Size (Object : in out Storage_Ref; + Value : in Integer) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 4, Impl.File_Size, Value); + end Set_File_Size; + + function Get_File_Size (Object : in Storage_Ref) + return Integer is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.File_Size; + end Get_File_Size; + + + procedure Set_Mime_Type (Object : in out Storage_Ref; + Value : in String) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 5, Impl.Mime_Type, Value); + end Set_Mime_Type; + + procedure Set_Mime_Type (Object : in out Storage_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 5, Impl.Mime_Type, Value); + end Set_Mime_Type; + + function Get_Mime_Type (Object : in Storage_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Mime_Type); + end Get_Mime_Type; + function Get_Mime_Type (Object : in Storage_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Mime_Type; + end Get_Mime_Type; + + + procedure Set_Uri (Object : in out Storage_Ref; + Value : in String) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 6, Impl.Uri, Value); + end Set_Uri; + + procedure Set_Uri (Object : in out Storage_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 6, Impl.Uri, Value); + end Set_Uri; + + function Get_Uri (Object : in Storage_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Uri); + end Get_Uri; + function Get_Uri (Object : in Storage_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Uri; + end Get_Uri; + + + function Get_Version (Object : in Storage_Ref) + return Integer is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Version; + end Get_Version; + + + procedure Set_Id (Object : in out Storage_Ref; + Value : in ADO.Identifier) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Key_Value (Impl.all, 8, Value); + end Set_Id; + + function Get_Id (Object : in Storage_Ref) + return ADO.Identifier is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Object.all)'Access; + begin + return Impl.Get_Key_Value; + end Get_Id; + + + procedure Set_Is_Public (Object : in out Storage_Ref; + Value : in Boolean) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Boolean (Impl.all, 9, Impl.Is_Public, Value); + ADO.Objects.Set_Field_Boolean (Impl.all, 9, Impl.Is_Public, Value); + end Set_Is_Public; + + function Get_Is_Public (Object : in Storage_Ref) + return Boolean is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Is_Public; + end Get_Is_Public; + + + procedure Set_Original (Object : in out Storage_Ref; + Value : in AWA.Storages.Models.Storage_Ref'Class) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 10, Impl.Original, Value); + end Set_Original; + + function Get_Original (Object : in Storage_Ref) + return AWA.Storages.Models.Storage_Ref'Class is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Original; + end Get_Original; + + + procedure Set_Store_Data (Object : in out Storage_Ref; + Value : in AWA.Storages.Models.Storage_Data_Ref'Class) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 11, Impl.Store_Data, Value); + end Set_Store_Data; + + function Get_Store_Data (Object : in Storage_Ref) + return AWA.Storages.Models.Storage_Data_Ref'Class is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Store_Data; + end Get_Store_Data; + + + procedure Set_Owner (Object : in out Storage_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 12, Impl.Owner, Value); + end Set_Owner; + + function Get_Owner (Object : in Storage_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Owner; + end Get_Owner; + + + procedure Set_Workspace (Object : in out Storage_Ref; + Value : in AWA.Workspaces.Models.Workspace_Ref'Class) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 13, Impl.Workspace, Value); + end Set_Workspace; + + function Get_Workspace (Object : in Storage_Ref) + return AWA.Workspaces.Models.Workspace_Ref'Class is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Workspace; + end Get_Workspace; + + + procedure Set_Folder (Object : in out Storage_Ref; + Value : in AWA.Storages.Models.Storage_Folder_Ref'Class) is + Impl : Storage_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 14, Impl.Folder, Value); + end Set_Folder; + + function Get_Folder (Object : in Storage_Ref) + return AWA.Storages.Models.Storage_Folder_Ref'Class is + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Folder; + end Get_Folder; + + -- Copy of the object. + procedure Copy (Object : in Storage_Ref; + Into : in out Storage_Ref) is + Result : Storage_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Storage_Access + := Storage_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Storage_Access + := new Storage_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Storage := Impl.Storage; + Copy.Create_Date := Impl.Create_Date; + Copy.Name := Impl.Name; + Copy.File_Size := Impl.File_Size; + Copy.Mime_Type := Impl.Mime_Type; + Copy.Uri := Impl.Uri; + Copy.Version := Impl.Version; + Copy.Is_Public := Impl.Is_Public; + Copy.Original := Impl.Original; + Copy.Store_Data := Impl.Store_Data; + Copy.Owner := Impl.Owner; + Copy.Workspace := Impl.Workspace; + Copy.Folder := Impl.Folder;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Storage_Impl, Storage_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Storage_Impl_Ptr := Storage_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Storage_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, STORAGE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Storage_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Storage_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (STORAGE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- storage + Value => Integer (Storage_Type'Pos (Object.Storage))); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_3_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_3_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_3_NAME, -- file_size + Value => Object.File_Size); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_3_NAME, -- mime_type + Value => Object.Mime_Type); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_3_NAME, -- uri + Value => Object.Uri); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_3_NAME, -- is_public + Value => Object.Is_Public); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_3_NAME, -- original_id + Value => Object.Original); + Object.Clear_Modified (10); + end if; + if Object.Is_Modified (11) then + Stmt.Save_Field (Name => COL_10_3_NAME, -- store_data_id + Value => Object.Store_Data); + Object.Clear_Modified (11); + end if; + if Object.Is_Modified (12) then + Stmt.Save_Field (Name => COL_11_3_NAME, -- owner_id + Value => Object.Owner); + Object.Clear_Modified (12); + end if; + if Object.Is_Modified (13) then + Stmt.Save_Field (Name => COL_12_3_NAME, -- workspace_id + Value => Object.Workspace); + Object.Clear_Modified (13); + end if; + if Object.Is_Modified (14) then + Stmt.Save_Field (Name => COL_13_3_NAME, -- folder_id + Value => Object.Folder); + Object.Clear_Modified (14); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Store_Local_Impl, Store_Local_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Store_Local_Impl_Ptr := Store_Local_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Store_Local_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, STORE_LOCAL_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Store_Local_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Store_Local_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (STORE_LOCAL_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_4_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_4_NAME, -- store_version + Value => Object.Store_Version); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_4_NAME, -- shared + Value => Object.Shared); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_4_NAME, -- path + Value => Object.Path); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_4_NAME, -- expire_date + Value => Object.Expire_Date); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_4_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_4_NAME, -- storage_id + Value => Object.Storage); + Object.Clear_Modified (8); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Job_Status_Type); + Impl : Job_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 2, Impl.Status, Value); + end Set_Status; + + function Get_Status (Object : in Job_Ref) + return AWA.Jobs.Models.Job_Status_Type is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Status; + end Get_Status; + + + procedure Set_Name (Object : in out Job_Ref; + Value : in String) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 3, Impl.Name, Value); + end Set_Name; + + procedure Set_Name (Object : in out Job_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 3, Impl.Name, Value); + end Set_Name; + + function Get_Name (Object : in Job_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Name); + end Get_Name; + function Get_Name (Object : in Job_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Name; + end Get_Name; + + + procedure Set_Start_Date (Object : in out Job_Ref; + Value : in ADO.Nullable_Time) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 4, Impl.Start_Date, Value); + end Set_Start_Date; + + function Get_Start_Date (Object : in Job_Ref) + return ADO.Nullable_Time is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Start_Date; + end Get_Start_Date; + + + procedure Set_Create_Date (Object : in out Job_Ref; + Value : in Ada.Calendar.Time) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 5, Impl.Create_Date, Value); + end Set_Create_Date; + + function Get_Create_Date (Object : in Job_Ref) + return Ada.Calendar.Time is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Create_Date; + end Get_Create_Date; + + + procedure Set_Finish_Date (Object : in out Job_Ref; + Value : in ADO.Nullable_Time) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 6, Impl.Finish_Date, Value); + end Set_Finish_Date; + + function Get_Finish_Date (Object : in Job_Ref) + return ADO.Nullable_Time is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Finish_Date; + end Get_Finish_Date; + + + procedure Set_Progress (Object : in out Job_Ref; + Value : in Integer) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 7, Impl.Progress, Value); + end Set_Progress; + + function Get_Progress (Object : in Job_Ref) + return Integer is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Progress; + end Get_Progress; + + + procedure Set_Parameters (Object : in out Job_Ref; + Value : in String) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 8, Impl.Parameters, Value); + end Set_Parameters; + + procedure Set_Parameters (Object : in out Job_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 8, Impl.Parameters, Value); + end Set_Parameters; + + function Get_Parameters (Object : in Job_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Parameters); + end Get_Parameters; + function Get_Parameters (Object : in Job_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Parameters; + end Get_Parameters; + + + procedure Set_Results (Object : in out Job_Ref; + Value : in String) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 9, Impl.Results, Value); + end Set_Results; + + procedure Set_Results (Object : in out Job_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 9, Impl.Results, Value); + end Set_Results; + + function Get_Results (Object : in Job_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Results); + end Get_Results; + function Get_Results (Object : in Job_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Results; + end Get_Results; + + + function Get_Version (Object : in Job_Ref) + return Integer is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Version; + end Get_Version; + + + procedure Set_Priority (Object : in out Job_Ref; + Value : in Integer) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 11, Impl.Priority, Value); + end Set_Priority; + + function Get_Priority (Object : in Job_Ref) + return Integer is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Priority; + end Get_Priority; + + + procedure Set_User (Object : in out Job_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 12, Impl.User, Value); + end Set_User; + + function Get_User (Object : in Job_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.User; + end Get_User; + + + procedure Set_Event (Object : in out Job_Ref; + Value : in AWA.Events.Models.Message_Ref'Class) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 13, Impl.Event, Value); + end Set_Event; + + function Get_Event (Object : in Job_Ref) + return AWA.Events.Models.Message_Ref'Class is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Event; + end Get_Event; + + + procedure Set_Session (Object : in out Job_Ref; + Value : in AWA.Users.Models.Session_Ref'Class) is + Impl : Job_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 14, Impl.Session, Value); + end Set_Session; + + function Get_Session (Object : in Job_Ref) + return AWA.Users.Models.Session_Ref'Class is + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Session; + end Get_Session; + + -- Copy of the object. + procedure Copy (Object : in Job_Ref; + Into : in out Job_Ref) is + Result : Job_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Job_Access + := Job_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Job_Access + := new Job_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Status := Impl.Status; + Copy.Name := Impl.Name; + Copy.Start_Date := Impl.Start_Date; + Copy.Create_Date := Impl.Create_Date; + Copy.Finish_Date := Impl.Finish_Date; + Copy.Progress := Impl.Progress; + Copy.Parameters := Impl.Parameters; + Copy.Results := Impl.Results; + Copy.Version := Impl.Version; + Copy.Priority := Impl.Priority; + Copy.User := Impl.User; + Copy.Event := Impl.Event; + Copy.Session := Impl.Session;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Job_Impl, Job_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Job_Impl_Ptr := Job_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Job_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, JOB_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Job_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Job_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (JOB_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- status + Value => Integer (Job_Status_Type'Pos (Object.Status))); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- start_date + Value => Object.Start_Date); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- finish_date + Value => Object.Finish_Date); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- progress + Value => Object.Progress); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_1_NAME, -- parameters + Value => Object.Parameters); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_1_NAME, -- results + Value => Object.Results); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (11) then + Stmt.Save_Field (Name => COL_10_1_NAME, -- priority + Value => Object.Priority); + Object.Clear_Modified (11); + end if; + if Object.Is_Modified (12) then + Stmt.Save_Field (Name => COL_11_1_NAME, -- user_id + Value => Object.User); + Object.Clear_Modified (12); + end if; + if Object.Is_Modified (13) then + Stmt.Save_Field (Name => COL_12_1_NAME, -- event_id + Value => Object.Event); + Object.Clear_Modified (13); + end if; + if Object.Is_Modified (14) then + Stmt.Save_Field (Name => COL_13_1_NAME, -- session_id + Value => Object.Session); + Object.Clear_Modified (14); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Load_List (Into : in out Post_List_Bean) is,"use AWA.Blogs.Models; + use AWA.Services; + + Session : ADO.Sessions.Session := Into.Service.Get_Session; + Query : ADO.Queries.Context; + Count_Query : ADO.Queries.Context; + Tag_Id : ADO.Identifier; + First : constant Natural := (Into.Page - 1) * Into.Page_Size; + begin + AWA.Tags.Modules.Find_Tag_Id (Session, Ada.Strings.Unbounded.To_String (Into.Tag), Tag_Id); + if Tag_Id /= ADO.NO_IDENTIFIER then + Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_Tag_List); + Query.Bind_Param (Name => ""tag"", Value => Tag_Id); + Count_Query.Set_Count_Query (AWA.Blogs.Models.Query_Blog_Post_Tag_List); + Count_Query.Bind_Param (Name => ""tag"", Value => Tag_Id); + else + Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); + Count_Query.Set_Count_Query (AWA.Blogs.Models.Query_Blog_Post_List); + end if; + Query.Bind_Param (Name => ""first"", Value => First); + Query.Bind_Param (Name => ""count"", Value => Into.Page_Size); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""entity_type"", + Table => AWA.Blogs.Models.POST_TABLE, + Session => Session); + ADO.Sessions.Entities.Bind_Param (Params => Count_Query, + Name => ""entity_type"", + Table => AWA.Blogs.Models.POST_TABLE, + Session => Session); + AWA.Blogs.Models.List (Into.Posts, Session, Query); + Into.Count := ADO.Datasets.Get_Count (Session, Count_Query); + declare + List : ADO.Utils.Identifier_Vector; + Iter : Post_Info_Vectors.Cursor := Into.Posts.List.First; + begin + while Post_Info_Vectors.Has_Element (Iter) loop + List.Append (Post_Info_Vectors.Element (Iter).Id); + Post_Info_Vectors.Next (Iter); + end loop; + Into.Tags.Load_Tags (Session, AWA.Blogs.Models.POST_TABLE.Table.all, + List);" +function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access),"return Util.Beans.Basic.Readonly_Bean_Access is + Object : constant Post_List_Bean_Access := new Post_List_Bean; + begin + Object.Service := Module; + Object.Posts_Bean := Object.Posts'Access; + Object.Page_Size := 20; + Object.Page := 1; + Object.Count := 0; + Object.Counter_Bean := Object.Counter'Access; + Object.Counter.Counter := AWA.Blogs.Modules.Read_Counter.Index; + return Object.all'Access; + end Create_Post_List_Bean; + + -- ------------------------------ + -- Create the Blog_List_Bean bean instance. + -- ------------------------------ + function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) + return Util.Beans.Basic.Readonly_Bean_Access is + Object : constant Blog_Admin_Bean_Access := new Blog_Admin_Bean; + begin + Object.Module := Module; + Object.Flags := Object.Init_Flags'Access; + Object.Post_List_Bean := Object.Post_List'Access; + Object.Blog_List_Bean := Object.Blog_List'Access; + Object.Comment_List_Bean := Object.Comment_List'Access; + return Object.all'Access; + end Create_Blog_Admin_Bean; + + function Create_From_Status is + new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type, + ""blog_status_""); + + -- ------------------------------ + -- Get a select item list which contains a list of post status. + -- ------------------------------ + function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) + return Util.Beans.Basic.Readonly_Bean_Access is + pragma Unreferenced (Module); + use AWA.Helpers; + begin + return Selectors.Create_Selector_Bean (Bundle => ""blogs"", + Context => null, + Create => Create_From_Status'Access).all'Access; + end Create_Status_List; + + -- ------------------------------ + -- Load the list of blogs. + -- ------------------------------ + procedure Load_Blogs (List : in Blog_Admin_Bean) is + use AWA.Blogs.Models; + use AWA.Services; + + Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant ADO.Identifier := Ctx.Get_User_Identifier; + Session : ADO.Sessions.Session := List.Module.Get_Session; + Query : ADO.Queries.Context; + begin + Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); + Query.Bind_Param (""user_id"", User); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""table"", + Table => AWA.Blogs.Models.BLOG_TABLE, + Session => Session); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""entity_type"", + Table => AWA.Blogs.Models.POST_TABLE, + Session => Session); + AWA.Blogs.Models.List (List.Blog_List_Bean.all, Session, Query); + List.Flags (INIT_BLOG_LIST) := True; + end Load_Blogs; + + -- ------------------------------ + -- Get the blog identifier. + -- ------------------------------ + function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier is + begin + if List.Blog_Id = ADO.NO_IDENTIFIER then + if not List.Flags (INIT_BLOG_LIST) then + Load_Blogs (List); + end if; + if not List.Blog_List.List.Is_Empty then + return List.Blog_List.List.Element (0).Id; + end if; + end if; + return List.Blog_Id; + end Get_Blog_Id; + + -- ------------------------------ + -- Load the posts associated with the current blog. + -- ------------------------------ + procedure Load_Posts (List : in Blog_Admin_Bean) is + use AWA.Blogs.Models; + use AWA.Services; + + Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant ADO.Identifier := Ctx.Get_User_Identifier; + Session : ADO.Sessions.Session := List.Module.Get_Session; + Query : ADO.Queries.Context; + Blog_Id : constant ADO.Identifier := List.Get_Blog_Id; + begin + if Blog_Id /= ADO.NO_IDENTIFIER then + Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); + Query.Bind_Param (""blog_id"", Blog_Id); + Query.Bind_Param (""user_id"", User); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""table"", + Table => AWA.Blogs.Models.BLOG_TABLE, + Session => Session); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""entity_type"", + Table => AWA.Blogs.Models.POST_TABLE, + Session => Session); + + AWA.Blogs.Models.List (List.Post_List_Bean.all, Session, Query); + List.Flags (INIT_POST_LIST) := True; + end if; + end Load_Posts; + + -- ------------------------------ + -- Load the comments associated with the current blog. + -- ------------------------------ + procedure Load_Comments (List : in Blog_Admin_Bean) is + use AWA.Blogs.Models; + use AWA.Services; + + Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant ADO.Identifier := Ctx.Get_User_Identifier; + Session : ADO.Sessions.Session := List.Module.Get_Session; + Query : ADO.Queries.Context; + Blog_Id : constant ADO.Identifier := List.Get_Blog_Id; + begin + if Blog_Id /= ADO.NO_IDENTIFIER then + Query.Set_Query (AWA.Blogs.Models.Query_Comment_List); + Query.Bind_Param (""blog_id"", Blog_Id); + Query.Bind_Param (""user_id"", User); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""table"", + Table => AWA.Blogs.Models.BLOG_TABLE, + Session => Session); + ADO.Sessions.Entities.Bind_Param (Params => Query, + Name => ""entity_type"", + Table => AWA.Blogs.Models.POST_TABLE, + Session => Session); + + AWA.Blogs.Models.List (List.Comment_List_Bean.all, Session, Query); + List.Flags (INIT_COMMENT_LIST) := True; + end if; + end Load_Comments; + + overriding + function Get_Value (List : in Blog_Admin_Bean; + Name : in String) return Util.Beans.Objects.Object is + begin + if Name = ""blogs"" then + if not List.Init_Flags (INIT_BLOG_LIST) then + Load_Blogs (List); + end if; + return Util.Beans.Objects.To_Object (Value => List.Blog_List_Bean, + Storage => Util.Beans.Objects.STATIC); + + elsif Name = ""posts"" then + if not List.Init_Flags (INIT_POST_LIST) then + Load_Posts (List); + end if; + return Util.Beans.Objects.To_Object (Value => List.Post_List_Bean, + Storage => Util.Beans.Objects.STATIC); + + elsif Name = ""comments"" then + if not List.Init_Flags (INIT_COMMENT_LIST) then + Load_Comments (List); + end if; + return Util.Beans.Objects.To_Object (Value => List.Comment_List_Bean, + Storage => Util.Beans.Objects.STATIC); + + elsif Name = ""id"" then + declare + Id : constant ADO.Identifier := List.Get_Blog_Id; + begin + if Id = ADO.NO_IDENTIFIER then + return Util.Beans.Objects.Null_Object; + else + return Util.Beans.Objects.To_Object (Long_Long_Integer (Id)); + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Blog_Impl, Blog_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Blog_Impl_Ptr := Blog_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Blog_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, BLOG_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Blog_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Blog_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (BLOG_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- uid + Value => Object.Uid); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- update_date + Value => Object.Update_Date); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- url + Value => Object.Url); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_1_NAME, -- workspace_id + Value => Object.Workspace); + Object.Clear_Modified (8); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Blog_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, BLOG_DEF'Access); + begin + Stmt.Execute; + Blog_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Blog_Ref; + Impl : constant Blog_Access := new Blog_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Set_Publish_Date (Object : in out Post_Ref;,"Value : in ADO.Nullable_Time) is + Impl : Post_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 7, Impl.Publish_Date, Value); + end Set_Publish_Date; + + function Get_Publish_Date (Object : in Post_Ref) + return ADO.Nullable_Time is + Impl : constant Post_Access + := Post_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Publish_Date; + end Get_Publish_Date; + + + procedure Set_Status (Object : in out Post_Ref; + Value : in AWA.Blogs.Models.Post_Status_Type) is + procedure Set_Field_Enum is + new ADO.Objects.Set_Field_Operation (Post_Status_Type); + Impl : Post_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 8, Impl.Status, Value); + end Set_Status; + + function Get_Status (Object : in Post_Ref) + return AWA.Blogs.Models.Post_Status_Type is + Impl : constant Post_Access + := Post_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Status; + end Get_Status; + + + procedure Set_Allow_Comments (Object : in out Post_Ref; + Value : in Boolean) is + Impl : Post_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Boolean (Impl.all, 9, Impl.Allow_Comments, Value); + ADO.Objects.Set_Field_Boolean (Impl.all, 9, Impl.Allow_Comments, Value); + end Set_Allow_Comments; + + function Get_Allow_Comments (Object : in Post_Ref) + return Boolean is + Impl : constant Post_Access + := Post_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Allow_Comments; + end Get_Allow_Comments; + + + procedure Set_Read_Count (Object : in out Post_Ref; + Value : in Integer) is + Impl : Post_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 10, Impl.Read_Count, Value); + end Set_Read_Count; + + function Get_Read_Count (Object : in Post_Ref) + return Integer is + Impl : constant Post_Access + := Post_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Read_Count; + end Get_Read_Count; + + + procedure Set_Author (Object : in out Post_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Post_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 11, Impl.Author, Value); + end Set_Author; + + function Get_Author (Object : in Post_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Post_Access + := Post_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Author; + end Get_Author; + + + procedure Set_Blog (Object : in out Post_Ref; + Value : in AWA.Blogs.Models.Blog_Ref'Class) is + Impl : Post_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 12, Impl.Blog, Value); + end Set_Blog; + + function Get_Blog (Object : in Post_Ref) + return AWA.Blogs.Models.Blog_Ref'Class is + Impl : constant Post_Access + := Post_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Blog; + end Get_Blog; + + -- Copy of the object. + procedure Copy (Object : in Post_Ref; + Into : in out Post_Ref) is + Result : Post_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Post_Access + := Post_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Post_Access + := new Post_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Title := Impl.Title; + Copy.Text := Impl.Text; + Copy.Create_Date := Impl.Create_Date; + Copy.Uri := Impl.Uri; + Copy.Version := Impl.Version; + Copy.Publish_Date := Impl.Publish_Date; + Copy.Status := Impl.Status; + Copy.Allow_Comments := Impl.Allow_Comments; + Copy.Read_Count := Impl.Read_Count; + Copy.Author := Impl.Author; + Copy.Blog := Impl.Blog;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Post_Impl, Post_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Post_Impl_Ptr := Post_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Post_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, POST_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Post_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Post_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (POST_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- title + Value => Object.Title); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- text + Value => Object.Text); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- uri + Value => Object.Uri); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_2_NAME, -- publish_date + Value => Object.Publish_Date); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_2_NAME, -- status + Value => Integer (Post_Status_Type'Pos (Object.Status))); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_2_NAME, -- allow_comments + Value => Object.Allow_Comments); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_2_NAME, -- read_count + Value => Object.Read_Count); + Object.Clear_Modified (10); + end if; + if Object.Is_Modified (11) then + Stmt.Save_Field (Name => COL_10_2_NAME, -- author_id + Value => Object.Author); + Object.Clear_Modified (11); + end if; + if Object.Is_Modified (12) then + Stmt.Save_Field (Name => COL_11_2_NAME, -- blog_id + Value => Object.Blog); + Object.Clear_Modified (12); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array is,"use Ada.Strings.Unbounded; + begin + return Security.Permissions.Get_Permission_Array (To_String (Manager.Owner_Permissions)); + end Get_Owner_Permissions; + + -- Get the workspace module. + function Get_Workspace_Module return Workspace_Module_Access is + function Get is new AWA.Modules.Get (Workspace_Module, Workspace_Module_Access, NAME); + begin + return Get; + end Get_Workspace_Module; + + -- ------------------------------ + -- Get the current workspace associated with the current user. + -- If the user has not workspace, create one. + -- ------------------------------ + procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; + Context : in AWA.Services.Contexts.Service_Context_Access; + Workspace : out AWA.Workspaces.Models.Workspace_Ref) is + User : constant AWA.Users.Models.User_Ref := Context.Get_User; + WS : AWA.Workspaces.Models.Workspace_Ref; + Member : AWA.Workspaces.Models.Workspace_Member_Ref; + Query : ADO.SQL.Query; + Found : Boolean; + Plugin : constant Workspace_Module_Access := Get_Workspace_Module; + begin + if User.Is_Null then + Log.Error (""There is no current user. The workspace cannot be identified""); + Workspace := AWA.Workspaces.Models.Null_Workspace; + return; + end if; + + -- Find the workspace associated with the current user. + Query.Add_Param (User.Get_Id); + Query.Set_Filter (""o.owner_id = ?""); + WS.Find (Session, Query, Found); + if Found then + Workspace := WS; + return; + end if; + + -- Check that the user has the permission to create a new workspace. + AWA.Permissions.Check (Permission => ACL_Create_Workspace.Permission, + Entity => User); + + -- Create a workspace for this user. + WS.Set_Owner (User); + WS.Set_Create_Date (Ada.Calendar.Clock); + WS.Save (Session); + + -- Create the member instance for this user. + Member.Set_Workspace (WS); + Member.Set_Member (User); + Member.Set_Role (""Owner""); + Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => WS.Get_Create_Date)); + Member.Save (Session); + + -- And give full control of the workspace for this user + Add_Permission (Session => Session, + User => User.Get_Id, + Entity => WS, + Workspace => WS.Get_Id, + List => Plugin.Get_Owner_Permissions); + + Workspace := WS; + end Get_Workspace; + + -- ------------------------------ + -- Create a workspace for the user. + -- ------------------------------ + procedure Create_Workspace (Module : in Workspace_Module; + Workspace : out AWA.Workspaces.Models.Workspace_Ref) is + Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + WS : AWA.Workspaces.Models.Workspace_Ref; + Member : AWA.Workspaces.Models.Workspace_Member_Ref; + begin + if User.Is_Null then + Log.Error (""There is no current user. The workspace cannot be identified""); + Workspace := AWA.Workspaces.Models.Null_Workspace; + return; + end if; + + -- Check that the user has the permission to create a new workspace. + AWA.Permissions.Check (Permission => ACL_Create_Workspace.Permission, + Entity => User); + + DB.Begin_Transaction; + + -- Create a workspace for this user. + WS.Set_Owner (User); + WS.Set_Create_Date (Ada.Calendar.Clock); + WS.Save (DB); + + -- Create the member instance for this user. + Member.Set_Workspace (WS); + Member.Set_Member (User); + Member.Set_Role (""Owner""); + Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => WS.Get_Create_Date)); + Member.Save (DB); + + -- And give full control of the workspace for this user + Add_Permission (Session => DB, + User => User.Get_Id, + Entity => WS, + Workspace => WS.Get_Id, + List => Module.Get_Owner_Permissions); + + Workspace := WS; + DB.Commit; + end Create_Workspace; + + -- ------------------------------ + -- Load the invitation from the access key and verify that the key is still valid. + -- ------------------------------ + procedure Load_Invitation (Module : in Workspace_Module; + Key : in String; + Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; + Inviter : in out AWA.Users.Models.User_Ref) is + pragma Unreferenced (Module); + use type Ada.Calendar.Time; + + Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + Query : ADO.SQL.Query; + DB_Key : AWA.Users.Models.Access_Key_Ref; + Found : Boolean; + begin + Log.Debug (""Loading invitation from key {0}"", Key); + + Query.Set_Filter (""o.access_key = :key""); + Query.Bind_Param (""key"", Key); + DB_Key.Find (DB, Query, Found); + if not Found then + Log.Info (""Invitation key {0} does not exist""); + raise Not_Found; + end if; + if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then + Log.Info (""Invitation key {0} has expired""); + raise Not_Found; + end if; + Query.Set_Filter (""o.invitee_id = :user""); + Query.Bind_Param (""user"", DB_Key.Get_User.Get_Id); + Invitation.Find (DB, Query, Found); + if not Found then + Log.Warn (""Invitation key {0} has been withdawn""); + raise Not_Found; + end if; + Inviter := AWA.Users.Models.User_Ref (Invitation.Get_Inviter); + end Load_Invitation; + + -- ------------------------------ + -- Accept the invitation identified by the access key. + -- ------------------------------ + procedure Accept_Invitation (Module : in Workspace_Module; + Key : in String) is + use type Ada.Calendar.Time; + + Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; + DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + Query : ADO.SQL.Query; + DB_Key : AWA.Users.Models.Access_Key_Ref; + Found : Boolean; + Invitation : AWA.Workspaces.Models.Invitation_Ref; + Invitee_Id : ADO.Identifier; + Workspace_Id : ADO.Identifier; + Member : AWA.Workspaces.Models.Workspace_Member_Ref; + User_Member : AWA.Workspaces.Models.Workspace_Member_Ref; + Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; + begin + Log.Debug (""Accept invitation with key {0}"", Key); + Ctx.Start; + + -- Get the access key and verify its validity. + Query.Set_Filter (""o.access_key = :key""); + Query.Bind_Param (""key"", Key); + DB_Key.Find (DB, Query, Found); + if not Found then + Log.Info (""Invitation key {0} does not exist"", Key); + raise Not_Found; + end if; + if DB_Key.Get_Expire_Date < Now then + Log.Info (""Invitation key {0} has expired"", Key); + raise Not_Found; + end if; + + -- Find the invitation associated with the access key. + Invitee_Id := DB_Key.Get_User.Get_Id; + Query.Set_Filter (""o.invitee_id = :user""); + Query.Bind_Param (""user"", Invitee_Id); + Invitation.Find (DB, Query, Found); + if not Found then + Log.Warn (""Invitation key {0} has been withdawn"", Key); + raise Not_Found; + end if; + Member := AWA.Workspaces.Models.Workspace_Member_Ref (Invitation.Get_Member); + Workspace_Id := Invitation.Get_Workspace.Get_Id; + + -- Update the workspace member relation. + Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, + Value => Now)); + Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False, + Value => Now)); + + -- The user who received the invitation is different from the user who is + -- logged and accepted the validation. Since the key is verified, this is + -- the same user but the user who accepted the invitation registered using + -- another email address. + if Invitee_Id /= User.Get_Id then + -- Check whether the user is not already part of the workspace. + Query.Clear; + Query.Set_Filter (""o.member_id = ? AND o.workspace_id = ?""); + Query.Add_Param (User.Get_Id); + Query.Add_Param (Workspace_Id); + User_Member.Find (DB, Query, Found); + if Found then + Member.Delete (DB); + Invitation.Delete (DB); + Log.Info (""Invitation accepted by user who is already a member""); + else + Member.Set_Member (User); + Log.Info (""Invitation accepted by user with another email address""); + Invitation.Set_Invitee (User); + end if; + end if; + if not Member.Is_Null then + Member.Save (DB); + end if; + DB_Key.Delete (DB); + if not Invitation.Is_Null then + Invitation.Save (DB); + + -- Send the accepted invitation event. + declare + Event : AWA.Events.Module_Event; + begin + Event.Set_Parameter (""invitee_email"", User.Get_Email.Get_Email); + Event.Set_Parameter (""invitee_name"", User.Get_Name); + Event.Set_Parameter (""message"", Invitation.Get_Message); + Event.Set_Parameter (""inviter_email"", Invitation.Get_Inviter.Get_Email.Get_Email); + Event.Set_Parameter (""inviter_name"", Invitation.Get_Inviter.Get_Name); + Event.Set_Event_Kind (Accept_Invitation_Event.Kind); + Module.Send_Event (Event);" +procedure Add_Permission (Session : in out ADO.Sessions.Master_Session;,"User : in ADO.Identifier; + Entity : in ADO.Objects.Object_Ref'Class; + Workspace : in ADO.Identifier; + List : in Security.Permissions.Permission_Index_Array) is + Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; + Key : constant ADO.Objects.Object_Key := Entity.Get_Key; + Id : constant ADO.Identifier := ADO.Objects.Get_Value (Key); + Kind : constant ADO.Entity_Type + := ADO.Sessions.Entities.Find_Entity_Type (Session => Session, + Object => Key); + Manager : constant AWA.Permissions.Services.Permission_Manager_Access + := AWA.Permissions.Services.Get_Permission_Manager (Ctx); + begin + for Perm of List loop + declare + Member : ADO.Identifier; + Query : ADO.Queries.Context; + Names : constant Security.Policies.Roles.Role_Name_Array + := Manager.Get_Role_Names (Perm); + Need_Sep : Boolean := False; + User_Added : Boolean := False; + begin + if Names'Length > 0 then + Query.Set_Query (AWA.Workspaces.Models.Query_Member_In_Role); + ADO.SQL.Append (Query.Filter, ""user_member.workspace_id = :workspace_id""); + ADO.SQL.Append (Query.Filter, "" AND user_member.member_id IN (""); + for Name of Names loop + ADO.SQL.Append (Query.Filter, (if Need_Sep then "",?"" else ""?"")); + Query.Add_Param (Name.all); + Need_Sep := True; + end loop; + Query.Bind_Param (""workspace_id"", Workspace); + ADO.SQL.Append (Query.Filter, "")""); + declare + Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); + begin + Stmt.Execute; + while Stmt.Has_Elements loop + Member := Stmt.Get_Identifier (0); + if Member = User then + User_Added := True; + end if; + Manager.Add_Permission (Session => Session, + User => Member, + Entity => Id, + Kind => Kind, + Workspace => Workspace, + Permission => Perm); + Stmt.Next; + end loop;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Workspace_Impl, Workspace_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Workspace_Impl_Ptr := Workspace_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Workspace_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, WORKSPACE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Workspace_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Workspace_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (WORKSPACE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- owner_id + Value => Object.Owner); + Object.Clear_Modified (4); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Workspace_Member_Impl, Workspace_Member_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Workspace_Member_Impl_Ptr := Workspace_Member_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Workspace_Member_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, WORKSPACE_MEMBER_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Workspace_Member_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Workspace_Member_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (WORKSPACE_MEMBER_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- join_date + Value => Object.Join_Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- role + Value => Object.Role); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- member_id + Value => Object.Member); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- workspace_id + Value => Object.Workspace); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Invitation_Impl, Invitation_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Invitation_Impl_Ptr := Invitation_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Invitation_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, INVITATION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Invitation_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Invitation_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (INVITATION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_3_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_3_NAME, -- email + Value => Object.Email); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_3_NAME, -- message + Value => Object.Message); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_3_NAME, -- acceptance_date + Value => Object.Acceptance_Date); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_3_NAME, -- workspace_id + Value => Object.Workspace); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_3_NAME, -- access_key_id + Value => Object.Access_Key); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_3_NAME, -- invitee_id + Value => Object.Invitee); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_3_NAME, -- inviter_id + Value => Object.Inviter); + Object.Clear_Modified (10); + end if; + if Object.Is_Modified (11) then + Stmt.Save_Field (Name => COL_10_3_NAME, -- member_id + Value => Object.Member); + Object.Clear_Modified (11); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Workspace_Feature_Impl, Workspace_Feature_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Workspace_Feature_Impl_Ptr := Workspace_Feature_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Workspace_Feature_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, WORKSPACE_FEATURE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Workspace_Feature_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Workspace_Feature_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (WORKSPACE_FEATURE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_4_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_4_NAME, -- limit + Value => Object.Limit); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_4_NAME, -- workspace_id + Value => Object.Workspace); + Object.Clear_Modified (3); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +function Get_Invitation_Bean is,"new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean, + Element_Access => Beans.Invitation_Bean_Access); + + package Caller is new Util.Test_Caller (Test, ""Workspaces.Beans""); + + procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is + begin + Caller.Add_Test (Suite, ""Test AWA.Workspaces.Beans.Send"", + Test_Invite_User'Access); + Caller.Add_Test (Suite, ""Test AWA.Workspaces.Beans.Delete"", + Test_Delete_Member'Access); + Caller.Add_Test (Suite, ""Test AWA.Workspaces.Beans.Accept"", + Test_Accept_Invitation'Access); + Caller.Add_Test (Suite, ""Test AWA.Workspaces.Beans.Member_List"", + Test_List_Members'Access); + end Add_Tests; + + -- ------------------------------ + -- Verify the anonymous access for the invitation page. + -- ------------------------------ + procedure Verify_Anonymous (T : in out Test; + Key : in String) is + Request : ASF.Requests.Mockup.Request; + Reply : ASF.Responses.Mockup.Response; + begin + ASF.Tests.Do_Get (Request, Reply, ""/auth/invitation.html"", ""invitation-view.html""); + ASF.Tests.Assert_Contains (T, ""Bad or invalid invitation"", Reply, + ""This invitation is invalid""); + + ASF.Tests.Do_Get (Request, Reply, ""/auth/invitation.html?key=test"", ""invitation-bad.html""); + ASF.Tests.Assert_Contains (T, ""This invitation is invalid or has expired"", Reply, + ""This invitation is invalid (key)""); + + ASF.Tests.Do_Get (Request, Reply, ""/auth/invitation.html?key=x"" & key, + ""invitation-bad2.html""); + ASF.Tests.Assert_Contains (T, ""This invitation is invalid or has expired"", + Reply, ""This invitation is invalid (key)""); + + if Key = """" then + return; + end if; + + ASF.Tests.Do_Get (Request, Reply, ""/auth/invitation.html?key="" & Key, ""invitation-ok.html""); + ASF.Tests.Assert_Contains (T, ""Accept invitation"", Reply, + ""Accept invitation page is invalid""); + + end Verify_Anonymous; + + -- ------------------------------ + -- Test sending an invitation. + -- ------------------------------ + procedure Test_Invite_User (T : in out Test) is + use type ADO.Identifier; + use type AWA.Workspaces.Beans.Invitation_Bean_Access; + + Request : ASF.Requests.Mockup.Request; + Reply : ASF.Responses.Mockup.Response; + Invite : AWA.Workspaces.Beans.Invitation_Bean_Access; + begin + AWA.Tests.Helpers.Users.Login (""test-invite@test.com"", Request); + Request.Set_Parameter (""email"", ""invited-user@test.com""); + Request.Set_Parameter (""message"", ""I invite you to this application""); + Request.Set_Parameter (""send"", ""1""); + Request.Set_Parameter (""invite"", ""1""); + ASF.Tests.Do_Post (Request, Reply, ""/workspaces/invite.html"", ""invite.html""); + + T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, + ""Invalid response after invitation creation""); + + -- Verify the invitation by looking at the inviteUser bean. + Invite := Get_Invitation_Bean (Request, ""inviteUser""); + T.Assert (Invite /= null, ""Null inviteUser bean""); + T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, ""The invite ID is invalid""); + T.Assert (not Invite.Get_Access_Key.Is_Null, ""The invite access key is null""); + T.Assert (Invite.Get_Member.Is_Inserted, ""The invitation has a workspace member""); + T.Key := Invite.Get_Access_Key.Get_Access_Key; + T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key); + + T.Member_ID := Invite.Get_Member.Get_Id; + end Test_Invite_User; + + -- ------------------------------ + -- Test deleting the member. + -- ------------------------------ + procedure Test_Delete_Member (T : in out Test) is + Request : ASF.Requests.Mockup.Request; + Reply : ASF.Responses.Mockup.Response; + begin + T.Test_Invite_User; + AWA.Tests.Helpers.Users.Login (""test-invite@test.com"", Request); + declare + Id : constant String := ADO.Identifier'Image (T.Member_Id); + begin + Request.Set_Parameter (""member-id"", Id); + Request.Set_Parameter (""delete"", ""1""); + Request.Set_Parameter (""delete-member-form"", ""1""); + ASF.Tests.Do_Post (Request, Reply, ""/workspaces/forms/delete-member.html"", + ""delete-member.html""); + + T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, + ""Invalid response after delete member operation""); + ASF.Tests.Assert_Contains (T, ""deleteDialog_"" & Id (Id'First + 1 .. Id'Last), Reply, + ""Delete member dialog operation response is invalid"");" +"function Get is new AWA.Modules.Get (Counter_Module, Counter_Module_Access, NAME);","begin + return Get; + end Get_Counter_Module; + + -- ------------------------------ + -- Increment the counter identified by Counter and associated with the + -- database object Object. + -- ------------------------------ + procedure Increment (Plugin : in out Counter_Module; + Counter : in Counter_Index_Type; + Object : in ADO.Objects.Object_Ref'Class) is + Key : constant ADO.Objects.Object_Key := Object.Get_Key; + begin + if Plugin.Counters.Need_Flush (Plugin.Counter_Limit, Plugin.Age_Limit) then + Plugin.Flush; + end if; + Plugin.Counters.Increment (Counter, Key); + end Increment; + + -- ------------------------------ + -- Increment the counter identified by Counter and associated with the + -- database object key Key. + -- ------------------------------ + procedure Increment (Plugin : in out Counter_Module; + Counter : in Counter_Index_Type; + Key : in ADO.Objects.Object_Key) is + begin + if Plugin.Counters.Need_Flush (Plugin.Counter_Limit, Plugin.Age_Limit) then + Plugin.Flush; + end if; + Plugin.Counters.Increment (Counter, Key); + end Increment; + + -- ------------------------------ + -- Increment the counter identified by Counter. + -- ------------------------------ + procedure Increment (Plugin : in out Counter_Module; + Counter : in Counter_Index_Type) is + Key : ADO.Objects.Object_Key (ADO.Objects.KEY_INTEGER, null); + begin + if Plugin.Counters.Need_Flush (Plugin.Counter_Limit, Plugin.Age_Limit) then + Plugin.Flush; + end if; + Plugin.Counters.Increment (Counter, Key); + end Increment; + + -- ------------------------------ + -- Get the current counter value. + -- ------------------------------ + procedure Get_Counter (Plugin : in out Counter_Module; + Counter : in AWA.Counters.Counter_Index_Type; + Object : in ADO.Objects.Object_Ref'Class; + Result : out Natural) is + Id : constant ADO.Identifier := ADO.Objects.Get_Value (Object.Get_Key); + DB : ADO.Sessions.Master_Session := Plugin.Get_Master_Session; + Stmt : ADO.Statements.Query_Statement + := DB.Create_Statement (""SELECT SUM(counter) FROM awa_counter WHERE "" + & ""object_id = :id AND definition_id = :definition_id""); + Def_Id : Natural; + begin + Plugin.Counters.Get_Definition (DB, Counter, Def_Id); + Stmt.Bind_Param (""id"", Id); + Stmt.Bind_Param (""definition_id"", Def_Id); + Stmt.Execute; + Result := Stmt.Get_Result_Integer; + end Get_Counter; + + protected body Counter_Table is + + -- ------------------------------ + -- Increment the counter identified by Counter and associated with the + -- database object Key. + -- ------------------------------ + procedure Increment (Counter : in Counter_Index_Type; + Key : in ADO.Objects.Object_Key) is + + procedure Increment (Key : in ADO.Objects.Object_Key; + Element : in out Positive); + + procedure Increment (Key : in ADO.Objects.Object_Key; + Element : in out Positive) is + pragma Unreferenced (Key); + begin + Element := Element + 1; + end Increment; + + Pos : Counter_Maps.Cursor; + begin + if Counters = null then + Counters := new Counter_Map_Array (1 .. Counter_Arrays.Get_Last); + Day := Ada.Calendar.Clock; + Day_End := Util.Dates.Get_Day_End (Day); + end if; + Pos := Counters (Counter).Find (Key); + if Counter_Maps.Has_Element (Pos) then + Counters (Counter).Update_Element (Pos, Increment'Access); + else + Counters (Counter).Insert (Key, 1); + Nb_Counters := Nb_Counters + 1; + end if; + end Increment; + + -- ------------------------------ + -- Get the counters that have been collected with the date and prepare to collect + -- new counters. + -- ------------------------------ + procedure Steal_Counters (Result : out Counter_Map_Array_Access; + Date : out Ada.Calendar.Time) is + begin + Result := Counters; + Date := Day; + Counters := null; + Nb_Counters := 0; + end Steal_Counters; + + -- ------------------------------ + -- Check if we must flush the counters. + -- ------------------------------ + function Need_Flush (Limit : in Natural; + Seconds : in Duration) return Boolean is + use type Ada.Calendar.Time; + begin + if Counters = null then + return False; + elsif Nb_Counters > Limit then + return True; + else + declare + Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; + begin + return Now > Day_End or Now - Day >= Seconds;" +procedure Free is new,"Ada.Unchecked_Deallocation (Object => Counter_Map_Array, + Name => Counter_Map_Array_Access); + + Day : Ada.Calendar.Time; + Counters : Counter_Map_Array_Access; + begin + Plugin.Counters.Steal_Counters (Counters, Day); + if Counters = null then + return; + end if; + declare + DB : ADO.Sessions.Master_Session := Plugin.Get_Master_Session; + Date : constant Ada.Calendar.Time := Util.Dates.Get_Day_Start (Day); + Def_Id : Natural; + begin + DB.Begin_Transaction; + for I in Counters'Range loop + if not Counters (I).Is_Empty then + declare + Counter : constant Counter_Def := Counter_Arrays.Get_Element (I).all; + begin + Plugin.Counters.Get_Definition (DB, I, Def_Id); + Flush (DB, Counter, Def_Id, Counters (I), Date);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Counter_Impl, Counter_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Counter_Impl_Ptr := Counter_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Counter_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, COUNTER_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Counter_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""definition_id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Counter_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (COUNTER_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- object_id + Value => Object.Object_Id); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- date + Value => Object.Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- counter + Value => Object.Counter); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- definition_id + Value => Object.Get_Key); + Object.Clear_Modified (4); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""definition_id = ? AND object_id = ? AND date = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Object_Id); + Stmt.Add_Param (Value => Object.Date); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Counter_Definition_Impl, Counter_Definition_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Counter_Definition_Impl_Ptr := Counter_Definition_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Counter_Definition_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, COUNTER_DEFINITION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Counter_Definition_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Counter_Definition_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (COUNTER_DEFINITION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- entity_type + Value => Object.Entity_Type); + Object.Clear_Modified (3); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +function Visit_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is,"Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, + Of_Class => VISIT_DEF'Access); + begin + ADO.Objects.Set_Value (Result, Id); + return Result; + end Visit_Key; + + function Visit_Key (Id : in String) return ADO.Objects.Object_Key is + Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, + Of_Class => VISIT_DEF'Access); + begin + ADO.Objects.Set_Value (Result, Id); + return Result; + end Visit_Key; + + function ""="" (Left, Right : Visit_Ref'Class) return Boolean is + begin + return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); + end ""=""; + + procedure Set_Field (Object : in out Visit_Ref'Class; + Impl : out Visit_Access) is + Result : ADO.Objects.Object_Record_Access; + begin + Object.Prepare_Modify (Result); + Impl := Visit_Impl (Result.all)'Access; + end Set_Field; + + -- Internal method to allocate the Object_Record instance + procedure Allocate (Object : in out Visit_Ref) is + Impl : Visit_Access; + begin + Impl := new Visit_Impl; + Impl.Object_Id := ADO.NO_IDENTIFIER; + Impl.Counter := 0; + Impl.Date := ADO.DEFAULT_TIME; + Impl.User := ADO.NO_IDENTIFIER; + ADO.Objects.Set_Object (Object, Impl.all'Access); + end Allocate; + + -- ---------------------------------------- + -- Data object: Visit + -- ---------------------------------------- + + procedure Set_Object_Id (Object : in out Visit_Ref; + Value : in ADO.Identifier) is + Impl : Visit_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Identifier (Impl.all, 1, Impl.Object_Id, Value); + end Set_Object_Id; + + function Get_Object_Id (Object : in Visit_Ref) + return ADO.Identifier is + Impl : constant Visit_Access + := Visit_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Object_Id; + end Get_Object_Id; + + + procedure Set_Counter (Object : in out Visit_Ref; + Value : in Integer) is + Impl : Visit_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 2, Impl.Counter, Value); + end Set_Counter; + + function Get_Counter (Object : in Visit_Ref) + return Integer is + Impl : constant Visit_Access + := Visit_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Counter; + end Get_Counter; + + + procedure Set_Date (Object : in out Visit_Ref; + Value : in Ada.Calendar.Time) is + Impl : Visit_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 3, Impl.Date, Value); + end Set_Date; + + function Get_Date (Object : in Visit_Ref) + return Ada.Calendar.Time is + Impl : constant Visit_Access + := Visit_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Date; + end Get_Date; + + + procedure Set_User (Object : in out Visit_Ref; + Value : in ADO.Identifier) is + Impl : Visit_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Identifier (Impl.all, 4, Impl.User, Value); + end Set_User; + + function Get_User (Object : in Visit_Ref) + return ADO.Identifier is + Impl : constant Visit_Access + := Visit_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.User; + end Get_User; + + + procedure Set_Definition_Id (Object : in out Visit_Ref; + Value : in ADO.Identifier) is + Impl : Visit_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Key_Value (Impl.all, 5, Value); + end Set_Definition_Id; + + function Get_Definition_Id (Object : in Visit_Ref) + return ADO.Identifier is + Impl : constant Visit_Access + := Visit_Impl (Object.Get_Object.all)'Access; + begin + return Impl.Get_Key_Value; + end Get_Definition_Id; + + -- Copy of the object. + procedure Copy (Object : in Visit_Ref; + Into : in out Visit_Ref) is + Result : Visit_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Visit_Access + := Visit_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Visit_Access + := new Visit_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Object_Id := Impl.Object_Id; + Copy.Counter := Impl.Counter; + Copy.Date := Impl.Date; + Copy.User := Impl.User;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Visit_Impl, Visit_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Visit_Impl_Ptr := Visit_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Visit_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, VISIT_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Visit_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""definition_id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Visit_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (VISIT_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- object_id + Value => Object.Object_Id); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_3_NAME, -- counter + Value => Object.Counter); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_3_NAME, -- date + Value => Object.Date); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_3_NAME, -- user + Value => Object.User); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_3_NAME, -- definition_id + Value => Object.Get_Key); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""definition_id = ? AND object_id = ? AND user = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Object_Id); + Stmt.Add_Param (Value => Object.User); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure List (Object : in out Visit_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, VISIT_DEF'Access); + begin + Stmt.Execute; + Visit_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Visit_Ref; + Impl : constant Visit_Access := new Visit_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Register_Functions is,"new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions); + begin + Log.Info (""Initializing application components""); + + ASF.Applications.Main.Application (App).Initialize_Components; + App.Add_Components (AWA.Components.Factory.Definition); + Register_Functions (App); + end Initialize_Components; + + -- ------------------------------ + -- Read the application configuration file awa.xml. This is called after the servlets + -- and filters have been registered in the application but before the module registration. + -- ------------------------------ + procedure Load_Configuration (App : in out Application; + Files : in String) is + procedure Load_Config (File : in String; + Done : out Boolean); + + Paths : constant String := App.Get_Config (P_Module_Dir.P); + Ctx : aliased EL.Contexts.Default.Default_Context; + + procedure Load_Config (File : in String; + Done : out Boolean) is + Path : constant String := Util.Files.Find_File_Path (File, Paths); + begin + Done := False; + AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access, True); + + exception + when Ada.IO_Exceptions.Name_Error => + Log.Warn (""Application configuration file '{0}' does not exist"", Path); + + end Load_Config; + + begin + Util.Files.Iterate_Path (Files, Load_Config'Access); + end Load_Configuration; + + -- ------------------------------ + -- Initialize the AWA modules provided by the application. + -- This procedure is called by Initialize. + -- It should register the modules used by the application. + -- ------------------------------ + procedure Initialize_Modules (App : in out Application) is + begin + null; + end Initialize_Modules; + + -- ------------------------------ + -- Start the application. This is called by the server container when the server is started. + -- ------------------------------ + overriding + procedure Start (App : in out Application) is + Manager : constant Security.Policies.Policy_Manager_Access + := App.Get_Security_Manager; + begin + -- Start the security manager. + AWA.Permissions.Services.Permission_Manager'Class (Manager.all).Start; + + -- Start the event service. + App.Events.Start; + + -- Start the application. + ASF.Applications.Main.Application (App).Start; + + -- Dump the route and filters to help in configuration issues. + App.Dump_Routes (Util.Log.INFO_LEVEL); + end Start; + + -- ------------------------------ + -- Close the application. + -- ------------------------------ + overriding + procedure Close (App : in out Application) is + begin + App.Events.Stop; + ASF.Applications.Main.Application (App).Close; + end Close; + + -- ------------------------------ + -- Register the module in the application + -- ------------------------------ + procedure Register (App : in Application_Access; + Module : access AWA.Modules.Module'Class; + Name : in String; + URI : in String := """") is + begin + App.Register (Module.all'Unchecked_Access, Name, URI); + end Register; + + -- ------------------------------ + -- Get the database connection for reading + -- ------------------------------ + function Get_Session (App : Application) + return ADO.Sessions.Session is + begin + return App.DB_Factory.Get_Session; + end Get_Session; + + -- ------------------------------ + -- Get the database connection for writing + -- ------------------------------ + function Get_Master_Session (App : Application) + return ADO.Sessions.Master_Session is + begin + return App.DB_Factory.Get_Master_Session; + end Get_Master_Session; + + -- ------------------------------ + -- Find the module with the given name + -- ------------------------------ + function Find_Module (App : in Application; + Name : in String) return AWA.Modules.Module_Access is + begin + return AWA.Modules.Find_By_Name (App.Modules, Name); + end Find_Module; + + -- ------------------------------ + -- Register the module in the application + -- ------------------------------ + procedure Register (App : in out Application; + Module : in AWA.Modules.Module_Access; + Name : in String; + URI : in String := """") is + begin + AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); + end Register; + + -- ------------------------------ + -- Send the event in the application event queues. + -- ------------------------------ + procedure Send_Event (App : in Application; + Event : in AWA.Events.Module_Event'Class) is + begin + App.Events.Send (Event); + end Send_Event; + + -- ------------------------------ + -- Execute the Process procedure with the event manager used by the application. + -- ------------------------------ + procedure Do_Event_Manager (App : in out Application; + Process : access procedure + (Events : in out AWA.Events.Services.Event_Manager)) is + begin + Process (App.Events); + end Do_Event_Manager; + + -- ------------------------------ + -- Initialize the parser represented by Parser to recognize the configuration + -- that are specific to the plugins that have been registered so far. + -- ------------------------------ + procedure Initialize_Parser (App : in out Application'Class; + Parser : in out Util.Serialize.IO.Parser'Class) is + procedure Process (Module : in out AWA.Modules.Module'Class); + + procedure Process (Module : in out AWA.Modules.Module'Class) is + begin + Module.Initialize_Parser (Parser); + end Process; + begin + AWA.Modules.Iterate (App.Modules, Process'Access); + end Initialize_Parser; + + -- ------------------------------ + -- Get the current application from the servlet context or service context. + -- ------------------------------ + function Current return Application_Access is + use type AWA.Services.Contexts.Service_Context_Access; + + Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + begin + if Ctx /= null then + return Ctx.Get_Application; + end if; + + -- If there is no service context, look in the servlet current context. + declare + use type ASF.Servlets.Servlet_Registry_Access; + + Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current; + begin + if Ctx = null then + Log.Warn (""There is no service context""); + return null; + end if; + if not (Ctx.all in AWA.Applications.Application'Class) then + Log.Warn (""The servlet context is not an application""); + return null; + end if; + return AWA.Applications.Application'Class (Ctx.all)'Access;" +procedure Free is,"new Ada.Unchecked_Deallocation (Object => Consumer_Array, + Name => Consumer_Array_Access); + begin + if Manager.Workers /= null then + Log.Info (""Stopping the event dispatcher tasks""); + + for I in Manager.Workers'Range loop + if Manager.Workers (I)'Callable then + Manager.Workers (I).Stop; + else + Log.Error (""Event consumer task terminated abnormally""); + end if; + end loop; + Free (Manager.Workers); + end if; + end Stop; + + procedure Add_Queue (Manager : in out Task_Dispatcher; + Queue : in AWA.Events.Queues.Queue_Ref; + Added : out Boolean) is + begin + Log.Info (""Adding queue {0} to the task dispatcher"", Queue.Get_Name); + + Manager.Queues.Enqueue (Queue); + Added := True; + end Add_Queue; + + function Create_Dispatcher (Service : in AWA.Events.Services.Event_Manager_Access; + Match : in String; + Count : in Positive; + Priority : in Positive) return Dispatcher_Access is + Result : constant Task_Dispatcher_Access := new Task_Dispatcher; + begin + Result.Task_Count := Count; + Result.Priority := Priority; + Result.Match := To_Unbounded_String (Match); + Result.Manager := Service.all'Access; + return Result.all'Access; + end Create_Dispatcher; + + task body Consumer is + Dispatcher : Task_Dispatcher_Access; + Time : Duration := 0.01; + Do_Work : Boolean := True; + Context : AWA.Services.Contexts.Service_Context; + begin + Log.Info (""Event consumer is ready""); + select + accept Start (D : in Task_Dispatcher_Access) do + Dispatcher := D; + end Start; + Log.Info (""Event consumer is started""); + + -- Set the service context. + Context.Set_Context (Application => Dispatcher.Manager.Get_Application.all'Access, + Principal => null); + while Do_Work loop + declare + Nb_Queues : constant Natural := Dispatcher.Queues.Get_Count; + Queue : AWA.Events.Queues.Queue_Ref; + Nb_Events : Natural := 0; + begin + -- We can have several tasks that dispatch events from several queues. + -- Each queue in the list must be given the same polling quota. + -- Pick a queue and dispatch some pending events. + -- Put back the queue in the fifo. + for I in 1 .. Nb_Queues loop + Dispatcher.Queues.Dequeue (Queue); + begin + Dispatcher.Dispatch (Queue, Nb_Events); + + exception + when E : others => + Log.Error (""Exception when dispatching events"", E, True);" +procedure Register_User (Data : in out Authenticate_Bean;,"Outcome : in out Unbounded_String) is + User : User_Ref; + Email : Email_Ref; + Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; + Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; + begin + Email.Set_Email (Data.Email); + User.Set_First_Name (Data.First_Name); + User.Set_Last_Name (Data.Last_Name); + User.Set_Password (Data.Password); + Data.Manager.Create_User (User => User, + Email => Email); + Outcome := To_Unbounded_String (""success""); + + -- Add a message to the flash context so that it will be displayed on the next page. + Flash.Set_Keep_Messages (True); + Messages.Factory.Add_Message (Ctx.all, ""users.message_signup_sent"", Messages.INFO); + + exception + when Services.User_Exist => + Outcome := To_Unbounded_String (""failure""); + + Messages.Factory.Add_Message (Ctx.all, ""users.signup_error_message""); + end Register_User; + + -- ------------------------------ + -- Action to verify the user after the registration + -- ------------------------------ + procedure Verify_User (Data : in out Authenticate_Bean; + Outcome : in out Unbounded_String) is + Principal : AWA.Users.Principals.Principal_Access; + Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; + Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; + begin + Data.Manager.Verify_User (Key => To_String (Data.Access_Key), + IpAddr => """", + Principal => Principal); + + Data.Set_Session_Principal (Principal); + Outcome := To_Unbounded_String (""success""); + + -- Add a message to the flash context so that it will be displayed on the next page. + Flash.Set_Keep_Messages (True); + Messages.Factory.Add_Message (Ctx.all, ""users.message_registration_done"", Messages.INFO); + + exception + when Services.Not_Found => + Outcome := To_Unbounded_String (""failure""); + Messages.Factory.Add_Message (Ctx.all, ""users.error_verify_register_key""); + end Verify_User; + + + -- ------------------------------ + -- Action to trigger the lost password email process. + -- ------------------------------ + procedure Lost_Password (Data : in out Authenticate_Bean; + Outcome : in out Unbounded_String) is + Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; + Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; + begin + Data.Manager.Lost_Password (Email => To_String (Data.Email)); + Outcome := To_Unbounded_String (""success""); + + -- Add a message to the flash context so that it will be displayed on the next page. + Flash.Set_Keep_Messages (True); + Messages.Factory.Add_Message (Ctx.all, ""users.message_lost_password_sent"", Messages.INFO); + + exception + when Services.Not_Found => + Messages.Factory.Add_Message (Ctx.all, ""users.error_email_not_found""); + + end Lost_Password; + + -- ------------------------------ + -- Action to validate the reset password key and set a new password. + -- ------------------------------ + procedure Reset_Password (Data : in out Authenticate_Bean; + Outcome : in out Unbounded_String) is + Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; + Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash; + Principal : AWA.Users.Principals.Principal_Access; + begin + Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), + Password => To_String (Data.Password), + IpAddr => """", + Principal => Principal); + Data.Set_Session_Principal (Principal); + Outcome := To_Unbounded_String (""success""); + + -- Add a message to the flash context so that it will be displayed on the next page. + Flash.Set_Keep_Messages (True); + Messages.Factory.Add_Message (Ctx.all, ""users.message_reset_password_done"", Messages.INFO); + + exception + when Services.Not_Found => + Messages.Factory.Add_Message (Ctx.all, ""users.error_reset_password""); + end Reset_Password; + + + procedure Set_Session_Principal (Data : in Authenticate_Bean; + Principal : in AWA.Users.Principals.Principal_Access) is + pragma Unreferenced (Data); + + Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; + Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); + begin + Session.Set_Principal (Principal.all'Access); + end Set_Session_Principal; + + procedure Set_Authenticate_Cookie (Data : in out Authenticate_Bean; + Principal : in AWA.Users.Principals.Principal_Access) is + Id : constant ADO.Identifier := Principal.Get_Session_Identifier; + Cookie : constant String := Data.Manager.Get_Authenticate_Cookie (Id); + Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; + C : ASF.Cookies.Cookie := ASF.Cookies.Create (ASF.Security.Filters.AID_COOKIE, Cookie); + begin + ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); + ASF.Cookies.Set_Max_Age (C, 15 * 86400); + Ctx.Get_Response.Add_Cookie (Cookie => C); + end Set_Authenticate_Cookie; + + -- ------------------------------ + -- Action to authenticate a user (password authentication). + -- ------------------------------ + procedure Authenticate_User (Data : in out Authenticate_Bean; + Outcome : in out Unbounded_String) is + Principal : AWA.Users.Principals.Principal_Access; + begin + Data.Manager.Authenticate (Email => To_String (Data.Email), + Password => To_String (Data.Password), + IpAddr => """", + Principal => Principal); + Outcome := To_Unbounded_String (""success""); + + Data.Set_Session_Principal (Principal); + Data.Set_Authenticate_Cookie (Principal); + + exception + when Services.Not_Found => + Outcome := To_Unbounded_String (""failure""); + + ASF.Applications.Messages.Factory.Add_Message (""users.login_signup_fail_message""); + end Authenticate_User; + + -- ------------------------------ + -- Helper to send a remove cookie in the current response + -- ------------------------------ + procedure Remove_Cookie (Name : in String) is + Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; + C : ASF.Cookies.Cookie := ASF.Cookies.Create (Name, """"); + begin + ASF.Cookies.Set_Path (C, Ctx.Get_Request.Get_Context_Path); + ASF.Cookies.Set_Max_Age (C, 0); + Ctx.Get_Response.Add_Cookie (Cookie => C); + end Remove_Cookie; + + -- ------------------------------ + -- Logout the user and closes the session. + -- ------------------------------ + procedure Logout_User (Data : in out Authenticate_Bean; + Outcome : in out Unbounded_String) is + use type ASF.Principals.Principal_Access; + + Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; + Session : ASF.Sessions.Session := Ctx.Get_Session (Create => False); + begin + Outcome := To_Unbounded_String (""success""); + + -- If there is no session, we are done. + if not Session.Is_Valid then + return; + end if; + + declare + Principal : constant ASF.Principals.Principal_Access := Session.Get_Principal; + begin + if Principal /= null and then Principal.all in AWA.Users.Principals.Principal'Class then + declare + P : constant AWA.Users.Principals.Principal_Access := + AWA.Users.Principals.Principal'Class (Principal.all)'Access; + begin + Data.Manager.Close_Session (Id => P.Get_Session_Identifier, + Logout => True); + + exception + when others => + Log.Error (""Exception when closing user session..."");" +procedure Dispatch (Manager : in Event_Manager;,"Queue : in AWA.Events.Queues.Queue_Ref; + Event : in Module_Event'Class) is + procedure Find_Queue (List : in Queue_Dispatcher); + + Found : Boolean := False; + + procedure Find_Queue (List : in Queue_Dispatcher) is + begin + if List.Queue = Queue then + List.Dispatcher.Dispatch (Event); + Found := True; + end if; + end Find_Queue; + + Name : constant Name_Access := Get_Event_Type_Name (Event.Kind); + begin + if Name = null then + Log.Error (""Cannot dispatch event type {0}"", Event_Index'Image (Event.Kind)); + raise Not_Found; + end if; + + declare + Pos : Queue_Dispatcher_Lists.Cursor := Manager.Actions (Event.Kind).Queues.First; + begin + if not Queue_Dispatcher_Lists.Has_Element (Pos) then + Log.Debug (""Dispatching event {0} but there is no listener"", Name.all); + else + Log.Debug (""Dispatching event {0}"", Name.all); + loop + Queue_Dispatcher_Lists.Query_Element (Pos, Find_Queue'Access); + exit when Found; + Queue_Dispatcher_Lists.Next (Pos); + if not Queue_Dispatcher_Lists.Has_Element (Pos) then + Log.Debug (""Dispatched event {0} but there was no listener"", Name.all); + exit; + end if; + end loop; + end if;" +procedure Add_Dispatcher (Manager : in out Event_Manager;,"Match : in String; + Count : in Positive; + Priority : in Positive) is + use type AWA.Events.Dispatchers.Dispatcher_Access; + begin + Log.Info (""Adding event dispatcher with {0} tasks prio {1} and dispatching queues '{2}'"", + Positive'Image (Count), Positive'Image (Priority), Match); + + for I in Manager.Dispatchers'Range loop + if Manager.Dispatchers (I) = null then + Manager.Dispatchers (I) := + AWA.Events.Dispatchers.Tasks.Create_Dispatcher (Manager'Unchecked_Access, + Match, Count, Priority); + return; + end if; + end loop; + Log.Error (""Implementation limit is reached. Too many dispatcher.""); + end Add_Dispatcher; + + -- ------------------------------ + -- Initialize the event manager. + -- ------------------------------ + procedure Initialize (Manager : in out Event_Manager; + App : in Application_Access) is + procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref); + + Msg_Types : AWA.Events.Models.Message_Type_Vector; + + Query : ADO.SQL.Query; + + procedure Set_Events (Msg : in AWA.Events.Models.Message_Type_Ref) is + Name : constant String := Msg.Get_Name; + begin + declare + Index : constant Event_Index := Find_Event_Index (Name); + begin + Manager.Actions (Index).Event := Msg;" +procedure Associate_Dispatcher (Key : in String;,"Queue : in out AWA.Events.Queues.Queue_Ref); + + -- ------------------------------ + -- Dispatch the event queues to the dispatcher according to the dispatcher configuration. + -- ------------------------------ + procedure Associate_Dispatcher (Key : in String; + Queue : in out AWA.Events.Queues.Queue_Ref) is + pragma Unreferenced (Key); + + Added : Boolean := False; + begin + for I in reverse Manager.Dispatchers'Range loop + if Manager.Dispatchers (I) /= null then + Manager.Dispatchers (I).Add_Queue (Queue, Added); + exit when Added; + end if; + end loop; + end Associate_Dispatcher; + + Iter : AWA.Events.Queues.Maps.Cursor := Manager.Queues.First; + begin + Log.Info (""Starting the event manager""); + + while AWA.Events.Queues.Maps.Has_Element (Iter) loop + Manager.Queues.Update_Element (Iter, Associate_Dispatcher'Access); + AWA.Events.Queues.Maps.Next (Iter); + end loop; + + -- Start the dispatchers. + for I in Manager.Dispatchers'Range loop + exit when Manager.Dispatchers (I) = null; + Manager.Dispatchers (I).Start; + end loop; + end Start; + + -- ------------------------------ + -- Stop the event manager. + -- ------------------------------ + procedure Stop (Manager : in out Event_Manager) is + use type AWA.Events.Dispatchers.Dispatcher_Access; + begin + Log.Info (""Stopping the event manager""); + + -- Stop the dispatchers. + for I in Manager.Dispatchers'Range loop + exit when Manager.Dispatchers (I) = null; + Manager.Dispatchers (I).Stop; + end loop; + end Stop; + + -- ------------------------------ + -- Get the application associated with the event manager. + -- ------------------------------ + function Get_Application (Manager : in Event_Manager) return Application_Access is + begin + return Manager.Application; + end Get_Application; + + -- ------------------------------ + -- Finalize the queue dispatcher releasing the dispatcher memory. + -- ------------------------------ + procedure Finalize (Object : in out Queue_Dispatcher) is + procedure Free is + new Ada.Unchecked_Deallocation (Object => AWA.Events.Dispatchers.Dispatcher'Class, + Name => AWA.Events.Dispatchers.Dispatcher_Access); + begin + Free (Object.Dispatcher); + end Finalize; + + -- ------------------------------ + -- Finalize the event queues and the dispatchers. + -- ------------------------------ + procedure Finalize (Object : in out Event_Queues) is + begin + loop + declare + Pos : constant Queue_Dispatcher_Lists.Cursor := Object.Queues.First; + begin + exit when not Queue_Dispatcher_Lists.Has_Element (Pos); + + Object.Queues.Update_Element (Position => Pos, + Process => Finalize'Access); + Object.Queues.Delete_First;" +function Has_Permission (Handler : in Entity_Controller;,"Context : in Security.Contexts.Security_Context'Class; + Permission : in Security.Permissions.Permission'Class) + return Boolean is + use AWA.Permissions.Services; + use AWA.Users.Principals; + use type ADO.Identifier; + use type ADO.Entity_Type; + + Manager : constant Permission_Manager_Access := Get_Permission_Manager (Context); + User_Id : constant ADO.Identifier := Get_User_Identifier (Context.Get_User_Principal); + Entity_Id : ADO.Identifier; + begin + -- If there is no permission manager, permission is denied. + if Manager = null or else User_Id = ADO.NO_IDENTIFIER then + return False; + end if; + + -- If the user is not logged, permission is denied. + if Manager = null or else User_Id = ADO.NO_IDENTIFIER then + Log.Info (""No user identifier in the security context. Permission is denied""); + return False; + end if; + + if not (Permission in Entity_Permission'Class) then + Log.Info (""Permission {0} denied because the entity is not given."", + Security.Permissions.Permission_Index'Image (Permission.Id)); + return False; + end if; + Entity_Id := Entity_Permission'Class (Permission).Entity; + + -- If the security context does not contain the entity identifier, permission is denied. + if Entity_Id = ADO.NO_IDENTIFIER then + Log.Info (""No entity identifier in the security context. Permission is denied""); + return False; + end if; + + declare + function Get_Session return ADO.Sessions.Session; + + -- ------------------------------ + -- Get a database session from the AWA application. + -- There is no guarantee that a AWA.Services.Contexts be available. + -- But if we are within a service context, we must use the current session so + -- that we are part of the current transaction. + -- ------------------------------ + function Get_Session return ADO.Sessions.Session is + package ASC renames AWA.Services.Contexts; + use type ASC.Service_Context_Access; + + Ctx : constant ASC.Service_Context_Access := ASC.Current; + begin + if Ctx /= null then + return AWA.Services.Contexts.Get_Session (Ctx); + else + return Manager.Get_Application.Get_Session; + end if; + end Get_Session; + + Session : constant ADO.Sessions.Session := Get_Session; + Query : ADO.Statements.Query_Statement := Session.Create_Statement (Handler.SQL); + Result : Integer; + begin + -- Build the query + Query.Bind_Param (Name => ""entity_id"", Value => Entity_Id); + Query.Bind_Param (Name => ""user_id"", Value => User_Id); + if Handler.Entities (2) /= ADO.NO_ENTITY_TYPE then + for I in Handler.Entities'Range loop + exit when Handler.Entities (I) = ADO.NO_ENTITY_TYPE; + Query.Bind_Param (Name => ""entity_type_"" & Util.Strings.Image (I), + Value => Handler.Entities (I)); + end loop; + else + Query.Bind_Param (Name => ""entity_type"", Value => Handler.Entities (1)); + end if; + + -- Run the query. We must get a single row result and the value must be > 0. + Query.Execute; + + Result := Query.Get_Result_Integer; + if Result >= 0 and Query.Has_Elements then + Log.Info (""Permission granted to {0} on entity {1}"", + ADO.Identifier'Image (User_Id), + ADO.Identifier'Image (Entity_Id)); + return True; + else + Log.Info (""Permission denied to {0} on entity {1}"", + ADO.Identifier'Image (User_Id), + ADO.Identifier'Image (Entity_Id)); + return False; + end if;" +procedure Free is,"new Ada.Unchecked_Deallocation (Object => AWA.Events.Module_Event'Class, + Name => AWA.Events.Module_Event_Access); + + -- ------------------------------ + -- Get the queue name. + -- ------------------------------ + overriding + function Get_Name (From : in Fifo_Queue) return String is + begin + return From.Name; + end Get_Name; + + -- ------------------------------ + -- Get the model queue reference object. + -- Returns a null object if the queue is not persistent. + -- ------------------------------ + overriding + function Get_Queue (From : in Fifo_Queue) return AWA.Events.Models.Queue_Ref is + pragma Unreferenced (From); + begin + return AWA.Events.Models.Null_Queue; + end Get_Queue; + + -- ------------------------------ + -- Queue the event. + -- ------------------------------ + procedure Enqueue (Into : in out Fifo_Queue; + Event : in AWA.Events.Module_Event'Class) is + E : constant Module_Event_Access := Copy (Event); + begin + Log.Debug (""Enqueue event on queue {0}"", Into.Name); + + E.Set_Event_Kind (Event.Get_Event_Kind); + Into.Fifo.Enqueue (E); + end Enqueue; + + -- ------------------------------ + -- Dequeue an event and process it with the Process procedure. + -- ------------------------------ + procedure Dequeue (From : in out Fifo_Queue; + Process : access procedure (Event : in Module_Event'Class)) is + E : Module_Event_Access; + begin + Log.Debug (""Dequeue event queue {0}"", From.Name); + + From.Fifo.Dequeue (E, 0.0); + begin + Process (E.all); + + exception + when E : others => + Log.Error (""Exception when processing event"", E);" +procedure Free is,"new Ada.Unchecked_Deallocation (Object => Name_Pair_Array, + Name => Name_Pair_Array_Access); + procedure Free is + new Ada.Unchecked_Deallocation (Object => Name_Array, + Name => Name_Array_Access); + + Left : Index_Type := Index_Type'First + 1; + Right : Index_Type := Last_Index; + begin + -- Check the storage and allocate it if necessary. + if Indexes = null then + Indexes := new Name_Pair_Array (Index_Type'First + 1 .. Index_Type'First + 10); + Names := new Name_Array (Index_Type'First + 1 .. Index_Type'First + 10); + elsif Indexes'Last = Last_Index then + declare + E : constant Name_Pair_Array_Access + := new Name_Pair_Array (1 .. Last_Index + 10); + N : constant Name_Array_Access := new Name_Array (1 .. Last_Index + 10); + begin + E (Indexes'Range) := Indexes.all; + N (Names'Range) := Names.all; + Free (Indexes); + Free (Names); + Names := N; + Indexes := E;" +procedure Update_User;,"OpenId : constant String := Security.Auth.Get_Claimed_Id (Auth); + Email : constant String := Security.Auth.Get_Email (Auth); + Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + Query : ADO.SQL.Query; + Found : Boolean; + User : User_Ref; + Session : Session_Ref; + + -- ------------------------------ + -- Update the user first name/last name + -- ------------------------------ + procedure Update_User is + Name : constant String := Security.Auth.Get_Full_Name (Auth); + First_Name : constant String := Security.Auth.Get_First_Name (Auth); + Last_Name : constant String := Security.Auth.Get_Last_Name (Auth); + Sep : constant Natural := Util.Strings.Index (Name, ' '); + begin + if Name'Length > 0 and Name /= String '(User.Get_Name) then + User.Set_Name (Name); + end if; + if First_Name'Length > 0 and First_Name /= String '(User.Get_First_Name) then + User.Set_First_Name (First_Name); + end if; + if Last_Name'Length > 0 and Last_Name /= String '(User.Get_Last_Name) then + User.Set_Last_Name (Last_Name); + end if; + if Sep > 0 and String '(User.Get_First_Name) = """" then + User.Set_First_Name (Name (Name'First .. Sep - 1)); + end if; + if Sep > 0 and String '(User.Get_Last_Name) = """" then + User.Set_Last_Name (Name (Sep + 1 .. Name'Last)); + end if; + if Name'Length > 0 and String '(User.Get_First_Name) = """" then + User.Set_First_Name (Name); + end if; + if Name'Length = 0 then + User.Set_Name (Get_Name_From_Email (Email => Email)); + end if; + User.Save (DB); + end Update_User; + + begin + Log.Info (""Authenticated user {0}"", Email); + + Ctx.Start; + + -- Find the user registered under the given OpenID identifier. + Query.Bind_Param (1, OpenId); + Query.Set_Filter (""o.open_id = ?""); + User.Find (DB, Query, Found); + if not Found then + Log.Info (""User {0} is not known"", Email); + declare + E : Email_Ref; + begin + E.Set_Email (Email); + E.Set_User_Id (0); + E.Save (DB); + + User.Set_Email (E); + User.Set_Open_Id (OpenId); + Update_User; + E.Set_User_Id (User.Get_Id); + E.Save (DB);" +procedure Register (Plugin : in out Module;,"Name : in String; + Bind : in ASF.Beans.Class_Binding_Access) is + begin + Plugin.App.Register_Class (Name, Bind); + end Register; + + -- ------------------------------ + -- Finalize the module. + -- ------------------------------ + overriding + procedure Finalize (Plugin : in out Module) is + begin + null; + end Finalize; + + procedure Initialize (Manager : in out Module_Manager; + Module : in AWA.Modules.Module'Class) is + begin + Manager.Module := Module.Self; + end Initialize; + + function Get_Value (Manager : in Module_Manager; + Name : in String) return Util.Beans.Objects.Object is + pragma Unreferenced (Manager, Name); + begin + return Util.Beans.Objects.Null_Object; + end Get_Value; + + -- Module manager + -- + -- ------------------------------ + -- Get the database connection for reading + -- ------------------------------ + function Get_Session (Manager : Module_Manager) + return ADO.Sessions.Session is + begin + return Manager.Module.Get_Session; + end Get_Session; + + -- ------------------------------ + -- Get the database connection for writing + -- ------------------------------ + function Get_Master_Session (Manager : Module_Manager) + return ADO.Sessions.Master_Session is + begin + return Manager.Module.Get_Master_Session; + end Get_Master_Session; + + -- ------------------------------ + -- Send the event to the module. The module identified by To is + -- found and the event is posted on its event channel. + -- ------------------------------ + procedure Send_Event (Manager : in Module_Manager; + Content : in AWA.Events.Module_Event'Class) is + begin + Manager.Module.Send_Event (Content); + end Send_Event; + + procedure Initialize (Plugin : in out Module; + App : in Application_Access; + Props : in ASF.Applications.Config) is + pragma Unreferenced (Props); + begin + Plugin.Self := Plugin'Unchecked_Access; + Plugin.App := App; + end Initialize; + + -- ------------------------------ + -- Initialize the registry + -- ------------------------------ + procedure Initialize (Registry : in out Module_Registry; + Config : in ASF.Applications.Config) is + begin + Registry.Config := Config; + end Initialize; + + -- ------------------------------ + -- Register the module in the registry. + -- ------------------------------ + procedure Register (Registry : in Module_Registry_Access; + App : in Application_Access; + Plugin : in Module_Access; + Name : in String; + URI : in String) is + procedure Copy (Params : in Util.Properties.Manager'Class); + + procedure Copy (Params : in Util.Properties.Manager'Class) is + begin + Plugin.Config.Copy (From => Params, Prefix => Name & ""."", Strip => True); + end Copy; + + Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); + begin + Log.Info (""Register module '{0}' under URI '{1}'"", Name, URI); + + if Plugin.Registry /= null then + Log.Error (""Module '{0}' is already attached to a registry"", Name); + + raise Program_Error with ""Module '"" & Name & ""' already registered""; + end if; + Plugin.App := App; + Plugin.Registry := Registry; + Plugin.Name := To_Unbounded_String (Name); + Plugin.URI := To_Unbounded_String (URI); + Plugin.Registry.Name_Map.Insert (Name, Plugin); + if URI /= """" then + Plugin.Registry.URI_Map.Insert (URI, Plugin); + end if; + + -- Load the module configuration file + Log.Debug (""Module search path: {0}"", Paths); + declare + Base : constant String := Name & "".properties""; + Path : constant String := Util.Files.Find_File_Path (Base, Paths); + begin + Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ""."", Strip => True); + + exception + when Ada.IO_Exceptions.Name_Error => + Log.Info (""Module configuration file '{0}' does not exist"", Path);" +procedure Add_Listener (Into : in out Module;,"Item : in Util.Listeners.Listener_Access) is + begin + Util.Listeners.Add_Listener (Into.Listeners, Item); + end Add_Listener; + + -- ------------------------------ + -- Find the module with the given name in the application and add the listener to the + -- module listener list. + -- ------------------------------ + procedure Add_Listener (Plugin : in Module; + Name : in String; + Item : in Util.Listeners.Listener_Access) is + M : constant Module_Access := Plugin.App.Find_Module (Name); + begin + if M = null then + Log.Error (""Cannot find module {0} to add a lifecycle listener"", Name); + else + M.Add_Listener (Item); + end if; + end Add_Listener; + + -- ------------------------------ + -- Remove a listener from the module listener list. + -- ------------------------------ + procedure Remove_Listener (Into : in out Module; + Item : in Util.Listeners.Listener_Access) is + begin + Util.Listeners.Remove_Listener (Into.Listeners, Item); + end Remove_Listener; + + -- Get per request manager => look in Request + -- Get per session manager => look in Request.Get_Session + -- Get per application manager => look in Application + -- Get per pool manager => look in pool attached to Application + function Get_Manager return Manager_Type_Access is + + procedure Process (Request : in out ASF.Requests.Request'Class; + Response : in out ASF.Responses.Response'Class); + + Value : Util.Beans.Objects.Object; + + procedure Process (Request : in out ASF.Requests.Request'Class; + Response : in out ASF.Responses.Response'Class) is + pragma Unreferenced (Response); + begin + Value := Request.Get_Attribute (Name); + if Util.Beans.Objects.Is_Null (Value) then + declare + M : constant Manager_Type_Access := new Manager_Type; + begin + Value := Util.Beans.Objects.To_Object (M.all'Unchecked_Access); + Request.Set_Attribute (Name, Value);" +function Has_Permission (Name : in Util.Beans.Objects.Object;,"Entity : in Util.Beans.Objects.Object) + return Util.Beans.Objects.Object is + use type Security.Contexts.Security_Context_Access; + + Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; + Perm : constant String := Util.Beans.Objects.To_String (Name); + Result : Boolean; + begin + if Util.Beans.Objects.Is_Empty (Name) or Context = null then + Result := False; + + elsif Util.Beans.Objects.Is_Empty (Entity) then + Result := Context.Has_Permission (Perm); + + else + declare + P : Entity_Permission (Security.Permissions.Get_Permission_Index (Perm)); + begin + P.Entity := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Entity)); + Result := Context.Has_Permission (P);" +function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class),"return Permission_Manager_Access is + use type Security.Policies.Policy_Manager_Access; + + M : constant Security.Policies.Policy_Manager_Access + := Context.Get_Permission_Manager; + begin + if M = null then + Log.Info (""There is no permission manager""); + return null; + + elsif not (M.all in Permission_Manager'Class) then + Log.Info (""Permission manager is not a AWA permission manager""); + return null; + + else + return Permission_Manager'Class (M.all)'Access; + end if; + end Get_Permission_Manager; + + -- ------------------------------ + -- Get the permission manager associated with the security context. + -- Returns null if there is none. + -- ------------------------------ + function Get_Permission_Manager (Context : in ASC.Service_Context_Access) + return Permission_Manager_Access is + Manager : constant Security.Policies.Policy_Manager_Access + := Context.Get_Application.Get_Security_Manager; + begin + return Permission_Manager'Class (Manager.all)'Access; + end Get_Permission_Manager; + + -- ------------------------------ + -- Get the application instance. + -- ------------------------------ + function Get_Application (Manager : in Permission_Manager) + return AWA.Applications.Application_Access is + begin + return Manager.App; + end Get_Application; + + -- ------------------------------ + -- Set the application instance. + -- ------------------------------ + procedure Set_Application (Manager : in out Permission_Manager; + App : in AWA.Applications.Application_Access) is + begin + Manager.App := App; + end Set_Application; + + -- ------------------------------ + -- Initialize the permissions. + -- ------------------------------ + procedure Start (Manager : in out Permission_Manager) is + package Perm renames Security.Permissions; + + DB : ADO.Sessions.Master_Session := Manager.App.Get_Master_Session; + Cache : constant Permission_Cache.Cache_Type_Access := new Permission_Cache.Cache_Type; + Count : constant Perm.Permission_Index := Perm.Get_Last_Permission_Index; + Last : ADO.Identifier := 0; + Insert : ADO.Statements.Insert_Statement; + Stmt : ADO.Statements.Query_Statement; + Load_Count : Natural := 0; + Add_Count : Natural := 0; + begin + Log.Info (""Initializing {0} permissions"", Perm.Permission_Index'Image (Count)); + + DB.Begin_Transaction; + + -- Step 1: load the permissions from the database. + Stmt := DB.Create_Statement (""SELECT id, name FROM awa_permission""); + Stmt.Execute; + while Stmt.Has_Elements loop + declare + Id : constant Integer := Stmt.Get_Integer (0); + Name : constant String := Stmt.Get_String (1); + begin + Log.Debug (""Loaded permission {0} as {1}"", Name, Util.Strings.Image (Id)); + Permission_Cache.Insert (Cache.all, Name, Id); + Load_Count := Load_Count + 1; + if ADO.Identifier (Id) > Last then + Last := ADO.Identifier (Id); + end if;" +procedure Add_Permission (Manager : in Permission_Manager;,"Entity : in ADO.Identifier; + Kind : in ADO.Entity_Type; + Workspace : in ADO.Identifier; + Permission : in Security.Permissions.Permission_Index) is + Ctx : constant AWA.Services.Contexts.Service_Context_Access + := AWA.Services.Contexts.Current; + DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); + Perm : AWA.Permissions.Models.ACL_Ref; + begin + Log.Info (""Adding permission""); + + Ctx.Start; + Perm.Set_Entity_Type (Kind); + Perm.Set_User_Id (Ctx.Get_User_Identifier); + Perm.Set_Entity_Id (Entity); + Perm.Set_Writeable (False); + Perm.Set_Workspace_Id (Workspace); + Perm.Set_Permission (Manager.Map (Permission)); + Perm.Save (DB); + Ctx.Commit; + end Add_Permission; + + -- ------------------------------ + -- Check that the current user has the specified permission. + -- Raise NO_PERMISSION exception if the user does not have the permission. + -- ------------------------------ + procedure Check_Permission (Manager : in Permission_Manager; + Entity : in ADO.Identifier; + Kind : in ADO.Entity_Type; + Permission : in Permission_Type) is + pragma Unreferenced (Manager, Permission); + use AWA.Services; + + Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; + User : constant ADO.Identifier := Ctx.Get_User_Identifier; + DB : constant Session := AWA.Services.Contexts.Get_Session (Ctx); + Query : ADO.Queries.Context; + begin + Query.Set_Query (AWA.Permissions.Models.Query_Check_Entity_Permission); + Query.Bind_Param (""user_id"", User); + Query.Bind_Param (""entity_id"", Entity); + Query.Bind_Param (""entity_type"", Integer (Kind)); + declare + Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query); + begin + Stmt.Execute; + if not Stmt.Has_Elements then + Log.Info (""User {0} does not have permission to access entity {1}/{2}"", + ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), + ADO.Entity_Type'Image (Kind)); + raise NO_PERMISSION; + end if;" +procedure Dispatch (Manager : in Action_Dispatcher;,"Event : in Module_Event'Class) is + + use Util.Beans.Objects; + + -- Dispatch the event to the event action identified by Action. + procedure Dispatch_One (Action : in Event_Action); + + type Event_Bean is new Util.Beans.Basic.Readonly_Bean with null record; + + overriding + function Get_Value (From : in Event_Bean; + Name : in String) return Util.Beans.Objects.Object; + + -- ------------------------------ + -- Get the value identified by the name. + -- If the name cannot be found, the method should return the Null object. + -- ------------------------------ + overriding + function Get_Value (From : in Event_Bean; + Name : in String) return Util.Beans.Objects.Object is + pragma Unreferenced (From); + begin + return Event.Get_Value (Name); + end Get_Value; + + Variables : aliased EL.Variables.Default.Default_Variable_Mapper; + + -- ------------------------------ + -- Default Resolver + -- ------------------------------ + type Event_ELResolver is limited new EL.Contexts.ELResolver with record + Request : ASF.Requests.Request_Access; + Application : AWA.Applications.Application_Access; + end record; + + overriding + function Get_Value (Resolver : Event_ELResolver; + Context : EL.Contexts.ELContext'Class; + Base : access Util.Beans.Basic.Readonly_Bean'Class; + Name : Unbounded_String) return Util.Beans.Objects.Object; + overriding + procedure Set_Value (Resolver : in out Event_ELResolver; + Context : in EL.Contexts.ELContext'Class; + Base : access Util.Beans.Basic.Bean'Class; + Name : in Unbounded_String; + Value : in Util.Beans.Objects.Object); + + -- ------------------------------ + -- Get the value associated with a base object and a given property. + -- ------------------------------ + overriding + function Get_Value (Resolver : Event_ELResolver; + Context : EL.Contexts.ELContext'Class; + Base : access Util.Beans.Basic.Readonly_Bean'Class; + Name : Unbounded_String) return Util.Beans.Objects.Object is + use Util.Beans.Basic; + use EL.Variables; + use type ASF.Requests.Request_Access; + + Result : Object; + Bean : Util.Beans.Basic.Readonly_Bean_Access; + Scope : ASF.Beans.Scope_Type; + Key : constant String := To_String (Name); + begin + if Base /= null then + return Base.Get_Value (Key); + end if; + + if Resolver.Request /= null then + Result := Resolver.Request.Get_Attribute (Key); + if not Util.Beans.Objects.Is_Null (Result) then + return Result; + end if; + + -- If there is a session, look if the attribute is defined there. + declare + Session : constant ASF.Sessions.Session := Resolver.Request.Get_Session; + begin + if Session.Is_Valid then + Result := Session.Get_Attribute (Key); + if not Util.Beans.Objects.Is_Null (Result) then + return Result; + end if; + end if;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (MailDeliveryStatus); + Impl : Email_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 2, Impl.Status, Value); + end Set_Status; + + function Get_Status (Object : in Email_Ref) + return AWA.Users.Models.MailDeliveryStatus is + Impl : constant Email_Access + := Email_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Status; + end Get_Status; + + + procedure Set_Last_Error_Date (Object : in out Email_Ref; + Value : in Ada.Calendar.Time) is + Impl : Email_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 3, Impl.Last_Error_Date, Value); + end Set_Last_Error_Date; + + function Get_Last_Error_Date (Object : in Email_Ref) + return Ada.Calendar.Time is + Impl : constant Email_Access + := Email_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Last_Error_Date; + end Get_Last_Error_Date; + + + function Get_Version (Object : in Email_Ref) + return Integer is + Impl : constant Email_Access + := Email_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Version; + end Get_Version; + + + procedure Set_Id (Object : in out Email_Ref; + Value : in ADO.Identifier) is + Impl : Email_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Key_Value (Impl.all, 5, Value); + end Set_Id; + + function Get_Id (Object : in Email_Ref) + return ADO.Identifier is + Impl : constant Email_Access + := Email_Impl (Object.Get_Object.all)'Access; + begin + return Impl.Get_Key_Value; + end Get_Id; + + + procedure Set_User_Id (Object : in out Email_Ref; + Value : in ADO.Identifier) is + Impl : Email_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Identifier (Impl.all, 6, Impl.User_Id, Value); + end Set_User_Id; + + function Get_User_Id (Object : in Email_Ref) + return ADO.Identifier is + Impl : constant Email_Access + := Email_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.User_Id; + end Get_User_Id; + + -- Copy of the object. + procedure Copy (Object : in Email_Ref; + Into : in out Email_Ref) is + Result : Email_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Email_Access + := Email_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Email_Access + := new Email_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Email := Impl.Email; + Copy.Status := Impl.Status; + Copy.Last_Error_Date := Impl.Last_Error_Date; + Copy.Version := Impl.Version; + Copy.User_Id := Impl.User_Id;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Email_Impl, Email_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Email_Impl_Ptr := Email_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Email_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, EMAIL_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Email_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Email_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (EMAIL_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- email + Value => Object.Email); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- status + Value => Integer (MailDeliveryStatus'Pos (Object.Status))); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- last_error_date + Value => Object.Last_Error_Date); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- user_id + Value => Object.User_Id); + Object.Clear_Modified (6); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(User_Impl, User_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : User_Impl_Ptr := User_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out User_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, USER_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out User_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out User_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (USER_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- first_name + Value => Object.First_Name); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- last_name + Value => Object.Last_Name); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- password + Value => Object.Password); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- open_id + Value => Object.Open_Id); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- country + Value => Object.Country); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_2_NAME, -- salt + Value => Object.Salt); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_2_NAME, -- email_id + Value => Object.Email); + Object.Clear_Modified (10); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Key_Type); + Impl : Access_Key_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 5, Impl.Kind, Value); + end Set_Kind; + + function Get_Kind (Object : in Access_Key_Ref) + return AWA.Users.Models.Key_Type is + Impl : constant Access_Key_Access + := Access_Key_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Kind; + end Get_Kind; + + + procedure Set_User (Object : in out Access_Key_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Access_Key_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 6, Impl.User, Value); + end Set_User; + + function Get_User (Object : in Access_Key_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Access_Key_Access + := Access_Key_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.User; + end Get_User; + + -- Copy of the object. + procedure Copy (Object : in Access_Key_Ref; + Into : in out Access_Key_Ref) is + Result : Access_Key_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Access_Key_Access + := Access_Key_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Access_Key_Access + := new Access_Key_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Access_Key := Impl.Access_Key; + Copy.Expire_Date := Impl.Expire_Date; + Copy.Version := Impl.Version; + Copy.Kind := Impl.Kind; + Copy.User := Impl.User;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Access_Key_Impl, Access_Key_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Access_Key_Impl_Ptr := Access_Key_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Access_Key_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, ACCESS_KEY_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Access_Key_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Access_Key_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (ACCESS_KEY_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- access_key + Value => Object.Access_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_3_NAME, -- expire_date + Value => Object.Expire_Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_3_NAME, -- kind + Value => Integer (Key_Type'Pos (Object.Kind))); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_3_NAME, -- user_id + Value => Object.User); + Object.Clear_Modified (6); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Session_Type); + Impl : Session_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 4, Impl.Stype, Value); + end Set_Stype; + + function Get_Stype (Object : in Session_Ref) + return AWA.Users.Models.Session_Type is + Impl : constant Session_Access + := Session_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Stype; + end Get_Stype; + + + function Get_Version (Object : in Session_Ref) + return Integer is + Impl : constant Session_Access + := Session_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Version; + end Get_Version; + + + procedure Set_Server_Id (Object : in out Session_Ref; + Value : in Integer) is + Impl : Session_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Integer (Impl.all, 6, Impl.Server_Id, Value); + end Set_Server_Id; + + function Get_Server_Id (Object : in Session_Ref) + return Integer is + Impl : constant Session_Access + := Session_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Server_Id; + end Get_Server_Id; + + + procedure Set_Id (Object : in out Session_Ref; + Value : in ADO.Identifier) is + Impl : Session_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Key_Value (Impl.all, 7, Value); + end Set_Id; + + function Get_Id (Object : in Session_Ref) + return ADO.Identifier is + Impl : constant Session_Access + := Session_Impl (Object.Get_Object.all)'Access; + begin + return Impl.Get_Key_Value; + end Get_Id; + + + procedure Set_Auth (Object : in out Session_Ref; + Value : in AWA.Users.Models.Session_Ref'Class) is + Impl : Session_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 8, Impl.Auth, Value); + end Set_Auth; + + function Get_Auth (Object : in Session_Ref) + return AWA.Users.Models.Session_Ref'Class is + Impl : constant Session_Access + := Session_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Auth; + end Get_Auth; + + + procedure Set_User (Object : in out Session_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Session_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 9, Impl.User, Value); + end Set_User; + + function Get_User (Object : in Session_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Session_Access + := Session_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.User; + end Get_User; + + -- Copy of the object. + procedure Copy (Object : in Session_Ref; + Into : in out Session_Ref) is + Result : Session_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Session_Access + := Session_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Session_Access + := new Session_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Start_Date := Impl.Start_Date; + Copy.End_Date := Impl.End_Date; + Copy.Ip_Address := Impl.Ip_Address; + Copy.Stype := Impl.Stype; + Copy.Version := Impl.Version; + Copy.Server_Id := Impl.Server_Id; + Copy.Auth := Impl.Auth; + Copy.User := Impl.User;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Session_Impl, Session_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Session_Impl_Ptr := Session_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Session_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SESSION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Session_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Session_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (SESSION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_4_NAME, -- start_date + Value => Object.Start_Date); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_4_NAME, -- end_date + Value => Object.End_Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_4_NAME, -- ip_address + Value => Object.Ip_Address); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_4_NAME, -- stype + Value => Integer (Session_Type'Pos (Object.Stype))); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_4_NAME, -- server_id + Value => Object.Server_Id); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_4_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_4_NAME, -- auth_id + Value => Object.Auth); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_4_NAME, -- user_id + Value => Object.User); + Object.Clear_Modified (9); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Set_Permission (Object : in out Acl_Ref;,"Value : in ADO.Identifier) is + Impl : Acl_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Identifier (Impl.all, 7, Impl.Permission, Value); + end Set_Permission; + + function Get_Permission (Object : in Acl_Ref) + return ADO.Identifier is + Impl : constant Acl_Access + := Acl_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Permission; + end Get_Permission; + + -- Copy of the object. + procedure Copy (Object : in Acl_Ref; + Into : in out Acl_Ref) is + Result : Acl_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Acl_Access + := Acl_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Acl_Access + := new Acl_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Entity_Id := Impl.Entity_Id; + Copy.Writeable := Impl.Writeable; + Copy.User_Id := Impl.User_Id; + Copy.Workspace_Id := Impl.Workspace_Id; + Copy.Entity_Type := Impl.Entity_Type; + Copy.Permission := Impl.Permission;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Acl_Impl, Acl_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Acl_Impl_Ptr := Acl_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Acl_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, ACL_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Acl_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Acl_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (ACL_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- entity_id + Value => Object.Entity_Id); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- writeable + Value => Object.Writeable); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- user_id + Value => Object.User_Id); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- workspace_id + Value => Object.Workspace_Id); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- entity_type + Value => Object.Entity_Type); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- permission + Value => Object.Permission); + Object.Clear_Modified (7); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +function Permission_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is,"Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, + Of_Class => PERMISSION_DEF'Access); + begin + ADO.Objects.Set_Value (Result, Id); + return Result; + end Permission_Key; + + function Permission_Key (Id : in String) return ADO.Objects.Object_Key is + Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, + Of_Class => PERMISSION_DEF'Access); + begin + ADO.Objects.Set_Value (Result, Id); + return Result; + end Permission_Key; + + function ""="" (Left, Right : Permission_Ref'Class) return Boolean is + begin + return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); + end ""=""; + + procedure Set_Field (Object : in out Permission_Ref'Class; + Impl : out Permission_Access) is + Result : ADO.Objects.Object_Record_Access; + begin + Object.Prepare_Modify (Result); + Impl := Permission_Impl (Result.all)'Access; + end Set_Field; + + -- Internal method to allocate the Object_Record instance + procedure Allocate (Object : in out Permission_Ref) is + Impl : Permission_Access; + begin + Impl := new Permission_Impl; + ADO.Objects.Set_Object (Object, Impl.all'Access); + end Allocate; + + -- ---------------------------------------- + -- Data object: Permission + -- ---------------------------------------- + + procedure Set_Id (Object : in out Permission_Ref; + Value : in ADO.Identifier) is + Impl : Permission_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); + end Set_Id; + + function Get_Id (Object : in Permission_Ref) + return ADO.Identifier is + Impl : constant Permission_Access + := Permission_Impl (Object.Get_Object.all)'Access; + begin + return Impl.Get_Key_Value; + end Get_Id; + + + procedure Set_Name (Object : in out Permission_Ref; + Value : in String) is + Impl : Permission_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Name, Value); + end Set_Name; + + procedure Set_Name (Object : in out Permission_Ref; + Value : in Ada.Strings.Unbounded.Unbounded_String) is + Impl : Permission_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Name, Value); + end Set_Name; + + function Get_Name (Object : in Permission_Ref) + return String is + begin + return Ada.Strings.Unbounded.To_String (Object.Get_Name); + end Get_Name; + function Get_Name (Object : in Permission_Ref) + return Ada.Strings.Unbounded.Unbounded_String is + Impl : constant Permission_Access + := Permission_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Name; + end Get_Name; + + -- Copy of the object. + procedure Copy (Object : in Permission_Ref; + Into : in out Permission_Ref) is + Result : Permission_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Permission_Access + := Permission_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Permission_Access + := new Permission_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Name := Impl.Name;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Permission_Impl, Permission_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Permission_Impl_Ptr := Permission_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Permission_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, PERMISSION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Permission_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Permission_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (PERMISSION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Message_Type_Impl, Message_Type_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Message_Type_Impl_Ptr := Message_Type_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Message_Type_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, MESSAGE_TYPE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Message_Type_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Message_Type_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (MESSAGE_TYPE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure List (Object : in out Message_Type_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, MESSAGE_TYPE_DEF'Access); + begin + Stmt.Execute; + Message_Type_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Message_Type_Ref; + Impl : constant Message_Type_Access := new Message_Type_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Queue_Impl, Queue_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Queue_Impl_Ptr := Queue_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Queue_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, QUEUE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Queue_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Queue_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (QUEUE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- server_id + Value => Object.Server_Id); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (3); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Message_Status_Type); + Impl : Message_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 8, Impl.Status, Value); + end Set_Status; + + function Get_Status (Object : in Message_Ref) + return AWA.Events.Models.Message_Status_Type is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Status; + end Get_Status; + + + procedure Set_Processing_Date (Object : in out Message_Ref; + Value : in ADO.Nullable_Time) is + Impl : Message_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 9, Impl.Processing_Date, Value); + end Set_Processing_Date; + + function Get_Processing_Date (Object : in Message_Ref) + return ADO.Nullable_Time is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Processing_Date; + end Get_Processing_Date; + + + function Get_Version (Object : in Message_Ref) + return Integer is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Version; + end Get_Version; + + + procedure Set_Entity_Id (Object : in out Message_Ref; + Value : in ADO.Identifier) is + Impl : Message_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Identifier (Impl.all, 11, Impl.Entity_Id, Value); + end Set_Entity_Id; + + function Get_Entity_Id (Object : in Message_Ref) + return ADO.Identifier is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Entity_Id; + end Get_Entity_Id; + + + procedure Set_Entity_Type (Object : in out Message_Ref; + Value : in ADO.Entity_Type) is + Impl : Message_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Entity_Type (Impl.all, 12, Impl.Entity_Type, Value); + end Set_Entity_Type; + + function Get_Entity_Type (Object : in Message_Ref) + return ADO.Entity_Type is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Entity_Type; + end Get_Entity_Type; + + + procedure Set_Finish_Date (Object : in out Message_Ref; + Value : in ADO.Nullable_Time) is + Impl : Message_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Time (Impl.all, 13, Impl.Finish_Date, Value); + end Set_Finish_Date; + + function Get_Finish_Date (Object : in Message_Ref) + return ADO.Nullable_Time is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Finish_Date; + end Get_Finish_Date; + + + procedure Set_Queue (Object : in out Message_Ref; + Value : in AWA.Events.Models.Queue_Ref'Class) is + Impl : Message_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 14, Impl.Queue, Value); + end Set_Queue; + + function Get_Queue (Object : in Message_Ref) + return AWA.Events.Models.Queue_Ref'Class is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Queue; + end Get_Queue; + + + procedure Set_Message_Type (Object : in out Message_Ref; + Value : in AWA.Events.Models.Message_Type_Ref'Class) is + Impl : Message_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 15, Impl.Message_Type, Value); + end Set_Message_Type; + + function Get_Message_Type (Object : in Message_Ref) + return AWA.Events.Models.Message_Type_Ref'Class is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Message_Type; + end Get_Message_Type; + + + procedure Set_User (Object : in out Message_Ref; + Value : in AWA.Users.Models.User_Ref'Class) is + Impl : Message_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 16, Impl.User, Value); + end Set_User; + + function Get_User (Object : in Message_Ref) + return AWA.Users.Models.User_Ref'Class is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.User; + end Get_User; + + + procedure Set_Session (Object : in out Message_Ref; + Value : in AWA.Users.Models.Session_Ref'Class) is + Impl : Message_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 17, Impl.Session, Value); + end Set_Session; + + function Get_Session (Object : in Message_Ref) + return AWA.Users.Models.Session_Ref'Class is + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Session; + end Get_Session; + + -- Copy of the object. + procedure Copy (Object : in Message_Ref; + Into : in out Message_Ref) is + Result : Message_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Message_Access + := Message_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Message_Access + := new Message_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Create_Date := Impl.Create_Date; + Copy.Priority := Impl.Priority; + Copy.Count := Impl.Count; + Copy.Parameters := Impl.Parameters; + Copy.Server_Id := Impl.Server_Id; + Copy.Task_Id := Impl.Task_Id; + Copy.Status := Impl.Status; + Copy.Processing_Date := Impl.Processing_Date; + Copy.Version := Impl.Version; + Copy.Entity_Id := Impl.Entity_Id; + Copy.Entity_Type := Impl.Entity_Type; + Copy.Finish_Date := Impl.Finish_Date; + Copy.Queue := Impl.Queue; + Copy.Message_Type := Impl.Message_Type; + Copy.User := Impl.User; + Copy.Session := Impl.Session;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Message_Impl, Message_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Message_Impl_Ptr := Message_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Message_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, MESSAGE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Message_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Message_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (MESSAGE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_3_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_3_NAME, -- priority + Value => Object.Priority); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_3_NAME, -- count + Value => Object.Count); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_3_NAME, -- parameters + Value => Object.Parameters); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_3_NAME, -- server_id + Value => Object.Server_Id); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_3_NAME, -- task_id + Value => Object.Task_Id); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_3_NAME, -- status + Value => Integer (Message_Status_Type'Pos (Object.Status))); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_3_NAME, -- processing_date + Value => Object.Processing_Date); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (11) then + Stmt.Save_Field (Name => COL_10_3_NAME, -- entity_id + Value => Object.Entity_Id); + Object.Clear_Modified (11); + end if; + if Object.Is_Modified (12) then + Stmt.Save_Field (Name => COL_11_3_NAME, -- entity_type + Value => Object.Entity_Type); + Object.Clear_Modified (12); + end if; + if Object.Is_Modified (13) then + Stmt.Save_Field (Name => COL_12_3_NAME, -- finish_date + Value => Object.Finish_Date); + Object.Clear_Modified (13); + end if; + if Object.Is_Modified (14) then + Stmt.Save_Field (Name => COL_13_3_NAME, -- queue_id + Value => Object.Queue); + Object.Clear_Modified (14); + end if; + if Object.Is_Modified (15) then + Stmt.Save_Field (Name => COL_14_3_NAME, -- message_type_id + Value => Object.Message_Type); + Object.Clear_Modified (15); + end if; + if Object.Is_Modified (16) then + Stmt.Save_Field (Name => COL_15_3_NAME, -- user_id + Value => Object.User); + Object.Clear_Modified (16); + end if; + if Object.Is_Modified (17) then + Stmt.Save_Field (Name => COL_16_3_NAME, -- session_id + Value => Object.Session); + Object.Clear_Modified (17); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Message_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, MESSAGE_DEF'Access); + begin + Stmt.Execute; + Message_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Message_Ref; + Impl : constant Message_Access := new Message_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Application_Impl, Application_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Application_Impl_Ptr := Application_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Application_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, APPLICATION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Application_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Application_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (APPLICATION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- secret_key + Value => Object.Secret_Key); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- client_id + Value => Object.Client_Id); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_1_NAME, -- update_date + Value => Object.Update_Date); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_1_NAME, -- title + Value => Object.Title); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_1_NAME, -- description + Value => Object.Description); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_1_NAME, -- app_login_url + Value => Object.App_Login_Url); + Object.Clear_Modified (10); + end if; + if Object.Is_Modified (11) then + Stmt.Save_Field (Name => COL_10_1_NAME, -- app_logo_url + Value => Object.App_Logo_Url); + Object.Clear_Modified (11); + end if; + if Object.Is_Modified (12) then + Stmt.Save_Field (Name => COL_11_1_NAME, -- user_id + Value => Object.User); + Object.Clear_Modified (12); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Application_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, APPLICATION_DEF'Access); + begin + Stmt.Execute; + Application_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Application_Ref; + Impl : constant Application_Access := new Application_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Callback_Impl, Callback_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Callback_Impl_Ptr := Callback_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Callback_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, CALLBACK_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Callback_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Callback_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (CALLBACK_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- url + Value => Object.Url); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- application_id + Value => Object.Application); + Object.Clear_Modified (4); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Callback_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, CALLBACK_DEF'Access); + begin + Stmt.Execute; + Callback_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Callback_Ref; + Impl : constant Callback_Access := new Callback_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Session_Impl, Session_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Session_Impl_Ptr := Session_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Session_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SESSION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Session_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Session_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (SESSION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_3_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_3_NAME, -- salt + Value => Object.Salt); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_3_NAME, -- expire_date + Value => Object.Expire_Date); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_3_NAME, -- application_id + Value => Object.Application); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_3_NAME, -- user_id + Value => Object.User); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_3_NAME, -- session_id + Value => Object.Session); + Object.Clear_Modified (7); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure List (Object : in out Session_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SESSION_DEF'Access); + begin + Stmt.Execute; + Session_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Session_Ref; + Impl : constant Session_Access := new Session_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Dispatch_Event (T : in out Test;,"Kind : in Event_Index; + Expect_Count : in Natural; + Expect_Prio : in Natural) is + + Factory : AWA.Applications.Factory.Application_Factory; + Conf : ASF.Applications.Config; + Ctx : aliased EL.Contexts.Default.Default_Context; + Path : constant String := Util.Tests.Get_Test_Path (""regtests/config/event-test.xml""); + Action : aliased Action_Bean; + begin + Conf.Set (""database"", Util.Tests.Get_Parameter (""database"")); + + declare + App : aliased AWA.Tests.Test_Application; + S : Util.Measures.Stamp; + Faces : aliased ASF.Servlets.Faces.Faces_Servlet; + SC : AWA.Services.Contexts.Service_Context; + begin + App.Initialize (Conf => Conf, + Factory => Factory); + App.Set_Global (""event_test"", + Util.Beans.Objects.To_Object (Action'Unchecked_Access, + Util.Beans.Objects.STATIC)); + + SC.Set_Context (App'Unchecked_Access, null); + + App.Add_Servlet (Name => ""faces"", Server => Faces'Unchecked_Access); + App.Register_Class (""AWA.Events.Tests.Event_Action"", + Create_Action_Bean'Access); + AWA.Applications.Configs.Read_Configuration (App => App, + File => Path, + Context => Ctx'Unchecked_Access, + Override_Context => True); + Util.Measures.Report (S, ""Initialize AWA application and read config""); + App.Start; + Util.Measures.Report (S, ""Start event tasks""); + + for I in 1 .. 100 loop + declare + Event : Module_Event; + begin + Event.Set_Event_Kind (Kind); + Event.Set_Parameter (""prio"", ""3""); + Event.Set_Parameter (""template"", ""def""); + App.Send_Event (Event);" +"function Create_From_Color is new Create_From_Enum (Color, ""color_"");","procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is + begin + Caller.Add_Test (Suite, ""Test AWA.Helpers.Selectors.Create_From_Query"", + Test_Create_From_Query'Access); + Caller.Add_Test (Suite, ""Test AWA.Helpers.Selectors.Create_From_Enum"", + Test_Create_From_Enum'Access); + end Add_Tests; + + -- ------------------------------ + -- Test creation of selector from an SQL query + -- ------------------------------ + procedure Test_Create_From_Query (T : in out Test) is + Session : constant ADO.Sessions.Session := AWA.Tests.Get_Application.Get_Session; + Query : constant String := ""SELECT id, name from entity_type order by id""; + Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query); + Result : ASF.Models.Selects.Select_Item_List; + Found_User : Boolean := False; + begin + Append_From_Query (Result, Stmt); + T.Assert (Result.Length > 0, ""The list should not be empty""); + + for I in 1 .. Result.Length loop + declare + Item : constant ASF.Models.Selects.Select_Item := Result.Get_Select_Item (I); + begin + -- The SQL query will return two different columns. + -- Just check that label and values are different. + T.Assert (Item.Get_Value /= Item.Get_Label, ""Item and label are equals""); + + -- To make this test simple, check only for one known entry in the list. + if Item.Get_Label = ""awa_user"" then + Found_User := True; + end if;" +procedure Day02 is,"package ASU renames Ada.Strings.Unbounded; + -- for convenience purpose + + type US_Array is array(Positive range <>) of ASU.Unbounded_String; + -- The IDs in the input data are all the same length, so we could use a + -- fixed-length String array, but it would not be very generic, and it would + -- not be suited for examples either. + + type Natural_Couple is array(1..2) of Natural; + -- This data structure will be used to store two things: + -- * IDs that have exactly 2 of any letter and exactly 3 of any letter; + -- * the absolute count of IDs for the previous item. + -- I could/should use a record for that, but meh, later maybe. + + type Character_Count is array(Character range 'a' .. 'z') of Natural; + -- An array indexed on characters that will be used to count occurrences. + -- This is not very generic (cough), but it will do for the input. + + -- Creates the ""String"" array from the file name + function Read_Input(file_name : in String) return US_Array is + -- Tail-call recursion to create the final array. + function Read_Input_Rec(input : in Ada.Text_IO.File_Type; acc : in US_Array) return US_Array is + begin + if Ada.Text_IO.End_Of_File(input) then + return acc; + else + return Read_Input_Rec + ( + input, + acc & (1 => ASU.To_Unbounded_String(Ada.Text_IO.Get_Line(input))) + ); + end if; + end Read_Input_Rec; + + F : Ada.Text_IO.File_Type; + acc : US_Array(1 .. 0); + begin + Ada.Text_IO.Open + ( + File => F, + Mode => Ada.Text_IO.In_File, + Name => file_name + ); + declare + result : US_Array := Read_Input_Rec(F, acc); + begin + Ada.Text_IO.Close(F); + return result;" +procedure Day01 is,"type Integer_Array is array(Positive range <>) of Integer; + -- The data structure to store the input. + + function Hash is new Ada.Unchecked_Conversion + ( + Source => Integer, + Target => Ada.Containers.Hash_Type + ); + -- Creates a hash value from integers. + -- Supposes that integers and Hash_Type have the same size. + + package Integer_Sets is new Ada.Containers.Hashed_Sets + ( + Element_Type => Integer, + Hash => Hash, + Equivalent_Elements => ""="" + ); + -- For part 2: using a set to store frequencies. + + -- Creates the integer array from the name of the input file. + function Read_Input(file_name : in String) return Integer_Array is + -- Tail-call recursion to create the array of Integers. + -- Using an accumulator allows to generate arbitrary length arrays. + function Read_Input_Rec(input : in Ada.Text_IO.File_Type; acc : in Integer_Array) return Integer_Array is + begin + -- The stop condition. + -- Not using End_Of_File will make the compiler issue a warning, which + -- can prevent you from running the code if -Werror flag is enabled. + if Ada.Text_IO.End_Of_File(input) then + return acc; + else + return Read_Input_Rec + ( + input, + acc & (1 => Integer'Value(Ada.Text_IO.Get_Line(input))) + ); + end if; + end Read_Input_Rec; + + F : Ada.Text_IO.File_Type; + acc : Integer_Array(1 .. 0); + begin + Ada.Text_IO.Open + ( + File => F, + Mode => Ada.Text_IO.In_File, + Name => file_name + ); + declare + result : Integer_Array := Read_Input_Rec(F, acc); + begin + Ada.Text_IO.Close(F); + return result;" +function Convert is new Ada.Unchecked_Conversion,"(Source => Key_Kind, Target => Key_Code); + begin + return Convert (Kind); + end To_Code; + + function To_Key (Code : Key_Code) return Key_Kind is + begin + for Kind in Key_Kind'Range loop + if Code = To_Code (Kind) then + return Kind; + end if; + end loop; + + return Key_Unknown; + end To_Key; + + function Hex_Image (Value : Unsigned_8) return String is + Hex : constant array (Unsigned_8 range 0 .. 15) of Character := ""0123456789abcdef""; + begin + return Hex (Value / 16) & Hex (Value mod 16); + end Hex_Image; + + function Hex_Image (Value : Unsigned_16; Bit_Order : System.Bit_Order) return String is + Low : constant Unsigned_8 := Unsigned_8 (16#FF# and Value); + High : constant Unsigned_8 := Unsigned_8 (16#FF# and (Value / 256)); + + use type System.Bit_Order; + begin + if System.Default_Bit_Order = Bit_Order then + return Hex_Image (Low) & Hex_Image (High); + else + return Hex_Image (High) & Hex_Image (Low); + end if; + end Hex_Image; + + function Hex_Image (Value : Unsigned_16) return String is + (Hex_Image (Value, System.High_Order_First)); + + function GUID (ID : Device_ID) return String is + (Hex_Image (ID.Bus, System.Low_Order_First) & ""0000"" & + Hex_Image (ID.Vendor, System.Low_Order_First) & ""0000"" & + Hex_Image (ID.Product, System.Low_Order_First) & ""0000"" & + Hex_Image (ID.Version, System.Low_Order_First) & ""0000""); + + ---------------------------------------------------------------------------- + + use all type Event_Device.Input_Dev.Access_Mode; + use type Event_Device.Input_Dev.Unsigned_14; + + function ID (Object : Input_Device) return Device_ID is + Result : aliased Device_ID; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#02#, Result'Size / System.Storage_Unit), Result'Address); + begin + return (if Error_Code /= -1 then Result else (others => 0)); + end ID; + + function Location (Object : Input_Device) return String is + Result : aliased String (1 .. 128) := (others => ' '); + + Length : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#07#, Result'Length), Result'Address); + begin + return (if Length > 0 then Result (1 .. Length - 1) else """"); + end Location; + + function Unique_ID (Object : Input_Device) return String is + Result : aliased String (1 .. 128) := (others => ' '); + + Length : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#08#, Result'Length), Result'Address); + begin + return (if Length > 0 then Result (1 .. Length - 1) else """"); + end Unique_ID; + + ---------------------------------------------------------------------------- + + function Properties (Object : Input_Device) return Device_Properties is + Result : aliased Device_Properties; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#09#, Result'Size / System.Storage_Unit), Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Properties; + + function Events (Object : Input_Device) return Device_Events is + Result : aliased Device_Events; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#20#, Result'Size / System.Storage_Unit), Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Events; + + function Convert is new Ada.Unchecked_Conversion + (Source => Event_Kind, Target => Interfaces.C.unsigned_short); + + function Features (Object : Input_Device) return Synchronization_Features is + Result : aliased Synchronization_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#20# + Unsigned_8 (Convert (Synchronization)), + Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Features; + + function Features (Object : Input_Device) return Key_Features is + Result : aliased Key_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#20# + Unsigned_8 (Convert (Key)), + Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + + return Result; + end Features; + + function Features (Object : Input_Device) return Relative_Axis_Features is + Result : aliased Internal_Relative_Axis_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#20# + Unsigned_8 (Convert (Relative)), Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + + return + (X => Result.X, + Y => Result.Y, + Z => Result.Z, + Rx => Result.Rx, + Ry => Result.Ry, + Rz => Result.Rz, + Horizontal_Wheel => Result.Horizontal_Wheel, + Diagonal => Result.Diagonal, + Wheel => Result.Wheel, + Misc => Result.Misc, + Wheel_High_Res => Result.Wheel_High_Res, + Horizontal_Wheel_High_Res => Result.Horizontal_Wheel_High_Res); + end Features; + + function Features (Object : Input_Device) return Absolute_Axis_Features is + Result : aliased Internal_Absolute_Axis_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#20# + Unsigned_8 (Convert (Absolute)), Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + + return + (X => Result.X, + Y => Result.Y, + Z => Result.Z, + Rx => Result.Rx, + Ry => Result.Ry, + Rz => Result.Rz, + Throttle => Result.Throttle, + Rudder => Result.Rudder, + Wheel => Result.Wheel, + Gas => Result.Gas, + Brake => Result.Brake, + Hat_0X => Result.Hat_0X, + Hat_0Y => Result.Hat_0Y, + Hat_1X => Result.Hat_1X, + Hat_1Y => Result.Hat_1Y, + Hat_2X => Result.Hat_2X, + Hat_2Y => Result.Hat_2Y, + Hat_3X => Result.Hat_3X, + Hat_3Y => Result.Hat_3Y, + Pressure => Result.Pressure, + Distance => Result.Distance, + Tilt_X => Result.Tilt_X, + Tilt_Y => Result.Tilt_Y, + Tool_Width => Result.Tool_Width, + Volume => Result.Volume, + Misc => Result.Misc, + MT_Slot => Result.MT_Slot, + MT_Touch_Major => Result.MT_Touch_Major, + MT_Touch_Minor => Result.MT_Touch_Minor, + MT_Width_Major => Result.MT_Width_Major, + MT_Width_Minor => Result.MT_Width_Minor, + MT_Orientation => Result.MT_Orientation, + MT_Position_X => Result.MT_Position_X, + MT_Position_Y => Result.MT_Position_Y, + MT_Tool_Type => Result.MT_Tool_Type, + MT_Blob_ID => Result.MT_Blob_ID, + MT_Tracking_ID => Result.MT_Tracking_ID, + MT_Pressure => Result.MT_Pressure, + MT_Distance => Result.MT_Distance, + MT_Tool_X => Result.MT_Tool_X, + MT_Tool_Y => Result.MT_Tool_Y); + end Features; + + function Features (Object : Input_Device) return Switch_Features is + Result : aliased Switch_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#20# + Unsigned_8 (Convert (Switch)), Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Features; + + function Features (Object : Input_Device) return Miscellaneous_Features is + Result : aliased Miscellaneous_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#20# + Unsigned_8 (Convert (Miscellaneous)), + Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Features; + + function Features (Object : Input_Device) return LED_Features is + Result : aliased LED_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#20# + Unsigned_8 (Convert (LED)), Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Features; + + function Features (Object : Input_Device) return Repeat_Features is + Result : aliased Repeat_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#20# + Unsigned_8 (Convert (Repeat)), Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Features; + + function Features (Object : Input_Device) return Sound_Features is + Result : aliased Sound_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#20# + Unsigned_8 (Convert (Sound)), Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Features; + + function Features (Object : Input_Device) return Force_Feedback_Features is + Result : aliased Internal_Force_Feedback_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#20# + Unsigned_8 (Convert (Force_Feedback)), + Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + + return + (Rumble => Result.Rumble, + Periodic => Result.Periodic, + Constant_V => Result.Constant_V, + Spring => Result.Spring, + Friction => Result.Friction, + Damper => Result.Damper, + Inertia => Result.Inertia, + Ramp => Result.Ramp, + Square => Result.Square, + Triangle => Result.Triangle, + Sine => Result.Sine, + Saw_Up => Result.Saw_Up, + Saw_Down => Result.Saw_Down, + Custom => Result.Custom, + Gain => Result.Gain, + Auto_Center => Result.Auto_Center); + end Features; + + ---------------------------------------------------------------------------- + + function Axis (Object : Input_Device; Axis : Absolute_Axis_Kind) return Axis_Info is + Result : aliased Axis_Info; + + function Convert is new Ada.Unchecked_Conversion + (Source => Absolute_Axis_Info_Kind, Target => Unsigned_64); + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#40# + Unsigned_8 (Convert (Absolute_Axis_Info_Kind (Axis))), + Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Axis; + + function Key_Statuses (Object : Input_Device) return Key_Features is + Result : aliased Key_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#18#, + Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + + return Result; + end Key_Statuses; + + function LED_Statuses (Object : Input_Device) return LED_Features is + Result : aliased LED_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#19#, Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end LED_Statuses; + + function Sound_Statuses (Object : Input_Device) return Sound_Features is + Result : aliased Sound_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#1A#, Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Sound_Statuses; + + function Switch_Statuses (Object : Input_Device) return Switch_Features is + Result : aliased Switch_Features; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, + (Read, 'E', 16#1B#, Result'Size / System.Storage_Unit), + Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Switch_Statuses; + + function Force_Feedback_Effects (Object : Input_Device) return Natural is + Result : aliased Integer; + + Error_Code : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#84#, Result'Size / System.Storage_Unit), Result'Address); + begin + pragma Assert (Error_Code /= -1); + return Result; + end Force_Feedback_Effects; + + procedure Set_Force_Feedback_Gain + (Object : Input_Device; + Value : Force_Feedback_Gain) + is + FF_Gain_Code : constant := 16#60#; + + Event : constant Input_Dev.Input_Event := + (Time => (0, 0), + Event => Force_Feedback, + Code => FF_Gain_Code, + Value => Interfaces.C.int (16#FF_FF.00# * Value)); + + Result_Unused : constant Input_Dev.Result := Input_Dev.Write (Object.FD, Event); + begin + -- Ignore any possible errors. If the device has been disconnected + -- then playing a force-feedback effect will fail, which can be + -- detected by the boolean returned by Play_Force_Feedback_Effect. + null; + end Set_Force_Feedback_Gain; + + procedure Set_Force_Feedback_Auto_Center + (Object : Input_Device; + Value : Force_Feedback_Auto_Center) + is + FF_Auto_Center_Code : constant := 16#61#; + + Event : constant Input_Dev.Input_Event := + (Time => (0, 0), + Event => Force_Feedback, + Code => FF_Auto_Center_Code, + Value => Interfaces.C.int (16#FF_FF.00# * Value)); + + Result_Unused : constant Input_Dev.Result := Input_Dev.Write (Object.FD, Event); + begin + -- Ignore any possible errors. If the device has been disconnected + -- then playing a force-feedback effect will fail, which can be + -- detected by the boolean returned by Play_Force_Feedback_Effect. + null; + end Set_Force_Feedback_Auto_Center; + + function Play_Force_Feedback_Effect + (Object : Input_Device; + Identifier : Uploaded_Force_Feedback_Effect_ID; + Count : Natural := 1) return Boolean + is + Event : constant Input_Dev.Input_Event := + (Time => (0, 0), + Event => Force_Feedback, + Code => Interfaces.C.unsigned_short (Identifier), + Value => Interfaces.C.int (Count)); + + Result : constant Input_Dev.Result := Input_Dev.Write (Object.FD, Event); + begin + return Result.Is_Success; + end Play_Force_Feedback_Effect; + + function Name (Object : Input_Device) return String is + Result : aliased String (1 .. 128) := (others => ' '); + + Length : constant Integer := Event_Device.Input_Dev.IO_Control + (Object.FD, (Read, 'E', 16#06#, Result'Length), Result'Address); + begin + return (if Length > 0 then Result (1 .. Length - 1) else """"); + end Name; + + function Is_Open (Object : Input_Device) return Boolean is + (Object.Open); + + function Open + (Object : in out Input_Device; + File_Name : String; + Blocking : Boolean := True) return Boolean + is + Result : constant Input_Dev.Result := Input_Dev.Open (File_Name, Blocking => Blocking); + begin + if Result.Is_Success then + Object.FD := Result.FD; + end if; + Object.Open := Result.Is_Success; + return Object.Open; + end Open; + + procedure Close (Object : in out Input_Device) is + Result : constant Input_Dev.Result := Input_Dev.Close (Object.FD); + begin + Object.FD := -1; + Object.Open := not Result.Is_Success; + end Close; + + overriding procedure Finalize (Object : in out Input_Device) is + begin + if Object.Is_Open then + Object.Close; + end if; + end Finalize; + + function Read + (Object : Input_Device; + Value : out State) return Read_Result + is + use Event_Device.Input_Dev; + use type Interfaces.C.unsigned_short; + use type Interfaces.C.int; + + function Convert is new Ada.Unchecked_Conversion + (Source => Interfaces.C.unsigned_short, Target => Synchronization_Kind); + + function Convert is new Ada.Unchecked_Conversion + (Source => Interfaces.C.unsigned_short, Target => Unsigned_16); + + function Convert is new Ada.Unchecked_Conversion + (Source => Interfaces.C.unsigned_short, Target => Relative_Axis_Info_Kind); + + function Convert is new Ada.Unchecked_Conversion + (Source => Unsigned_64, Target => Absolute_Axis_Info_Kind); + -- Convert to Absolute_Axis_Info_Kind first before converting to + -- Absolute_Axis_Kind, because the former has a representation clause + + Event : Input_Event; + Result : Input_Dev.Result; + + Has_Dropped : Boolean := False; + begin + loop + Result := Input_Dev.Read (Object.FD, Event); + + if not Result.Is_Success then + if Result.Error = Would_Block then + return Would_Block; + else + Value := (others => <>); + return Error; + end if; + end if; + + case Event.Event is + when Key => + declare + Code : constant Key_Code := Key_Code (Unsigned_16'(Convert (Event.Code))); + begin + Value.Keys (Key_Code_Index (Code)) := + (if Event.Value /= 0 then Pressed else Released);" +procedure Info is,"package ACL renames Ada.Command_Line; + + EF : Event_Device.Input_Device; + + Do_Rumble : constant Boolean := + ACL.Argument_Count = 2 and then ACL.Argument (2) = ""--ff=rumble""; + Do_Periodic : constant Boolean := + ACL.Argument_Count = 2 and then ACL.Argument (2) = ""--ff=periodic""; + Do_Read : constant Boolean := + ACL.Argument_Count = 2 and then ACL.Argument (2) = ""--read""; +begin + if ACL.Argument_Count /= 1 and not (Do_Rumble or Do_Periodic or Do_Read) then + Ada.Text_IO.Put_Line (""Usage: [--read|--ff=rumble|periodic]""); + ACL.Set_Exit_Status (ACL.Failure); + return; + end if; + + if not EF.Open (ACL.Argument (1)) then + Ada.Text_IO.Put_Line (""Cannot open device "" & ACL.Argument (1)); + ACL.Set_Exit_Status (ACL.Failure); + return; + end if; + + Ada.Text_IO.Put_Line (""Device name: '"" & EF.Name & ""'""); + Ada.Text_IO.Put_Line (""Location: '"" & EF.Location & ""'""); + Ada.Text_IO.Put_Line (""Uniq ID: '"" & EF.Unique_ID & ""'""); + declare + ID : constant Event_Device.Device_ID := EF.ID; + Props : constant Event_Device.Device_Properties := EF.Properties; + Events : constant Event_Device.Device_Events := EF.Events; + + ID_A : constant String := Event_Device.Hex_Image (ID.Bus); + ID_B : constant String := Event_Device.Hex_Image (ID.Vendor); + ID_C : constant String := Event_Device.Hex_Image (ID.Product); + ID_D : constant String := Event_Device.Hex_Image (ID.Version); + begin + Ada.Text_IO.Put_Line (""Bus ven pro ver: "" & + ID_A & "" "" & ID_B & "" "" & ID_C & "" "" & ID_D); + Ada.Text_IO.Put_Line (""GUID: "" & Event_Device.GUID (ID)); + Ada.Text_IO.Put_Line (""Properties:""); + Ada.Text_IO.Put_Line ("" Pointer: "" & Props.Pointer'Image); + Ada.Text_IO.Put_Line ("" Direct: "" & Props.Direct'Image); + Ada.Text_IO.Put_Line ("" Button pad: "" & Props.Button_Pad'Image); + Ada.Text_IO.Put_Line ("" Semi mt: "" & Props.Semi_Multi_Touch'Image); + Ada.Text_IO.Put_Line ("" Top button pad: "" & Props.Top_Button_Pad'Image); + Ada.Text_IO.Put_Line ("" Pointing stick: "" & Props.Pointing_Stick'Image); + Ada.Text_IO.Put_Line ("" Accelerometer: "" & Props.Accelerometer'Image); + + Ada.Text_IO.Put_Line (""Events:""); + Ada.Text_IO.Put_Line ("" Synchronization: "" & Events.Synchronization'Image); + if Events.Synchronization then + declare + Features : constant Event_Device.Synchronization_Features := EF.Features; + begin + for K in Event_Device.Synchronization_Kind'Range loop + if Features (K) then + Ada.Text_IO.Put_Line ("" "" & K'Image); + end if; + end loop;" +procedure Register_Tests (T : in out TC) is,"use AUnit.Test_Cases.Registration; + begin + Register_Routine + (T, Test_Get_String_Flag_OK_With_Default'Access, ""Test CLI get string with default values""); + Register_Routine + (T, Test_Get_String_Flag_Throws_No_Flag_Or_Short'Access, ""Test CLI get string throws when no flag and short""); + Register_Routine + (T, Test_Get_String_Flag_Throws_When_Required'Access, ""Test CLI get string when required argument not found""); + end Register_Tests; + + function Name (T : TC) return Message_String is + pragma Unreferenced (T); + begin + return AUnit.Format (""CLI Get_String_Flag""); + end Name; + + procedure Set_Up (T : in out TC) is + begin + null; + end Set_Up; + + -- Test_Get_String_Flag_OK_With_Default + -- ------------------------------------ + + procedure Test_Get_String_Flag_OK_With_Default (T : in out Test_Cases.Test_Case'Class) is + Required_Flag : constant String := ""--test-switch""; + Default_Value : constant String := ""this is the default value""; + begin + declare + Res : String := Cli.Get_String_Flag(Flag => Required_Flag, Required => false, DefaultValue => Default_Value); + begin + Assert(Res = Default_Value, ""Expected didn't match received: expected="" & Default_Value & "", received="" & Res);" +procedure Main is,"begin + begin + declare + GrossSalaryValue : Float := Get_Float_Flag(Flag => ""--gross"", Short => ""-g"", Required => true); + GrossMode : String := Get_String_Flag(Flag => ""--mode"", Short => ""-m"", DefaultValue => ""annual""); + begin + Put_Line(""Hello, World... gross="" & Float'Image(GrossSalaryValue) & "", mode="" & GrossMode);" +procedure Represent is,"use Ada; + + type Byte is mod 2**8 with Size => 8; + + type T_Instruction is (Load, Store, Clear, Move) + with Size => 2; + + for T_Instruction use (Load => 2#00#, + Store => 2#01#, + Clear => 2#10#, + Move => 2#11#); + + type T_Register is mod 2**3 with Size => 3; + + type Command is record + Instruction : T_Instruction; + Source : T_Register; + Dest : T_Register; + end record + with + Size => 8, + Bit_Order => System.Low_Order_First; + + for Command use record + Instruction at 0 range 6 .. 7; + Source at 0 range 3 .. 5; + Dest at 0 range 0 .. 2; + end record; + + function To_Byte is new Unchecked_Conversion + (Source => Command, + Target => Byte); + + procedure Put_Instruction + (Instruction : T_Instruction; + Src, Dest : T_Register) + is + Instr : Command := (Instruction, Src, Dest); + begin + Put_Line (Byte'Image (To_Byte (Instr)));" +procedure Task_Queue is,"-- cf. Barnes, J., ""Programming in Ada 2012"" (Chapter 20) + task Buffer is + entry Put (X : in Integer); + entry Get (X : out Integer);" +procedure represent2 is,"type Action_Type is (Load, + Store, + Copy, + Add, + Clear, + Jump, + Ret) + with Size => 4; + + for Action_Type use + (Load => 2#1000#, + Store => 2#1001#, + Copy => 2#1010#, + Add => 2#1011#, + Clear => 2#1100#, + Jump => 2#1101#, + Ret => 2#1110#); + + type Register_Type is mod 2**4 with Size => 4; + type Ref_Register_Type is mod 2**2 + with Size => 2; + + + type Mode_Type is (Direct, Register, Indirect) + with Size => 2; + + for Mode_Type use + (Direct => 2#01#, + Register => 2#10#, + Indirect => 2#11#); + + + type Mult_Factor_Type is mod 2**2 + with Size => 2; + + type Long_Reg (Mode : Mode_Type := Direct) is record + Action : Action_Type; -- 4 + case Mode is + when Direct => + Bit_Fill : Mult_Factor_Type; -- 2 + Address : Unsigned_8; -- 8 + when Register => + Mult_Factor : Mult_Factor_Type; -- 2 + Reg1 : Register_Type; -- 4 + Reg2 : Register_Type; -- 4 + when Indirect => + Ref_Reg : Ref_Register_Type; -- 2 + Offset : Unsigned_8; -- 8 + end case; + end record with + Size => 16, -- Pack, + Bit_Order => System.Low_Order_First; + + -- This works. + for Long_Reg use record + Action at 0 range 12 .. 15; + Mode at 0 range 10 .. 11; + + Bit_Fill at 0 range 8 .. 9; + Address at 0 range 0 .. 7; + + Mult_Factor at 0 range 8 .. 9; + Reg1 at 0 range 4 .. 7; + Reg2 at 0 range 0 .. 3; + Ref_Reg at 0 range 8 .. 9; + Offset at 0 range 0 .. 7; + end record; + + type Word is new Interfaces.Unsigned_16; + + function To_Word is + new Unchecked_Conversion (Long_Reg, Word); + + procedure Put_Word (S : Long_Reg) is + begin + Put_Line (Word'Image (To_Word (S)));" +procedure Protect2 is,"procedure Put_Time_Diff (D : in Time) is + T : Duration := Clock - D; + begin + Put (Duration'Image (T)); + end Put_Time_Diff; + + + protected One_A_Time is + function Read (Id : String) return Integer; + procedure Write (X : Integer); + private + V : Integer := 2; + T : Time := Clock; + end One_A_Time; + + protected body One_A_Time is + + function Read (Id : String) return Integer is + begin + Put_Time_Diff (T); Put_Line ("" OAT reads for "" & Id); + return V; + end Read; + + procedure Write (X : Integer) is + begin + Put_Time_Diff (T); Put_Line ("" OAT starts writing...""); + delay 5.0; + V := X; + Put_Time_Diff (T); Put_Line ("" OAT ended writing...""); + end Write; + + end One_A_Time; + + task Reader1; + task Reader2; + + task body Reader1 is + I : Integer := One_A_Time.Read (""R1""); + begin + loop + exit when I = 0; + I := One_A_Time.Read (""R1""); + delay 0.5; + end loop; + end Reader1; + + task body Reader2 is + I : Integer := One_A_Time.Read (""R2""); + begin + loop + exit when I = 0; + I := One_A_Time.Read (""R2""); + delay 0.5; + end loop; + end Reader2; + + T : Time := Clock; +begin + -- The main writes + Put_Time_Diff (T); Put_Line ("" ET writes 1...""); + One_A_Time.Write (1); + Put_Time_Diff (T); Put_Line ("" ET has written 1""); + delay 5.0; + Put_Time_Diff (T); Put_Line ("" ET writes 0...""); + One_A_Time.Write (0); + Put_Time_Diff (T); Put_Line ("" ET has written 0"");" +procedure Protect is,"procedure Put_Time_Diff (D : in Time) is + T : Duration := Clock - D; + begin + Put (Duration'Image (T)); + end Put_Time_Diff; + + + protected One_A_Time is + function Read return Integer; + -- Reading takes 3s + + procedure Write (X : Integer); + -- Writing takes 5s + private + V : Integer := 0; + T : Time := Clock; + end One_A_Time; + + + + protected body One_A_Time is + + function Read return Integer is + begin + Put_Time_Diff (T); Put_Line ("" OAT starts reading...""); + delay 3.0; + Put_Time_Diff (T); Put_Line ("" OAT ended read""); + return V; + end Read; + + procedure Write (X : Integer) is + begin + Put_Time_Diff (T); Put_Line ("" OAT starts writing...""); + delay 5.0; + V := X; + Put_Time_Diff (T); Put_Line ("" OAT ended writing...""); + end Write; + + end One_A_Time; + + task Reader1; + task Reader2; + + task body Reader1 is + I : Integer; + T : Time := Clock; + begin + Put_Time_Diff (T); + Put_Line ("" R1 reading...""); + I := One_A_Time.Read; + Put_Time_Diff (T); + Put_Line ("" ...R1 read"" & Integer'Image (I)); + delay 5.0; + -- try to read with R2 + I := One_A_Time.Read; + Put_Time_Diff (T); Put_Line (""*** R1 exit ***""); + end Reader1; + + task body Reader2 is + I : Integer; + T : Time := Clock; + begin + Put_Time_Diff (T); + Put_Line ("" R2 works for 2s""); + delay 2.0; + Put_Time_Diff (T); + Put_Line ("" R2 reading...""); + I := One_A_Time.Read; + Put_Time_Diff (T); + Put_Line ("" ...R2 read"" & Integer'Image (I)); + Put_Line (""*** R2 exit ***""); + end Reader2; + + T : Time := Clock; +begin + -- The main writes + Put_Time_Diff (T); + Put_Line ("" ET writes 1...""); + One_A_Time.Write (1); + Put_Time_Diff (T); + Put_Line ("" ET has written 1"");" +procedure Mandel_UTF is,"package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Float); + use Complex_Types; + + -- Configuration constants. + Bitmap_Size : constant := 128; -- pixels + Max_Iterations : constant := 32; + Num_Of_Threads : constant := 4; + + ------------------------------------------------------ + -- This part replaces Given's glyphs table + subtype Brush_Levels is Integer range 0 .. 255; + type Brushes is array (Brush_Levels) of Wide_Character; + + function Generate_Glyphs return Brushes is + First_Code_Point : constant := 10240; + begin + return E : Brushes do + for I in Brush_Levels'Range loop + E (I) := Wide_Character'Val (First_Code_Point + I); + end loop; + end return; + end Generate_Glyphs; + + Glyphs : constant Brushes := Generate_Glyphs; + ------------------------------------------------------ + + -- Returns the intensity of a single point in the Mandelbrot set. + function Render_Pixel (C : Complex) return Float is + Z : Complex := Complex'(0.0, 0.0); + begin + for N in Integer range 0 .. Max_Iterations loop + Z := Z*Z + C; + if (abs Z > 2.0) then + return Float (N) / Float (Max_Iterations); + end if; + end loop; + return 0.0;" +procedure Free_Bitmap is new Ada.Unchecked_Deallocation,"(Object => Bitmap, Name => Bitmap_Ref); + + -- Encapsulates the multithreaded render: creates a bunch of workers + -- and a scheduler, which hands out work units to the renderers. + procedure Mandelbrot + (Data : Bitmap_Ref; + R1, I1, R2, I2 : Float) + is + Width : Integer := Data'Length (1); + Height : Integer := Data'Length (2); + Xdelta : Float := (R2-R1) / Float (Width); + Ydelta : Float := (I2-I1) / Float (Height); + + task Scheduler is + -- Each worker calls this to find out what it needs to do. + entry Request_Work_Unit (Y : out Integer; I : out Float);" +procedure MandelPNG is,"package C renames Interfaces.C; + + + package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Float); + use Complex_Types; + + -- Configuration constants. + Width : constant := 800; + Height : constant := 600; + + Max_Iterations : constant := 32; + + -- Returns the intensity of a single point in the Mandelbrot set. + function Render_Pixel (C : Complex) return Float is + Z : Complex := Complex'(0.0, 0.0); + begin + for N in Integer range 0 .. Max_Iterations loop + Z := Z*Z + C; + if (abs Z > 2.0) then + return Float (N) / Float (Max_Iterations); + end if; + end loop; + return 0.0;" +procedure Free_Bitmap is new Ada.Unchecked_Deallocation,"(Object => Bitmap, Name => Bitmap_Ref); + + + procedure Mandelbrot + (Data : Bitmap_Ref; + R1, I1, R2, I2 : Float) + is + Width : Integer := Data'Length (1); + Height : Integer := Data'Length (2); + Xdelta : Float := (R2-R1) / Float (Width); + Ydelta : Float := (I2-I1) / Float (Height); + + I : Float; + C : Complex; + begin + Put_Line (""Width: "" & Integer'Image (Width)); + Put_Line (""Height: "" & Integer'Image (Height)); + Put_Line (""Xdelta: "" & Float'Image (Xdelta)); + Put_Line (""Ydelta: "" & Float'Image (Ydelta)); + + for Y in Data'Range (2) loop + I := I1 + Float (Y) * Ydelta; + for X in Data'Range (1) loop + C := Complex'(R1 + Float (X) * Xdelta, I); + Data (X, Y) := Render_Pixel (C); + end loop; + end loop;" +procedure Main_Lab1 is,"n: Integer := 5 ; + package data1 is new data (n); + use data1; + + CPU0: CPU_Range :=0; + CPU1: CPU_Range :=1; + CPU2: CPU_Range :=2; + f1, f2, f3:Integer; + + procedure tasks is + task T1 is + pragma Priority(1); + pragma CPU(CPU0);" +procedure Ada_Lexer_Test is,"type File_Source is new Incr.Lexers.Batch_Lexers.Abstract_Source with record + Text : League.Strings.Universal_String; + Index : Positive := 1; + end record; + + overriding function Get_Next (Self : not null access File_Source) + return Wide_Wide_Character; + + function Debug_Image + (Value : Incr.Ada_Lexers.Token) return Wide_Wide_String; + + function Debug_Image + (Value : Incr.Ada_Lexers.Token) return Wide_Wide_String + is + use Incr.Ada_Lexers; + begin + case Value is + when Arrow_Token => return ""Arrow_Token""; + when Double_Dot_Token => return ""Double_Dot_Token""; + when Double_Star_Token => return ""Double_Star_Token""; + when Assignment_Token => return ""Assignment_Token""; + when Inequality_Token => return ""Inequality_Token""; + when Greater_Or_Equal_Token => return ""Greater_Or_Equal_Token""; + when Less_Or_Equal_Token => return ""Less_Or_Equal_Token""; + when Left_Label_Token => return ""Left_Label_Token""; + when Right_Label_Token => return ""Right_Label_Token""; + when Box_Token => return ""Box_Token""; + when Ampersand_Token => return ""Ampersand_Token""; + when Apostrophe_Token => return ""Apostrophe_Token""; + when Left_Parenthesis_Token => return ""Left_Parenthesis_Token""; + when Right_Parenthesis_Token => return ""Right_Parenthesis_Token""; + when Star_Token => return ""Star_Token""; + when Plus_Token => return ""Plus_Token""; + when Comma_Token => return ""Comma_Token""; + when Hyphen_Token => return ""Hyphen_Token""; + when Dot_Token => return ""Dot_Token""; + when Slash_Token => return ""Slash_Token""; + when Colon_Token => return ""Colon_Token""; + when Semicolon_Token => return ""Semicolon_Token""; + when Less_Token => return ""Less_Token""; + when Equal_Token => return ""Equal_Token""; + when Greater_Token => return ""Greater_Token""; + when Vertical_Line_Token => return ""Vertical_Line_Token""; + when Identifier_Token => return ""Identifier_Token""; + when Numeric_Literal_Token => return ""Numeric_Literal_Token""; + when Character_Literal_Token => return ""Character_Literal_Token""; + when String_Literal_Token => return ""String_Literal_Token""; + when Comment_Token => return ""Comment_Token""; + when Space_Token => return ""Space_Token""; + when New_Line_Token => return ""New_Line_Token""; + when Error_Token => return ""Error_Token""; + when Abort_Token => return ""Abort_Token""; + when Abs_Token => return ""Abs_Token""; + when Abstract_Token => return ""Abstract_Token""; + when Accept_Token => return ""Accept_Token""; + when Access_Token => return ""Access_Token""; + when Aliased_Token => return ""Aliased_Token""; + when All_Token => return ""All_Token""; + when And_Token => return ""And_Token""; + when Array_Token => return ""Array_Token""; + when At_Token => return ""At_Token""; + when Begin_Token => return ""Begin_Token""; + when Body_Token => return ""Body_Token""; + when Case_Token => return ""Case_Token""; + when Constant_Token => return ""Constant_Token""; + when Declare_Token => return ""Declare_Token""; + when Delay_Token => return ""Delay_Token""; + when Delta_Token => return ""Delta_Token""; + when Digits_Token => return ""Digits_Token""; + when Do_Token => return ""Do_Token""; + when Else_Token => return ""Else_Token""; + when Elsif_Token => return ""Elsif_Token""; + when End_Token => return ""End_Token""; + when Entry_Token => return ""Entry_Token""; + when Exception_Token => return ""Exception_Token""; + when Exit_Token => return ""Exit_Token""; + when For_Token => return ""For_Token""; + when Function_Token => return ""Function_Token""; + when Generic_Token => return ""Generic_Token""; + when Goto_Token => return ""Goto_Token""; + when If_Token => return ""If_Token""; + when In_Token => return ""In_Token""; + when Interface_Token => return ""Interface_Token""; + when Is_Token => return ""Is_Token""; + when Limited_Token => return ""Limited_Token""; + when Loop_Token => return ""Loop_Token""; + when Mod_Token => return ""Mod_Token""; + when New_Token => return ""New_Token""; + when Not_Token => return ""Not_Token""; + when Null_Token => return ""Null_Token""; + when Of_Token => return ""Of_Token""; + when Or_Token => return ""Or_Token""; + when Others_Token => return ""Others_Token""; + when Out_Token => return ""Out_Token""; + when Overriding_Token => return ""Overriding_Token""; + when Package_Token => return ""Package_Token""; + when Pragma_Token => return ""Pragma_Token""; + when Private_Token => return ""Private_Token""; + when Procedure_Token => return ""Procedure_Token""; + when Protected_Token => return ""Protected_Token""; + when Raise_Token => return ""Raise_Token""; + when Range_Token => return ""Range_Token""; + when Record_Token => return ""Record_Token""; + when Rem_Token => return ""Rem_Token""; + when Renames_Token => return ""Renames_Token""; + when Requeue_Token => return ""Requeue_Token""; + when Return_Token => return ""Return_Token""; + when Reverse_Token => return ""Reverse_Token""; + when Select_Token => return ""Select_Token""; + when Separate_Token => return ""Separate_Token""; + when Some_Token => return ""Some_Token""; + when Subtype_Token => return ""Subtype_Token""; + when Synchronized_Token => return ""Synchronized_Token""; + when Tagged_Token => return ""Tagged_Token""; + when Task_Token => return ""Task_Token""; + when Terminate_Token => return ""Terminate_Token""; + when Then_Token => return ""Then_Token""; + when Type_Token => return ""Type_Token""; + when Until_Token => return ""Until_Token""; + when Use_Token => return ""Use_Token""; + when When_Token => return ""When_Token""; + when While_Token => return ""While_Token""; + when With_Token => return ""With_Token""; + when Xor_Token => return ""Xor_Token""; + when others => + return Token'Wide_Wide_Image (Value); + end case; + end Debug_Image; + + -------------- + -- Get_Next -- + -------------- + + overriding function Get_Next (Self : not null access File_Source) + return Wide_Wide_Character is + begin + if Self.Index < Self.Text.Length then + return Result : constant Wide_Wide_Character := + Self.Text.Element (Self.Index).To_Wide_Wide_Character + do + Self.Index := Self.Index + 1; + end return; + else + return Incr.Lexers.Batch_Lexers.End_Of_Input; + end if; + end Get_Next; + + use type Incr.Ada_Lexers.Token; + Token : Incr.Ada_Lexers.Token; + Source : aliased File_Source; + Batch_Lexer : constant Incr.Lexers.Batch_Lexers.Batch_Lexer_Access := + new Incr.Ada_Lexers.Batch_Lexer; + +begin + while not Ada.Wide_Wide_Text_IO.End_Of_File loop + declare + Line : constant Wide_Wide_String := Ada.Wide_Wide_Text_IO.Get_Line; + begin + Source.Text.Append (Line); + Source.Text.Append (Ada.Characters.Wide_Wide_Latin_1.LF);" +overriding procedure Discard (Self : in out Joint) is,"Now : constant Version_Trees.Version := Self.Document.History.Changing; + Diff : Integer := 0; + begin + Versioned_Booleans.Discard (Self.Exist, Now, Diff); + + for J in Self.Kids'Range loop + Versioned_Nodes.Discard (Self.Kids (J), Now, Diff); + Self.Child (J, Now).Discard_Parent; + end loop; + + Self.Update_Local_Changes (Diff); + end Discard; + + -------------- + -- Is_Token -- + -------------- + + overriding function Is_Token (Self : Joint) return Boolean is + pragma Unreferenced (Self); + begin + return False; + end Is_Token; + + ---------- + -- Kind -- + ---------- + + overriding function Kind (Self : Joint) return Node_Kind is + begin + return Self.Kind; + end Kind; + + -------------------- + -- Nested_Changes -- + -------------------- + + overriding function Nested_Changes + (Self : Joint; + From : Version_Trees.Version; + To : Version_Trees.Version) return Boolean + is + use type Version_Trees.Version; + + Time : Version_Trees.Version := To; + begin + if Self.Document.History.Is_Changing (To) then + if Self.Nested_Changes > 0 then + return True; + elsif Time = From then + return False; + end if; + + Time := Self.Document.History.Parent (Time); + end if; + + while Time /= From loop + if Versioned_Booleans.Get (Self.NC, Time) then + return True; + end if; + + Time := Self.Document.History.Parent (Time); + end loop; + + return False; + end Nested_Changes; + + ------------------- + -- Nested_Errors -- + ------------------- + + overriding function Nested_Errors + (Self : Joint; + Time : Version_Trees.Version) return Boolean is + begin + return Versioned_Booleans.Get (Self.NE, Time); + end Nested_Errors; + + --------------- + -- On_Commit -- + --------------- + + overriding procedure On_Commit + (Self : in out Joint; + Parent : Node_Access) + is + Now : constant Version_Trees.Version := Self.Document.History.Changing; + + Prev : constant Version_Trees.Version := + Self.Document.History.Parent (Now); + Child : Nodes.Node_Access; + Errors : Boolean := False; + Ignore : Integer := 0; + begin + if Self.Local_Changes > 0 and then Self.Exists (Prev) then + Mark_Deleted_Children (Self); + end if; + + Versioned_Booleans.Set + (Self => Self.NC, + Value => Self.Nested_Changes > 0, + Time => Self.Document.History.Changing, + Changes => Ignore); + + Node_With_Parent (Self).On_Commit (Parent); + + for J in Self.Kids'Range loop + Child := Self.Child (J, Now); + + if Child.Nested_Errors (Now) or else Child.Local_Errors (Now) then + Errors := True; + exit; + end if; + end loop; + + Versioned_Booleans.Set (Self.NE, Errors, Now, Ignore); + end On_Commit; + + --------------- + -- Set_Child -- + --------------- + + overriding procedure Set_Child + (Self : aliased in out Joint; + Index : Positive; + Value : Node_Access) + is + Diff : Integer := 0; + Now : constant Version_Trees.Version := Self.Document.History.Changing; + Old : constant Node_Access := Self.Child (Index, Now); + begin + if Old /= null then + Old.Set_Parent (null); + end if; + + Versioned_Nodes.Set (Self.Kids (Index), Value, Now, Diff); + Self.Update_Local_Changes (Diff); + + if Value /= null then + declare + Parent : constant Node_Access := Value.Parent (Now); + begin + if Parent /= null then + declare + Index : constant Natural := + Parent.Child_Index (Constant_Node_Access (Value), Now); + begin + Value.Set_Parent (null); + Parent.Set_Child (Index, null); + Value.Set_Parent (Self'Unchecked_Access);" +procedure Right_Breakdown;,"procedure Recover (LA : out Nodes.Node_Access); + procedure Recover_2 (LA : out Nodes.Node_Access); + + Stack : Parser_Stack; + State : Parser_State := 1; + Now : constant Version_Trees.Version := Document.History.Changing; + + Previous : constant Version_Trees.Version := + Document.History.Parent (Now); + Next_Action : constant Action_Table_Access := Provider.Actions; + Next_State : constant State_Table_Access := Provider.States; + Counts : constant Parts_Count_Table_Access := Provider.Part_Counts; + + procedure Clear (Self : out Parser_Stack) is + begin + Self.Top := 0; + end Clear; + + -------------- + -- Do_Shift -- + -------------- + + procedure Do_Shift (Node : Nodes.Node_Access) is + begin + if Node.Is_Token then + -- Next_Action should be shift + On_Shift (State, Next_Action (State, Node.Kind).State, Node); + else + On_Shift (State, Next_State (State, Node.Kind), Node); + end if; + end Do_Shift; + + -------------------- + -- Left_Breakdown -- + -------------------- + + function Left_Breakdown + (Node : Nodes.Node_Access) return Nodes.Node_Access is + begin + if Node.Arity > 0 then + return Node.Child (1, Reference); + else + return Node.Next_Subtree (Reference); + end if; + end Left_Breakdown; + + --------------- + -- On_Reduce -- + --------------- + + procedure On_Reduce (Parts : Production_Index) is + Count : constant Natural := Counts (Parts); + subtype First_Nodes is Nodes.Node_Array (1 .. Count); + + Kind : Nodes.Node_Kind; + begin + Stack.Top := Stack.Top - Count + 1; + + Factory.Create_Node + (Parts, + First_Nodes (Stack.Node (Stack.Top .. Stack.Top + Count - 1)), + Stack.Node (Stack.Top), + Kind); + + if Count = 0 then + Stack.State (Stack.Top) := State; + end if; + + State := Next_State (Stack.State (Stack.Top), Kind); + end On_Reduce; + + -------------- + -- On_Shift -- + -------------- + + procedure On_Shift + (State : in out Parser_State; + New_State : Parser_State; + Node : access Nodes.Node'Class) is + begin + Push (Stack, State, Nodes.Node_Access (Node)); + State := New_State; + end On_Shift; + + --------- + -- Pop -- + --------- + + procedure Pop + (Self : in out Parser_Stack; + State : out Parser_State; + Node : out Nodes.Node_Access) is + begin + State := Self.State (Self.Top); + Node := Self.Node (Self.Top); + Self.Top := Self.Top - 1; + end Pop; + + ---------- + -- Push -- + ---------- + + procedure Push + (Self : in out Parser_Stack; + State : Parser_State; + Node : Nodes.Node_Access) is + begin + Self.Top := Self.Top + 1; + Self.State (Self.Top) := State; + Self.Node (Self.Top) := Node; + Node.Set_Local_Errors (False); + end Push; + + ------------- + -- Recover -- + ------------- + + procedure Recover (LA : out Nodes.Node_Access) is + begin + if Stack.Top > 1 then + -- Remove any default reductions from the parse stack + Right_Breakdown; + end if; + + Recover_2 (LA); + end Recover; + + --------------- + -- Recover_2 -- + --------------- + + procedure Recover_2 (LA : out Nodes.Node_Access) is + + type Offset_Array is array (Positive range <>) of Natural; + + function Is_Valid_Isolation + (Node : Nodes.Node_Access; + Offset : Natural; + State : Parser_State) return Boolean; + + function Node_Offset + (Node : Nodes.Node_Access; + Time : Version_Trees.Version) return Natural; + -- Compute offset of Node in given Time + + function Get_Cut + (Node : Nodes.Node_Access; + Offset : Offset_Array; + Top : Positive) return Natural; + -- Compute stack entry corresponding to leading edge of node’s + -- subtree in the previous version. Returns False if no entry is + -- so aligned. Top limits stack depth search. + + procedure Isolate (Node : Nodes.Node_Access; Top : Positive); + -- Resets configuration so parsing can continue. + + procedure Refine (Node : Nodes.Node_Access); + -- Isolate the argument and recursively recover the subtree that it + -- roots. + + procedure Discard_Changes_And_Mark_Errors + (Node : access Nodes.Node'Class); + + Jam_Offset : Natural; + + ------------------------------------- + -- Discard_Changes_And_Mark_Errors -- + ------------------------------------- + + procedure Discard_Changes_And_Mark_Errors + (Node : access Nodes.Node'Class) is + begin + Node.Discard; + + if Node.Local_Changes (Reference, Now) then + Node.Set_Local_Errors (True); + end if; + end Discard_Changes_And_Mark_Errors; + + ------------- + -- Get_Cut -- + ------------- + + function Get_Cut + (Node : Nodes.Node_Access; + Offset : Offset_Array; + Top : Positive) return Natural + is + Old_Offset : constant Natural := Node_Offset (Node, Previous); + begin + for J in 1 .. Top loop + if Offset (J) > Old_Offset then + return 0; + elsif Offset (J) = Old_Offset then + for K in J + 1 .. Top loop + if Offset (K) /= Offset (J) then + return K - 1; + end if; + end loop; + + return J; + end if; + end loop; + + return 0; + end Get_Cut; + + ------------------------ + -- Is_Valid_Isolation -- + ------------------------ + + function Is_Valid_Isolation + (Node : Nodes.Node_Access; + Offset : Natural; + State : Parser_State) return Boolean + is + Old_Offset : constant Natural := Node_Offset (Node, Previous); + begin + if Offset /= Old_Offset then + -- The starting offset of the subtree must be the same in both + -- the previous and current versions. + -- I have no idea how this could fail??? + return False; + elsif Offset > Jam_Offset then + -- Cannot be to the right of the point where the error was + -- detected by the parser. + return False; + elsif Offset + Node.Span (Nodes.Text_Length, Previous) <= + Jam_Offset + then + -- The ending offset must meet or exceed the detection point. + return False; + elsif Node.Span (Nodes.Text_Length, Previous) /= + Node.Span (Nodes.Text_Length, Now) + then + -- The subtree span must the same in current and prev versions. + return False; + end if; + + declare + Right : constant Nodes.Tokens.Token_Access := + Node.Last_Token (Previous); + Next : constant Nodes.Tokens.Token_Access := + Right.Next_Token (Previous); + begin + -- Check if lexical analysis cross right edge of Node + if Right.Get_Flag (Nodes.Need_Analysis) and + (Next not in null and then + Next.Get_Flag (Nodes.Need_Analysis)) + then + return False; + end if;" +procedure Right_Breakdown is,"Node : Nodes.Node_Access; + Limit : constant Natural := Stack.Top - 1; + begin + loop + Pop (Stack, State, Node); + + exit when Node.Is_Token; + + for J in 1 .. Node.Arity loop + Do_Shift (Node.Child (J, Now)); + end loop; + + if Stack.Top = Limit then + -- Empty subtree was on the top of the stack + return; + end if; + end loop; + + Do_Shift (Node); + end Right_Breakdown; + + Verify : Boolean := False; + Lexing : Boolean := False; + EOF : Boolean := False; + Term : Nodes.Tokens.Token_Access; + + LA : access Nodes.Node'Class := Document.Start_Of_Stream; + Next : Action; + begin + Document.Start_Of_Stream.Set_Text + (League.Strings.Empty_Universal_String); + Document.End_Of_Stream.Set_Text + (League.Strings.Empty_Universal_String); + + Lexer.Prepare_Document (Document, Reference); + Clear (Stack); + Push (Stack, State, Nodes.Node_Access (Document.Start_Of_Stream)); + + if not LA.Get_Flag (Nodes.Need_Analysis) then + LA := LA.Next_Subtree (Reference); + end if; + + loop + if LA.Is_Token then + if not Lexing + and then LA.Get_Flag (Nodes.Need_Analysis) + and then not EOF + then + Term := Lexer.First_New_Token (Nodes.Tokens.Token_Access (LA)); + LA := Term; + Lexing := True; + else + Term := Nodes.Tokens.Token_Access (LA); + end if; + + Next := Next_Action (State, Term.Kind); + + case Next.Kind is + when Finish => + if Term.Kind = 0 then -- End_Of_Stream + declare + Node : Nodes.Node_Access; + begin + Pop (Stack, State, Node); + Document.Ultra_Root.Set_Child (2, Node); + + return;" +overriding function Exists,"(Self : Node_With_Exist; + Time : Version_Trees.Version) return Boolean is + begin + return Versioned_Booleans.Get (Self.Exist, Time); + end Exists; + + ----------------- + -- Child_Index -- + ----------------- + + function Child_Index + (Self : Node'Class; + Child : Constant_Node_Access; + Time : Version_Trees.Version) return Natural is + begin + for J in 1 .. Self.Arity loop + if Constant_Node_Access (Self.Child (J, Time)) = Child then + return J; + end if; + end loop; + + return 0; + end Child_Index; + + -------------------- + -- Discard_Parent -- + -------------------- + + overriding procedure Discard_Parent (Self : in out Node_With_Parent) is + Changed : Boolean; + Ignore : Integer := 0; + Now : constant Version_Trees.Version := + Self.Document.History.Changing; + begin + Changed := Self.Local_Changes > 0 or Self.Nested_Changes > 0; + + if Changed then + Self.Propagate_Nested_Changes (-1); + end if; + + Versioned_Nodes.Discard (Self.Parent, Now, Ignore); + + if Changed then + Self.Propagate_Nested_Changes (1); + end if; + end Discard_Parent; + + ----------------- + -- First_Token -- + ----------------- + + function First_Token + (Self : aliased in out Node'Class; + Time : Version_Trees.Version) + return Tokens.Token_Access + is + Child : Node_Access; + begin + if Self.Arity > 0 then + Child := Self.Child (1, Time); + + if Child.Is_Token then + return Tokens.Token_Access (Child); + else + return Child.First_Token (Time); + end if; + elsif Self.Is_Token then + return Tokens.Token'Class (Self)'Access; + else + return null; + end if; + end First_Token; + + -------------- + -- Get_Flag -- + -------------- + + overriding function Get_Flag + (Self : Node_With_Exist; + Flag : Transient_Flags) return Boolean is + begin + return Self.Flag (Flag); + end Get_Flag; + + ---------------- + -- Last_Token -- + ---------------- + + function Last_Token + (Self : aliased in out Node'Class; + Time : Version_Trees.Version) return Tokens.Token_Access + is + Child : Node_Access; + begin + if Self.Arity > 0 then + Child := Self.Child (Self.Arity, Time); + + if Child.Is_Token then + return Tokens.Token_Access (Child); + else + return Child.Last_Token (Time); + end if; + elsif Self.Is_Token then + return Tokens.Token'Class (Self)'Access; + else + return null; + end if; + end Last_Token; + + ------------------- + -- Local_Changes -- + ------------------- + + overriding function Local_Changes + (Self : Node_With_Exist; + From : Version_Trees.Version; + To : Version_Trees.Version) return Boolean + is + use type Version_Trees.Version; + + Time : Version_Trees.Version := To; + begin + if Self.Document.History.Is_Changing (To) then + -- Self.LC doesn't contain Local_Changes for Is_Changing version yet + -- Take it from Self.Nested_Changes + if Self.Local_Changes > 0 then + return True; + elsif Time = From then + return False; + end if; + + Time := Self.Document.History.Parent (Time); + end if; + + while Time /= From loop + if Versioned_Booleans.Get (Self.LC, Time) then + return True; + end if; + + Time := Self.Document.History.Parent (Time); + end loop; + + return False; + end Local_Changes; + + --------------------------- + -- Mark_Deleted_Children -- + --------------------------- + + procedure Mark_Deleted_Children (Self : in out Node'Class) is + + function Find_Root (Node : Node_Access) return Node_Access; + -- Find top root accessible from the Node + + procedure Delete_Tree + (Node : not null Node_Access; + Parent : Node_Access; + Index : Positive); + -- Check Node if it's disjointed from ultra-root. + -- Delete a subtree rooted from Node if so. + -- If Parent /= null also set Parent.Child(Index) to null. + + Now : constant Version_Trees.Version := Self.Document.History.Changing; + + ----------------- + -- In_The_Tree -- + ----------------- + + function Find_Root (Node : Node_Access) return Node_Access is + Child : not null Nodes.Node_Access := Node; + begin + loop + declare + Parent : constant Nodes.Node_Access := Child.Parent (Now); + begin + if Parent = null then + return Child; + else + Child := Parent; + end if;" +procedure Main is,"begin + -- Guide: http://archive.adaic.com/standards/83lrm/html/lrm-11-01.html + declare + PP : Positive; + P2 : Positive; + begin + P2 := 5; + PP := 3 - P2; -- intentionally violate Positive range constraint + exception + when Constraint_Error => + Put_Line(""HANDLED: violate range constraint gives Constraint_Error"");" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Agent_Impl, Agent_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Agent_Impl_Ptr := Agent_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Agent_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, AGENT_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Agent_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Agent_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (AGENT_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- hostname + Value => Object.Hostname); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- ip + Value => Object.Ip); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_1_NAME, -- key + Value => Object.Key); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Snapshot_Impl, Snapshot_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Snapshot_Impl_Ptr := Snapshot_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Snapshot_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SNAPSHOT_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Snapshot_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Snapshot_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (SNAPSHOT_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_1_NAME, -- start_date + Value => Object.Start_Date); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- end_date + Value => Object.End_Date); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_1_NAME, -- host_id + Value => Object.Host); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Snapshot_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SNAPSHOT_DEF'Access); + begin + Stmt.Execute; + Snapshot_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Snapshot_Ref; + Impl : constant Snapshot_Access := new Snapshot_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Source_Impl, Source_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Source_Impl_Ptr := Source_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Source_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SOURCE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Source_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Source_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (SOURCE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- label + Value => Object.Label); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- host_id + Value => Object.Host); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure List (Object : in out Source_Vector;,"Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SOURCE_DEF'Access); + begin + Stmt.Execute; + Source_Vectors.Clear (Object); + while Stmt.Has_Elements loop + declare + Item : Source_Ref; + Impl : constant Source_Access := new Source_Impl; + begin + Impl.Load (Stmt, Session); + ADO.Objects.Set_Object (Item, Impl.all'Access); + Object.Append (Item);" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Format_Type); + Impl : Series_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 8, Impl.Format, Value); + end Set_Format; + + function Get_Format (Object : in Series_Ref) + return Hyperion.Monitoring.Models.Format_Type is + Impl : constant Series_Access + := Series_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Format; + end Get_Format; + + + procedure Set_Source (Object : in out Series_Ref; + Value : in Hyperion.Monitoring.Models.Source_Ref'Class) is + Impl : Series_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 9, Impl.Source, Value); + end Set_Source; + + function Get_Source (Object : in Series_Ref) + return Hyperion.Monitoring.Models.Source_Ref'Class is + Impl : constant Series_Access + := Series_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Source; + end Get_Source; + + + procedure Set_Snapshot (Object : in out Series_Ref; + Value : in Hyperion.Monitoring.Models.Snapshot_Ref'Class) is + Impl : Series_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 10, Impl.Snapshot, Value); + end Set_Snapshot; + + function Get_Snapshot (Object : in Series_Ref) + return Hyperion.Monitoring.Models.Snapshot_Ref'Class is + Impl : constant Series_Access + := Series_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Snapshot; + end Get_Snapshot; + + -- Copy of the object. + procedure Copy (Object : in Series_Ref; + Into : in out Series_Ref) is + Result : Series_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Series_Access + := Series_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Series_Access + := new Series_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Version := Impl.Version; + Copy.Start_Date := Impl.Start_Date; + Copy.End_Date := Impl.End_Date; + Copy.Content := Impl.Content; + Copy.Count := Impl.Count; + Copy.First_Value := Impl.First_Value; + Copy.Format := Impl.Format; + Copy.Source := Impl.Source; + Copy.Snapshot := Impl.Snapshot;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Series_Impl, Series_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Series_Impl_Ptr := Series_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Series_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SERIES_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Series_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Series_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (SERIES_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_3_NAME, -- start_date + Value => Object.Start_Date); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_3_NAME, -- end_date + Value => Object.End_Date); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_3_NAME, -- content + Value => Object.Content); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_3_NAME, -- count + Value => Object.Count); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_3_NAME, -- first_value + Value => Object.First_Value); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_3_NAME, -- format + Value => Integer (Format_Type'Pos (Object.Format))); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_3_NAME, -- source_id + Value => Object.Source); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_3_NAME, -- snapshot_id + Value => Object.Snapshot); + Object.Clear_Modified (10); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Description_Impl, Description_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Description_Impl_Ptr := Description_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Description_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, DESCRIPTION_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Description_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Description_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (DESCRIPTION_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_1_NAME, -- content + Value => Object.Content); + Object.Clear_Modified (3); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Set_Field_Enum is,"new ADO.Objects.Set_Field_Operation (Status_Type); + Impl : Host_Access; + begin + Set_Field (Object, Impl); + Set_Field_Enum (Impl.all, 9, Impl.Status, Value); + end Set_Status; + + function Get_Status (Object : in Host_Ref) + return Hyperion.Hosts.Models.Status_Type is + Impl : constant Host_Access + := Host_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Status; + end Get_Status; + + + procedure Set_Agent (Object : in out Host_Ref; + Value : in Hyperion.Agents.Models.Agent_Ref'Class) is + Impl : Host_Access; + begin + Set_Field (Object, Impl); + ADO.Objects.Set_Field_Object (Impl.all, 10, Impl.Agent, Value); + end Set_Agent; + + function Get_Agent (Object : in Host_Ref) + return Hyperion.Agents.Models.Agent_Ref'Class is + Impl : constant Host_Access + := Host_Impl (Object.Get_Load_Object.all)'Access; + begin + return Impl.Agent; + end Get_Agent; + + -- Copy of the object. + procedure Copy (Object : in Host_Ref; + Into : in out Host_Ref) is + Result : Host_Ref; + begin + if not Object.Is_Null then + declare + Impl : constant Host_Access + := Host_Impl (Object.Get_Load_Object.all)'Access; + Copy : constant Host_Access + := new Host_Impl; + begin + ADO.Objects.Set_Object (Result, Copy.all'Access); + Copy.Copy (Impl.all); + Copy.Version := Impl.Version; + Copy.Name := Impl.Name; + Copy.Ip := Impl.Ip; + Copy.Key := Impl.Key; + Copy.Create_Date := Impl.Create_Date; + Copy.Serial := Impl.Serial; + Copy.Description := Impl.Description; + Copy.Status := Impl.Status; + Copy.Agent := Impl.Agent;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Host_Impl, Host_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Host_Impl_Ptr := Host_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Host_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, HOST_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Host_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Host_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (HOST_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_2_NAME, -- name + Value => Object.Name); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_2_NAME, -- ip + Value => Object.Ip); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_2_NAME, -- key + Value => Object.Key); + Object.Clear_Modified (5); + end if; + if Object.Is_Modified (6) then + Stmt.Save_Field (Name => COL_5_2_NAME, -- create_date + Value => Object.Create_Date); + Object.Clear_Modified (6); + end if; + if Object.Is_Modified (7) then + Stmt.Save_Field (Name => COL_6_2_NAME, -- serial + Value => Object.Serial); + Object.Clear_Modified (7); + end if; + if Object.Is_Modified (8) then + Stmt.Save_Field (Name => COL_7_2_NAME, -- description + Value => Object.Description); + Object.Clear_Modified (8); + end if; + if Object.Is_Modified (9) then + Stmt.Save_Field (Name => COL_8_2_NAME, -- status + Value => Integer (Status_Type'Pos (Object.Status))); + Object.Clear_Modified (9); + end if; + if Object.Is_Modified (10) then + Stmt.Save_Field (Name => COL_9_2_NAME, -- agent_id + Value => Object.Agent); + Object.Clear_Modified (10); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Host_Info_Impl, Host_Info_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Host_Info_Impl_Ptr := Host_Info_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + procedure Find (Object : in out Host_Info_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, HOST_INFO_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Host_Info_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + procedure Save (Object : in out Host_Info_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (HOST_INFO_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_3_NAME, -- index + Value => Object.Index); + Object.Clear_Modified (3); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_3_NAME, -- host_id + Value => Object.Host); + Object.Clear_Modified (4); + end if; + if Object.Is_Modified (5) then + Stmt.Save_Field (Name => COL_4_3_NAME, -- desc_id + Value => Object.Desc); + Object.Clear_Modified (5); + end if; + if Stmt.Has_Save_Fields then + Object.Version := Object.Version + 1; + Stmt.Save_Field (Name => ""version"", + Value => Object.Version); + Stmt.Set_Filter (Filter => ""id = ? and version = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Version - 1); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + else + raise ADO.Objects.LAZY_LOCK; + end if; + end if;" +procedure Main is,"Config : Command_Line_Configuration; + +begin + + Util.Define_CLI_Switches(Config); + Getopt(Config); + + Util.Process_Command_Arguments; + +exception + when E : Util.Execution_Error => + Put(""Execution error: ""); + Put_Line(Exception_Message(E)); + Put_Line(""... stopping.""); + + when E : Util.Argument_Error => + Put(""Invalid argument: ""); + Put_Line(Exception_Message(E)); + Display_Help(Config); + + when Exit_From_Command_Line => + return;" +procedure Process_Command_Arguments;, +procedure Put_Im_Instance_Info is,"new Put_Instance_Info(Image_WFC); + + procedure Put_Ch_Instance_Info is + new Put_Instance_Info(Character_WFC); + + Input_Image, Output_Image : IL_Image; + + Input_File : File_Type; + Output_File : File_Type; + + Im_Instance : Im_Instance_Access; + Ch_Instance : Ch_Instance_Access; + + type Input_Kind is (None, Pictoral, Textual); + -- The type of the last received input sample. + -- We want to be able to process both actual images + -- as well as simpler, textual files, for ease of use. + + Last_Input_Kind : Input_Kind := None; + -- Remember whether we've had an input yet, and if so, + -- what type it was. + + N, M : aliased Integer := 2; + -- The width and height of the tiles + -- to be used in the instantiation. + + Rot, Ref : aliased Boolean := False; + -- Whether to include rotations, and reflections, + -- respectively, in the instantiation tileset. + + Use_Stdout : aliased Boolean := False; + -- Whether to output text-only instance results + -- on stdout rather than using a separate file. + + Output_Scale : aliased Integer := 1; + -- When in image mode, how much to scale up the output image. + + Out_Name : XString; + -- The name of the file we will produce as output (sans extension, size info, id) + + Out_Ct : Natural := 0; + -- How many outputs we've handled so far. + + procedure Parse_Output_Command (Spec : String; W, H : out Natural) is + use Ada.Strings.Maps; + use Ada.Strings.Fixed; + + Separator_Set : constant Character_Set := To_Set(""xX,/:""); + Separator_Ix : constant Natural := Index(Spec, Separator_Set); + Last : Natural; + begin + if Separator_Ix = 0 then + raise Argument_Error with ""Cannot parse argument: ("" & Spec & "")""; + end if; + declare + Prefix : String renames Spec (Spec'First .. Separator_Ix - 1); + Suffix : String renames Spec (Separator_Ix + 1 .. Spec'Last); + begin + Get(Prefix, Item => W, Last => Last); + if Last /= Prefix'Last then + raise Argument_Error with ""Cannot parse integer: ("" & Prefix & "")""; + end if; + Get(Suffix, Item => H, Last => Last); + if Last /= Suffix'Last then + raise Argument_Error with ""Cannot parse integer: ("" & Suffix & "")""; + end if;" +procedure Process_Command_Arguments is,"type Output_Handler_Type is + access procedure (W, H : Natural); + + function Handle_Arg (Handler : not null Output_Handler_Type) return Boolean is + Arg : constant String := Get_Argument; + Out_W, Out_H : Natural; + begin + if Arg = """" then + return False; + end if; + + Parse_Output_Command(Arg, Out_W, Out_H); + Handler(Out_W, Out_H); + + return True;" +function Rotate_Clockwise (Matrix : in Element_Matrix) return Element_Matrix,"with Inline + is + Out_Matrix : Element_Matrix (Matrix'Range(2), Matrix'Range(1)); + Out_X : Natural; + begin + for The_X in Matrix'Range(1) loop + for The_Y in Matrix'Range(2) loop + Out_X := Matrix'First(2) + Matrix'Last(2) - The_Y; + Out_Matrix(Out_X, The_X) := Matrix(The_X, The_Y); + end loop; + end loop; + return Out_Matrix;" +function Collapse is new,"Extended.Generic_Collapse_Within + ( Set_Resulting_Element => Set_Resulting_Element + , Upon_Collapse => Upon_Collapse + ); + + begin + return Collapse(Parameters);" +function Log_Frequency_Noise return Float is,"use Ada.Numerics.Float_Random; + G : Generator; + begin + Reset(G); + return Random(G) * 1.0E-4;" +procedure Put_Debug_Info is,"begin + Put_Line(Standard_Error, ""Tile_ID_Bytes =>"" & Integer'Image(Tile_ID_Range'Object_Size / 8)); + Put_Line(Standard_Error, "" Small_Bytes =>"" & Integer'Image(Small_Integer'Object_Size / 8)); + Put_Line(Standard_Error, "" Cell_Bytes =>"" & Integer'Image(Wave_Function_Cell'Object_Size / 8)); + Put_Line(Standard_Error, "" Wave_Bytes =>"" & Integer'Image(Wave_Function'Object_Size / 8)); + Put_Line(Standard_Error, ""Enabler_Bytes =>"" & Integer'Image(Init_Enablers'Size / 8)); + Put_Line(Standard_Error, "" Matrix_Bytes =>"" & Integer'Image(Wave_Function_Matrix.all'Size / 8)); + New_Line(Standard_Error, 1); + + for Y in Y_Dim loop + for X in X_Dim loop + declare + Collapsed_Tile : constant Tile_ID_Range := Collapsed_Tile_Choices(X, Y); + begin + Put(Standard_Error, Tail(Tile_ID'Image(Collapsed_Tile), 4));" +procedure Polling is,"use Raspio.GPIO; +begin + Raspio.Initialize; + declare + -- connect button from pin 12 to ground + Button : constant Pin_Type := + Create + (Pin_ID => GPIO_P1_12, Mode => Input, Internal_Resistor => Pull_Up); + + State : Pin_State := Off; + begin + loop + State := Read (Button); + Ada.Text_IO.Put_Line (State'Image); + delay 0.2; + end loop;" +procedure awordcount is,"-- *** Variable declarations *** +begin + + New_Line; + + if Ada.Command_Line.Argument_Count = 0 then + Put_Line(Item => "" ERROR! Filename required.""); + Put_Line(Item => "" USAGE: awordcount file-to-get-counts-for.txt""); + else + declare + -- *** Variable declarations *** + FileName : String(1..Ada.Command_Line.Argument(1)'length); + FileNameLength : Natural := Ada.Command_Line.Argument(1)'length; + SourceFile : Ada.Text_IO.File_Type; + begin + FileName := Ada.Command_Line.Argument(1); + Put(Item => ""Parsing file: ""); + Put_Line(Item => FileName); + if GNAT.IO_Aux.File_Exists(FileName) then + + Open(SourceFile, In_File, FileName); + declare + package UStrings renames Ada.Strings.Unbounded; + package UnboundedIO renames Ada.Strings.Unbounded.Text_IO; + CurrentLine : UStrings.Unbounded_String := UStrings.Null_Unbounded_String; + CurrentLineLength : Integer := 0; + CharacterCount : Integer := 0; + LineCount : Integer := 0; + LineWordCount : GNAT.String_Split.Slice_Number; + SplitArr : GNAT.String_Split.Slice_Set; + WordSeparators : String := "" ""; + WordCount : Integer := 0; + begin + while not End_Of_File(SourceFile) + loop + CurrentLine := UnboundedIO.Get_Line(File => SourceFile); + LineCount := LineCount + 1; + CurrentLineLength := UStrings.To_String(CurrentLine)'Length; + CharacterCount := CharacterCount + CurrentLineLength; + GNAT.String_Split.Create(SplitArr, UStrings.To_String(CurrentLine), WordSeparators, Mode => GNAT.String_Split.Multiple); + LineWordCount := GNAT.String_Split.Slice_Count(S => SplitArr); + WordCount := WordCount + Integer(LineWordCount); + end loop; + Put(Item => ""Characters: ""); + Ada.Integer_Text_IO.Put(CharacterCount); + New_Line; + Put(Item => ""Lines: ""); + Ada.Integer_Text_IO.Put(LineCount); + New_Line; + Put(Item => ""Words: ""); + Ada.Integer_Text_IO.Put(WordCount);" +function Convert is new Ada.Unchecked_Conversion,"(Source => Watch_Bits, Target => Interfaces.C.unsigned); + + Result : constant Interfaces.C.int := Inotify_Add_Watch + (Object.Instance, Interfaces.C.To_C (Path), Convert (Mask)); + begin + if Result = -1 then + raise Program_Error; + end if; + + Object.Watches.Include (Result, Path); + return (Watch => Result); + end Add_Watch; + + procedure Add_Watch + (Object : in out Instance; + Path : String; + Mask : Watch_Bits := All_Events) + is + Result : constant Watch := Instance'Class (Object).Add_Watch (Path, Mask); + begin + pragma Assert (Result.Watch /= -1); + end Add_Watch; + + procedure Remove_Watch (Object : in out Instance; Subject : Watch) is + function Inotify_Remove_Watch + (Instance : GNAT.OS_Lib.File_Descriptor; + Watch : Interfaces.C.int) return Interfaces.C.int + with Import, Convention => C, External_Name => ""inotify_rm_watch""; + begin + -- Procedure Process_Events might read multiple events for a specific + -- watch and the callback for the first event may immediately try to + -- remove the watch + if Object.Defer_Remove then + if not Object.Pending_Removals.Contains (Subject) then + Object.Pending_Removals.Append (Subject); + end if; + return; + end if; + + if Inotify_Remove_Watch (Object.Instance, Subject.Watch) = -1 then + raise Program_Error; + end if; + + Object.Watches.Delete (Subject.Watch); + end Remove_Watch; + + function Has_Watches (Object : in out Instance) return Boolean is + (not Object.Watches.Is_Empty); + + function Name (Object : Instance; Subject : Watch) return String is + (Object.Watches.Element (Subject.Watch)); + + ----------------------------------------------------------------------------- + + type Inotify_Event is record + Watch : Interfaces.C.int; -- -1 if event queue has overflowed + Mask : Interfaces.C.unsigned; + Cookie : Interfaces.C.unsigned; + Length : Interfaces.C.unsigned; + end record + with Convention => C, + Alignment => 4; + + type Event_Bits is record + Event : Event_Kind; + + Queue_Overflowed : Boolean := False; + Ignored : Boolean := False; + Is_Directory : Boolean := False; + end record; + + for Event_Bits use record + Event at 0 range 0 .. 13; + + Queue_Overflowed at 0 range 14 .. 14; + Ignored at 0 range 15 .. 15; + Is_Directory at 0 range 30 .. 30; + end record; + for Event_Bits'Size use Interfaces.C.unsigned'Size; + for Event_Bits'Alignment use Interfaces.C.unsigned'Alignment; + + procedure Process_Events + (Object : in out Instance; + Handle : not null access procedure + (Subject : Watch; + Event : Event_Kind; + Is_Directory : Boolean; + Name : String); + Move_Handle : not null access procedure + (Subject : Watch; + Is_Directory : Boolean; + From, To : String)) + is + use Ada.Streams; + + function Convert is new Ada.Unchecked_Conversion + (Source => Stream_Element_Array, Target => Inotify_Event); + + function Convert is new Ada.Unchecked_Conversion + (Source => Interfaces.C.unsigned, Target => Event_Bits); + + Event_In_Bytes : constant Stream_Element_Offset + := Inotify_Event'Size / System.Storage_Unit; + + Length : Stream_Element_Offset; + Buffer : Stream_Element_Array (1 .. 4096) + with Alignment => 4; + + function Find_Move (Cookie : Interfaces.C.unsigned) return Move_Vectors.Cursor is + Cursor : Move_Vectors.Cursor := Move_Vectors.No_Element; + + procedure Reverse_Iterate (Position : Move_Vectors.Cursor) is + use type Interfaces.C.unsigned; + begin + if Cookie = Object.Moves (Position).Key then + Cursor := Position; + end if; + end Reverse_Iterate; + begin + Object.Moves.Reverse_Iterate (Reverse_Iterate'Access); + return Cursor; + end Find_Move; + + use type Ada.Containers.Count_Type; + begin + if Object.Watches.Is_Empty then + return; + end if; + + Length := Stream_Element_Offset (GNAT.OS_Lib.Read + (Object.Instance, Buffer'Address, Buffer'Length)); + + if Length = -1 then + raise Read_Error; + end if; + + if Length = 0 then + return; + end if; + + declare + Index : Stream_Element_Offset := Buffer'First; + begin + Object.Defer_Remove := True; + + while Index < Buffer'First + Length loop + declare + Event : constant Inotify_Event + := Convert (Buffer (Index .. Index + Event_In_Bytes - 1)); + Mask : constant Event_Bits := Convert (Event.Mask); + + Name_Length : constant Stream_Element_Offset + := Stream_Element_Offset (Event.Length); + begin + if Mask.Queue_Overflowed then + raise Queue_Overflow_Error; + end if; + pragma Assert (Event.Watch /= -1); + + if Mask.Ignored then + Object.Watches.Exclude (Event.Watch); + else + declare + Directory : constant String := Object.Watches.Element (Event.Watch); + begin + if Name_Length > 0 then + declare + subtype Name_Array is Interfaces.C.char_array + (1 .. Interfaces.C.size_t (Event.Length)); + subtype Name_Buffer is Stream_Element_Array + (1 .. Name_Length); + + function Convert is new Ada.Unchecked_Conversion + (Source => Name_Buffer, Target => Name_Array); + + Name_Index : constant Stream_Element_Offset + := Index + Event_In_Bytes; + + Name : constant String := Interfaces.C.To_Ada (Convert + (Buffer (Name_Index .. Name_Index + Name_Length - 1))); + begin + Handle + ((Watch => Event.Watch), Mask.Event, + Mask.Is_Directory, Directory & ""/"" & Name); + + case Mask.Event is + when Moved_From => + if Object.Moves.Length = Object.Moves.Capacity then + Object.Moves.Delete_First; + end if; + Object.Moves.Append ((Event.Cookie, + (From => SU.To_Unbounded_String (Directory & ""/"" & Name), + To => <>))); + -- If inode is moved to outside watched directory, + -- then there will never be a Moved_To or Moved_Self + -- if instance is not recursive + when Moved_To => + declare + Cursor : Move_Vectors.Cursor := Find_Move (Event.Cookie); + use type Move_Vectors.Cursor; + begin + if Cursor /= Move_Vectors.No_Element then + -- It's a rename + Move_Handle + (Subject => (Watch => Event.Watch), + Is_Directory => Mask.Is_Directory, + From => SU.To_String + (Object.Moves (Cursor).Value.From), + To => Directory & ""/"" & Name); + Object.Moves.Delete (Cursor); + else + Move_Handle + (Subject => (Watch => Event.Watch), + Is_Directory => Mask.Is_Directory, + From => """", + To => Directory & ""/"" & Name); + end if;" +procedure Main is,"task type Sieve is + entry Pass_On(Int: Integer); + end Sieve; + + type Sieve_Ptr is access Sieve; + + function Get_New_Sieve return Sieve_Ptr is + begin + return new Sieve; + end Get_New_Sieve; + + task Odd; + task body Odd is + Limit : constant Positive := 1000; + Num: Positive; + S: Sieve_Ptr := Get_New_Sieve; + begin + Num := 3; + while Num < Limit loop + S.Pass_On(Num); + Num := Num + 2; + end loop; + end Odd; + + task body Sieve is + New_Sieve : Sieve_Ptr; + Prime, Num: Natural; + begin + accept Pass_On(Int : Integer) do + Prime := Int; + end Pass_On; + Text_IO.Put(Prime'Img & "", ""); + -- Prime is a prime number, which coud be output + loop + accept Pass_On(Int : Integer) do + Num := Int; + end Pass_On; + exit when Num rem Prime /= 0; + end loop; + + New_Sieve := Get_New_Sieve; + New_Sieve.Pass_On(Num); + + loop + accept Pass_On (Int : Integer) do + Num := Int; + end Pass_On; + if Num rem Prime /= 0 then + New_Sieve.Pass_On(Num); + end if; + end loop; + end Sieve; + +begin + null;" +procedure Toggle_LedR is,"begin + null;" +procedure Toggle_LedL is,"begin + null;" +procedure Off_LedR is,"begin + null;" +procedure Off_LedL is,"begin + null;" +procedure Main is,"--pragma Priority(Priority'Last); + + Stop : Boolean := False; + S: String(1..5) := (others => ASCII.NUL); + --CMD : BControl.Command_Type := (1 => 'b', 2 => 'l', 3 => 's'); + CMD : BControl.Command_Type; +begin +-- Init; +-- Gio.Gio_Set_Direction(Reg_Het.hetPort1'Access, 16#FFFFFFFF#); + + loop + --Control.Put_Line(""Before Get_Line""); + S := Control.Get_Line; + Control.Put_Line(""Got Data""); + Control.Put_Line(S); + --CMD := Bcontrol.Command_Type(S(1..3)); + CMD := BControl.Command_Type'Value(S(1..3)); + + Bcontrol.Command.Send(CMD); + end loop; + + + -- Blinker_Control.Blink_Stop;" +procedure Main is,"task type Blinker_Type is + entry Start(S : String); + entry Stop; + end Blinker_Type; + + task Blinker_Control is + entry Blink_Left; + entry Blink_Right; + entry Blink_Emergency; + entry Blink_Stop; + end Blinker_Control; + + Left_Blinker, Right_Blinker: Blinker_Type; + + task body Blinker_Control is + Blinker_Left_Started : Boolean := False; + Blinker_Right_Started : Boolean := False; + begin + loop + select + when not Blinker_Left_Started => + accept Blink_Left; + Left_Blinker.Start(""left ""); + Blinker_Left_Started := True; + or + when not Blinker_Right_Started => + accept Blink_Right; + Right_Blinker.Start(""right""); + Blinker_Right_Started := True; + or + accept Blink_Emergency; + Left_Blinker.Start(""left ""); + Right_Blinker.Start(""right""); + Blinker_Left_Started := True; + Blinker_Right_Started := True; + + or + when Blinker_Left_Started or Blinker_Right_Started => + accept Blink_Stop; + if Blinker_Left_Started then + Left_Blinker.Stop; + end if; + if Blinker_Right_Started then + Right_Blinker.Stop; + end if; + or + terminate; + end select; + end loop; + end Blinker_Control; + + + task body Blinker_Type is + Id : String(1..5); + begin + loop + select + accept Start(S : String) do + Id := S; + end Start; + + loop + select + accept Stop; + exit; + or + delay 0.5; + Text_Io.Put_Line(""Blinker "" & Id & "" toggling""); + end select; + end loop; + or terminate; + end select; + + end loop; + end Blinker_Type; + + + +begin + Blinker_Control.Blink_Left; + delay 3.0; + Blinker_Control.Blink_Stop; + delay 3.0; + Blinker_Control.Blink_Emergency; + delay 3.0; + Blinker_Control.Blink_Stop;" +procedure LSP_Test is,"function ""+"" (Text : Wide_Wide_String) + return League.Strings.Universal_String renames + League.Strings.To_Universal_String; + + package Document_Maps is new Ada.Containers.Hashed_Maps + (Key_Type => LSP.Messages.DocumentUri, + Element_Type => LSP_Documents.Document, + Hash => League.Strings.Hash, + Equivalent_Keys => League.Strings.""="", + ""="" => LSP_Documents.""=""); + + type Message_Handler (Server : access LSP.Servers.Server) is limited + new LSP.Message_Handlers.Request_Handler + and LSP.Message_Handlers.Notification_Handler with record + Documents : Document_Maps.Map; + Checker : Checkers.Checker; + XRef : Cross_References.Database; + end record; + + overriding procedure Initialize_Request + (Self : access Message_Handler; + Value : LSP.Messages.InitializeParams; + Response : in out LSP.Messages.Initialize_Response); + + overriding procedure Exit_Notification + (Self : access Message_Handler); + + overriding procedure Text_Document_Definition_Request + (Self : access Message_Handler; + Value : LSP.Messages.TextDocumentPositionParams; + Response : in out LSP.Messages.Location_Response); + + overriding procedure Text_Document_Did_Open + (Self : access Message_Handler; + Value : LSP.Messages.DidOpenTextDocumentParams); + + overriding procedure Text_Document_Did_Change + (Self : access Message_Handler; + Value : LSP.Messages.DidChangeTextDocumentParams); + + overriding procedure Text_Document_Did_Close + (Self : access Message_Handler; + Value : LSP.Messages.DidCloseTextDocumentParams); + + overriding procedure Text_Document_Did_Save + (Self : access Message_Handler; + Value : LSP.Messages.DidSaveTextDocumentParams); + + overriding procedure Text_Document_Completion_Request + (Self : access Message_Handler; + Value : LSP.Messages.TextDocumentPositionParams; + Response : in out LSP.Messages.Completion_Response); + + overriding procedure Text_Document_Code_Action_Request + (Self : access Message_Handler; + Value : LSP.Messages.CodeActionParams; + Response : in out LSP.Messages.CodeAction_Response); + + overriding procedure Text_Document_Highlight_Request + (Self : access Message_Handler; + Value : LSP.Messages.TextDocumentPositionParams; + Response : in out LSP.Messages.Highlight_Response); + + overriding procedure Text_Document_Hover_Request + (Self : access Message_Handler; + Value : LSP.Messages.TextDocumentPositionParams; + Response : in out LSP.Messages.Hover_Response); + + overriding procedure Text_Document_References_Request + (Self : access Message_Handler; + Value : LSP.Messages.ReferenceParams; + Response : in out LSP.Messages.Location_Response); + + overriding procedure Text_Document_Signature_Help_Request + (Self : access Message_Handler; + Value : LSP.Messages.TextDocumentPositionParams; + Response : in out LSP.Messages.SignatureHelp_Response); + + overriding procedure Text_Document_Symbol_Request + (Self : access Message_Handler; + Value : LSP.Messages.DocumentSymbolParams; + Response : in out LSP.Messages.Symbol_Response); + + overriding procedure Workspace_Did_Change_Configuration + (Self : access Message_Handler; + Value : LSP.Messages.DidChangeConfigurationParams); + + overriding procedure Workspace_Execute_Command_Request + (Self : access Message_Handler; + Value : LSP.Messages.ExecuteCommandParams; + Response : in out LSP.Messages.ExecuteCommand_Response); + + overriding procedure Workspace_Symbol_Request + (Self : access Message_Handler; + Value : LSP.Messages.WorkspaceSymbolParams; + Response : in out LSP.Messages.Symbol_Response); + + ------------------------ + -- Initialize_Request -- + ------------------------ + + overriding procedure Initialize_Request + (Self : access Message_Handler; + Value : LSP.Messages.InitializeParams; + Response : in out LSP.Messages.Initialize_Response) + is + use type LSP.Types.LSP_String; + + Completion_Characters : LSP.Types.LSP_String_Vector; + Commands : LSP.Types.LSP_String_Vector; + Signature_Keys : LSP.Types.LSP_String_Vector; + begin + Self.XRef.Initialize (Value.rootUri & ""/source/protocol/""); + Completion_Characters.Append (+""'""); + Commands.Append (+""Text_Edit""); + Signature_Keys.Append (+""(""); + Signature_Keys.Append (+"",""); + + Response.result.capabilities.textDocumentSync := + (Is_Set => True, Is_Number => True, Value => LSP.Messages.Full); + + Response.result.capabilities.completionProvider := + (Is_Set => True, Value => + (resolveProvider => LSP.Types.Optional_False, + triggerCharacters => Completion_Characters)); + + Response.result.capabilities.codeActionProvider := + LSP.Types.Optional_True; + + Response.result.capabilities.executeCommandProvider := + (commands => Commands); + + Response.result.capabilities.hoverProvider := LSP.Types.Optional_True; + Response.result.capabilities.signatureHelpProvider := + (True, (triggerCharacters => Signature_Keys)); + Response.result.capabilities.definitionProvider := + LSP.Types.Optional_True; + Response.result.capabilities.referencesProvider := + LSP.Types.Optional_True; + Response.result.capabilities.documentSymbolProvider := + LSP.Types.Optional_True; + Response.result.capabilities.workspaceSymbolProvider := + LSP.Types.Optional_True; + end Initialize_Request; + + --------------------------------------- + -- Text_Document_Code_Action_Request -- + --------------------------------------- + + overriding procedure Text_Document_Code_Action_Request + (Self : access Message_Handler; + Value : LSP.Messages.CodeActionParams; + Response : in out LSP.Messages.CodeAction_Response) + is + use type League.Strings.Universal_String; + begin + for Item of Value.context.diagnostics loop + if Item.message = +""missing """";"""""" then + declare + Edit : LSP.Messages.TextDocumentEdit; + Command : LSP.Messages.Command; + JS : aliased League.JSON.Streams.JSON_Stream; + Insert : constant LSP.Messages.TextEdit := + (Value.span, +"";""); + begin + Edit.textDocument := + (Value.textDocument with + version => Self.Documents (Value.textDocument.uri).Version); + Edit.edits.Append (Insert); + LSP.Messages.TextDocumentEdit'Write (JS'Access, Edit); + Command.title := +""Insert semicolon""; + Command.command := +""Text_Edit""; + Command.arguments := + JS.Get_JSON_Document.To_JSON_Array.To_JSON_Value; + Response.result.Append (Command);" +procedure Initialize is,"JSON : constant League.JSON.Documents.JSON_Document := + League.JSON.Documents.From_JSON (Read_File (""tests/wellknown.json"")); + Attr_List : constant League.JSON.Arrays.JSON_Array := + JSON.To_JSON_Object.Value (+""Attributes"").To_Array; + Hover : constant League.JSON.Objects.JSON_Object := + JSON.To_JSON_Object.Value (+""Hover"").To_Object; + Hover_Keys : constant League.String_Vectors.Universal_String_Vector := + Hover.Keys; + Sign : constant League.JSON.Objects.JSON_Object := + JSON.To_JSON_Object.Value (+""Signatures"").To_Object; + Sign_Keys : constant League.String_Vectors.Universal_String_Vector := + Sign.Keys; + begin + for J in 1 .. Attr_List.Length loop + declare + function ""-"" (Name : Wide_Wide_String) return LSP.Types.LSP_String; + + function ""-"" (Name : Wide_Wide_String) + return LSP.Types.LSP_String is + begin + return Attr_List (J).To_Object.Value (+Name).To_String; + end ""-""; + + Item : LSP.Messages.CompletionItem; + begin + Item.label := -""label""; + Item.detail := (True, -""detail""); + Item.documentation := (True, -""documentation""); + Item.sortText := (True, -""sortText""); + Item.filterText := (True, -""filterText""); + Item.insertText := (True, -""insertText""); + + if Item.insertText.Value.Index ('$') > 0 then + Item.insertTextFormat := (True, LSP.Messages.Snippet); + end if; + + Attr.Append (Item);" +overriding procedure Fill_Completion_List,"(Self : Completion_Handler; + Context : Ada_LSP.Completions.Context'Class; + Result : in out LSP.Messages.CompletionList) + is + use Incr.Parsers.Incremental.Parser_Data_Providers; +-- use type Incr.Nodes.Node_Access; + + Provider : constant Ada_LSP.Ada_Parser_Data.Provider_Access := + Self.Context.Get_Parser_Data_Provider; + Next_Action : constant Action_Table_Access := Provider.Actions; + Next_State : constant State_Table_Access := Provider.States; + State : Parser_State := 1; + Token : constant Incr.Nodes.Tokens.Token_Access := Context.Token; + Doc : constant Ada_LSP.Documents.Constant_Document_Access := + Context.Document; + Start : constant Incr.Nodes.Node_Access := + Incr.Nodes.Node_Access (Doc.Start_Of_Stream); + Now : constant Incr.Version_Trees.Version := Doc.History.Changing; + List : Node_Lists.List; + Subtree : Incr.Nodes.Node_Access := Token.Previous_Subtree (Now); + begin + while Subtree not in Start | null loop + List.Prepend (Subtree); + Subtree := Subtree.Previous_Subtree (Now); + end loop; + + for Node of List loop + State := Next_State (State, Node.Kind); + end loop; + + for J in Incr.Nodes.Node_Kind'(1) .. 108 loop + if Next_Action (State, J).Kind /= Error then + declare + Item : LSP.Messages.CompletionItem; + begin + Item.label := +Provider.Kind_Image (J); + Item.kind := (True, LSP.Messages.Keyword); + Result.items.Append (Item);" +not overriding procedure Read_dynamicRegistration,"(S : access Ada.Streams.Root_Stream_Type'Class; + V : out dynamicRegistration) + is + JS : League.JSON.Streams.JSON_Stream'Class renames + League.JSON.Streams.JSON_Stream'Class (S.all); + begin + JS.Start_Object; + Read_Optional_Boolean + (JS, +""dynamicRegistration"", Optional_Boolean (V)); + JS.End_Object; + end Read_dynamicRegistration; + + ------------------------------- + -- Read_ExecuteCommandParams -- + ------------------------------- + + not overriding procedure Read_ExecuteCommandParams + (S : access Ada.Streams.Root_Stream_Type'Class; + V : out ExecuteCommandParams) + is + JS : League.JSON.Streams.JSON_Stream'Class renames + League.JSON.Streams.JSON_Stream'Class (S.all); + begin + JS.Start_Object; + Read_String (JS, +""command"", V.command); + JS.Key (+""arguments""); + V.arguments := JS.Read; + JS.End_Object; + end Read_ExecuteCommandParams; + + --------------------------- + -- Read_InitializeParams -- + --------------------------- + + procedure Read_InitializeParams + (S : access Ada.Streams.Root_Stream_Type'Class; + V : out InitializeParams) + is + use type League.Strings.Universal_String; + JS : League.JSON.Streams.JSON_Stream'Class renames + League.JSON.Streams.JSON_Stream'Class (S.all); + Trace : LSP.Types.Optional_String; + begin + JS.Start_Object; + Read_Optional_Number (JS, +""processId"", V.processId); + Read_String (JS, +""rootPath"", V.rootPath); + Read_IRI (JS, +""rootUri"", V.rootUri); + JS.Key (+""capabilities""); + LSP.Messages.ClientCapabilities'Read (S, V.capabilities); + Read_Optional_String (JS, +""trace"", Trace); + + if not Trace.Is_Set then + V.trace := LSP.Types.Unspecified; + elsif Trace.Value = +""off"" then + V.trace := LSP.Types.Off; + elsif Trace.Value = +""messages"" then + V.trace := LSP.Types.Messages; + elsif Trace.Value = +""verbose"" then + V.trace := LSP.Types.Verbose; + end if; + + JS.End_Object; + end Read_InitializeParams; + + -------------------------- + -- Read_synchronization -- + -------------------------- + + not overriding procedure Read_synchronization + (S : access Ada.Streams.Root_Stream_Type'Class; + V : out synchronization) + is + JS : League.JSON.Streams.JSON_Stream'Class renames + League.JSON.Streams.JSON_Stream'Class (S.all); + begin + JS.Start_Object; + Read_Optional_Boolean + (JS, +""dynamicRegistration"", V.dynamicRegistration); + Read_Optional_Boolean (JS, +""willSave"", V.willSave); + Read_Optional_Boolean (JS, +""willSaveWaitUntil"", V.willSaveWaitUntil); + Read_Optional_Boolean (JS, +""didSave"", V.didSave); + JS.End_Object; + end Read_synchronization; + + ----------------------------------------- + -- Read_TextDocumentClientCapabilities -- + ----------------------------------------- + + not overriding procedure Read_TextDocumentClientCapabilities + (S : access Ada.Streams.Root_Stream_Type'Class; + V : out TextDocumentClientCapabilities) + is + JS : League.JSON.Streams.JSON_Stream'Class renames + League.JSON.Streams.JSON_Stream'Class (S.all); + begin + JS.Start_Object; + JS.Key (+""synchronization""); + synchronization'Read (S, V.synchronization); + JS.Key (+""completion""); + completion'Read (S, V.completion); + JS.Key (+""hover""); + dynamicRegistration'Read (S, V.hover); + JS.Key (+""signatureHelp""); + dynamicRegistration'Read (S, V.signatureHelp); + JS.Key (+""references""); + dynamicRegistration'Read (S, V.references); + JS.Key (+""documentHighlight""); + dynamicRegistration'Read (S, V.documentHighlight); + JS.Key (+""documentSymbol""); + dynamicRegistration'Read (S, V.documentSymbol); + JS.Key (+""formatting""); + dynamicRegistration'Read (S, V.formatting); + JS.Key (+""rangeFormatting""); + dynamicRegistration'Read (S, V.rangeFormatting); + JS.Key (+""onTypeFormatting""); + dynamicRegistration'Read (S, V.onTypeFormatting); + JS.Key (+""definition""); + dynamicRegistration'Read (S, V.definition); + JS.Key (+""codeAction""); + dynamicRegistration'Read (S, V.codeAction); + JS.Key (+""codeLens""); + dynamicRegistration'Read (S, V.codeLens); + JS.Key (+""documentLink""); + dynamicRegistration'Read (S, V.documentLink); + JS.Key (+""rename""); + dynamicRegistration'Read (S, V.rename); + JS.End_Object; + end Read_TextDocumentClientCapabilities; + + ----------------------------------------- + -- Read_TextDocumentContentChangeEvent -- + ----------------------------------------- + + not overriding procedure Read_TextDocumentContentChangeEvent + (S : access Ada.Streams.Root_Stream_Type'Class; + V : out TextDocumentContentChangeEvent) + is + JS : League.JSON.Streams.JSON_Stream'Class renames + League.JSON.Streams.JSON_Stream'Class (S.all); + begin + JS.Start_Object; + JS.Key (+""range""); + Optional_Span'Read (S, V.span); + Read_Optional_Number (JS, +""rangeLength"", V.rangeLength); + Read_String (JS, +""text"", V.text); + JS.End_Object; + end Read_TextDocumentContentChangeEvent; + + ------------------------------------------------ + -- Read_TextDocumentContentChangeEvent_Vector -- + ------------------------------------------------ + + not overriding procedure Read_TextDocumentContentChangeEvent_Vector + (S : access Ada.Streams.Root_Stream_Type'Class; + V : out TextDocumentContentChangeEvent_Vector) + is + JS : League.JSON.Streams.JSON_Stream'Class renames + League.JSON.Streams.JSON_Stream'Class (S.all); + begin + V.Clear; + JS.Start_Array; + while not JS.End_Of_Array loop + declare + Item : TextDocumentContentChangeEvent; + begin + TextDocumentContentChangeEvent'Read (S, Item); + V.Append (Item);" +procedure Create_Filename is,"File : Stream_IO.File_Type; + begin + Ada.Text_IO.Put_Line (Source_Location & "":"" & Enclosing_Entity); + Stream_IO.Create (File, Stream_IO.Out_File, Filename); + Stream_IO.Close (File); + end Create_Filename; + + overriding + function End_Of_File (Resource : Pump_Stream) return Boolean is + begin + return not Resource.Is_Open;" +procedure Create_Filename;,"Filename : constant String := ""dm_file.data""; + URI : Services.Dispatchers.URI.Handler; + Handler : Services.Dispatchers.Linker.Handler; + Conf : Config.Object := Config.Get_Current; + WS : Server.HTTP; + type Pump_Stream is limited new AWS.Resources.Streams.Memory.Stream_Type with private; + + + procedure Open (S : in out Pump_Stream); + overriding + function End_Of_File (Resource : Pump_Stream) return Boolean; + + overriding + procedure Read + (Resource : in out Pump_Stream; + Buffer : out Stream_Element_Array; + Last : out Stream_Element_Offset); + + overriding + procedure Close (Resource : in out Pump_Stream); + + overriding + procedure Reset (Resource : in out Pump_Stream) is null; + + overriding + procedure Set_Index + (Resource : in out Pump_Stream; + To : Stream_Element_Offset) is null; + + +private + not overriding + procedure Real_Read + (Resource : in out Pump_Stream; + Buffer : out Stream_Element_Array; + Last : out Stream_Element_Offset); + type Pump_Stream is limited new AWS.Resources.Streams.Memory.Stream_Type with record + Is_Open : Boolean := False; + end record;" +procedure finalize_library is,"begin + E65 := E65 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__text_io__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""system__file_io__finalize_body""); + begin + E73 := E73 - 1; + F2;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (C, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Leap_Seconds_Support : Integer; + pragma Import (C, Leap_Seconds_Support, ""__gl_leap_seconds_support""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 0; + Default_Stack_Size := -1; + Leap_Seconds_Support := 0; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E25 := E25 + 1; + System.Exceptions'Elab_Spec; + E27 := E27 + 1; + System.Soft_Links.Initialize'Elab_Body; + E21 := E21 + 1; + E13 := E13 + 1; + Ada.Io_Exceptions'Elab_Spec; + E68 := E68 + 1; + System.Os_Lib'Elab_Body; + E78 := E78 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E06 := E06 + 1; + Ada.Streams'Elab_Spec; + E67 := E67 + 1; + System.File_Control_Block'Elab_Spec; + E81 := E81 + 1; + System.Finalization_Root'Elab_Spec; + E76 := E76 + 1; + Ada.Finalization'Elab_Spec; + E74 := E74 + 1; + System.File_Io'Elab_Body; + E73 := E73 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E65 := E65 + 1; + Rasp_Code'Elab_Spec; + E83 := E83 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + gnat_argc := argc; + gnat_argv := argv; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure computus_test is,"NL : constant String := CR & LF ; + Prompter : constant String := ""Type command and figure, or H for Help:""; + Help_text : constant String := + ""This line mode program challenges the Milesian Easter computation method"" + & NL & ""with standard Meeus methods."" & NL & + ""Copyright Louis-A. de Fouquieres, Miletus, 2015-2017."" & NL & + ""More at www.calendriermilesien.org."" & NL & + ""Syntax: ."" & NL & + "" is one character as described hereunder."" & NL & + "" is an integer, the final year for the test."" & NL & + ""Tests begin with year 0 for both Julian and Gregorian algorithms, "" & NL & + ""although there is no historical sense"" & NL & + ""before around 525 (julian) or 1583 (gregorian)."" & NL & + ""Result of Eater computation is Easter day rank, i.e. "" & NL & + ""number of days after March 21st when Easter Sunday occurs."" & NL & + ""Available commands:"" & NL & + ""S: Silent mode (by default), list discrepancies only."" & NL & + ""V: Verbose mode, report year per year results."" & NL & + ""J : test Julian calendar computus from 0 to ."" & NL & + ""G ."" & NL & + ""H: Help, display this text."" & NL & + ""X: Exit program.""; + + Command : Character := ' '; + Verbose : Boolean := False; + Level, D1, D2 : Natural := 0; + + Help_request, Command_error : exception; + + +begin + Put (""Copyright Louis-A. de Fouquieres, Miletus, 2015-2019, calendriermilesien.org""); + New_Line; + loop + begin -- a block with exception handler + Put (Prompter); New_Line; + Get (Command); + case Command is + when 'X' => Put (""Bye !""); + when 'H' => Skip_Line; raise Help_request; + when 'V' => Verbose := True; Put (""Verbose mode on""); + when 'S' => Verbose := False; Put (""Verbose mode off""); + when 'G' | 'J' => + Get (Level); + Put(""Calendar: ""); Put (Command); + Put ("", final year: ""); Put (Level, 7); + + case Command is + when 'G' => + For Year in 0 .. Level loop + D1 := Butcher (Year); D2 := Easter_days (Year, Gregorian); + if Verbose or D1 /= D2 then + New_Line; Put (""Year: ""); Put (Year); + Put ("", Butcher: ""); Put (D1,2); + Put ("", Milesian: ""); Put (D2,2); + end if; + end loop; + when 'J' => + For Year in 0 .. Level loop + D1 := Delambre (Year); D2 := Easter_days (Year, Julian); + if Verbose or D1 /= D2 then + New_Line; Put (""Year: ""); Put (Year); + Put ("", Delambre: ""); Put (D1,2); + Put ("", Milesian: ""); Put (D2,2); + end if; + end loop; + when others => raise Command_error; + end case; + New_Line; Put (""== End comparison ==""); + + when others => raise Command_error; + end case; + exception + when Help_request => Put (Help_text); + when Command_error => Put ("" Invalid command !""); Skip_Line; + when others => Put ("" Unknown error !""); Skip_Line;" +procedure Milesian_converter is,"NL : constant String := CR & LF ; + Licence_text : constant String := + ""Date converter and moon phase computer using the Milesian calendar."" & NL & + ""Written by Louis A. de Fouquieres, Miletus,"" & NL & + ""Initial version M2015-09-30, actual version M2019-01-16."" & NL & + ""Generated with the GNAT Programming Studio GPL Edition 2014."" & NL & + ""No warranty of any kind arising from or in connection with this application."" + & NL & ""Library sources available on demand under GP licence."" + & NL & ""No commercial usage allowed - inquiries: www.calendriermilesien.org""; + + Prompter : constant String := ""Type command and figures, or H for Help:""; + + Help_text : constant String := + ""This line mode program converts dates from and to "" + & NL & + ""Julian day, Milesian, Gregorian, and Julian calendars."" & NL & + ""Mean Moon age, residue and lunar time are also computed, "" & NL & + ""as well as yearly key figures."" + & NL & + ""Syntax: <1 to 6 numbers separated with spaces>."" & NL & + "" is one character as described hereunder."" & NL & + ""Numbers are decimal possibly beginning with + or -, without spaces,"" & NL & + ""with a dot (.) as decimal separator when applicable."" & NL & + ""When a date is expected, it must be entered as: year (-4800 to 9999),"" + & NL & + ""month number (1 to 12, by default: 1), day number (1 to 31, by default: 1),"" + & NL & + ""hours (0 to 23, default 12), minutes and seconds (default 0, max 59)."" + & NL & ""Time of day is Terrestrial Time (64,184 s ahead of UTC in 2000)."" + & NL & + ""Lunar time is time of day where the mean Moon stands"" & NL & + ""at the same azimuth than the mean Sun at this solar time."" & NL & + ""Yearly key figures ('Y' command) include"" & NL & + ""- doomsday, i.e. day of the week that falls at same dates every year,"" & NL & + ""- lunar figures at new year's eve at 7h30 UTC,"" & NL & + ""- Milesian epact and yearly lunar residue, in half-integer,"" & NL & + ""- spring full moon residue in integer value,"" & NL & + ""- for years A.D., days between 21st March and Easter"" + & NL & + ""following the Gregorian and Julian Catholic ecclesiastical computus,"" & NL & + ""and finally the delay, in days, of dates in Julian compared to Gregorian."" + & NL & + ""Available commands:"" & NL & + ""D : Julian day;"" & NL & + ""G : Date in Gregorian calendar (even before 1582);"" & NL & + ""J : Date in Julian calendar;"" & NL & + ""M : Date in Milesian calendar;"" & NL & + ""Y : Yearly key figures (see above);"" + & NL & + ""A [ [ []]]: Add days, hours, mins, secs"" + & NL & ""to current date, each figure is a signed integer, 0 by default;"" + & NL & + ""H: display this text;"" & NL & + ""L: display licence notice;"" & NL & + ""X: exit program.""; + + Command : Character := ' '; + Roman_calendar_type : Calendar_type := Unspecified; + + -- Duration to substract to Julian Day of first day of a year, in order + -- to obtain time of ""doomsday"" at which the moon phase is computed. + To_Doomsday_time_duration : constant Historical_Duration + := 86_400.0 + 4*3600.0 + 30*60.0; + + -- To substract to Milesian epact to obtain a good estimate + -- of Easter full moon residue + To_Spring_Full_Moon : Constant := 12.52 * 86_400; + + This_year : Historical_year_number := 0; + + M_date: Milesian_date := (4, 12, -4713); + R_date : Roman_date := (1, 1, -4712); + This_Julian_day: Julian_day := 0; -- in integer days + This_historical_time: Historical_Time := 0.0; -- in seconds + Displayed_time: Fractional_day_duration := 0.0; -- in fractional days + This_hour : Hour_Number := 12; + This_minute : Minute_Number := 0; + This_second : Second_Number :=0; + + Day_time : Day_Duration := 0.0; + Julian_hour : Day_Historical_Duration := 0.0; + + Day_Number_in_Week : Integer range 0..6; + + Moon_time, Moon_time_shift : H24_Historical_Duration; + Moon_hour : Hour_Number; + Moon_minute: Minute_Number; + Moon_second: Second_Number; + Moon_subsecond: Second_Duration; + + Help_request, Licence_request : Exception; + +begin + Put (Licence_text); New_Line; + loop + begin -- a block with exception handler + Put (Prompter); New_Line; + Get (Command); + case Command is + when 'H' => Skip_Line; raise Help_request; + when 'L' => Skip_Line; raise Licence_request; + when 'D' => + --Get section + Get (Displayed_time); Skip_Line; + -- Conversion section + This_historical_time := Convert_from_julian_day (Displayed_time); + This_Julian_day := Julian_Day_Of (This_historical_time); + M_date := jd_to_milesian (This_Julian_day); + Julian_hour := This_historical_time - Julian_Duration_Of (This_Julian_day); + Day_time := Day_Offset (Julian_hour); + This_hour := Integer (Day_time) / 3600; + This_minute := Integer (Day_time) / 60 - This_hour*60; + This_second := Integer (Day_time) - This_hour*3600 - This_minute*60; + + when 'G' | 'J' => + -- Get section. + case Command is + when 'G' => Roman_calendar_type := Gregorian; + when 'J' => Roman_calendar_type := Julian; + when others => Roman_calendar_type := Unspecified; + end case; + R_date := (1, 1, -4712); + This_hour := 12; This_minute := 0; This_second := 0; + Get (R_date.year); + if not End_Of_Line then Get (R_date.month); end if; + if not End_Of_Line then Get (R_date.day); end if; + if not End_Of_Line then Get (This_hour); end if; + if not End_Of_Line then Get (This_minute); end if; + if not End_Of_Line then Get (This_second); end if; + Skip_Line; + -- Conversion section; + This_Julian_day := Roman_to_JD (R_date, Roman_calendar_type); + -- This function raises Time_Error if date is improper + Day_time := 3600.0 * This_hour + 60.0 * This_minute + 1.0 * This_second; + This_historical_time := Julian_Duration_Of (This_Julian_day) + Day_Julian_Offset (Day_time); + Displayed_time := Fractionnal_day_of (This_historical_time); + M_date := JD_to_Milesian (This_Julian_day); + + when 'M' => + M_Date := (1, 1, -4712); + This_hour := 12; This_minute := 0; This_second := 0; + Get (M_date.year); + if not End_Of_Line then Get (M_date.month); end if; + if not End_Of_Line then Get (M_date.day); end if; + if not End_Of_Line then Get (This_hour); end if; + if not End_Of_Line then Get (This_minute); end if; + if not End_Of_Line then Get (This_second); end if; + Skip_Line; + -- Conversion section; + This_Julian_day := Milesian_to_JD (M_date); + -- This function raises Time_Error if date is improper + Day_time := 3600.0 * This_hour + 60.0 * This_minute + 1.0 * This_second; + This_historical_time := Julian_Duration_Of (This_Julian_day) + Day_Julian_Offset (Day_time); + Displayed_time := Fractionnal_day_of (This_historical_time); + M_date := JD_to_Milesian (This_Julian_day); + + when 'Y' => + M_Date := (1, 1, -4712); + This_hour := 12; This_minute := 0; This_second := 0; + Get (This_year); M_date.year := This_year; + Skip_Line; + -- Conversion section: compute ""doomsday"" + This_Julian_day := Milesian_to_JD (M_date); + -- Set to ""doomsday"" + Day_time := 3600.0 * This_hour + 60.0 * This_minute + 1.0 * This_second; + This_historical_time := Julian_Duration_Of (This_Julian_day) + + Day_Julian_Offset (Day_time) + - To_Doomsday_time_duration; + This_Julian_day := Julian_Day_Of (This_historical_time); + M_date := jd_to_milesian (This_Julian_day); + Displayed_time := Fractionnal_day_of (This_historical_time); + + when 'A' => + declare + Days : Julian_Day_Duration := 0; + Hour_Offset, Minute_Offset, Second_Offset : Integer := 0; + Julian_Time_Offset : Historical_Duration := 0.0; + + begin + -- Get section + Get (Days); + if not End_Of_Line then Get (Hour_Offset); end if; + if not End_Of_Line then Get (Minute_Offset); end if; + if not End_Of_Line then Get (Second_Offset); end if; + Skip_Line; + -- Conversion section + Julian_Time_Offset := Julian_Duration_Of + (3600.0 * Hour_Offset + + 60.0 * Minute_Offset + + 1.0 * Second_Offset); + This_historical_time := + This_historical_time + Julian_Duration_Of (Days) + Julian_Time_Offset ; + This_Julian_day := Julian_Day_Of (This_historical_time); + M_date := jd_to_milesian (This_Julian_day); + Julian_hour := This_historical_time - Julian_Duration_Of (This_Julian_day); + Displayed_time := Fractionnal_day_of (This_historical_time); + begin + Day_time := Day_Offset (Julian_hour); + exception + when Constraint_Error => + Put(""Day time out of bounds - correcting""); New_Line; + Day_time := 86_399.88; + -- avoids out of bounds." +procedure match is,"type Edge_Record is record + id : Natural; + conf : Configuration; + end record; + + package Edge_Maps is new Ada.Containers.Indefinite_Hashed_Maps + (Key_Type => Line_Value, + Element_Type => Edge_Record, + Hash => line_hash, + Equivalent_Keys => ""=""); + use Edge_Maps; + + edge_map : Edge_Maps.Map := Edge_Maps.Empty_Map; + begin + for c in tiles.Iterate loop + declare + t : Tile := tiles(c); + es : constant Edge_Sets.Set := get_edges(t.id); + begin + for val of es loop + if edge_map.contains(val) then + declare + matched_edge : constant Edge_Record := edge_map(val); + matched_tile : Tile := tiles(matched_edge.id); + begin + matched_tile.neighbors.include(t.id); + tiles(matched_tile.id) := matched_tile; + t.neighbors.include(matched_tile.id); + tiles(c) := t;" +procedure rotate_complete_image is,"max : constant Natural := Natural(Ada.Numerics.Elementary_Functions.sqrt(Float(tiles.length)) * 8.0) - 1; + new_image : Complete_Image_Sets.Set := Complete_Image_Sets.Empty_Set; + begin + for pixel of complete_image loop + new_image.insert(Position'(x=>pixel.y, y=>max-pixel.x)); + end loop; + complete_image := new_image; + end rotate_complete_image; + + procedure flip_complete_image is + max : constant Natural := Natural(Ada.Numerics.Elementary_Functions.sqrt(Float(tiles.length)) * 8.0) - 1; + new_image : Complete_Image_Sets.Set := Complete_Image_Sets.Empty_Set; + begin + for pixel of complete_image loop + new_image.insert(Position'(x=>max-pixel.x, y=>pixel.y)); + end loop; + complete_image := new_image; + end flip_complete_image; + + pragma Warnings (Off, ""procedure """"put_line"""" is not referenced""); + procedure put_line(i : in Complete_Image_Sets.Set) is + pragma Warnings (On, ""procedure """"put_line"""" is not referenced""); + max : constant Natural := Natural(Ada.Numerics.Elementary_Functions.sqrt(Float(tiles.length)) * 8.0) - 1; + begin + for y in 0..max loop + for x in 0..max loop + if i.contains(Position'(x=>x, y=>y)) then + TIO.put(""#""); + else + TIO.put("".""); + end if; + end loop; + TIO.new_line; + end loop; + end put_line; + + function dragon_pixel(x, y : in Natural) return Boolean is + begin + return complete_image.contains(Position'(x=>x, y=>y)); + end dragon_pixel; + + function dragon_start(x, y : in Natural) return Boolean is + begin + return + dragon_pixel(x+0, y+1) and then + dragon_pixel(x+1, y+2) and then + dragon_pixel(x+4, y+2) and then + dragon_pixel(x+5, y+1) and then + dragon_pixel(x+6, y+1) and then + dragon_pixel(x+7, y+2) and then + dragon_pixel(x+10, y+2) and then + dragon_pixel(x+11, y+1) and then + dragon_pixel(x+12, y+1) and then + dragon_pixel(x+13, y+2) and then + dragon_pixel(x+16, y+2) and then + dragon_pixel(x+17, y+1) and then + dragon_pixel(x+18, y+0) and then + dragon_pixel(x+18, y+1) and then + dragon_pixel(x+19, y+1); + end dragon_start; + + function count_dragon_pixels return Natural is + max : constant Natural := Natural(Ada.Numerics.Elementary_Functions.sqrt(Float(tiles.length)) * 8.0) - 1; + cnt : Natural := 0; + begin + for rot in 0..3 loop + for y in 0..max loop + for x in 0..max loop + if dragon_start(x, y) then + cnt := cnt + 1; + end if; + end loop; + end loop; + TIO.put_line(""Found dragons: "" & cnt'IMAGE); + if cnt /= 0 then + return cnt * 15; + end if; + TIO.put_line(""Rotating...""); + rotate_complete_image; + end loop; + TIO.put_line(""Flipping...""); + flip_complete_image; + return count_dragon_pixels; + end count_dragon_pixels; + + procedure layout is + type Candidate is record + id : Natural; + orientation : Configuration; + left, right, up, down : Natural; + end record; + + package Natural_Vectors is new Ada.Containers.Vectors + (Index_Type => Natural, + Element_Type => Natural); + use Natural_Vectors; + + package Candidate_Maps is new Ada.Containers.Indefinite_Hashed_Maps + (Key_Type => Natural, + Element_Type => Candidate, + Hash => id_hash, + Equivalent_Keys => ""=""); + use Candidate_Maps; + + function update_neighbor_links(id : in Natural; state : in out Candidate_Maps.Map) return Boolean is + c : Candidate := state(id); + es : constant Edge_Array := edges(c.id, c.orientation); + t : constant Tile := tiles(c.id); + begin + for n of t.neighbors loop + if state.contains(n) then + declare + neigh_cand : Candidate := state(n); + neigh_es : constant Edge_Array := edges(neigh_cand.id, neigh_cand.orientation); + begin + if es(0) = neigh_es(2) then + c.up := neigh_cand.id; + neigh_cand.down := id; + elsif es(1) = neigh_es(3) then + c.right := neigh_cand.id; + neigh_cand.left := id; + elsif es(2) = neigh_es(0) then + c.down := neigh_cand.id; + neigh_cand.up := id; + elsif es(3) = neigh_es(1) then + c.left := neigh_cand.id; + neigh_cand.right := id; + else + return false; + end if; + + state(c.id) := c; + state(neigh_cand.id) := neigh_cand;" +procedure flatten_allergens is,"s : String_Sets.Set; + begin + for c in allergen_ingredients.Iterate loop + s.clear; + for v of allergen_ingredients(c) loop + s := s or v; + end loop; + allergens.insert(key(c), s); + end loop; + end flatten_allergens; + + function all_length_one return Boolean is + begin + for c in allergens.iterate loop + if allergens(c).length /= 1 then + return false; + end if; + end loop; + return true; + end all_length_one; + + function all_singles return String_Sets.Set is + s : String_Sets.Set := String_Sets.Empty_Set; + begin + for c in allergens.iterate loop + if allergens(c).length = 1 then + s.include(allergens(c).first_element); + end if; + end loop; + return s; + end all_singles; + + procedure reduce_allergens is + begin + loop + if all_length_one then + exit; + end if; + declare + singles : constant String_Sets.Set := all_singles; + begin + if singles.is_empty then + TIO.put_line(""No single element sets!""); + exit; + end if; + for k of allergen_keys loop + if allergens(to_string(k)).length > 1 then + allergens(to_string(k)) := allergens(to_string(k)) - singles; + end if; + end loop;" +procedure Test_Create_Decoder is,"Decoder_Mono_8_kHz : Decoder_Data; + begin + Decoder_Mono_8_kHz := Create (Rate_8_kHz, Mono); + Assert (Get_Sample_Rate (Decoder_Mono_8_kHz) = Rate_8_kHz, Unexpected_Sampling_Rate_Message); + end Test_Create_Decoder; + + procedure Test_Destroy_Decoder is + Decoder : constant Decoder_Data := Create (Rate_8_kHz, Mono); + begin + Destroy (Decoder); + end Test_Destroy_Decoder; + + procedure Test_Reset_State is + Decoder : constant Decoder_Data := Create (Rate_8_kHz, Stereo); + begin + Reset_State (Decoder); + end Test_Reset_State; + + procedure Test_Default_Configuration is + Decoder : constant Decoder_Data := Create (Rate_8_kHz, Mono); + begin + Assert (Get_Sample_Rate (Decoder) = Rate_8_kHz, Unexpected_Configuration_Message); + Assert (Get_Channels (Decoder) = Mono, Unexpected_Configuration_Message); + Assert (Get_Pitch (Decoder) = 0, Unexpected_Configuration_Message); + Assert (Get_Gain (Decoder) = 0, Unexpected_Configuration_Message); + Assert (Get_Last_Packet_Duration (Decoder) = 0, Unexpected_Configuration_Message); + + declare + Unused_Result : Bandwidth; + begin + Unused_Result := Get_Bandwidth (Decoder); + Fail (Expected_No_Packets_Decoded_Message); + exception + when No_Packets_Decoded => + null;" +procedure Chess_Main is,"use type Common_Types.Colour_Type; + +begin + + Game.Initialize (Game_Board => Board.Make); + + while not Game.Is_Game_Over loop + + Game.Get_Board.Print; + + declare + The_Move : constant Move.Object := Move.Get_Move (Game.Get_Turn); + begin + The_Move.Perform_Move;" +procedure Dg_Loada is,"SemVer : constant String := ""1.4.3""; -- TODO Update SemVer on each release + + Dump_File_Name : Unbounded_String; + Extracting : Boolean := False; + Ignoring_Errors : Boolean := False; + Listing : Boolean := False; + Summary : Boolean := True; + Verbose : Boolean := False; + + ArgIx : Integer := 1; + Dump_File : File_Type; + Dump_File_Stream : Stream_Access; + Write_File : File_Type; + + -- dump images can legally contain 'too many' directory pops, so we + -- store the starting directory and never traverse above it... + Base_Dir : constant String := Current_Directory; + Working_Dir : Unbounded_String := To_Unbounded_String (Base_Dir); + + Buffer : array (1 .. MaxBlockSize) of Unsigned_8; + FSB_Type_Indicator : Integer; + Current_File_Name : Unbounded_String; + + SOD : SOD_Type; + Record_Header : Record_Header_Type; + Total_File_Size, Padding_Size : Unsigned_32 := 0; + Done, In_A_File, Load_It : Boolean := False; + File_Count : Natural := 0; + + Cannot_Create_Link : exception; + + function symlink (fname, linkname : String) return Integer; + pragma Import (C, symlink); + + procedure Print_Help is + begin + Ada.Text_IO.Put_Line (""Usage of dg_loada:""); + Ada.Text_IO.Put_Line ("" -dumpfile DUMP_II or DUMP_III file to read/load (required)""); + Ada.Text_IO.Put_Line ("" -extract extract the files from the DUMP_II/III into the current directory""); + Ada.Text_IO.Put_Line ("" -ignoreErrors do not exit if a file or link cannot be created""); + Ada.Text_IO.Put_Line ("" -list list the contents of the DUMP_II/III file""); + Ada.Text_IO.Put_Line ("" -summary concise summary of the DUMP_II/III file contents (default true)""); + Ada.Text_IO.Put_Line ("" -verbose be rather wordy about what dg_loada is doing""); + Ada.Text_IO.Put_Line ("" -version show the version number of dg_loada and exit""); + + Set_Exit_Status (Failure); + end Print_Help; + + procedure Load_Buffer (Num_Bytes : Integer; Reason : String) + is + Tmp_Blob : Blob_Type (1 .. Num_Bytes); + begin + Tmp_Blob := Read_Blob (Num_Bytes, Dump_File_Stream, Reason); + for B in 1 .. Num_Bytes loop + Buffer (B) := Tmp_Blob (B); + end loop; + end Load_Buffer; + + function Process_Name_Block (Record_Header : Record_Header_Type) return Unbounded_String + is + Name_Bytes : Blob_Type (1 .. Record_Header.Record_Length); + File_Name, Write_Path, Display_Path : Unbounded_String; + This_Entry_Type : Fstat_Entry_Rec; + begin + Name_Bytes := + Read_Blob (Record_Header.Record_Length, Dump_File_Stream, ""File Name""); + File_Name := Extract_First_String (Name_Bytes); + File_Name := To_Linux_Filename (File_Name); + if Summary and Verbose then + Ada.Text_IO.Put_Line (""""); + end if; + This_Entry_Type := Known_Fstat_Entry_Types (FSB_Type_Indicator); + + Load_It := This_Entry_Type.Has_Payload; + if This_Entry_Type.Is_Dir then + Working_Dir := Working_Dir & ""/"" & File_Name; + if Extracting then + Create_Directory (To_String (Working_Dir)); + end if; + end if; + + if Listing then + if Working_Dir = """" then + Display_Path := File_Name; + else + Display_Path := Working_Dir & ""/"" & File_Name; + end if; + Ada.Text_IO.Put + (To_String (This_Entry_Type.Desc) & "" "" & + To_String (Display_Path)); + if Verbose or else This_Entry_Type.Is_Dir then + Ada.Text_IO.Put_Line (""""); + else + Ada.Text_IO.Put ("" ""); + end if; + end if; + + File_Count := File_Count + 1; + + if Extracting and Load_It then + if Working_Dir = """" then + Write_Path := File_Name; + else + Write_Path := Working_Dir & ""/"" & File_Name; + end if; + if Verbose then + Ada.Text_IO.Put_Line ("" Creating file: "" & To_String (Write_Path)); + end if; + Create (Write_File, Out_File, To_String (Write_Path)); + -- Ada.Text_IO.Put_Line (""DEBUG: Output file created"" ); + end if; + + return File_Name; + end Process_Name_Block; + + procedure Process_Data_Block is + DHB : Data_Header_Type; + FourBytes : Blob_Type (1 .. 4); + TwoBytes : Blob_Type (1 .. 2); + begin + -- first get the address and length + FourBytes := Read_Blob (4, Dump_File_Stream, ""Byte Addr""); + DHB.Byte_Address := Unsigned_32 (FourBytes (1)); + DHB.Byte_Address := + Shift_Left (DHB.Byte_Address, 8) + Unsigned_32 (FourBytes (2)); + DHB.Byte_Address := + Shift_Left (DHB.Byte_Address, 8) + Unsigned_32 (FourBytes (3)); + DHB.Byte_Address := + Shift_Left (DHB.Byte_Address, 8) + Unsigned_32 (FourBytes (4)); + + FourBytes := Read_Blob (4, Dump_File_Stream, ""Byte Length""); + DHB.Byte_Length := Unsigned_32 (FourBytes (1)); + DHB.Byte_Length := + Shift_Left (DHB.Byte_Length, 8) + Unsigned_32 (FourBytes (2)); + DHB.Byte_Length := + Shift_Left (DHB.Byte_Length, 8) + Unsigned_32 (FourBytes (3)); + DHB.Byte_Length := + Shift_Left (DHB.Byte_Length, 8) + Unsigned_32 (FourBytes (4)); + + if DHB.Byte_Length > Unsigned_32 (MaxBlockSize) then + Ada.Text_IO.Put_Line + (Ada.Text_IO.Standard_Error, + ""ERROR: Maximum Block Size Exceeded.""); + Set_Exit_Status (Failure); + Abort_Task (Current_Task); + end if; + + if Verbose then + Ada.Text_IO.Put_Line + ("" Data block: "" & Unsigned_32'Image (DHB.Byte_Length) & + "" (bytes)""); + end if; + + TwoBytes := Read_Blob (2, Dump_File_Stream, ""Alignment Count""); + DHB.Alighnment_Count := Unsigned_16 (TwoBytes (1)); + DHB.Alighnment_Count := + Shift_Left (DHB.Alighnment_Count, 8) + Unsigned_16 (TwoBytes (2)); + + -- skip any alignment bytes - usually just one + if DHB.Alighnment_Count /= 0 then + if Verbose then + Ada.Text_IO.Put_Line + ("" Skipping "" & Unsigned_16'Image (DHB.Alighnment_Count) & + "" alignment byte(s)""); + end if; + declare + Dummy_Blob : Blob_Type (1 .. Integer (DHB.Alighnment_Count)); + begin + Dummy_Blob := Read_Blob (Integer (DHB.Alighnment_Count), Dump_File_Stream, ""Alignment"");" +procedure Process_End_Block is,"begin + if Is_Open (Write_File) then + Close (Write_File); + if Verbose then + Ada.Text_IO.Put_Line ("" File Closed""); + end if; + end if; + if In_A_File then + if Listing then + Ada.Text_IO.Put_Line ("" "" & Unsigned_32'Image (Total_File_Size) & "" bytes""); + end if; + Total_File_Size := 0; + In_A_File := False; + else + if Working_Dir /= Base_Dir then -- Don't go up from start dir + declare lastSlash : constant Natural := Ada.Strings.Unbounded.Index (Working_Dir, ""/"", Ada.Strings.Backward); + begin + Working_Dir := Head (Working_Dir, lastSlash - 1);" +procedure Ada_Split is,"src : File_Type; + + max_recurse_depth : Constant := 10; + recurse_depth : Integer := 0; + + src_file_name : String := read_command_arg ('i',""""); + out_file_name : String := read_command_arg ('o',""""); + + type tag_type is (beg_tag, end_tag, neither); + + function Path_Exists (the_path_name : string) return boolean renames Ada.Directories.Exists; + function File_Exists (the_file_name : string) return boolean renames Ada.Directories.Exists; + + procedure write_file + (parent : String; -- "" -- beg03: foo/bah/cat.tex"" + child : String) -- "" --- beg04: foo/bah/moo/cow/dog.tex"" + is + + re_beg_tag : String := ""^[\t ]*(--|#|%) beg[0-9]{2}:""; + re_end_tag : String := ""^[\t ]*(--|#|%) end[0-9]{2}:""; + + function full_dir (text : String) return String is -- text := "" -- beg01: ./foo/bah/cat.tex"" + re_dirname : String := ""([_a-zA-Z0-9./-]*\/)""; -- as per dirname in bash + begin + return grep (text,re_dirname,1,fail => """"); -- returns ""./foo/bah/"" + end full_dir; + + function full_file (text : String) return String is -- text := "" -- beg01: ./foo/bah/cat.tex"" + re_file : String := re_beg_tag & "" (.+)""; + begin + return grep (text,re_file,2,fail => """"); -- returns ""./foo/bah/cat.tex"" + end full_file; + + function relative_path + (parent : String; -- "" -- beg03: foo/bah/cat.tex"" + child : String) -- "" -- beg04: foo/bah/moo/cow/dog.tex"" + Return String -- relative path of the child to the parent, e.g., ""moo/cow/dog.tex"" + is + re_dirname : String := ""([_a-zA-Z0-9./-]*\/)""; -- as per dirname in bash + re_basename : String := re_beg_tag & "" "" &re_dirname & ""(.+)""; -- as per basename in bash + parent_dir : String := trim ( grep (parent,re_dirname,1,fail => ""./"") ); -- ""foo/bah/"" + child_dir : String := trim ( grep (child,re_dirname,1,fail => ""./"") ); -- ""foo/bah/moo/cow/"" + child_file : String := trim ( grep (child,re_basename,3,fail => ""??.txt"") ); -- ""dog.tex"" + begin + -- strip parent_directory from front of child + return trim ( child_dir(child_dir'first+get_strlen(parent_dir)..child_dir'last)&str(child_file) ); -- ""moo/cow/dog.tex"" + end relative_path; + + function absolute_indent (text : String) return Integer is + indent : Integer; + begin + indent := 0; + for i in text'Range loop + if text (i) /= ' ' then + indent := max(0,i-1); + exit; + end if; + end loop; + return indent; + end absolute_indent; + + function relative_indent + (parent : String; + child : String) + Return Integer + is + begin + return absolute_indent(child) - absolute_indent(parent); + end relative_indent; + + function classify (the_line : String) return tag_type is + begin + if grep (the_line,re_beg_tag) then return beg_tag; + elsif grep (the_line,re_end_tag) then return end_tag; + else return neither; + end if; + end classify; + + begin + + recurse_depth := recurse_depth + 1; + + if recurse_depth > max_recurse_depth then + Put_Line (""> split-mrg: Recursion limit reached (max = ""&str(max_recurse_depth)&""), exit""); + halt(1); + end if; + + declare + txt : File_Type; + the_dir : String := full_dir (child); + the_file : String := full_file (child); + the_path : String := relative_path (parent, child); + the_indent : Integer := absolute_indent (child); + + procedure write_path (parent : String; child : String) is + the_path : String := relative_path (parent, child); + the_indent : Integer := relative_indent (parent, child); + begin + put_line (txt,spc(the_indent)&""$Input{""""""&the_path&""""""}""); + end write_path; + + procedure write_line (the_line : String; the_indent : Integer) is + begin + if the_indent > get_strlen(the_line) + then put_line (txt, str(the_line)); + else put_line (txt, str(the_line(the_indent+1..the_line'last))); + end if; + end write_line; + + begin + + if not Path_Exists (the_dir) then + Ada.Directories.Create_Path (the_dir); + end if; + + if File_Exists (the_file) + then Open (txt, out_file, the_file); + else Create (txt, out_file, the_file); + end if; + + loop + begin + declare + the_line : String := Get_Line (src); + begin + case classify (the_line) is + when beg_tag => write_path (child, the_line); + write_file (child, the_line); + when end_tag => exit; + when others => write_line (the_line, the_indent); + end case;" +procedure cdb2ada is,"target_line_length : constant := 256; + + src_file_name : String := read_command_arg ('i',""foo.c""); + txt_file_name : String := read_command_arg ('o',""foo.ad""); + procedure_name : String := read_command_arg ('n',""foo""); + + symbol : Character := read_command_arg ('s','t'); -- the 'x' in vars like x0123 or + -- the 't' in t321 + + ----------------------------------------------------------------------------- + + procedure rewrite_cdb is + txt : File_Type; + src : File_Type; + start_line : Boolean; + finished : Boolean; + this_lead_in : Integer; + break_at : integer; + found_at : integer; + found : Boolean; + beg_at : integer; + end_at : integer; + var_beg : integer; + var_end : integer; + rhs_beg : integer; + rhs_end : integer; + tail_beg : integer; + tail_end : integer; + max_xvars_width : Integer; + + procedure write_procedure_begin is + re_name : String := ""([a-zA-Z0-9_-]+)""; + the_name : String := grep (procedure_name, re_name, 1, fail => ""no_name""); + begin + + for i in the_name'range loop + if the_name (i) = '-' then + the_name (i) := '_'; + end if; + end loop; + + Put_Line (txt, ""Procedure ""&the_name&"" is""); + + end write_procedure_begin; + + procedure write_procedure_end is + re_name : String := ""([a-zA-Z0-9_-]+)""; + the_name : String := grep (procedure_name, re_name, 1, fail => ""no_name""); + begin + + for i in the_name'range loop + if the_name (i) = '-' then + the_name (i) := '_'; + end if; + end loop; + + Put_Line (txt, ""end ""&the_name&"";""); + + end write_procedure_end; + + procedure add_declarations is + + src : File_Type; + count : integer; + max_count : integer; + width : integer; + target : integer; + lead_in : integer; + num_chars : integer; + tmp_xvars : Integer; + num_xvars : Integer; + max_width : Integer; + + type action_list is (wrote_xvar, wrote_type, wrote_space); + last_action : action_list; + + begin + + -- first pass: count the number of xvars and record max width + + Open (src, In_File, src_file_name); + + num_xvars := 0; -- number of xvars + max_width := 0; -- maximum widt of the xvars + + loop + begin + declare + re_numb : String := ""^ *""&symbol&""([0-9]+) +=""; + this_line : String := get_line (src); + this_numb : String := grep (this_line, re_numb, 1, fail => """"); + begin + if this_numb /= """" then + num_xvars := num_xvars + 1; + max_width := max (max_width, this_numb'length); + end if;" +procedure Ada_Merge is,"txt : File_Type; + + max_recurse_depth : Constant := 10; + recurse_depth : Integer := 0; + + src_file_name : String := read_command_arg ('i',""""); + out_file_name : String := read_command_arg ('o',""""); + + silent : Boolean := find_command_arg ('S'); -- true: do not wrap include text in beg/end pairs + markup : Boolean := not silent; -- true: do wrap include text in beg/end pairs + + function File_Exists (the_file_name : string) return boolean renames Ada.Directories.Exists; + + procedure include_files + (prev_path : String; + this_line : String; + prev_indent : Integer) + is + + -- allow simple variations of the Input syntax: + -- \Input for TeX, use \Input to avoid confusion with \input + -- $Input for Ada/Python/Cadabra + -- note that this is only for convenience, the comment string will be deduced + -- from the file extension of the Input'ed file + re_inc_file : String := ""^[\t ]*(\\|\$)Input\{""""([_a-zA-Z0-9./-]+)""""\}""; + + -- this function is not used + function not_tex_comment + (the_line : String) + return Boolean + is + re_tex_comment : String := ""^\s*%""; + begin + return (not grep (the_line, re_tex_comment)); + end not_tex_comment; + + function is_include_file + (the_line : String) + Return Boolean + is + begin + return grep (the_line,re_inc_file); + end is_include_file; + + function absolute_path + (the_path : String; -- full path to most recent include file, e.g. foo/bah/cow.tex + the_line : String) -- contains relative path to new include file, e.g., \Input{""cat/dot/fly.tex""} + Return String -- full path to new include file, e.g., foo/bah/cat/dog/fly.tex + is + re_dirname : String := ""([_a-zA-Z0-9./-]*\/)""; -- as per dirname in bash + tmp_path : String (1..the_path'last+the_line'last); -- overestimate length of string + new_path : String (1..the_path'last+the_line'last); + begin + -- drop the simple file name from the existing path + writestr (tmp_path, trim ( grep (the_path,re_dirname,1,fail => """") )); + -- append new file path to the path + writestr (new_path, cut(tmp_path)&trim ( grep (the_line,re_inc_file,2,fail => """") )); + return cut(new_path); + end absolute_path; + + function absolute_indent + (indent : Integer; + the_line : String) + Return Integer + is + start : Integer; + begin + start := 0; + for i in the_line'Range loop + if the_line (i) /= ' ' then + start := max(0,i-1); + exit; + end if; + end loop; + return indent + start; + end absolute_indent; + + function set_comment (the_line : String) return String + is + re_file_ext : String := ""(\.[a-z]+)""""""; + the_ext : String := grep (the_line,re_file_ext,1,fail => ""?""); + begin + if markup then + if the_ext = "".tex"" then return ""%""; + elsif the_ext = "".py"" then return ""#""; + elsif the_ext = "".cdb"" then return ""#""; + elsif the_ext = "".ads"" then return ""--""; + elsif the_ext = "".adb"" then return ""--""; + elsif the_ext = "".adt"" then return ""--""; + elsif the_ext = "".ad"" then return ""--""; + else return ""#""; + end if; + else + return ""#""; + end if; + end set_comment; + + function filter (the_line : String) return String + is + tmp_line : String := the_line; + re_uuid : String := ""(uuid):([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12})""; + the_beg, the_end : Integer; + found : Boolean; + begin + -- ""uuid"" is reserved for the original source + -- the new file being created by this job must use a prefix other than ""uuid"" + -- replace the prefix ""uuid"" with ""file"" + if regex_match (the_line, re_uuid) then + grep (the_beg, the_end, found, the_line, re_uuid, 1); + tmp_line (the_beg..the_end) := ""file""; + end if; + return tmp_line; + end filter; + + begin + + recurse_depth := recurse_depth + 1; + + if recurse_depth > max_recurse_depth then + Put_Line (""> merge-src: Too many nested Input{...}'s (max = ""&str(max_recurse_depth)&""), exit""); + halt(1); + end if; + + declare + src : File_Type; + the_path : String := absolute_path (prev_path, this_line); + the_indent : Integer := absolute_indent (prev_indent, this_line); + comment : String := set_comment (this_line); + begin + + if markup then + Put_Line (txt, spc(the_indent)&comment&"" beg""&make_str(recurse_depth,2)&"": ./"" & the_path); + end if; + + if File_Exists (the_path) + then Open (src, In_File, the_path); + else raise Name_Error with ""Could not find the file ""&""""""""&str(the_path)&""""""""; + end if; + + loop + begin + declare + the_line : String := filter (Get_Line (src)); + begin + if is_include_file (the_line) + then include_files (the_path, the_line, the_indent); + else Put_Line (txt, spc(the_indent)&the_line); + end if;" +procedure evolve_data is,"looping : Boolean; + + task type SlaveTask is + entry resume; + entry pause; + entry release; + entry set_params (slave_params : SlaveParams); + end SlaveTask; + + task body SlaveTask is + params : SlaveParams; + begin + + -- collect parameters for this task ------------------------ + + accept set_params (slave_params : SlaveParams) do + params := slave_params;" +procedure write_results is,"num_loop_str : String := fill_str (num_loop, 5, '0'); + begin + + set_constraints; + + Ada.Directories.create_path (results_directory & ""/xy/""); + Ada.Directories.create_path (results_directory & ""/xz/""); + Ada.Directories.create_path (results_directory & ""/yz/""); + + write_results (xy_index_list, xy_index_num, results_directory & ""/xy/"" & num_loop_str & "".txt""); + write_results (xz_index_list, xz_index_num, results_directory & ""/xz/"" & num_loop_str & "".txt""); + write_results (yz_index_list, yz_index_num, results_directory & ""/yz/"" & num_loop_str & "".txt""); + + end write_results; + + procedure write_history (point : GridPoint; + file_name : String) + is + txt : File_Type; + + i, j, k : Integer; + x, y, z : Real; + + gab : MetricPointArray; + Kab : ExtcurvPointArray; + begin + + i := sample_point.i; + j := sample_point.j; + k := sample_point.k; + + x := sample_point.x; + y := sample_point.y; + z := sample_point.z; + + begin + + Open (txt, Append_File, file_name); + + exception when Name_Error => + + Create (txt, Out_File, file_name); + + Put_Line (txt, ""# 4 more lines before the data""); + + Put_Line (txt, ""# 13 columns of data""); + + Put_Line (txt,""# ("" & str (i,0) & "", "" & + str (j,0) & "", "" & + str (k,0) & "") = grid indices of target""); + + Put_Line (txt,""# ("" & str (x,10) & "", "" & + str (y,10) & "", "" & + str (z,10) & "") = grid coords of target""); + Put_Line (txt, ""# "" & + centre (""Time"",10) & + centre (""gxx"",11) & + centre (""gyy"",11) & + centre (""gzz"",11) & + centre (""Kxx"",11) & + centre (""Kyy"",11) & + centre (""Kzz"",11) & + centre (""Ham"",11) & + centre (""Mom(x)"",11) & + centre (""Mom(y)"",11) & + centre (""Mom(z)"",11) & + centre (""detg"",11) & + centre (""trABar"",11));" +procedure echo_command_name is,"begin + Put_Line (echo_command_name); + end echo_command_name; + + procedure echo_command_line is + begin + Put_Line (echo_command_line); + end echo_command_line; + + procedure echo_command_line_args is + begin + Put_Line (echo_command_line_args); + end echo_command_line_args; + + ---------------------------------------------------------------------------- + + procedure get_command_args + is + begin + + for i in 1 .. Argument_Count loop + declare + the_arg : String := Argument (i); + the_len : Integer := the_arg'last; + the_flag : flags; + begin + if the_len > 1 then + if the_arg (1) = '-' then + the_flag := to_flags (the_arg (2)); + cmd_args (the_flag) := (exists => True, + image => the_arg (2), + index => i, + value => str (the_arg (3..the_len),max_arg_length)); + end if; + end if;" +procedure write_results is,"num_loop_str : String := fill_str (num_loop, 5, '0'); + begin + + set_constraints; + + Ada.Directories.create_path (results_directory & ""/xy/""); + Ada.Directories.create_path (results_directory & ""/xz/""); + Ada.Directories.create_path (results_directory & ""/yz/""); + + write_results (xy_index_list, xy_index_num, results_directory & ""/xy/"" & num_loop_str & "".txt""); + write_results (xz_index_list, xz_index_num, results_directory & ""/xz/"" & num_loop_str & "".txt""); + write_results (yz_index_list, yz_index_num, results_directory & ""/yz/"" & num_loop_str & "".txt""); + + end write_results; + + procedure write_history (point : GridPoint; + file_name : String) + is + txt : File_Type; + + i, j, k : Integer; + x, y, z : Real; + begin + + i := sample_point.i; + j := sample_point.j; + k := sample_point.k; + + x := sample_point.x; + y := sample_point.y; + z := sample_point.z; + + begin + + Open (txt, Append_File, file_name); + + exception when Name_Error => + + Create (txt, Out_File, file_name); + + Put_Line (txt, ""# 4 more lines before the data""); + + Put_Line (txt, ""# 11 columns of data""); + + Put_Line (txt,""# ("" & str (i,0) & "", "" & + str (j,0) & "", "" & + str (k,0) & "") = grid indices of target""); + + Put_Line (txt,""# ("" & str (x,10) & "", "" & + str (y,10) & "", "" & + str (z,10) & "") = grid coords of target""); + Put_Line (txt, ""# "" & + centre (""Time"",10) & + centre (""gxx"",11) & + centre (""gyy"",11) & + centre (""gzz"",11) & + centre (""Kxx"",11) & + centre (""Kyy"",11) & + centre (""Kzz"",11) & + centre (""Ham"",11) & + centre (""Mom(x)"",11) & + centre (""Mom(y)"",11) & + centre (""Mom(z)"",11));" +procedure evolve_data is,"looping : Boolean; + + task type SlaveTask is + entry resume; + entry pause; + entry release; + entry set_params (slave_params : SlaveParams); + end SlaveTask; + + task body SlaveTask is + params : SlaveParams; + begin + + -- collect parameters for this task ------------------------ + + accept set_params (slave_params : SlaveParams) do + params := slave_params;" +procedure Parse_Command_Line;,"procedure Print_Help; + + procedure Increment_Total (Ignore : Ada.Directories.Directory_Entry_Type); + + procedure Each_Torrents + (Dir : League.Strings.Universal_String; + Proc : not null access procedure + (Item : Ada.Directories.Directory_Entry_Type)); + + Cmd : constant League.String_Vectors.Universal_String_Vector := + League.Application.Arguments; + + Log_Option : constant Wide_Wide_String := ""--log=""; + Out_Option : constant Wide_Wide_String := ""--output=""; + Dir_Option : constant Wide_Wide_String := ""--torrent-dir=""; + Port_Option : constant Wide_Wide_String := ""--port=""; + Help_Option : constant Wide_Wide_String := ""--help""; + + Port : Positive := 33411; + Path : League.Strings.Universal_String := +""result""; + Input_Path : League.Strings.Universal_String := +""torrents""; + Total : Ada.Containers.Count_Type := 0; + + procedure Set_Peer_Id (Value : out SHA1); + + ----------------- + -- Set_Peer_Id -- + ----------------- + + procedure Set_Peer_Id (Value : out SHA1) is + Settings : League.Settings.Settings; + Context : GNAT.SHA1.Context; + Element : League.Strings.Universal_String; + Vector : League.Stream_Element_Vectors.Stream_Element_Vector; + + Key : constant League.Strings.Universal_String := +""torrent/peer_id""; + Now : constant String := Ada.Calendar.Formatting.Image + (Ada.Calendar.Clock); + begin + if Settings.Contains (Key) then + Element := League.Holders.Element (Settings.Value (Key)); + Vector := League.Base_Codecs.From_Base_64 (Element); + Value := Vector.To_Stream_Element_Array; + else + GNAT.SHA1.Update (Context, Path.To_UTF_8_String); + GNAT.SHA1.Update (Context, Now); + GNAT.SHA1.Update (Context, GNAT.Sockets.Host_Name); + + Value := GNAT.SHA1.Digest (Context); + Vector.Append (Value); + Element := League.Base_Codecs.To_Base_64 (Vector); + Settings.Set_Value (Key, League.Holders.To_Holder (Element)); + end if; + end Set_Peer_Id; + + --------------------- + -- Increment_Total -- + --------------------- + + procedure Increment_Total (Ignore : Ada.Directories.Directory_Entry_Type) is + use type Ada.Containers.Count_Type; + begin + Total := Total + 1; + end Increment_Total; + + ------------------- + -- Each_Torrents -- + ------------------- + + procedure Each_Torrents + (Dir : League.Strings.Universal_String; + Proc : not null access procedure + (Item : Ada.Directories.Directory_Entry_Type)) + is + begin + Ada.Directories.Search + (Directory => Dir.To_UTF_8_String, + Pattern => ""*.torrent"", + Filter => (Ada.Directories.Ordinary_File => True, others => False), + Process => Proc); + end Each_Torrents; + + ------------------------ + -- Parse_Command_Line -- + ------------------------ + + procedure Parse_Command_Line is + Arg : League.Strings.Universal_String; + begin + for J in 1 .. Cmd.Length loop + Arg := Cmd.Element (J); + + if Arg.Starts_With (Port_Option) then + Port := Positive'Wide_Wide_Value + (Arg.Tail_From (Port_Option'Length + 1).To_Wide_Wide_String); + elsif Arg.Starts_With (Out_Option) then + Path := Arg.Tail_From (Out_Option'Length + 1); + elsif Arg.Starts_With (Dir_Option) then + Input_Path := Arg.Tail_From (Dir_Option'Length + 1); + elsif Arg.Starts_With (Help_Option) then + Print_Help; + elsif Arg.Starts_With (Log_Option) then + Torrent.Logs.Initialize + (Arg.Tail_From (Log_Option'Length + 1)); + end if; + end loop; + end Parse_Command_Line; + + ---------------- + -- Print_Help -- + ---------------- + + procedure Print_Help is + begin + Ada.Wide_Wide_Text_IO.Put_Line (""Usage: torrent-run ""); + Ada.Wide_Wide_Text_IO.Put_Line (""Options are""); + Ada.Wide_Wide_Text_IO.Put_Line + ("" "" & Port_Option & ""int - a port to listen""); + Ada.Wide_Wide_Text_IO.Put_Line + ("" "" & Out_Option & ""path - a directory to save downloaded files""); + Ada.Wide_Wide_Text_IO.Put_Line + ("" "" & Dir_Option & ""path - a directory with torrent files""); + Ada.Wide_Wide_Text_IO.Put_Line + ("" "" & Log_Option & ""path - a trace file, if you need it""); + end Print_Help; + +begin + if Cmd.Is_Empty then + Print_Help; + return; + end if; + + League.Application.Set_Application_Name (+""Torrent Client""); + League.Application.Set_Application_Version (+""0.1""); + League.Application.Set_Organization_Name (+""Matreshka Project""); + League.Application.Set_Organization_Domain (+""forge.ada-ru.org""); + + Parse_Command_Line; + Each_Torrents (Input_Path, Increment_Total'Access); + + declare + procedure Add (Item : Ada.Directories.Directory_Entry_Type); + + Recycle : aliased Torrent.Connections.Queues.Queue; + + Context : Torrent.Contexts.Context + (Capacity => Total, + Port => Port, + Recycle => Recycle'Unchecked_Access); + + --------- + -- Add -- + --------- + + procedure Add (Item : Ada.Directories.Directory_Entry_Type) is + Meta : constant Torrent.Metainfo_Files.Metainfo_File_Access := + new Torrent.Metainfo_Files.Metainfo_File; + begin + Meta.Read + (League.Strings.From_UTF_8_String + (Ada.Directories.Full_Name (Item))); + + Context.Add_Metainfo_File (Meta); + end Add; + + Peer_Id : Torrent.SHA1; + Next_Update : Ada.Calendar.Time; + begin + Set_Peer_Id (Peer_Id); + Context.Initialize (Peer_Id, Path); + Each_Torrents (Input_Path, Add'Access); + Context.Start (Next_Update); + + loop + select + Torrent.Shutdown.Signal.Wait_SIGINT; + Ada.Wide_Wide_Text_IO.Put_Line (""Ctrl+C!""); + exit; + or + delay until Next_Update; + Context.Update (Next_Update); + end select; + end loop; + + Context.Stop;" +procedure Free is new Ada.Unchecked_Deallocation,"(Torrent.Connections.Connection'Class, + Torrent.Connections.Connection_Access); + + --------------- + -- Initiator -- + --------------- + + task body Initiator is + use type Ada.Streams.Stream_Element_Offset; + + type Socket_Connection is record + Socket : GNAT.Sockets.Socket_Type; + Addr : GNAT.Sockets.Sock_Addr_Type; + Job : Torrent.Downloaders.Downloader_Access; + end record; + + package Socket_Connection_Vectors is new Ada.Containers.Vectors + (Positive, Socket_Connection); + + type Planned_Connection is record + Time : Ada.Calendar.Time; + Addr : GNAT.Sockets.Sock_Addr_Type; + Job : Torrent.Downloaders.Downloader_Access; + end record; + + function Less (Left, Right : Planned_Connection) return Boolean; + + package Planned_Connection_Sets is new Ada.Containers.Ordered_Sets + (Element_Type => Planned_Connection, + ""<"" => Less); + + type Accepted_Connection is record + Socket : GNAT.Sockets.Socket_Type; + Address : GNAT.Sockets.Sock_Addr_Type; + Data : Torrent.Handshakes.Handshake_Image; + Last : Ada.Streams.Stream_Element_Count; + Done : Boolean; + Session : Torrent.Connections.Connection_Access; + end record; + + package Accepted_Connection_Vectors is new Ada.Containers.Vectors + (Positive, Accepted_Connection); + + procedure Accept_Connection + (Server : GNAT.Sockets.Socket_Type; + Accepted : in out Accepted_Connection_Vectors.Vector); + + procedure Read_Handshake (Item : in out Accepted_Connection); + + function Hash (Item : Torrent.Connections.Connection_Access) + return Ada.Containers.Hash_Type; + + package Connection_Sets is new Ada.Containers.Hashed_Sets + (Element_Type => Torrent.Connections.Connection_Access, + Hash => Hash, + Equivalent_Elements => Torrent.Connections.""="", + ""="" => Torrent.Connections.""=""); + + function ""+"" + (Value : Torrent.Connections.Connection_Access) + return System.Storage_Elements.Integer_Address; + + --------- + -- ""+"" -- + --------- + + function ""+"" + (Value : Torrent.Connections.Connection_Access) + return System.Storage_Elements.Integer_Address + is + package Conv is new System.Address_To_Access_Conversions + (Object => Torrent.Connections.Connection'Class); + begin + return System.Storage_Elements.To_Integer + (Conv.To_Address (Conv.Object_Pointer (Value))); + end ""+""; + + ----------------------- + -- Accept_Connection -- + ----------------------- + + procedure Accept_Connection + (Server : GNAT.Sockets.Socket_Type; + Accepted : in out Accepted_Connection_Vectors.Vector) + is + Address : GNAT.Sockets.Sock_Addr_Type; + Socket : GNAT.Sockets.Socket_Type; + begin + GNAT.Sockets.Accept_Socket (Server, Socket, Address); + + pragma Debug + (Torrent.Logs.Enabled, + Torrent.Logs.Print (""Accepted: "" & GNAT.Sockets.Image (Address))); + + GNAT.Sockets.Set_Socket_Option + (Socket => Socket, + Level => GNAT.Sockets.Socket_Level, + Option => (GNAT.Sockets.Receive_Timeout, 0.0)); + + Accepted.Append + ((Socket, + Last => 0, + Done => False, + Address => Address, + others => <>)); + end Accept_Connection; + + ---------- + -- Hash -- + ---------- + + function Hash (Item : Torrent.Connections.Connection_Access) + return Ada.Containers.Hash_Type is + begin + return Ada.Containers.Hash_Type'Mod (+Item); + end Hash; + + ---------- + -- Less -- + ---------- + + function Less (Left, Right : Planned_Connection) return Boolean is + use type Ada.Calendar.Time; + function ""+"" (V : GNAT.Sockets.Sock_Addr_Type) return String + renames GNAT.Sockets.Image; + + begin + return Left.Time < Right.Time + or else (Left.Time = Right.Time and +Left.Addr < +Right.Addr); + end Less; + + -------------------- + -- Read_Handshake -- + -------------------- + + procedure Read_Handshake (Item : in out Accepted_Connection) is + use Torrent.Handshakes; + use type Ada.Streams.Stream_Element; + Last : Ada.Streams.Stream_Element_Count; + Job : Torrent.Downloaders.Downloader_Access; + begin + GNAT.Sockets.Receive_Socket + (Item.Socket, + Item.Data (Item.Last + 1 .. Item.Data'Last), + Last); + + if Last <= Item.Last then + Item.Done := True; -- Connection closed + elsif Last = Item.Data'Last then + declare + Value : constant Handshake_Type := -Item.Data; + begin + Job := Context.Find_Download (Value.Info_Hash); + Item.Done := True; + + if Value.Length = Header'Length + and then Value.Head = Header + and then Job not in null + then + Item.Session := Job.Create_Session (Item.Address); + + Item.Session.Do_Handshake + (Item.Socket, Job.Completed, Inbound => True); + end if;" +procedure Check_Intrested;,"procedure Send_Initial_Requests; + function Get_Handshake + (Data : Ada.Streams.Stream_Element_Array) return Boolean; + + function Get_Length + (Data : Ada.Streams.Stream_Element_Array) + return Ada.Streams.Stream_Element_Offset; + + procedure Read_Messages + (Data : in out Ada.Streams.Stream_Element_Array; + Last : out Ada.Streams.Stream_Element_Count); + + procedure On_Message (Data : Ada.Streams.Stream_Element_Array); + + procedure Save_Piece + (Index : Piece_Index; + Offset : Natural; + Data : Ada.Streams.Stream_Element_Array); + + --------------------- + -- Check_Intrested -- + --------------------- + + procedure Check_Intrested is + begin + if not Self.We_Intrested + and then Self.Listener.We_Are_Intrested (Self.Piece_Map) + then + Self.Send_Message ((00, 00, 00, 01, 02)); -- interested + Self.We_Intrested := True; + end if; + end Check_Intrested; + + ------------------- + -- Get_Handshake -- + ------------------- + + function Get_Handshake + (Data : Ada.Streams.Stream_Element_Array) return Boolean + is + function ""+"" is new Ada.Unchecked_Conversion + (Handshake_Image, Handshake_Type); + + HS : constant Handshake_Type := +Data (1 .. Handshake_Image'Length); + begin + if HS.Length = Header'Length + and then HS.Head = Header + and then HS.Info_Hash = Self.Meta.Info_Hash + then + Self.Got_Handshake := True; + Self.Unparsed.Clear; + Self.Unparsed.Append + (Data (Handshake_Image'Length + 1 .. Data'Last)); + + return True; + else + return False; + end if; + end Get_Handshake; + + ---------------- + -- Get_Length -- + ---------------- + + function Get_Length + (Data : Ada.Streams.Stream_Element_Array) + return Ada.Streams.Stream_Element_Offset + is + subtype X is Ada.Streams.Stream_Element_Offset; + begin + return ((X (Data (Data'First)) * 256 + + X (Data (Data'First + 1))) * 256 + + X (Data (Data'First + 2))) * 256 + + X (Data (Data'First + 3)); + end Get_Length; + + ---------------- + -- On_Message -- + ---------------- + + procedure On_Message (Data : Ada.Streams.Stream_Element_Array) is + function Get_Int + (From : Ada.Streams.Stream_Element_Count := 0) return Natural + is (Get_Int (Data, From)); + + Index : Piece_Index; + begin + case Data (Data'First) is + when 0 => -- choke + pragma Debug + (Torrent.Logs.Enabled, + Torrent.Logs.Print + (GNAT.Sockets.Image (Self.Peer) & "" choke"")); + + Self.We_Choked := True; + Self.Unreserve_Intervals; + when 1 => -- unchoke + pragma Debug + (Torrent.Logs.Enabled, + Torrent.Logs.Print + (GNAT.Sockets.Image (Self.Peer) & "" unchoke"")); + + Self.We_Choked := False; + Send_Initial_Requests; + when 2 => -- interested + pragma Debug + (Torrent.Logs.Enabled, + Torrent.Logs.Print + (GNAT.Sockets.Image (Self.Peer) & "" interested"")); + + Self.He_Intrested := True; + when 3 => -- not interested + pragma Debug + (Torrent.Logs.Enabled, + Torrent.Logs.Print + (GNAT.Sockets.Image (Self.Peer) & "" not interested"")); + + Self.He_Intrested := False; + when 4 => -- have + + declare + Index : constant Piece_Index := + Piece_Index (Get_Int (1) + 1); + begin + if Index in Self.Piece_Map'Range then + pragma Debug + (Torrent.Logs.Enabled, + Torrent.Logs.Print + (GNAT.Sockets.Image (Self.Peer) + & "" have"" & (Index'Img))); + + Self.Piece_Map (Index) := True; + Check_Intrested; + end if;" +procedure Send_Initial_Requests is,"Length : Piece_Interval_Count; + begin + if Self.Current_Piece.Intervals.Is_Empty then + Self.Listener.Reserve_Intervals + (Map => Self.Piece_Map, + Value => Self.Current_Piece); + end if; + + Length := Piece_Interval_Count'Min + (Piece_Interval_Count'Last, + Self.Current_Piece.Intervals.Last_Index); + + Self.Pipelined := + (Length => Length, + Expire => (1 .. Length => Length * Expire_Loops), + Request => (Length, others => <>)); + + for J in 1 .. Length loop + declare + Last : constant Interval := + Self.Current_Piece.Intervals.Last_Element; + Index : constant Piece_Index := Self.Current_Piece.Piece; + Offset : constant Piece_Offset := Last.From; + Length : constant Piece_Offset := Last.To - Offset + 1; + begin + Self.Send_Message + ((00, 00, 00, 13, 06) & + To_Int (Natural (Index - 1)) & + To_Int (Natural (Offset)) & + To_Int (Natural (Length))); + + Self.Pipelined.Request.List (J) := + (Piece => Self.Current_Piece.Piece, + Span => (Offset, Last.To)); + + Self.Current_Piece.Intervals.Delete_Last;" +procedure Free is new Ada.Unchecked_Deallocation,"(Metainfo, Metainfo_Access); + + -------------- + -- Announce -- + -------------- + + not overriding function Announce + (Self : Metainfo_File) return League.IRIs.IRI is + begin + return Self.Data.Announce; + end Announce; + + ------------------- + -- Announce_List -- + ------------------- + + not overriding function Announce_List + (Self : Metainfo_File) return String_Vector_Array is + begin + return Self.Data.Announces; + end Announce_List; + + ---------------- + -- File_Count -- + ---------------- + + not overriding function File_Count (Self : Metainfo_File) return Positive is + begin + return Self.Data.File_Count; + end File_Count; + + ----------------- + -- File_Length -- + ----------------- + + not overriding function File_Length + (Self : Metainfo_File; + Index : Positive) return Ada.Streams.Stream_Element_Count is + begin + return Self.Data.Files (Index).Length; + end File_Length; + + --------------- + -- File_Path -- + --------------- + + not overriding function File_Path + (Self : Metainfo_File; + Index : Positive) return League.String_Vectors.Universal_String_Vector + is + begin + return Self.Data.Files (Index).Path; + end File_Path; + + -------------- + -- Finalize -- + -------------- + + procedure Finalize (Self : in out Metainfo_File) is + begin + Free (Self.Data); + end Finalize; + + --------------- + -- Info_Hash -- + --------------- + + not overriding function Info_Hash (Self : Metainfo_File) return SHA1 is + begin + return Self.Data.Info_Hash; + end Info_Hash; + + ----------------------- + -- Last_Piece_Length -- + ----------------------- + + not overriding function Last_Piece_Length + (Self : Metainfo_File) return Piece_Offset is + begin + return Self.Data.Last_Piece; + end Last_Piece_Length; + + ---------- + -- Name -- + ---------- + + not overriding function Name + (Self : Metainfo_File) return League.Strings.Universal_String is + begin + return Self.Data.Name; + end Name; + + ----------------- + -- Piece_Count -- + ----------------- + + not overriding function Piece_Count + (Self : Metainfo_File) return Piece_Index is + begin + return Self.Data.Piece_Count; + end Piece_Count; + + ------------------ + -- Piece_Length -- + ------------------ + + not overriding function Piece_Length + (Self : Metainfo_File) return Piece_Offset is + begin + return Self.Data.Piece_Length; + end Piece_Length; + + ---------------- + -- Piece_SHA1 -- + ---------------- + + not overriding function Piece_SHA1 + (Self : Metainfo_File; + Index : Piece_Index) return SHA1 + is + begin + return Self.Data.Hashes (Index); + end Piece_SHA1; + + ---------- + -- Read -- + ---------- + + not overriding procedure Read + (Self : in out Metainfo_File; + File_Name : League.Strings.Universal_String) + is + use type Ada.Streams.Stream_Element; + use type Ada.Streams.Stream_Element_Offset; + use type League.Strings.Universal_String; + + package File_Vectors is new Ada.Containers.Vectors + (Index_Type => Positive, + Element_Type => File_Information); + + package String_Vector_Vectors is new Ada.Containers.Vectors + (Index_Type => Positive, + Element_Type => League.String_Vectors.Universal_String_Vector, + ""="" => League.String_Vectors.""=""); + + function ""+"" + (Text : Wide_Wide_String) return League.Strings.Universal_String + renames League.Strings.To_Universal_String; + + function Parse_Top_Dictionary return Metainfo; + + procedure Parse_Int (Value : out Ada.Streams.Stream_Element_Offset); + + procedure Parse_String (Value : out League.Strings.Universal_String); + + procedure Parse_Pieces + (Value : out League.Stream_Element_Vectors.Stream_Element_Vector); + + procedure Parse_String_List + (Value : out League.String_Vectors.Universal_String_Vector); + + procedure Parse_String_Vector_Vector + (Value : out String_Vector_Vectors.Vector); + + procedure Skip_Value; + procedure Skip_List; + procedure Skip_Dictionary; + procedure Skip_String; + procedure Skip_Int; + + procedure Parse_Files (Value : out File_Vectors.Vector); + + procedure Expect (Char : Ada.Streams.Stream_Element); + + procedure Parse_File + (Path : out League.String_Vectors.Universal_String_Vector; + Length : out Ada.Streams.Stream_Element_Count); + + procedure Parse_Info + (Name : out League.Strings.Universal_String; + Piece_Len : out Ada.Streams.Stream_Element_Count; + Files : out File_Vectors.Vector; + Pieces : out League.Stream_Element_Vectors.Stream_Element_Vector); + + procedure Read_Buffer; + + subtype Digit is Ada.Streams.Stream_Element + range Character'Pos ('0') .. Character'Pos ('9'); + + Input : Ada.Streams.Stream_IO.File_Type; + Buffer : Ada.Streams.Stream_Element_Array (1 .. 1024); + Last : Ada.Streams.Stream_Element_Count := 0; + Next : Ada.Streams.Stream_Element_Count := 1; + Error : constant String := ""Can't parse torrent file.""; + SHA_From : Ada.Streams.Stream_Element_Count := Buffer'Last + 1; + Context : GNAT.SHA1.Context := GNAT.SHA1.Initial_Context; + Codec : constant League.Text_Codecs.Text_Codec := + League.Text_Codecs.Codec (+""utf-8""); + + package Constants is + Announce : constant League.Strings.Universal_String := +""announce""; + Files : constant League.Strings.Universal_String := +""files""; + Info : constant League.Strings.Universal_String := +""info""; + Length : constant League.Strings.Universal_String := +""length""; + Name : constant League.Strings.Universal_String := +""name""; + Path : constant League.Strings.Universal_String := +""path""; + Pieces : constant League.Strings.Universal_String := +""pieces""; + + Announce_List : constant League.Strings.Universal_String := + +""announce-list""; + Piece_Length : constant League.Strings.Universal_String := + +""piece length""; + end Constants; + + ----------------- + -- Read_Buffer -- + ----------------- + + procedure Read_Buffer is + begin + if SHA_From <= Last then + GNAT.SHA1.Update (Context, Buffer (SHA_From .. Last)); + + SHA_From := 1; + end if; + + Ada.Streams.Stream_IO.Read (Input, Buffer, Last); + Next := 1; + end Read_Buffer; + + ------------ + -- Expect -- + ------------ + + procedure Expect (Char : Ada.Streams.Stream_Element) is + begin + if Buffer (Next) = Char then + + Next := Next + 1; + + if Next > Last then + Read_Buffer; + end if; + else + raise Constraint_Error with Error; + end if; + end Expect; + + ---------------- + -- Parse_File -- + ---------------- + + procedure Parse_File + (Path : out League.String_Vectors.Universal_String_Vector; + Length : out Ada.Streams.Stream_Element_Count) + is + Key : League.Strings.Universal_String; + begin + Expect (Character'Pos ('d')); + + while Buffer (Next) /= Character'Pos ('e') loop + Parse_String (Key); + + if Key = Constants.Length then + Parse_Int (Length); + + elsif Key = Constants.Path then + Parse_String_List (Path); + + else + Skip_Value; + end if; + end loop; + + Expect (Character'Pos ('e')); + end Parse_File; + + ----------------- + -- Parse_Files -- + ----------------- + + procedure Parse_Files (Value : out File_Vectors.Vector) is + Path : League.String_Vectors.Universal_String_Vector; + Length : Ada.Streams.Stream_Element_Count; + begin + Value.Clear; + Expect (Character'Pos ('l')); + + while Buffer (Next) /= Character'Pos ('e') loop + Parse_File (Path, Length); + Value.Append ((Length, Path)); + end loop; + + Expect (Character'Pos ('e')); + end Parse_Files; + + ---------------- + -- Parse_Info -- + ---------------- + + procedure Parse_Info + (Name : out League.Strings.Universal_String; + Piece_Len : out Ada.Streams.Stream_Element_Count; + Files : out File_Vectors.Vector; + Pieces : out League.Stream_Element_Vectors.Stream_Element_Vector) + is + Key : League.Strings.Universal_String; + Length : Ada.Streams.Stream_Element_Count := 0; + begin + Files.Clear; + SHA_From := Next; -- Activate SHA1 calculation + Expect (Character'Pos ('d')); + + while Buffer (Next) /= Character'Pos ('e') loop + Parse_String (Key); + + if Key = Constants.Name then + declare + Path : League.String_Vectors.Universal_String_Vector; + begin + Parse_String (Name); + + if Length > 0 then + -- There is a key length or a key files, but not both + -- or neither. If length is present then the download + -- represents a single file, otherwise it represents a + -- set of files which go in a directory structure. + + Path.Append (Name); + Files.Append ((Length, Path)); + end if;" +procedure Parse_String_List,"(Value : out League.String_Vectors.Universal_String_Vector) + is + Text : League.Strings.Universal_String; + begin + Value.Clear; + Expect (Character'Pos ('l')); + + while Buffer (Next) /= Character'Pos ('e') loop + Parse_String (Text); + Value.Append (Text); + end loop; + + Expect (Character'Pos ('e')); + end Parse_String_List; + + -------------------------------- + -- Parse_String_Vector_Vector -- + -------------------------------- + + procedure Parse_String_Vector_Vector + (Value : out String_Vector_Vectors.Vector) + is + Item : League.String_Vectors.Universal_String_Vector; + begin + Value.Clear; + Expect (Character'Pos ('l')); + + while Buffer (Next) /= Character'Pos ('e') loop + Parse_String_List (Item); + Value.Append (Item); + end loop; + + Expect (Character'Pos ('e')); + end Parse_String_Vector_Vector; + + --------------------- + -- Skip_Dictionary -- + --------------------- + + procedure Skip_Dictionary is + Key : League.Strings.Universal_String; + begin + Expect (Character'Pos ('d')); + + while Buffer (Next) /= Character'Pos ('e') loop + Parse_String (Key); + Skip_Value; + end loop; + + Expect (Character'Pos ('e')); + + end Skip_Dictionary; + + -------------- + -- Skip_Int -- + -------------- + + procedure Skip_Int is + begin + Expect (Character'Pos ('i')); + + if Buffer (Next) = Character'Pos ('-') then + Expect (Buffer (Next)); + end if; + + while Buffer (Next) in Digit loop + Expect (Buffer (Next)); + end loop; + + Expect (Character'Pos ('e')); + end Skip_Int; + + --------------- + -- Skip_List -- + --------------- + + procedure Skip_List is + begin + Expect (Character'Pos ('l')); + + while Buffer (Next) /= Character'Pos ('e') loop + Skip_Value; + end loop; + + Expect (Character'Pos ('e')); + end Skip_List; + + ----------------- + -- Skip_String -- + ----------------- + + procedure Skip_String is + Len : Ada.Streams.Stream_Element_Count := 0; + begin + while Buffer (Next) in Digit loop + Len := Len * 10 + + Ada.Streams.Stream_Element_Count (Buffer (Next)) + - Character'Pos ('0'); + + Expect (Buffer (Next)); + end loop; + + declare + To : Ada.Streams.Stream_Element_Count := 0; + begin + Expect (Character'Pos (':')); + + while Last - Next + 1 <= Len loop + To := To + Last - Next + 1; + Len := Len - (Last - Next + 1); + Read_Buffer; + end loop; + + if Len > 0 then + Next := Next + Len; + end if;" +procedure AgenTests is,"begin + Testing.Start(""Agen""); + + declare + Param : Parameter; + begin + Is_Equal(""Try_Parse(""""name:string"""")"", Try_Parse(""name:string"", Param), True); + Is_Equal(""Parameter"", Param, ""name"", ""string"");" +procedure Help is,"begin + Put_Line("" (func|function) name:return_type [parameter:type]* - Print the generated function""); + end Help; + + function Try_Act return Boolean is + Func : Parameter; + begin + if Argument_Stack.Is_Empty then goto Fail; end if; + declare + Action : constant String := Argument_Stack.Pop; + begin + if To_Upper(Action) /= ""FUNC"" and To_Upper(Action) /= ""FUNCTION"" then + goto Fail; + end if;" +procedure Help is,"begin + Put_Line("" (new|init)""); + Put_Line("" project - create a project from a basic template""); + Put_Line("" gpr - create a GPR from a basic template""); + end Help; + + function Try_Act return Boolean is + begin + if Argument_Stack.Is_Empty then goto Fail; end if; + declare + Action : constant String := Argument_Stack.Pop; + begin + if To_Upper(Action) /= ""NEW"" and To_Upper(Action) /= ""INIT"" then + goto Fail; + end if;" +procedure Help is,"begin + Put_Line("" (cmm|comment)""); + Put_Line("" (desc|description) - Print a description doc comment""); + Put_Line("" (ex|exception) - Print an exception doc comment""); + Put_Line("" field - Print a field doc comment""); + Put_Line("" param - Print a param doc comment""); + Put_Line("" (ret|return) - Prints a return doc comment""); + Put_Line("" (summ|summary) - Print a summary doc comment""); + Put_Line("" value - Print a value doc comment""); + end Help; + + function Try_Act return Boolean is + begin + if Argument_Stack.Is_Empty then goto Fail; end if; + declare + Action : constant String := Argument_Stack.Pop; + begin + if To_Upper(Action) /= ""CMM"" and To_Upper(Action) /= ""COMMENT"" then + goto Fail; + end if;" +procedure Help is,"begin + Put_Line("" (proc|procedure) [parameter:type]* - Print the generated procedure""); + end Help; + + function Try_Act return Boolean is + begin + if Argument_Stack.Is_Empty then goto Fail; end if; + declare + Action : constant String := Argument_Stack.Pop; + begin + if To_Upper(Action) /= ""PROC"" and To_Upper(Action) /= ""PROCEDURE"" then + goto Fail; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Index_Impl, Index_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Index_Impl_Ptr := Index_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + overriding + procedure Find (Object : in out Index_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, INDEX_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Index_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + overriding + procedure Save (Object : in out Index_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (INDEX_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_1_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Document_Impl, Document_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Document_Impl_Ptr := Document_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + overriding + procedure Find (Object : in out Document_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, DOCUMENT_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Document_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + overriding + procedure Save (Object : in out Document_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (DOCUMENT_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_2_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_2_NAME, -- index_id + Value => Object.Index); + Object.Clear_Modified (2); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Field_Impl, Field_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Field_Impl_Ptr := Field_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + overriding + procedure Find (Object : in out Field_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, FIELD_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Field_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + overriding + procedure Save (Object : in out Field_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (FIELD_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_3_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (4) then + Stmt.Save_Field (Name => COL_3_3_NAME, -- document_id + Value => Object.Document); + Object.Clear_Modified (4); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Sequence_Impl, Sequence_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Sequence_Impl_Ptr := Sequence_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + overriding + procedure Find (Object : in out Sequence_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, SEQUENCE_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Sequence_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""field = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + overriding + procedure Save (Object : in out Sequence_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (SEQUENCE_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_4_NAME, -- positions + Value => Object.Positions); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (2) then + Stmt.Save_Field (Name => COL_1_4_NAME, -- token + Value => Object.Token); + Object.Clear_Modified (2); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_4_NAME, -- field + Value => Object.Get_Key); + Object.Clear_Modified (3); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""field = ? AND token = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + Stmt.Add_Param (Value => Object.Token); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Unchecked_Free is new Ada.Unchecked_Deallocation,"(Token_Impl, Token_Impl_Ptr); + pragma Warnings (Off, ""*redundant conversion*""); + Ptr : Token_Impl_Ptr := Token_Impl (Object.all)'Access; + pragma Warnings (On, ""*redundant conversion*""); + begin + Unchecked_Free (Ptr); + end Destroy; + + overriding + procedure Find (Object : in out Token_Impl; + Session : in out ADO.Sessions.Session'Class; + Query : in ADO.SQL.Query'Class; + Found : out Boolean) is + Stmt : ADO.Statements.Query_Statement + := Session.Create_Statement (Query, TOKEN_DEF'Access); + begin + Stmt.Execute; + if Stmt.Has_Elements then + Object.Load (Stmt, Session); + Stmt.Next; + Found := not Stmt.Has_Elements; + else + Found := False; + end if; + end Find; + + overriding + procedure Load (Object : in out Token_Impl; + Session : in out ADO.Sessions.Session'Class) is + Found : Boolean; + Query : ADO.SQL.Query; + Id : constant ADO.Identifier := Object.Get_Key_Value; + begin + Query.Bind_Param (Position => 1, Value => Id); + Query.Set_Filter (""id = ?""); + Object.Find (Session, Query, Found); + if not Found then + raise ADO.Objects.NOT_FOUND; + end if; + end Load; + + overriding + procedure Save (Object : in out Token_Impl; + Session : in out ADO.Sessions.Master_Session'Class) is + Stmt : ADO.Statements.Update_Statement + := Session.Create_Statement (TOKEN_DEF'Access); + begin + if Object.Is_Modified (1) then + Stmt.Save_Field (Name => COL_0_5_NAME, -- id + Value => Object.Get_Key); + Object.Clear_Modified (1); + end if; + if Object.Is_Modified (3) then + Stmt.Save_Field (Name => COL_2_5_NAME, -- index_id + Value => Object.Index); + Object.Clear_Modified (3); + end if; + if Stmt.Has_Save_Fields then + Stmt.Set_Filter (Filter => ""id = ?""); + Stmt.Add_Param (Value => Object.Get_Key); + declare + Result : Integer; + begin + Stmt.Execute (Result); + if Result /= 1 then + if Result /= 0 then + raise ADO.Objects.UPDATE_ERROR; + end if; + end if;" +procedure Indexer is,"Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (""Indexer""); + + Factory : ADO.Sessions.Factory.Session_Factory; + Count : constant Natural := Ada.Command_Line.Argument_Count; +begin + ADO.SQLite.Initialize; + Factory.Create (""sqlite:///search.db?synchronous=OFF&encoding='UTF-8'""); + + if Count < 1 then + Ada.Text_IO.Put_Line (""Usage: indexer file...""); + return; + end if; + declare + DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; + Indexer : Search.Indexers.Databases.Indexer_Type; + Analyzer : Search.Analyzers.French.Analyzer_Type; + Tokenizer : Search.Tokenizers.Tokenizer_Type; + begin + Indexer.Initialize (DB, ADO.NO_IDENTIFIER); + for I in 1 .. Count loop + declare + Path : constant String := Ada.Command_Line.Argument (I); + Doc : Search.Documents.Document_Type; + begin + Doc.Add_Field (""path"", Path, Search.Fields.F_PATH); + Indexer.Add_Document (Doc, Analyzer, Tokenizer);" +procedure Finder is,"Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (""Indexer""); + + Factory : ADO.Sessions.Factory.Session_Factory; + Count : constant Natural := Ada.Command_Line.Argument_Count; +begin + ADO.SQLite.Initialize; + Factory.Create (""sqlite:///search.db?synchronous=OFF&encoding='UTF-8'""); + + if Count < 1 then + Ada.Text_IO.Put_Line (""Usage: finder query...""); + return; + end if; + declare + DB : ADO.Sessions.Master_Session := Factory.Get_Master_Session; + Indexer : Search.Indexers.Databases.Indexer_Type; + Analyzer : Search.Analyzers.French.Analyzer_Type; + Tokenizer : Search.Tokenizers.Tokenizer_Type; + begin + Indexer.Initialize (DB, ADO.NO_IDENTIFIER); + for I in 1 .. Count loop + declare + Query : constant String := Ada.Command_Line.Argument (I); + Result : Search.Results.Result_Vector; + begin + Indexer.Find (Query, Analyzer, Tokenizer, Result); + for Item of Result loop + declare + Doc : Search.Documents.Document_Type; + Field : Search.Fields.Field_Type; + begin + Indexer.Load (Doc, Item.Doc_Id); + Field := Doc.Get_Field (""path""); + Ada.Text_IO.Put_Line (Search.Fields.Get_Value (Field));" +"procedure Remove_Node is new Ada.Unchecked_Deallocation (Node_Type, Node_Access_Type);","procedure Remove_List is new Ada.Unchecked_Deallocation (List_Header_Type, List_Header_Access_Type); + +--------------------------------------------------------------------- + function Initialise return List_Header_Access_Type is + + Temp_Entry: List_Header_Access_Type; + + begin + -- + -- allocate new memory for the header information + -- + Temp_Entry := new List_Header_Type; + -- + -- and set the fields up. These could be replaced by default values in the + -- record declaration. + -- + Temp_Entry.First_Entry := null; + Temp_Entry.Count := 0; + Temp_Entry.Free_List := null; + Temp_Entry.Free_List_Count := 0; + + -- DEFECT 262 set Stepping_Pointer to null. + Temp_Entry.Stepping_Pointer := null; + + return Temp_Entry; + + end Initialise; + + --------------------------------------------------------------------- + + function Count_Of (Target_List : List_Header_Access_Type) return Application_Types.Base_Integer_Type is + begin + return Target_List.Count; + end Count_Of; + + --------------------------------------------------------------------- + + function Count_Of_Free_List (Target_List : List_Header_Access_Type) return Application_Types.Base_Integer_Type is + begin + return Target_List.Free_List_Count; + end Count_Of_Free_List; + + --------------------------------------------------------------------- + + function Max_Count_Of (Target_List : List_Header_Access_Type) return Application_Types.Base_Integer_Type is + begin + return Target_List.Max_Count; + end Max_Count_Of; + + --------------------------------------------------------------------- + + function First_Entry_Of (Target_List : List_Header_Access_Type) return Node_Access_Type is + begin + Target_List.Stepping_Pointer := Target_List.First_Entry; + return Target_List.Stepping_Pointer; + end First_Entry_Of; + + --------------------------------------------------------------------- + + function Next_Entry_Of (Target_List : List_Header_Access_Type) return Node_Access_Type is + begin + Target_List.Stepping_Pointer := Target_List.Stepping_Pointer.Next; + return Target_List.Stepping_Pointer; + end Next_Entry_Of; + + --------------------------------------------------------------------- + + procedure Insert (New_Item : in Element_Type; + On_To : in List_Header_Access_Type) is + + New_Cell: Node_Access_Type; + + begin + + if On_To.Free_List = null then + -- + -- there are no 'old' entries available for reuse + -- + begin + New_Cell:= new Node_Type; + + exception + when Storage_Error => raise List_Storage_Error ;" +procedure Register_M1_End_Class (M1_Instance: in Ada.Tags.Tag) is,"begin + M1_Side := M1_Instance; + M1_Single_M2_Multiple.Register_Single_End_Class (M1_Instance); + M2_Single_M1_Multiple.Register_Multiple_End_Class (M1_Instance); + end Register_M1_End_Class; + +--------------------------------------------------------------------- + + function Report_M1_End_Class return Ada.Tags.Tag is + begin + return M1_Side; + end Report_M1_End_Class; + +----------------------------------------------------------------------- + + procedure Register_M2_End_Class (M2_Instance: in Ada.Tags.Tag) is + begin + M2_Side := M2_Instance; + M1_Single_M2_Multiple.Register_Multiple_End_Class (M2_Instance); + M2_Single_M1_Multiple.Register_Single_End_Class (M2_Instance); + end Register_M2_End_Class; + +--------------------------------------------------------------------- + + function Report_M2_End_Class return Ada.Tags.Tag is + begin + return M2_Side; + end Report_M2_End_Class; + +----------------------------------------------------------------------- + + procedure Register_Associative_End_Class (Associative_Instance: in Ada.Tags.Tag) is + begin + Associative_Side := Associative_Instance; + M1_Single_M2_Multiple.Register_Associative_End_Class (Associative_Instance); + M2_Single_M1_Multiple.Register_Associative_End_Class (Associative_Instance); + end Register_Associative_End_Class; + +--------------------------------------------------------------------- + + function Report_Associative_End_Class return Ada.Tags.Tag is + begin + return Associative_Side; + end Report_Associative_End_Class; + +--------------------------------------------------------------------- + + procedure Link ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access; + Using : in Root_Object.Object_Access) is + + begin + + M1_Single_M2_Multiple.Link ( + A_Instance => A_Instance, + B_Instance => B_Instance, + Using => Using); + + M2_Single_M1_Multiple.Link ( + A_Instance => A_Instance, + B_Instance => B_Instance, + Using => Using); + + end Link; +----------------------------------------------------------------------- + procedure Unassociate ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access; + From : in Root_Object.Object_Access) is + + begin + + M1_Single_M2_Multiple.Unassociate ( + A_Instance => A_Instance, + B_Instance => B_Instance, + From => From); + + M2_Single_M1_Multiple.Unassociate ( + A_Instance => B_Instance, + B_Instance => A_Instance, + From => From); + + end Unassociate; + +----------------------------------------------------------------------- + + procedure Unlink ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access) is + + begin + + M1_Single_M2_Multiple.Unlink ( + A_Instance => A_Instance, + B_Instance => B_Instance); + + M2_Single_M1_Multiple.Unlink ( + A_Instance => B_Instance, + B_Instance => A_Instance); + + end Unlink; + +----------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_List.List_Header_Access_Type; + Class : in Ada.Tags.Tag; + To : in Root_Object.Object_List.List_Header_Access_Type) is + + The_A_Instance: Root_Object.Object_Access; + + begin + + The_A_Instance := Root_Object.Object_List.First_Entry_Of (From).Item; + + if The_A_Instance /= null then + + if The_A_Instance.all'tag = M1_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif The_A_Instance.all'tag = M2_Side then + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif The_A_Instance.all'tag = Associative_Side then + + if Class = M2_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif Class = M1_Side then + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + end if; + + end if; + + end if; + + + end Navigate; + +--------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : in Root_Object.Object_List.List_Header_Access_Type) is + -- + -- navigate from a single to a set + -- valid for: + -- M1 -> M2 + -- M1 -> A + -- M2 -> M1 + -- M2 -> A + -- + begin + + if From.all'tag = M1_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif From.all'tag = M2_Side then + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif From.all'tag = Associative_Side then + + if Class = M2_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif Class = M1_Side then + + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + end if; + + end if; + + end Navigate; + +--------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : out Root_Object.Object_Access) is + -- + -- navigate from a single to a single + -- valid for: + -- A -> M1 + -- A -> M2 + -- + begin + + if From.all'tag = Associative_Side then + + if Class = M2_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif Class = M1_Side then + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + end if; + + end if; + + + end Navigate; + +--------------------------------------------------------------------- + + + -- associative correlated navigation + procedure Navigate ( + From : in Root_Object.Object_Access; + Also : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : out Root_Object.Object_Access) is + + -- + -- navigate from two singles to a single + -- valid for: + -- M1 and M2 -> A + -- M1 and M2 -> A + + Temp_Associative_One, Temp_Associative_Two : Root_Object.Object_Access := null; + + Assoc_Set_One : Root_Object.Object_List.List_Header_Access_Type := Root_Object.Object_List.Initialise; + Assoc_Set_Two : Root_Object.Object_List.List_Header_Access_Type := Root_Object.Object_List.Initialise; + + Matched, Inner_Matched : Boolean := FALSE; + + begin + + -- Reset the output pointer to null so that if we don't find anything + -- useful, the caller can check for it. + To := null; + + if ((( From.all'tag = M1_Side) and then + ( Also.all'Tag = M2_Side)) + or else (( From.all'tag = M2_Side) and then + ( Also.all'Tag = M1_Side))) + then + + -- Navigate from single instance of first object + -- returns a set. + Navigate ( + From => Also, + Class => Class, + To => Assoc_Set_One); + + -- Navigate from single instance of second object + -- returns a set. + Navigate ( + From => From, + Class => Class, + To => Assoc_Set_Two); + + -- Compare results of the two sets from the above navigations. + -- A nice simple find operation on a set would be appropriate here, but + -- there isn't one available, so do it the hard way. + + -- Outer loop + declare + use type Root_Object.Object_List.Node_Access_Type; + Temp_Entry : Root_Object.Object_List.Node_Access_Type; + Matched : boolean := FALSE; + begin + -- Grab the first entry of the set + Temp_Entry := Root_Object.Object_List.First_Entry_Of(Assoc_Set_One); + -- While the set is not empty and the entry does not match the + -- assoc instance already found, burn rubber + + while (not Matched) and (Temp_Entry /= null) loop + + Temp_Associative_One := Temp_Entry.Item; + -- Compare this entry against the other set. + + -- Inner loop + declare + use type Root_Object.Object_List.Node_Access_Type; + Inner_Temp_Entry : Root_Object.Object_List.Node_Access_Type; + begin + + -- Grab the first entry of the set + Inner_Temp_Entry := Root_Object.Object_List.First_Entry_Of(Assoc_Set_Two); + + -- While the set is not empty and the entry does not match the + -- assoc instance already found, smoke 'em + + while (not matched) and (Inner_Temp_Entry /= null) loop + + Temp_Associative_Two := Inner_Temp_Entry.Item; + -- If M-M:M associative was ever implemented, + -- it would be easy to add the matched instance into a set for + -- return from this procedure. + + Matched := Temp_Associative_One = Temp_Associative_Two; + + if not Matched then + Inner_Temp_Entry := Root_Object.Object_List.Next_Entry_Of(Assoc_Set_Two); + end if; + + end loop; -- end of (Temp_Entry /= null) or else Matched loop" +procedure Remove_Pair is new Ada.Unchecked_Deallocation (,"Relationship_Pair_Type, Relationship_Pair_Access_Type); + + -- + -- 'Major' element + -- + type Relationship_Entry_Type; + type Relationship_Entry_Access_Type is access all Relationship_Entry_Type; + + type Relationship_Entry_Type is record + Single : Root_Object.Object_Access; + Completion_List : Relationship_Pair_Access_Type; + Next : Relationship_Entry_Access_Type; + Previous : Relationship_Entry_Access_Type; + end record; + + procedure Remove_Entry is new Ada.Unchecked_Deallocation ( + Relationship_Entry_Type, Relationship_Entry_Access_Type); + + ------------------------------------------------------------------------ + The_Relationship_List: Relationship_Entry_Access_Type; + + + subtype Role_Phrase_Type is string (1 .. Application_Types.Maximum_Number_Of_Characters_In_String); + + Multiple_Side : Ada.Tags.Tag; + Multiple_Side_Role : Role_Phrase_Type; + Multiple_Side_Role_Length : Natural; + + Single_Side : Ada.Tags.Tag; + Single_Side_Role : Role_Phrase_Type; + Single_Side_Role_Length : Natural; + + Associative_Side : Ada.Tags.Tag; + Associative_Side_Role : Role_Phrase_Type; + Associative_Side_Role_Length : Natural; + -- + -- A = LEFT = MULTIPLE + -- B = RIGHT = SINGLE + -- + ------------------------------------------------------------------------ + procedure Check_List_For_Multiple ( + Multiple_Instance : in Root_Object.Object_Access; + Associative_Instance : out Root_Object.Object_Access; + Single_Instance : out Root_Object.Object_Access; + Multiple_Instance_Found : out Boolean) is + + Temp_Minor_Pointer : Relationship_Pair_Access_Type; + Temp_Major_Pointer : Relationship_Entry_Access_Type; + + begin + + + Multiple_Instance_Found := False; + Temp_Major_Pointer := The_Relationship_List; + + Major_Loop: + while (not Multiple_Instance_Found) and then Temp_Major_Pointer /= null loop + + Temp_Minor_Pointer := Temp_Major_Pointer.Completion_List; + + Minor_Loop: + while (not Multiple_Instance_Found) and then Temp_Minor_Pointer /= null loop + + Multiple_Instance_Found := (Temp_Minor_Pointer.Multiple = Multiple_Instance); + + if Multiple_Instance_Found then + Associative_Instance := Temp_Minor_Pointer.Associative; + Single_Instance := Temp_Major_Pointer.Single; + else + -- Prevent access if we have got what we are after + -- Bailing out of the search loop is a neater solution, but test team defects + -- have been raised against this sort of thing. + Temp_Minor_Pointer := Temp_Minor_Pointer.Next; + end if; + + end loop Minor_Loop; + + -- Prevent the possibility that the next entry in the major queue is null causing an access error + if not Multiple_Instance_Found then + Temp_Major_Pointer := Temp_Major_Pointer.Next; + end if; + + end loop Major_Loop; + + end Check_List_For_Multiple; + + ------------------------------------------------------------------------ + procedure Check_List_For_Associative ( + Associative_Instance : in Root_Object.Object_Access; + Multiple_Instance : out Root_Object.Object_Access; + Single_Instance : out Root_Object.Object_Access; + Associative_Instance_Found : out Boolean) is + + Temp_Minor_Pointer : Relationship_Pair_Access_Type; + Temp_Major_Pointer : Relationship_Entry_Access_Type; + + begin + + Associative_Instance_Found := False; + Temp_Major_Pointer := The_Relationship_List; + + Major_Loop: + while (not Associative_Instance_Found) and then Temp_Major_Pointer /= null loop + + Temp_Minor_Pointer := Temp_Major_Pointer.Completion_List; + + Minor_Loop: + while (not Associative_Instance_Found) and then Temp_Minor_Pointer /= null loop + + Associative_Instance_Found := (Temp_Minor_Pointer.Associative = Associative_Instance); + + if Associative_Instance_Found then + Multiple_Instance := Temp_Minor_Pointer.Multiple; + Single_Instance := Temp_Major_Pointer.Single; + else + -- Prevent access if we have got what we are after + -- Bailing out of the search loop is a neater solution, but test team defects + -- have been raised against this sort of thing. + Temp_Minor_Pointer := Temp_Minor_Pointer.Next; + end if; + + end loop Minor_Loop; + + -- Prevent the possibility that the next entry in the major queue is null causing an access error + if not Associative_Instance_Found then + Temp_Major_Pointer := Temp_Major_Pointer.Next; + end if; + + end loop Major_Loop; + + end Check_List_For_Associative; + + ----------------------------------------------------------------------- + + procedure Do_Link ( + Multiple_Instance : in Root_Object.Object_Access; + Single_Instance : in Root_Object.Object_Access; + Associative_Instance : in Root_Object.Object_Access) is + + Temp_Minor_Pointer : Relationship_Pair_Access_Type; + Temp_Major_Pointer : Relationship_Entry_Access_Type; + Found : Boolean := False; + + begin + Temp_Major_Pointer := The_Relationship_List; + + while (not Found) and then Temp_Major_Pointer /= null loop + + Found := (Temp_Major_Pointer.Single = Single_Instance); + + if not Found then -- grab the next item + Temp_Major_Pointer := Temp_Major_Pointer.Next; + end if; + + end loop; + + if not Found then + Temp_Major_Pointer := new Relationship_Entry_Type; + Temp_Major_Pointer.Single := Single_Instance; + Temp_Major_Pointer.Completion_List := null; + Temp_Major_Pointer.Previous := null; + Temp_Major_Pointer.Next := The_Relationship_List; + + if The_Relationship_List /= null then + The_Relationship_List.Previous := Temp_Major_Pointer; + end if; + + The_Relationship_List := Temp_Major_Pointer; + + end if; + + Temp_Minor_Pointer := new Relationship_Pair_Type; + Temp_Minor_Pointer.Multiple := Multiple_Instance; + Temp_Minor_Pointer.Associative := Associative_Instance; + Temp_Minor_Pointer.Previous := null; + Temp_Minor_Pointer.Next := Temp_Major_Pointer.Completion_List; + + if Temp_Major_Pointer.Completion_List /= null then + Temp_Major_Pointer.Completion_List.Previous := Temp_Minor_Pointer; + end if; + + Temp_Major_Pointer.Completion_List := Temp_Minor_Pointer; + + end Do_Link; + + ----------------------------------------------------------------------- + + procedure Do_Unlink ( + Left_Instance : in Root_Object.Object_Access; + Right_Instance : in Root_Object.Object_Access) is + + Temp_Minor_Pointer : Relationship_Pair_Access_Type; + Temp_Major_Pointer : Relationship_Entry_Access_Type; + Delete_List : Boolean := False; + + begin + + Temp_Major_Pointer := The_Relationship_List; + + Major_Loop: + while Temp_Major_Pointer /= null loop + + if Temp_Major_Pointer.Single = Left_Instance then + Temp_Minor_Pointer := Temp_Major_Pointer.Completion_List; + + Minor_Loop: + while Temp_Minor_Pointer /= null loop + if Temp_Minor_Pointer.Multiple = Right_Instance then + if Temp_Minor_Pointer.Previous = null then + -- + -- first instance in list + -- + Temp_Major_Pointer.Completion_List := Temp_Minor_Pointer.Next; + -- + -- it's also the last and only instance in list + -- So we're going to delete the whole relationship instance + -- (but not just yet) + -- + Delete_List := (Temp_Minor_Pointer.Next = null); + + end if; + + if Temp_Minor_Pointer.Next /= null then + -- + -- there are more instances following in the list + -- + Temp_Minor_Pointer.Next.Previous := Temp_Minor_Pointer.Previous; + end if; + + if Temp_Minor_Pointer.Previous /= null then + -- + -- there are more instances previous in the list + -- + Temp_Minor_Pointer.Previous.Next := Temp_Minor_Pointer.Next; + end if; + + Remove_Pair (Temp_Minor_Pointer); + exit Major_Loop; + + end if; + + Temp_Minor_Pointer := Temp_Minor_Pointer.Next; + + end loop Minor_Loop; + + end if; + + Temp_Major_Pointer := Temp_Major_Pointer.Next; + + end loop Major_Loop; + -- + -- if needed, now delete the list + -- the same logic applies + -- + if Delete_List then + + if Temp_Major_Pointer.Previous = null then + -- + -- first instance in list + -- + The_Relationship_List := Temp_Major_Pointer.Next; + end if; + + if Temp_Major_Pointer.Next /= null then + -- + -- there are more instances following in the list + -- + Temp_Major_Pointer.Next.Previous := Temp_Major_Pointer.Previous; + end if; + + if Temp_Major_Pointer.Previous /= null then + -- + -- there are more instances previous in the list + -- + Temp_Major_Pointer.Previous.Next := Temp_Major_Pointer.Next; + end if; + + Remove_Entry (Temp_Major_Pointer); + + end if; + + end Do_Unlink; + + ------------------------------------------------------------------------- + procedure Register_Multiple_End_Class (Multiple_Instance : in Ada.Tags.Tag) is + begin + Multiple_Side := Multiple_Instance; + end Register_Multiple_End_Class; + + --------------------------------------------------------------------- + procedure Register_Multiple_End_Role (Multiple_Role : in String) is + begin + Multiple_Side_Role (1 .. Multiple_Role'Length) := Multiple_Role; + Multiple_Side_Role_Length := Multiple_Role'Length; + end Register_Multiple_End_Role; + + --------------------------------------------------------------------- + + procedure Register_Single_End_Class (Single_Instance : in Ada.Tags.Tag) is + begin + Single_Side := Single_Instance; + end Register_Single_End_Class; + + --------------------------------------------------------------------- + + procedure Register_Single_End_Role (Single_Role : in String) is + begin + + Single_Side_Role (1..Single_Role'Length) := Single_Role; + Single_Side_Role_Length := Single_Role'Length; + end Register_Single_End_Role; + + --------------------------------------------------------------------- + + procedure Register_Associative_End_Class (Associative_Instance : in Ada.Tags.Tag) is + begin + Associative_Side := Associative_Instance; + end Register_Associative_End_Class; + + --------------------------------------------------------------------- + + procedure Register_Associative_End_Role (Associative_Role : in String) is + begin + Associative_Side_Role (1 .. Associative_Role'Length) := Associative_Role; + Associative_Side_Role_Length := Associative_Role'Length; + end Register_Associative_End_Role; + + --------------------------------------------------------------------- + + procedure Link ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access; + Using : in Root_Object.Object_Access) is + + begin + + if Using.all'Tag = Associative_Side then + + if A_Instance.all'Tag = Multiple_Side then + + Do_Link ( + Multiple_Instance => A_Instance, + Single_Instance => B_Instance, + Associative_Instance => Using); + -- + -- PILOT_0000_0423 Include diagnostic references. + -- + Application_Types.Count_Of_Relationships := Application_Types.Count_Of_Relationships + 1; + + elsif A_Instance.all'Tag = Single_Side then + + Do_Link ( + Multiple_Instance => B_Instance, + Single_Instance => A_Instance, + Associative_Instance => Using); + -- + -- PILOT_0000_0423 Include diagnostic references. + -- + Application_Types.Count_Of_Relationships := Application_Types.Count_Of_Relationships + 1; + + end if; + end if; -- Using.all'tag /= Associative_Side + + end Link; + + ----------------------------------------------------------------------- + + procedure Unassociate ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access; + From : in Root_Object.Object_Access) is + begin + null; + end Unassociate; + + ----------------------------------------------------------------------- + + procedure Unlink ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access) is + + begin + + if A_Instance.all'Tag = Multiple_Side then + + Do_Unlink ( + Left_Instance => B_Instance, + Right_Instance => A_Instance); + -- + -- PILOT_0000_0423 Include diagnostic references. + -- + Application_Types.Count_Of_Relationships := Application_Types.Count_Of_Relationships - 1; + + elsif A_Instance.all'Tag = Single_Side then + -- + Do_Unlink ( + Left_Instance => A_Instance, + Right_Instance => B_Instance); + -- + -- PILOT_0000_0423 Include diagnostic references. + -- + Application_Types.Count_Of_Relationships := Application_Types.Count_Of_Relationships - 1; + + end if; + + end Unlink; + + ----------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_List.List_Header_Access_Type; + Class : in Ada.Tags.Tag; + To : in Root_Object.Object_List.List_Header_Access_Type) is + + Source_Instance: Root_Object.Object_Access; + Temp_Node: Root_Object.Object_List.Node_Access_Type; + Temp_Instance: Root_Object.Object_Access; + --Temp_Single: Root_Object.Object_Access; + --Temp_Associative: Root_Object.Object_Access; + --Temp_Multiple: Root_Object.Object_Access; + + begin + + Temp_Node := Root_Object.Object_List.First_Entry_Of (From); + + while Temp_Node /= null loop + + Source_Instance := Temp_Node.Item; + + if Source_Instance.all'Tag = Multiple_Side then + + Navigate ( + From => Source_Instance, + Class => Class, + To => Temp_Instance); + + if Temp_Instance /= null then + + Root_Object.Object_List.Insert ( + New_Item => Temp_Instance, + On_To => To ); + + end if; + -- + elsif Source_Instance.all'Tag = Single_Side then + + Navigate ( + From => Source_Instance, + Class => Class, + To => To); + -- + + elsif Source_Instance.all'Tag = Associative_Side then + + Navigate ( + From => Source_Instance, + Class => Class, + To => Temp_Instance); + + if Temp_Instance /= null then + + Root_Object.Object_List.Insert ( + New_Item => Temp_Instance, + On_To => To ); + + end if; + -- + + end if; + + Temp_Node := Root_Object.Object_List.Next_Entry_Of (From); + + end loop; + + end Navigate; + + ----------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : out Root_Object.Object_Access) is + + -- + -- navigate from a single to a single + -- valid for: + -- A -> M + -- A -> S + -- M -> S + -- M -> A + -- + Temp_Single: Root_Object.Object_Access; + Temp_Associative: Root_Object.Object_Access; + Temp_Multiple: Root_Object.Object_Access; + Found: Boolean; + + begin + + -- PILOT_0000_1422 + -- Defaulting the return parameter ensures that if an attempt + -- is made to navigate this type of one to many associative + -- without having linked it, the correct null parameter is + -- returned. This relationship mechanism relies on the link + -- operation to sort out all the tags. We can't rely on that + -- happening in all cases. + To := null; + + if From.all'Tag = Multiple_Side then + -- + + Check_List_For_Multiple ( + Multiple_Instance => From, + Associative_Instance => Temp_Associative, + Single_Instance => Temp_Single, + Multiple_Instance_Found => Found); + + if Found then + -- + if Class = Single_Side then + + To := Temp_Single; + + + elsif Class = Associative_Side then + + To := Temp_Associative; + + end if; + -- + + end if; + -- + + elsif From.all'Tag = Associative_Side then + + + Check_List_For_Associative ( + Associative_Instance => From, + Multiple_Instance => Temp_Multiple, + Single_Instance => Temp_Single, + Associative_Instance_Found => Found); + + if Found then + -- + if Class = Single_Side then + + To := Temp_Single; + + elsif Class = Multiple_Side then + + To := Temp_Multiple; + + end if; + + end if; + + end if; + + end Navigate; + + --------------------------------------------------------------------- + procedure Navigate ( + From : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : in Root_Object.Object_List.List_Header_Access_Type) is + + -- + -- navigate from a single to a set + -- valid for: + -- S -> M + -- S -> A + -- + + Temp_Minor_Pointer: Relationship_Pair_Access_Type; + Temp_Major_Pointer: Relationship_Entry_Access_Type; + + begin + + if From.all'Tag = Single_Side then + + Temp_Major_Pointer := The_Relationship_List; + + Major_Loop: + + while Temp_Major_Pointer /= null loop + + if Temp_Major_Pointer.Single = From then + + Temp_Minor_Pointer := Temp_Major_Pointer.Completion_List; + + Minor_Loop: + + while Temp_Minor_Pointer /= null loop + + if Class = Multiple_Side then + + Root_Object.Object_List.Insert ( + New_Item => Temp_Minor_Pointer.Multiple, + On_To => To); + + elsif Class = Associative_Side then + + Root_Object.Object_List.Insert ( + New_Item => Temp_Minor_Pointer.Associative, + On_To => To); + + end if; + + Temp_Minor_Pointer := Temp_Minor_Pointer.Next; + + end loop Minor_Loop; + + exit Major_Loop; + + end if; + + Temp_Major_Pointer := Temp_Major_Pointer.Next; + + end loop Major_Loop; + -- + end if; + + end Navigate; + + +------------------------------------------------------------------------ + + + -- associative correlated navigation + procedure Navigate ( + From : in Root_Object.Object_Access; + Also : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : out Root_Object.Object_Access) is + + + -- navigate from two singles to a single + -- valid for: + -- M and S -> A + -- S and M -> A + + Temp_Single, + Single_Side_Source , + Multiple_Side_Source, + Temp_Associative_Multiple, + Temp_Associative_Single : Root_Object.Object_Access := null; + + Assoc_Set : Root_Object.Object_List.List_Header_Access_Type := Root_Object.Object_List.Initialise; + + Found, + Tags_Correct : Boolean := FALSE; + + begin + + -- Reset the output pointer to null so that if we don't find anything + -- useful, the caller can check for it. + To := null; + + Tags_Correct := ((( From.all'Tag = Multiple_Side) and then + ( Also.all'Tag = Single_Side)) + or else ((( From.all'Tag = Single_Side) and then + ( Also.all'Tag = Multiple_Side)))) ; + + if Tags_Correct then + + if From.all'Tag = Multiple_Side then + + Multiple_Side_Source := From; + Single_Side_Source := Also; + else + Multiple_Side_Source := Also; + Single_Side_Source := From; + end if; + + -- Do the navigations now, all is correct. + + -- Navigate from multiple side to associative side. + Check_List_For_Multiple ( + Multiple_Instance => Multiple_Side_Source, + Associative_Instance => Temp_Associative_Multiple, + Single_Instance => Temp_Single, + Multiple_Instance_Found => Found); + + + -- Navigate from single side to associative side. + if Found then + + -- do the navigation + + declare + Input_List : Root_Object.Object_List.List_Header_Access_Type; + begin + Input_List := Root_Object.Object_List.Initialise; + + Root_Object.Object_List.Clear(Assoc_Set); + + Root_Object.Object_List.Insert ( + New_Item => Single_Side_Source, + On_To => Input_List); + + Navigate( + From => Input_List, + Class => Class, + To => Assoc_Set); + + Root_Object.Object_List.Destroy_List(Input_List);" +"procedure Remove_Node is new Ada.Unchecked_Deallocation (Node_Type, Node_Access_Type);","procedure Remove_List is new Ada.Unchecked_Deallocation (List_Header_Type, List_Header_Access_Type); + +--------------------------------------------------------------------- + function Initialise return List_Header_Access_Type is + + Temp_Entry: List_Header_Access_Type; + + begin + -- + -- allocate new memory for the header information + -- + Temp_Entry := new List_Header_Type; + -- + -- and set the fields up. These could be replaced by default values in the + -- record declaration. + -- + Temp_Entry.First_Entry := null; + Temp_Entry.Count := 0; + Temp_Entry.Free_List := null; + Temp_Entry.Free_List_Count := 0; + + -- DEFECT 262 set Stepping_Pointer to null. + Temp_Entry.Stepping_Pointer := null; + + return Temp_Entry; + + end Initialise; + + --------------------------------------------------------------------- + + function Count_Of (Target_List : List_Header_Access_Type) return Application_Types.Base_Integer_Type is + begin + return Target_List.Count; + end Count_Of; + + --------------------------------------------------------------------- + + function Count_Of_Free_List (Target_List : List_Header_Access_Type) return Application_Types.Base_Integer_Type is + begin + return Target_List.Free_List_Count; + end Count_Of_Free_List; + + --------------------------------------------------------------------- + + function Max_Count_Of (Target_List : List_Header_Access_Type) return Application_Types.Base_Integer_Type is + begin + return Target_List.Max_Count; + end Max_Count_Of; + + --------------------------------------------------------------------- + + function First_Entry_Of (Target_List : List_Header_Access_Type) return Node_Access_Type is + begin + Target_List.Stepping_Pointer := Target_List.First_Entry; + return Target_List.Stepping_Pointer; + end First_Entry_Of; + + --------------------------------------------------------------------- + + function Next_Entry_Of (Target_List : List_Header_Access_Type) return Node_Access_Type is + begin + Target_List.Stepping_Pointer := Target_List.Stepping_Pointer.Next; + return Target_List.Stepping_Pointer; + end Next_Entry_Of; + + --------------------------------------------------------------------- + + procedure Insert (New_Item : in Element_Type; + On_To : in List_Header_Access_Type) is + + New_Cell: Node_Access_Type; + + begin + + if On_To.Free_List = null then + -- + -- there are no 'old' entries available for reuse + -- + begin + New_Cell:= new Node_Type; + + exception + when Storage_Error => raise List_Storage_Error ;" +procedure Register_M1_End_Class (M1_Instance: in Ada.Tags.Tag) is,"begin + M1_Side := M1_Instance; + M1_Single_M2_Multiple.Register_Single_End_Class (M1_Instance); + M2_Single_M1_Multiple.Register_Multiple_End_Class (M1_Instance); + end Register_M1_End_Class; + +--------------------------------------------------------------------- + + function Report_M1_End_Class return Ada.Tags.Tag is + begin + return M1_Side; + end Report_M1_End_Class; + +----------------------------------------------------------------------- + + procedure Register_M2_End_Class (M2_Instance: in Ada.Tags.Tag) is + begin + M2_Side := M2_Instance; + M1_Single_M2_Multiple.Register_Multiple_End_Class (M2_Instance); + M2_Single_M1_Multiple.Register_Single_End_Class (M2_Instance); + end Register_M2_End_Class; + +--------------------------------------------------------------------- + + function Report_M2_End_Class return Ada.Tags.Tag is + begin + return M2_Side; + end Report_M2_End_Class; + +----------------------------------------------------------------------- + + procedure Register_Associative_End_Class (Associative_Instance: in Ada.Tags.Tag) is + begin + Associative_Side := Associative_Instance; + M1_Single_M2_Multiple.Register_Associative_End_Class (Associative_Instance); + M2_Single_M1_Multiple.Register_Associative_End_Class (Associative_Instance); + end Register_Associative_End_Class; + +--------------------------------------------------------------------- + + function Report_Associative_End_Class return Ada.Tags.Tag is + begin + return Associative_Side; + end Report_Associative_End_Class; + +--------------------------------------------------------------------- + + procedure Link ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access; + Using : in Root_Object.Object_Access) is + + begin + + M1_Single_M2_Multiple.Link ( + A_Instance => A_Instance, + B_Instance => B_Instance, + Using => Using); + + M2_Single_M1_Multiple.Link ( + A_Instance => A_Instance, + B_Instance => B_Instance, + Using => Using); + + end Link; +----------------------------------------------------------------------- + procedure Unassociate ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access; + From : in Root_Object.Object_Access) is + + begin + + M1_Single_M2_Multiple.Unassociate ( + A_Instance => A_Instance, + B_Instance => B_Instance, + From => From); + + M2_Single_M1_Multiple.Unassociate ( + A_Instance => B_Instance, + B_Instance => A_Instance, + From => From); + + end Unassociate; + +----------------------------------------------------------------------- + + procedure Unlink ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access) is + + begin + + M1_Single_M2_Multiple.Unlink ( + A_Instance => A_Instance, + B_Instance => B_Instance); + + M2_Single_M1_Multiple.Unlink ( + A_Instance => B_Instance, + B_Instance => A_Instance); + + end Unlink; + +----------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_List.List_Header_Access_Type; + Class : in Ada.Tags.Tag; + To : in Root_Object.Object_List.List_Header_Access_Type) is + + The_A_Instance: Root_Object.Object_Access; + + begin + + The_A_Instance := Root_Object.Object_List.First_Entry_Of (From).Item; + + if The_A_Instance /= null then + + if The_A_Instance.all'tag = M1_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif The_A_Instance.all'tag = M2_Side then + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif The_A_Instance.all'tag = Associative_Side then + + if Class = M2_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif Class = M1_Side then + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + end if; + + end if; + + end if; + + + end Navigate; + +--------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : in Root_Object.Object_List.List_Header_Access_Type) is + -- + -- navigate from a single to a set + -- valid for: + -- M1 -> M2 + -- M1 -> A + -- M2 -> M1 + -- M2 -> A + -- + begin + + if From.all'tag = M1_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif From.all'tag = M2_Side then + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif From.all'tag = Associative_Side then + + if Class = M2_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif Class = M1_Side then + + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + end if; + + end if; + + end Navigate; + +--------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : out Root_Object.Object_Access) is + -- + -- navigate from a single to a single + -- valid for: + -- A -> M1 + -- A -> M2 + -- + begin + + if From.all'tag = Associative_Side then + + if Class = M2_Side then + + M1_Single_M2_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + elsif Class = M1_Side then + + M2_Single_M1_Multiple.Navigate ( + From => From, + Class => Class, + To => To); + + end if; + + end if; + + + end Navigate; + +--------------------------------------------------------------------- + + + -- associative correlated navigation + procedure Navigate ( + From : in Root_Object.Object_Access; + Also : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : out Root_Object.Object_Access) is + + -- + -- navigate from two singles to a single + -- valid for: + -- M1 and M2 -> A + -- M1 and M2 -> A + + Temp_Associative_One, Temp_Associative_Two : Root_Object.Object_Access := null; + + Assoc_Set_One : Root_Object.Object_List.List_Header_Access_Type := Root_Object.Object_List.Initialise; + Assoc_Set_Two : Root_Object.Object_List.List_Header_Access_Type := Root_Object.Object_List.Initialise; + + Matched, Inner_Matched : Boolean := FALSE; + + begin + + -- Reset the output pointer to null so that if we don't find anything + -- useful, the caller can check for it. + To := null; + + if ((( From.all'tag = M1_Side) and then + ( Also.all'Tag = M2_Side)) + or else (( From.all'tag = M2_Side) and then + ( Also.all'Tag = M1_Side))) + then + + -- Navigate from single instance of first object + -- returns a set. + Navigate ( + From => Also, + Class => Class, + To => Assoc_Set_One); + + -- Navigate from single instance of second object + -- returns a set. + Navigate ( + From => From, + Class => Class, + To => Assoc_Set_Two); + + -- Compare results of the two sets from the above navigations. + -- A nice simple find operation on a set would be appropriate here, but + -- there isn't one available, so do it the hard way. + + -- Outer loop + declare + use type Root_Object.Object_List.Node_Access_Type; + Temp_Entry : Root_Object.Object_List.Node_Access_Type; + Matched : boolean := FALSE; + begin + -- Grab the first entry of the set + Temp_Entry := Root_Object.Object_List.First_Entry_Of(Assoc_Set_One); + -- While the set is not empty and the entry does not match the + -- assoc instance already found, burn rubber + + while (not Matched) and (Temp_Entry /= null) loop + + Temp_Associative_One := Temp_Entry.Item; + -- Compare this entry against the other set. + + -- Inner loop + declare + use type Root_Object.Object_List.Node_Access_Type; + Inner_Temp_Entry : Root_Object.Object_List.Node_Access_Type; + begin + + -- Grab the first entry of the set + Inner_Temp_Entry := Root_Object.Object_List.First_Entry_Of(Assoc_Set_Two); + + -- While the set is not empty and the entry does not match the + -- assoc instance already found, smoke 'em + + while (not matched) and (Inner_Temp_Entry /= null) loop + + Temp_Associative_Two := Inner_Temp_Entry.Item; + -- If M-M:M associative was ever implemented, + -- it would be easy to add the matched instance into a set for + -- return from this procedure. + + Matched := Temp_Associative_One = Temp_Associative_Two; + + if not Matched then + Inner_Temp_Entry := Root_Object.Object_List.Next_Entry_Of(Assoc_Set_Two); + end if; + + end loop; -- end of (Temp_Entry /= null) or else Matched loop" +procedure Remove_Pair is new Ada.Unchecked_Deallocation (,"Relationship_Pair_Type, Relationship_Pair_Access_Type); + + -- + -- 'Major' element + -- + type Relationship_Entry_Type; + type Relationship_Entry_Access_Type is access all Relationship_Entry_Type; + + type Relationship_Entry_Type is record + Single : Root_Object.Object_Access; + Completion_List : Relationship_Pair_Access_Type; + Next : Relationship_Entry_Access_Type; + Previous : Relationship_Entry_Access_Type; + end record; + + procedure Remove_Entry is new Ada.Unchecked_Deallocation ( + Relationship_Entry_Type, Relationship_Entry_Access_Type); + + ------------------------------------------------------------------------ + The_Relationship_List: Relationship_Entry_Access_Type; + + + subtype Role_Phrase_Type is string (1 .. Application_Types.Maximum_Number_Of_Characters_In_String); + + Multiple_Side : Ada.Tags.Tag; + Multiple_Side_Role : Role_Phrase_Type; + Multiple_Side_Role_Length : Natural; + + Single_Side : Ada.Tags.Tag; + Single_Side_Role : Role_Phrase_Type; + Single_Side_Role_Length : Natural; + + Associative_Side : Ada.Tags.Tag; + Associative_Side_Role : Role_Phrase_Type; + Associative_Side_Role_Length : Natural; + -- + -- A = LEFT = MULTIPLE + -- B = RIGHT = SINGLE + -- + ------------------------------------------------------------------------ + procedure Check_List_For_Multiple ( + Multiple_Instance : in Root_Object.Object_Access; + Associative_Instance : out Root_Object.Object_Access; + Single_Instance : out Root_Object.Object_Access; + Multiple_Instance_Found : out Boolean) is + + Temp_Minor_Pointer : Relationship_Pair_Access_Type; + Temp_Major_Pointer : Relationship_Entry_Access_Type; + + begin + + + Multiple_Instance_Found := False; + Temp_Major_Pointer := The_Relationship_List; + + Major_Loop: + while (not Multiple_Instance_Found) and then Temp_Major_Pointer /= null loop + + Temp_Minor_Pointer := Temp_Major_Pointer.Completion_List; + + Minor_Loop: + while (not Multiple_Instance_Found) and then Temp_Minor_Pointer /= null loop + + Multiple_Instance_Found := (Temp_Minor_Pointer.Multiple = Multiple_Instance); + + if Multiple_Instance_Found then + Associative_Instance := Temp_Minor_Pointer.Associative; + Single_Instance := Temp_Major_Pointer.Single; + else + -- Prevent access if we have got what we are after + -- Bailing out of the search loop is a neater solution, but test team defects + -- have been raised against this sort of thing. + Temp_Minor_Pointer := Temp_Minor_Pointer.Next; + end if; + + end loop Minor_Loop; + + -- Prevent the possibility that the next entry in the major queue is null causing an access error + if not Multiple_Instance_Found then + Temp_Major_Pointer := Temp_Major_Pointer.Next; + end if; + + end loop Major_Loop; + + end Check_List_For_Multiple; + + ------------------------------------------------------------------------ + procedure Check_List_For_Associative ( + Associative_Instance : in Root_Object.Object_Access; + Multiple_Instance : out Root_Object.Object_Access; + Single_Instance : out Root_Object.Object_Access; + Associative_Instance_Found : out Boolean) is + + Temp_Minor_Pointer : Relationship_Pair_Access_Type; + Temp_Major_Pointer : Relationship_Entry_Access_Type; + + begin + + Associative_Instance_Found := False; + Temp_Major_Pointer := The_Relationship_List; + + Major_Loop: + while (not Associative_Instance_Found) and then Temp_Major_Pointer /= null loop + + Temp_Minor_Pointer := Temp_Major_Pointer.Completion_List; + + Minor_Loop: + while (not Associative_Instance_Found) and then Temp_Minor_Pointer /= null loop + + Associative_Instance_Found := (Temp_Minor_Pointer.Associative = Associative_Instance); + + if Associative_Instance_Found then + Multiple_Instance := Temp_Minor_Pointer.Multiple; + Single_Instance := Temp_Major_Pointer.Single; + else + -- Prevent access if we have got what we are after + -- Bailing out of the search loop is a neater solution, but test team defects + -- have been raised against this sort of thing. + Temp_Minor_Pointer := Temp_Minor_Pointer.Next; + end if; + + end loop Minor_Loop; + + -- Prevent the possibility that the next entry in the major queue is null causing an access error + if not Associative_Instance_Found then + Temp_Major_Pointer := Temp_Major_Pointer.Next; + end if; + + end loop Major_Loop; + + end Check_List_For_Associative; + + ----------------------------------------------------------------------- + + procedure Do_Link ( + Multiple_Instance : in Root_Object.Object_Access; + Single_Instance : in Root_Object.Object_Access; + Associative_Instance : in Root_Object.Object_Access) is + + Temp_Minor_Pointer : Relationship_Pair_Access_Type; + Temp_Major_Pointer : Relationship_Entry_Access_Type; + Found : Boolean := False; + + begin + Temp_Major_Pointer := The_Relationship_List; + + while (not Found) and then Temp_Major_Pointer /= null loop + + Found := (Temp_Major_Pointer.Single = Single_Instance); + + if not Found then -- grab the next item + Temp_Major_Pointer := Temp_Major_Pointer.Next; + end if; + + end loop; + + if not Found then + Temp_Major_Pointer := new Relationship_Entry_Type; + Temp_Major_Pointer.Single := Single_Instance; + Temp_Major_Pointer.Completion_List := null; + Temp_Major_Pointer.Previous := null; + Temp_Major_Pointer.Next := The_Relationship_List; + + if The_Relationship_List /= null then + The_Relationship_List.Previous := Temp_Major_Pointer; + end if; + + The_Relationship_List := Temp_Major_Pointer; + + end if; + + Temp_Minor_Pointer := new Relationship_Pair_Type; + Temp_Minor_Pointer.Multiple := Multiple_Instance; + Temp_Minor_Pointer.Associative := Associative_Instance; + Temp_Minor_Pointer.Previous := null; + Temp_Minor_Pointer.Next := Temp_Major_Pointer.Completion_List; + + if Temp_Major_Pointer.Completion_List /= null then + Temp_Major_Pointer.Completion_List.Previous := Temp_Minor_Pointer; + end if; + + Temp_Major_Pointer.Completion_List := Temp_Minor_Pointer; + + end Do_Link; + + ----------------------------------------------------------------------- + + procedure Do_Unlink ( + Left_Instance : in Root_Object.Object_Access; + Right_Instance : in Root_Object.Object_Access) is + + Temp_Minor_Pointer : Relationship_Pair_Access_Type; + Temp_Major_Pointer : Relationship_Entry_Access_Type; + Delete_List : Boolean := False; + + begin + + Temp_Major_Pointer := The_Relationship_List; + + Major_Loop: + while Temp_Major_Pointer /= null loop + + if Temp_Major_Pointer.Single = Left_Instance then + Temp_Minor_Pointer := Temp_Major_Pointer.Completion_List; + + Minor_Loop: + while Temp_Minor_Pointer /= null loop + if Temp_Minor_Pointer.Multiple = Right_Instance then + if Temp_Minor_Pointer.Previous = null then + -- + -- first instance in list + -- + Temp_Major_Pointer.Completion_List := Temp_Minor_Pointer.Next; + -- + -- it's also the last and only instance in list + -- So we're going to delete the whole relationship instance + -- (but not just yet) + -- + Delete_List := (Temp_Minor_Pointer.Next = null); + + end if; + + if Temp_Minor_Pointer.Next /= null then + -- + -- there are more instances following in the list + -- + Temp_Minor_Pointer.Next.Previous := Temp_Minor_Pointer.Previous; + end if; + + if Temp_Minor_Pointer.Previous /= null then + -- + -- there are more instances previous in the list + -- + Temp_Minor_Pointer.Previous.Next := Temp_Minor_Pointer.Next; + end if; + + Remove_Pair (Temp_Minor_Pointer); + exit Major_Loop; + + end if; + + Temp_Minor_Pointer := Temp_Minor_Pointer.Next; + + end loop Minor_Loop; + + end if; + + Temp_Major_Pointer := Temp_Major_Pointer.Next; + + end loop Major_Loop; + -- + -- if needed, now delete the list + -- the same logic applies + -- + if Delete_List then + + if Temp_Major_Pointer.Previous = null then + -- + -- first instance in list + -- + The_Relationship_List := Temp_Major_Pointer.Next; + end if; + + if Temp_Major_Pointer.Next /= null then + -- + -- there are more instances following in the list + -- + Temp_Major_Pointer.Next.Previous := Temp_Major_Pointer.Previous; + end if; + + if Temp_Major_Pointer.Previous /= null then + -- + -- there are more instances previous in the list + -- + Temp_Major_Pointer.Previous.Next := Temp_Major_Pointer.Next; + end if; + + Remove_Entry (Temp_Major_Pointer); + + end if; + + end Do_Unlink; + + ------------------------------------------------------------------------- + procedure Register_Multiple_End_Class (Multiple_Instance : in Ada.Tags.Tag) is + begin + Multiple_Side := Multiple_Instance; + end Register_Multiple_End_Class; + + --------------------------------------------------------------------- + procedure Register_Multiple_End_Role (Multiple_Role : in String) is + begin + Multiple_Side_Role (1 .. Multiple_Role'Length) := Multiple_Role; + Multiple_Side_Role_Length := Multiple_Role'Length; + end Register_Multiple_End_Role; + + --------------------------------------------------------------------- + + procedure Register_Single_End_Class (Single_Instance : in Ada.Tags.Tag) is + begin + Single_Side := Single_Instance; + end Register_Single_End_Class; + + --------------------------------------------------------------------- + + procedure Register_Single_End_Role (Single_Role : in String) is + begin + + Single_Side_Role (1..Single_Role'Length) := Single_Role; + Single_Side_Role_Length := Single_Role'Length; + end Register_Single_End_Role; + + --------------------------------------------------------------------- + + procedure Register_Associative_End_Class (Associative_Instance : in Ada.Tags.Tag) is + begin + Associative_Side := Associative_Instance; + end Register_Associative_End_Class; + + --------------------------------------------------------------------- + + procedure Register_Associative_End_Role (Associative_Role : in String) is + begin + Associative_Side_Role (1 .. Associative_Role'Length) := Associative_Role; + Associative_Side_Role_Length := Associative_Role'Length; + end Register_Associative_End_Role; + + --------------------------------------------------------------------- + + procedure Link ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access; + Using : in Root_Object.Object_Access) is + + begin + + if Using.all'Tag = Associative_Side then + + if A_Instance.all'Tag = Multiple_Side then + + Do_Link ( + Multiple_Instance => A_Instance, + Single_Instance => B_Instance, + Associative_Instance => Using); + -- + -- PILOT_0000_0423 Include diagnostic references. + -- + Application_Types.Count_Of_Relationships := Application_Types.Count_Of_Relationships + 1; + + elsif A_Instance.all'Tag = Single_Side then + + Do_Link ( + Multiple_Instance => B_Instance, + Single_Instance => A_Instance, + Associative_Instance => Using); + -- + -- PILOT_0000_0423 Include diagnostic references. + -- + Application_Types.Count_Of_Relationships := Application_Types.Count_Of_Relationships + 1; + + end if; + end if; -- Using.all'tag /= Associative_Side + + end Link; + + ----------------------------------------------------------------------- + + procedure Unassociate ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access; + From : in Root_Object.Object_Access) is + begin + null; + end Unassociate; + + ----------------------------------------------------------------------- + + procedure Unlink ( + A_Instance : in Root_Object.Object_Access; + B_Instance : in Root_Object.Object_Access) is + + begin + + if A_Instance.all'Tag = Multiple_Side then + + Do_Unlink ( + Left_Instance => B_Instance, + Right_Instance => A_Instance); + -- + -- PILOT_0000_0423 Include diagnostic references. + -- + Application_Types.Count_Of_Relationships := Application_Types.Count_Of_Relationships - 1; + + elsif A_Instance.all'Tag = Single_Side then + -- + Do_Unlink ( + Left_Instance => A_Instance, + Right_Instance => B_Instance); + -- + -- PILOT_0000_0423 Include diagnostic references. + -- + Application_Types.Count_Of_Relationships := Application_Types.Count_Of_Relationships - 1; + + end if; + + end Unlink; + + ----------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_List.List_Header_Access_Type; + Class : in Ada.Tags.Tag; + To : in Root_Object.Object_List.List_Header_Access_Type) is + + Source_Instance: Root_Object.Object_Access; + Temp_Node: Root_Object.Object_List.Node_Access_Type; + Temp_Instance: Root_Object.Object_Access; + --Temp_Single: Root_Object.Object_Access; + --Temp_Associative: Root_Object.Object_Access; + --Temp_Multiple: Root_Object.Object_Access; + + begin + + Temp_Node := Root_Object.Object_List.First_Entry_Of (From); + + while Temp_Node /= null loop + + Source_Instance := Temp_Node.Item; + + if Source_Instance.all'Tag = Multiple_Side then + + Navigate ( + From => Source_Instance, + Class => Class, + To => Temp_Instance); + + if Temp_Instance /= null then + + Root_Object.Object_List.Insert ( + New_Item => Temp_Instance, + On_To => To ); + + end if; + -- + elsif Source_Instance.all'Tag = Single_Side then + + Navigate ( + From => Source_Instance, + Class => Class, + To => To); + -- + + elsif Source_Instance.all'Tag = Associative_Side then + + Navigate ( + From => Source_Instance, + Class => Class, + To => Temp_Instance); + + if Temp_Instance /= null then + + Root_Object.Object_List.Insert ( + New_Item => Temp_Instance, + On_To => To ); + + end if; + -- + + end if; + + Temp_Node := Root_Object.Object_List.Next_Entry_Of (From); + + end loop; + + end Navigate; + + ----------------------------------------------------------------------- + + procedure Navigate ( + From : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : out Root_Object.Object_Access) is + + -- + -- navigate from a single to a single + -- valid for: + -- A -> M + -- A -> S + -- M -> S + -- M -> A + -- + Temp_Single: Root_Object.Object_Access; + Temp_Associative: Root_Object.Object_Access; + Temp_Multiple: Root_Object.Object_Access; + Found: Boolean; + + begin + + -- PILOT_0000_1422 + -- Defaulting the return parameter ensures that if an attempt + -- is made to navigate this type of one to many associative + -- without having linked it, the correct null parameter is + -- returned. This relationship mechanism relies on the link + -- operation to sort out all the tags. We can't rely on that + -- happening in all cases. + To := null; + + if From.all'Tag = Multiple_Side then + -- + + Check_List_For_Multiple ( + Multiple_Instance => From, + Associative_Instance => Temp_Associative, + Single_Instance => Temp_Single, + Multiple_Instance_Found => Found); + + if Found then + -- + if Class = Single_Side then + + To := Temp_Single; + + + elsif Class = Associative_Side then + + To := Temp_Associative; + + end if; + -- + + end if; + -- + + elsif From.all'Tag = Associative_Side then + + + Check_List_For_Associative ( + Associative_Instance => From, + Multiple_Instance => Temp_Multiple, + Single_Instance => Temp_Single, + Associative_Instance_Found => Found); + + if Found then + -- + if Class = Single_Side then + + To := Temp_Single; + + elsif Class = Multiple_Side then + + To := Temp_Multiple; + + end if; + + end if; + + end if; + + end Navigate; + + --------------------------------------------------------------------- + procedure Navigate ( + From : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : in Root_Object.Object_List.List_Header_Access_Type) is + + -- + -- navigate from a single to a set + -- valid for: + -- S -> M + -- S -> A + -- + + Temp_Minor_Pointer: Relationship_Pair_Access_Type; + Temp_Major_Pointer: Relationship_Entry_Access_Type; + + begin + + if From.all'Tag = Single_Side then + + Temp_Major_Pointer := The_Relationship_List; + + Major_Loop: + + while Temp_Major_Pointer /= null loop + + if Temp_Major_Pointer.Single = From then + + Temp_Minor_Pointer := Temp_Major_Pointer.Completion_List; + + Minor_Loop: + + while Temp_Minor_Pointer /= null loop + + if Class = Multiple_Side then + + Root_Object.Object_List.Insert ( + New_Item => Temp_Minor_Pointer.Multiple, + On_To => To); + + elsif Class = Associative_Side then + + Root_Object.Object_List.Insert ( + New_Item => Temp_Minor_Pointer.Associative, + On_To => To); + + end if; + + Temp_Minor_Pointer := Temp_Minor_Pointer.Next; + + end loop Minor_Loop; + + exit Major_Loop; + + end if; + + Temp_Major_Pointer := Temp_Major_Pointer.Next; + + end loop Major_Loop; + -- + end if; + + end Navigate; + + +------------------------------------------------------------------------ + + + -- associative correlated navigation + procedure Navigate ( + From : in Root_Object.Object_Access; + Also : in Root_Object.Object_Access; + Class : in Ada.Tags.Tag; + To : out Root_Object.Object_Access) is + + + -- navigate from two singles to a single + -- valid for: + -- M and S -> A + -- S and M -> A + + Temp_Single, + Single_Side_Source , + Multiple_Side_Source, + Temp_Associative_Multiple, + Temp_Associative_Single : Root_Object.Object_Access := null; + + Assoc_Set : Root_Object.Object_List.List_Header_Access_Type := Root_Object.Object_List.Initialise; + + Found, + Tags_Correct : Boolean := FALSE; + + begin + + -- Reset the output pointer to null so that if we don't find anything + -- useful, the caller can check for it. + To := null; + + Tags_Correct := ((( From.all'Tag = Multiple_Side) and then + ( Also.all'Tag = Single_Side)) + or else ((( From.all'Tag = Single_Side) and then + ( Also.all'Tag = Multiple_Side)))) ; + + if Tags_Correct then + + if From.all'Tag = Multiple_Side then + + Multiple_Side_Source := From; + Single_Side_Source := Also; + else + Multiple_Side_Source := Also; + Single_Side_Source := From; + end if; + + -- Do the navigations now, all is correct. + + -- Navigate from multiple side to associative side. + Check_List_For_Multiple ( + Multiple_Instance => Multiple_Side_Source, + Associative_Instance => Temp_Associative_Multiple, + Single_Instance => Temp_Single, + Multiple_Instance_Found => Found); + + + -- Navigate from single side to associative side. + if Found then + + -- do the navigation + + declare + Input_List : Root_Object.Object_List.List_Header_Access_Type; + begin + Input_List := Root_Object.Object_List.Initialise; + + Root_Object.Object_List.Clear(Assoc_Set); + + Root_Object.Object_List.Insert ( + New_Item => Single_Side_Source, + On_To => Input_List); + + Navigate( + From => Input_List, + Class => Class, + To => Assoc_Set); + + Root_Object.Object_List.Destroy_List(Input_List);" +function distance(p : in Position) return Natural is,"begin + return abs(p.x) + abs(p.y); + end distance; + + function hash(p : in Position) return Ada.Containers.Hash_Type is + begin + return Ada.Strings.Hash(p.x'IMAGE & "","" & p.y'IMAGE); + end hash; + + function equivalent_positions(left, right: Position) return Boolean is + begin + return (left.x = right.x) and then (left.y = right.y); + end equivalent_positions; + + -- function ""="" (left : in Position; right : in Position) return Boolean is + -- begin + -- return (left.x = right.x) and (left.y = right.y); + -- end ""=""; + + function to_string(wp : in Wire_Points.Set) return String is + package Unbounded renames Ada.Strings.Unbounded; + s : Unbounded.Unbounded_String; + begin + for elt of wp loop + Unbounded.append(s, to_string(elt) & "", ""); + end loop; + return Unbounded.to_string(s); + end to_string; + + function to_string(ws : in Wire_Segment) return String is + begin + return to_string(ws.dir) & Integer'Image(ws.distance); + end to_string; + + function to_string(w : in Wire.Vector) return String is + package Unbounded renames Ada.Strings.Unbounded; + s : Unbounded.Unbounded_String; + begin + for elt of w loop + Unbounded.append(s, to_string(elt) & "", ""); + end loop; + return Unbounded.to_string(s); + end to_string; + + procedure parse_wire(w_str : in String; w : in out Wire.Vector) is + start : Natural := w_str'First; + finish : Natural; + delimiters : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.to_set(Sequence => "",""); + begin + w.clear; + while start <= w_str'Last loop + Ada.Strings.Fixed.find_token(Source => w_str(start .. w_str'Last), + Set => delimiters, + Test => Ada.Strings.outside, + First => start, Last => finish); + if not(finish = 0 and then start = w_str'First) then + w.append((dir => to_dir(w_str(start)), distance => Integer'Value(w_str(start+1 .. finish)))); + end if; + start := finish + 1; + end loop; + end parse_wire; + + procedure step(pos : in out Position; dir : in Direction) is + begin + case dir is + when Up => pos := (x => pos.x, y => pos.y - 1, dist => pos.dist + 1); + when Down => pos := (x => pos.x, y => pos.y + 1, dist => pos.dist + 1); + when Left => pos := (x => pos.x - 1, y => pos.y, dist => pos.dist + 1); + when Right => pos := (x => pos.x + 1, y => pos.y, dist => pos.dist + 1); + end case; + end step; + + procedure expand(pos : in out Position; segment : in Wire_Segment; points : in out Wire_Points.Set) is + begin + for i in 1 .. segment.distance loop + step(pos => pos, dir => segment.dir); + points.include(pos); + end loop; + end expand; + + procedure expand_segments(w : in Wire.Vector; points : in out Wire_Points.Set) is + start_pos : constant Position := (x => 0, y => 0, dist => 0); + curr_pos : Position := start_pos; + begin + points.clear; + for segment of w loop + expand(pos => curr_pos, segment => segment, points => points); + end loop; + end expand_segments; + + procedure load(w1 : in String; w2 : in String) is + begin + parse_wire(w1, wire_1); + expand_segments(wire_1, wire_points_1); + parse_wire(w2, wire_2); + expand_segments(wire_2, wire_points_2); + end load; + + procedure load_file(path : String) is + file : TIO.File_Type; + begin + TIO.open(File => file, Mode => TIO.In_File, Name => path); + declare + str1 : constant String := TIO.get_line(file); + str2 : constant String := TIO.get_line(file); + begin + load(w1 => str1, w2 => str2);" +procedure Ping is,"use type Interfaces.Unsigned_32; + use type Net.Ip_Addr; + use type Net.DHCP.State_Type; + use type Ada.Real_Time.Time; + use type Ada.Real_Time.Time_Span; + + procedure Refresh; + procedure Header; + + procedure Refresh is + Y : Natural := 90; + Hosts : constant Pinger.Ping_Info_Array := Pinger.Get_Hosts; + begin + for I in Hosts'Range loop + Demos.Put (0, Y, Net.Utils.To_String (Hosts (I).Ip)); + Demos.Put (250, Y, Net.Uint64 (Hosts (I).Seq)); + Demos.Put (350, Y, Net.Uint64 (Hosts (I).Received)); + Y := Y + 16; + end loop; + Demos.Refresh_Ifnet_Stats; + STM32.Board.Display.Update_Layer (1); + end Refresh; + + procedure Header is + begin + Demos.Put (0, 70, ""Host""); + Demos.Put (326, 70, ""Send""); + Demos.Put (402, 70, ""Receive""); + end Header; + + procedure Initialize is new Demos.Initialize (Header); + + -- The ping period. + PING_PERIOD : constant Ada.Real_Time.Time_Span := Ada.Real_Time.Milliseconds (1000); + + -- Send ping echo request deadline + Ping_Deadline : Ada.Real_Time.Time; + + Icmp_Handler : Net.Protos.Receive_Handler; +begin + Initialize (""STM32 Ping""); + + Pinger.Add_Host ((192, 168, 1, 1)); + Pinger.Add_Host ((8, 8, 8, 8)); + Net.Protos.Dispatchers.Set_Handler (Proto => Net.Protos.IPv4.P_ICMP, + Handler => Pinger.Receive'Access, + Previous => Icmp_Handler); + + -- Change font to 8x8. + Demos.Current_Font := BMP_Fonts.Font8x8; + Ping_Deadline := Ada.Real_Time.Clock; + loop + declare + Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; + Dhcp_Deadline : Ada.Real_Time.Time; + begin + Net.Protos.Arp.Timeout (Demos.Ifnet); + Demos.Dhcp.Process (Dhcp_Deadline); + if Demos.Dhcp.Get_State = Net.DHCP.STATE_BOUND then + Pinger.Add_Host (Demos.Dhcp.Get_Config.Router); + Pinger.Add_Host (Demos.Dhcp.Get_Config.Dns1); + Pinger.Add_Host (Demos.Dhcp.Get_Config.Dns2); + Pinger.Add_Host (Demos.Dhcp.Get_Config.Ntp); + Pinger.Add_Host (Demos.Dhcp.Get_Config.Www); + end if; + if Ping_Deadline < Now then + Pinger.Do_Ping; + Refresh; + Ping_Deadline := Ping_Deadline + PING_PERIOD; + end if; + if Ping_Deadline < Dhcp_Deadline then + delay until Ping_Deadline; + else + delay until Dhcp_Deadline; + end if;" +function Check_Monster_Collision return Boolean;,"-------------- + -- Collides -- + -------------- + + function Collides (Points : Collision_Points) return Boolean is + X : constant Integer := Integer (P.Position.X); + Y : constant Integer := Integer (P.Position.Y); + begin + for Pt of Points loop + + if Show_Collision_Points then + declare + Data : aliased HAL.UInt16_Array := (0 => 0); + begin + PyGamer.Screen.Set_Address (UInt16 (X + Pt.X), + UInt16 (X + Pt.X), + UInt16 (Y + Pt.Y), + UInt16 (Y + Pt.Y)); + PyGamer.Screen.Start_Pixel_TX; + PyGamer.Screen.Push_Pixels (Data'Address, Data'Length); + PyGamer.Screen.End_Pixel_TX;" +function Check_Monster_Collision return Boolean is,"X : constant Integer := Integer (P.Position.X); + Y : constant Integer := Integer (P.Position.Y); + begin + for Pt of Bounding_Box loop + if Monsters.Check_Hit ((X + Pt.X, + Y + Pt.Y), + Lethal => False) + then + return True; + end if; + end loop; + return False; + end Check_Monster_Collision; + + ----------- + -- Spawn -- + ----------- + + procedure Spawn is + begin + P.Alive := True; + P.Set_Mass (Value (90.0)); + P.Sprite.Flip_Vertical (False); + P.Set_Speed ((0.0, 0.0)); + GESTE.Add (P.Sprite'Access, 3); + P.Sprite.Flip_Horizontal (True); + + for Prj of Projs loop + Prj.Init; + end loop; + end Spawn; + + ---------- + -- Move -- + ---------- + + procedure Move (Pt : GESTE.Pix_Point) is + begin + P.Set_Position (GESTE.Maths_Types.Point'(Value (Pt.X), Value (Pt.Y))); + P.Sprite.Move ((Integer (P.Position.X) - 4, + Integer (P.Position.Y) - 4)); + end Move; + + -------------- + -- Position -- + -------------- + + function Position return GESTE.Pix_Point + is ((Integer (P.Position.X), Integer (P.Position.Y))); + + -------------- + -- Is_Alive -- + -------------- + + function Is_Alive return Boolean + is (P.Alive); + + ------------ + -- Update -- + ------------ + + procedure Update is + Old : constant Point := P.Position; + Elapsed : constant Value := Value (1.0 / 60.0); + + Collision_To_Fix : Boolean; + begin + -- Check collision with monsters + if Check_Monster_Collision then + P.Sprite.Flip_Vertical (True); + P.Alive := False; + end if; + + if Going_Right then + Facing_Left := False; + P.Sprite.Flip_Horizontal (True); + elsif Going_Left then + Facing_Left := True; + P.Sprite.Flip_Horizontal (False); + end if; + + -- Lateral movements + if Grounded then + if Going_Right then + P.Apply_Force ((14_000.0, 0.0)); + elsif Going_Left then + P.Apply_Force ((-14_000.0, 0.0)); + else + -- Friction on the floor + P.Apply_Force ( + (Value (Value (-2000.0) * P.Speed.X), + 0.0)); + end if; + else + if Going_Right then + P.Apply_Force ((7_000.0, 0.0)); + + elsif Going_Left then + P.Apply_Force ((-7_000.0, 0.0)); + + end if; + end if; + + -- Gavity + if not Grounded then + P.Apply_Gravity (Value (-500.0)); + end if; + + -- Wall grab + if not Grounded + + and then + P.Speed.Y > 0.0 -- Going down + + and then + -- Pushing against a wall + ((Collides (Right_Wall)) + or else + (Collides (Left_Wall))) + then + + -- Friction against the wall + P.Apply_Force ((0.0, -4_0000.0)); + + Grabing_Wall := True; + else + Grabing_Wall := False; + end if; + + -- Jump + if Do_Jump then + declare + Jmp_X : Value := 0.0; + begin + if Grabing_Wall then + -- Wall jump + Jmp_X := 215_000.0; + if Collides (Right_Wall) then + Jmp_X := -Jmp_X; + end if; + end if; + + P.Apply_Force ((Jmp_X, -900_000.0)); + Grounded := False; + Jumping := True; + Sound.Play_Jump;" +procedure Main_Ada_2048 is,"WIDTH : constant := 800; + HEIGHT : constant := 600; + + SDL_WINDOWPOS_UNDEFINED : constant := 16#1FFF_0000#; + + + package RC_Window is new My_RC(T => Windows, + T_Access => Windows_Pointer, + Free_T => SDL_DestroyWindow); + + package RC_Render is new My_RC(T => Renderers, + T_Access => Renderer_Pointer, + Free_T => SDL_DestroyRenderer); + + Window : RC_Window.Object; + Render : RC_Render.Object; + Title : RC_CString.RC_CString; + + Font_Path : RC_CString.RC_CString; + + discard : Boolean; +begin + Title.make(""Ada 2048""); + Font_Path.make(""/usr/share/fonts/TTF/NotoSansCJK.ttc""); + + if SDL_Init = true then + discard := TTF_Init; + Open_Font(TTF_OpenFont(Font_Path.To_C, 24)); + + RC_Window.Set(window, SDL_CreateWindow(Title.To_C, + SDL_WINDOWPOS_UNDEFINED, + SDL_WINDOWPOS_UNDEFINED, + WIDTH, HEIGHT, Shown or Resizable)); + + RC_Render.Set(render, SDL_CreateRenderer(window.Get, + Interfaces.C.int(-1), + SDL_RENDERER_ACCELERATED or SDL_RENDERER_PRESENTVSYNC)); + + + declare + r : Renderer_Pointer := render.Get; + + running : Boolean := true; + event : World_Machine.Events.Events; + begin + World_Machine.View.Clean_Screen(r); + World_Machine.View.Start_Screen(r); + + while running loop + event := Press_Event; + running := Mode.Dispatch(r, event); + end loop;" +procedure Main_Operations is,"Time_Interval : constant Time_Span := Measure_Interval; -- Time since last call + FrameRate : constant Natural := Natural (Average_Framerate (Time_Interval)); + Time_Interval_Real : constant Real := Real (To_Duration (Time_Interval)); + + Commands : Commands_Array := Command_Set_Reset; + + begin + Framerate_Limiter (Intented_Framerate); + + Get_Keys (Commands); + + case Camera_Mode is + when Scene => + Execute_Commands.Act_On_Input (Cam.Scene_Offset, Cam.Rotation, Time_Interval_Real, Commands); + case Camera_Mode is + when Scene => + Cam.Position := Swarm_Monitor.Centre_Of_Gravity; + when Chase => + Cam := Initial_Cams (Camera_Mode); + end case; + + when Chase => + Execute_Commands.Act_On_Input (Cam.Object_Offset, Cam.Rotation, Time_Interval_Real, Commands); + case Camera_Mode is + when Scene => Cam := Initial_Cams (Camera_Mode); + when Chase => + Cam.Position := Element (Swarm_State, 1).Position.all.Read; + declare + -- Element_Roll : constant Angle := Roll (Element (Swarm_State, 1).Rotation); + Element_Pitch : constant Radiants := Pitch (Element (Swarm_State, 1).Rotation.all.Read); + Element_Yaw : constant Radiants := Yaw (Element (Swarm_State, 1).Rotation.all.Read); + begin + Cam.Rotation := To_Rotation (0.0, 0.0, -Element_Yaw); + Cam.Rotation := Rotate (Cam.Rotation, To_Rotation (0.0, -Element_Pitch, 0.0)); + -- Cam.Rotation := Rotate (Cam.Rotation, To_Rotation (-Element_Roll, 0.0, 0.0));" +procedure Initialize is,"begin + for Model in Model_Name loop + case Model is +-- when Arrow => Arrow_P.Create (object => Model_Set (Model), scale => 0.003, centre => (0.0, 0.0, 0.0)); +-- when Cube => Cube_P.Create (object => Model_Set (Model), scale => 0.015, centre => (0.0, 0.0, 0.0)); +-- when Duck => Duck_P.Create (object => Model_Set (Model), scale => 0.003, centre => (0.0, 0.0, 0.0)); +-- when Plane => Plane_P.Create (object => Model_Set (Model), scale => 0.003, centre => (0.0, 0.0, 0.0)); + when Spaceship => Spaceship_P.Create (Object => Model_Set (Model), Object_Scale => 0.003, Centre => (0.0, 0.0, 0.0)); Assign_Material (Model_Set (Model), Pearl); +-- when Spaceship_Ruby => Spaceship_P.Create (object => Model_Set (Model), scale => 0.003, centre => (0.0, 0.0, 0.0)); Assign_Material (Model_Set (Model), Ruby); + when Sphere => Sphere_P.Create (object => Model_Set (Model), Object_Scale => 0.015, centre => (0.0, 0.0, 0.0)); Assign_Material (Model_Set (Model), Ruby); + end case; + end loop; + + for M in Spaceship_Gradient'Range (1) loop + for i in Spaceship_Gradient'Range (2) loop + Spaceship_P.Create (Object => Spaceship_Gradient (M, i), Object_Scale => 0.003, Centre => (0.0, 0.0, 0.0)); + declare + Ratio : constant Ratio_T := + ((Real (i) - Real (Spaceship_Gradient'First (2))) + / Real (Spaceship_Gradient'Last (2) - Spaceship_Gradient'First (2))) + + Ratio_T'First; + begin + case M is + when G_Ruby => Assign_Material (Spaceship_Gradient (M, i), Blend_Material (Ruby, Pearl, Ratio)); + when G_Turquoise => Assign_Material (Spaceship_Gradient (M, i), Blend_Material (Turquoise, Pearl, Ratio)); + end case;" +function Mean_Closest_Distance return Real is,"Acc_Distance : Real := 0.0; + + begin + for Element_Index in First_Index (Swarm_State) .. Last_Index (Swarm_State) loop + declare + This_Element : constant Swarm_Element_State := Element (Swarm_State, Element_Index); + Neighbours : constant Distance_Vectors.Vector := This_Element.Neighbours.all; + begin + if Distance_Vectors.Length (Neighbours) > 0 then + declare + Closest_Distance : constant Real := + Distance_Vectors.Element (Neighbours, Distance_Vectors.First_Index (Neighbours)).Distance; + begin + Acc_Distance := Acc_Distance + Closest_Distance;" +procedure Sorted_Close_Distances (Close_Dist : in out Distance_Vectors.Vector;,"Element_Index : Swarm_Element_Index; + Max_Distance : Distances) is + + This_Element : constant Swarm_Element_State := Element (Swarm_State, Element_Index); + This_Position : constant Positions := This_Element.Position.all.Read; + + begin + Distance_Vectors.Clear (Close_Dist); + Distance_Vectors.Reserve_Capacity (Close_Dist, Length (Swarm_State) - 1); + for Scan_Index in First_Index (Swarm_State) .. Last_Index (Swarm_State) loop + if Element_Index /= Scan_Index then + declare + Test_Element : constant Swarm_Element_State := Element (Swarm_State, Scan_Index); + Test_Position : constant Positions := Test_Element.Position.all.Read; + Test_Direction : constant Vector_3D := This_Position - Test_Position; + Test_Distance : constant Distances := abs (Test_Direction); + begin + if Test_Distance <= Max_Distance then + Distance_Vectors.Append (Close_Dist, (Index => Scan_Index, + Distance => Test_Distance, + Position_Diff => Test_Direction, + Velocity_Diff => This_Element.Velocity.all.Read - Test_Element.Velocity.all.Read)); + end if;" +procedure Set_All_Accelerations is,"begin + for Element_Index in First_Index (Swarm_State) .. Last_Index (Swarm_State) loop + Set_Acceleration (Element_Index); + end loop; + end Set_All_Accelerations; + + -- + -- + -- + + procedure Forward_Messages (Element_Index : Swarm_Element_Index) is + + This_Element : constant Swarm_Element_State := Element (Swarm_State, Element_Index); + Message_To_Be_Distributed : Inter_Vehicle_Messages; + + begin + while This_Element.Comms.all.Has_Outgoing_Messages loop + This_Element.Comms.all.Fetch_Message (Message_To_Be_Distributed); + Check_Neighbours : for Distance_Index in Distance_Vectors.First_Index (This_Element.Neighbours.all) .. Distance_Vectors.Last_Index (This_Element.Neighbours.all) loop + declare + Distance_Entry : constant Distance_Entries := Distance_Vectors.Element (This_Element.Neighbours.all, Distance_Index); + begin + if Distance_Entry.Distance <= Comms_Range then + Element (Swarm_State, Distance_Entry.Index).Comms.all.Push_Message (Message_To_Be_Distributed); + else + exit Check_Neighbours; + end if;" +procedure Forward_All_Messages is,"begin + for Element_Index in First_Index (Swarm_State) .. Last_Index (Swarm_State) loop + Forward_Messages (Element_Index); + end loop; + end Forward_All_Messages; + + -- + -- + -- + + procedure Move_Element (Element_Index : Swarm_Element_Index) is + + This_Element : Swarm_Element_State := Element (Swarm_State, Element_Index); + Interval : constant Real := Real'Min (Real (To_Duration (Clock - This_Element.Last_Update)), Max_Update_Interval); + + begin + This_Element.Velocity.all.Write (This_Element.Velocity.all.Read + (Interval * This_Element.Acceleration.all.Read)); + + declare + Move_Start : constant Positions := This_Element.Position.all.Read; + Move_End : constant Positions := Move_Start + (Interval * This_Element.Velocity.all.Read); + begin + This_Element.Position.all.Write (Move_End); + + This_Element.Charge.Level := Vehicle_Charges + (Real'Max (Real (Empty_Charge), + Real'Min (Real (Full_Charge), + Real (This_Element.Charge.Level) + - (Interval + * (Charging_Setup.Constant_Discharge_Rate_Per_Sec + + Charging_Setup.Propulsion_Discharge_Rate_Per_Sec * abs (This_Element.Acceleration.all.Read)))))); + + for Globe_Ix in Globes'Range loop + + declare + Globe_Pos : constant Positions := Globes (Globe_Ix).Position.all.Read; + Interratio : constant Real := (Globe_Pos - Move_Start) * ((Move_End - Move_Start) / (abs (Move_End - Move_Start))); + Intersection : constant Positions := Move_Start + Interratio * (Move_End - Move_Start); + Touching : constant Boolean := abs (Intersection - Globe_Pos) <= Energy_Globe_Detection and then Interratio >= 0.0 and then Interratio <= 1.0; + Slot_Passed : constant Boolean := Clock - This_Element.Charge.Charge_Time.all.Read > Charging_Setup.Max_Globe_Interval; + begin + if (not This_Element.Charge.Globes_Touched (Globe_Ix) or else Slot_Passed) and then Touching then + + if Slot_Passed then + This_Element.Charge.Globes_Touched := No_Globes_Touched; + This_Element.Charge.Charge_No := 0; + end if; + + This_Element.Charge.Charge_No := This_Element.Charge.Charge_No + 1; + This_Element.Charge.Globes_Touched (Globe_Ix) := True; + This_Element.Charge.Charge_Time.all.Write (Clock); + + if This_Element.Charge.Charge_No = Charging_Setup.Globes_Required then + This_Element.Charge.Level := Full_Charge; + This_Element.Charge.Charge_No := 0; + This_Element.Charge.Globes_Touched := No_Globes_Touched; + end if; + + end if;" +procedure Move_All_Elements is,"begin + for Element_Index in First_Index (Swarm_State) .. Last_Index (Swarm_State) loop + Move_Element (Element_Index); + end loop; + end Move_All_Elements; + + -- + -- + -- + + procedure Update_Rotation (Element_Index : Swarm_Element_Index) is + + function Vector_Yaw (In_Vector : Vector_3D) return Real is + (if In_Vector (x) = 0.0 and then In_Vector (z) = 0.0 + then 0.0 + else Arctan (In_Vector (x), In_Vector (z))); + + function Vector_Pitch (In_Vector : Vector_3D) return Real is + ((Pi / 2.0) - Angle_Between (In_Vector, (0.0, 1.0, 0.0))); + + This_Element : constant Swarm_Element_State := Element (Swarm_State, Element_Index); + + Velocity : constant Vector_3D := This_Element.Velocity.all.Read; + Element_Yaw : constant Real := Vector_Yaw (Velocity); + Element_Pitch : constant Real := Vector_Pitch (Velocity); + + Rotation : constant Quaternion_Rotation := To_Rotation (0.0, -Element_Pitch, Element_Yaw + Pi); + Norm_Acc : constant Vector_3D := Rotate (This_Element.Acceleration.all.Read, Rotation); + Lateral_Acc : constant Real := Norm_Acc (x) * abs (Velocity); + Element_Roll : constant Real := + Real'Max (-Pi / 2.0, + Real'Min (Pi / 2.0, + Lateral_Acc * (Pi / 2.0) / Max_Assumed_Acceleration)); + + begin + This_Element.Rotation.all.Write (To_Rotation (Element_Roll, -Element_Pitch, -Element_Yaw + Pi)); + Replace_Element (Swarm_State, Element_Index, This_Element); + end Update_Rotation; + + --- + --- + --- + + procedure Update_All_Rotations is + + begin + for Element_Index in First_Index (Swarm_State) .. Last_Index (Swarm_State) loop + Update_Rotation (Element_Index); + end loop; + end Update_All_Rotations; + + -- + -- + -- + + procedure Remove_Empties is + + begin + if Length (Swarm_State) > 1 then + declare + Element_Index : Swarm_Element_Index := First_Index (Swarm_State); + begin + while Element_Index <= Last_Index (Swarm_State) and then Length (Swarm_State) > 1 loop + if Element (Swarm_State, Element_Index).Charge.Level = Empty_Charge then + Remove_Vehicle_in_Stages (Element_Index); + else + Element_Index := Element_Index + 1; + end if; + end loop;" +procedure Distribute_Jobs (Job : Job_Type) is,"use Swarm_Vectors; + + First_Element_Ix : constant Swarm_Element_Index := First_Index (Swarm_State); + Last_Element_Ix : constant Swarm_Element_Index := Last_Index (Swarm_State); + No_Of_Elements : constant Swarm_Element_Index := Swarm_Element_Index (Length (Swarm_State)); + Elements_Per_Task : constant Swarm_Element_Index := Natural'Max (1, No_Of_Elements / No_Of_CPU_Cores); + + begin + for Task_Index in Workers'First .. Workers'Last - 1 loop + declare + From_Ix : constant Integer := Swarm_Element_Index ((Integer (Task_Index) - Workers'First) * Elements_Per_Task + First_Element_Ix); + To_Ix : constant Integer := Swarm_Element_Index ((Integer (Task_Index) - Workers'First + 1) * Elements_Per_Task + First_Element_Ix - 1); + begin + if From_Ix >= First_Element_Ix and then To_Ix <= Last_Element_Ix then + Workers (Task_Index).Set_Job (Job, From_Ix, To_Ix); + else + Workers (Task_Index).Set_Job (No_Job, From_Ix, To_Ix); + end if;" +function Current_Discharge_Per_Sec return Real is,"(Charging_Setup.Constant_Discharge_Rate_Per_Sec + Charging_Setup.Propulsion_Discharge_Rate_Per_Sec * abs (Acceleration)); + + function Energy_Globes_Around return Energy_Globes is + + Globes_Found : Natural := 0; + Globes_Detected : array (Globes'Range) of Boolean := (others => False); + This_Element_Position : constant Positions := Position; + + begin + for Globe_Ix in Globes'Range loop + if abs (This_Element_Position - Globes (Globe_Ix).Position.all.Read) <= Energy_Globe_Detection then + Globes_Detected (Globe_Ix) := True; + Globes_Found := Globes_Found + 1; + end if; + end loop; + + declare + Found_Globes : Energy_Globes (1 .. Globes_Found); + Found_Globes_Ix : Natural := Globes'First; + begin + for Globe_Ix in Globes'Range loop + if Globes_Detected (Globe_Ix) then + Found_Globes (Found_Globes_Ix) := (Position => Globes (Globe_Ix).Position.all.Read, + Velocity => Globes (Globe_Ix).Velocity.all.Read); + Found_Globes_Ix := Found_Globes_Ix + 1; + end if; + end loop; + return Found_Globes;" +"function Cvt is new Ada.Unchecked_Conversion (I16, U16);","function Cvt is new Ada.Unchecked_Conversion (I32, U32); + function Cvt is new Ada.Unchecked_Conversion (U16, I16); + function Cvt is new Ada.Unchecked_Conversion (U32, I32); + + generic + type Number is mod <>; + procedure Read_Intel_x86_number (sb : in out GL.IO.Input_buffer; n : out Number); + + procedure Read_Intel_x86_number (sb : in out GL.IO.Input_buffer; n : out Number) is + b : U8; + m : Number := 1; + bytes : constant Integer := Number'Size / 8; + begin + n := 0; + for i in 1 .. bytes loop + GL.IO.Get_Byte (sb, b); + n := n + m * Number (b); + m := m * 256; + end loop; + end Read_Intel_x86_number; + + procedure Read_Double ( + sb : in out GL.IO.Input_buffer; + n : out GL.Double +) is + procedure Read_Intel is new Read_Intel_x86_number (U16); + procedure Read_Intel is new Read_Intel_x86_number (U32); + m1, m2 : U32; e : U16; + begin + Read_Intel (sb, m1); + Read_Intel (sb, m2); + Read_Intel (sb, e); + Merge (Cvt (m1), Cvt (m2), Cvt (e), n); + -- Double is stored in two parts due to the absence of + -- 64 - bit integers on certain compilers (e.g. OA 8.2) + end Read_Double; + + generic + s : Ada.Streams.Stream_IO.Stream_Access; + type Number is mod <>; + procedure Write_Intel_x86_number (n : in Number); + + procedure Write_Intel_x86_number (n : in Number) is + m : Number := n; + bytes : constant Integer := Number'Size/8; + begin + for i in 1 .. bytes loop + U8'Write (s, U8 (m mod 256)); + m := m / 256; + end loop; + end Write_Intel_x86_number; + + procedure Write_Double ( + s : Ada.Streams.Stream_IO.Stream_Access; + n : in GL.Double) + is + procedure Write_Intel is new Write_Intel_x86_number (s, U16); + procedure Write_Intel is new Write_Intel_x86_number (s, U32); + m1, m2 : I32; e : I16; + begin + Split (n, m1, m2, e); + -- Double is stored in two parts due to the absence of + -- 64 - bit integers on certain compilers (e.g. OA 8.2) + Write_Intel (Cvt (m1)); + Write_Intel (Cvt (m2)); + Write_Intel (Cvt (e)); + end Write_Double; + + procedure Write_String ( + s : in Ada.Streams.Stream_IO.Stream_Access; + str : in String +) + is + tstr : constant String := Trim (str, Right); + begin + U8'Write (s, tstr'Length); + String'Write (s, tstr); + end Write_String; + + procedure Read_String ( + sb : in out GL.IO.Input_buffer; + str : out String +) + is + l8 : U8; + l : Natural; + begin + GL.IO.Get_Byte (sb, l8); + l := Natural (l8); + if l > str'Length then + raise Constraint_Error; + end if; + for i in str'First .. str'First + l - 1 loop + GL.IO.Get_Byte (sb, l8); + str (i) := Character'Val (l8); + end loop; + str (str'First + l .. str'Last) := (others => ' '); + end Read_String; + + ------------------- + -- Object_3D I/O -- + ------------------- + + procedure Read ( + s : in Ada.Streams.Stream_IO.Stream_Access; + o : out p_Object_3D +) + is + + buf : GL.IO.Input_buffer; + + procedure Read_Intel is new Read_Intel_x86_number (U16); + procedure Read_Intel is new Read_Intel_x86_number (U32); + + procedure Read_Float (n : out GL.C_Float) is + m : U32; e : U16; + begin + Read_Intel (buf, m); + Read_Intel (buf, e); + Merge (Cvt (m), Cvt (e), n); + end Read_Float; + + procedure Read_Material_Float_vector (mfv : out GL.Material_Float_vector) is + begin + for i in mfv'Range loop + Read_Float (mfv (i)); + end loop; + end Read_Material_Float_vector; + + procedure Read_Point_3D (p : out Point_3D) is + begin + for i in p'Range loop + Read_Double (buf, p (i)); + end loop; + end Read_Point_3D; + + procedure Read_Map_idx_pair_array (m : out Map_idx_pair_array) is + begin + for i in m'Range loop + Read_Double (buf, m (i).U); + Read_Double (buf, m (i).V); + end loop; + end Read_Map_idx_pair_array; + + v8 : U8; + v32, mp32, mf32 : U32; + + procedure Read_face (face : out Face_type; face_invar : in out Face_invariant_type) is + begin + -- 1/ Points + for i in face.p'Range loop + Read_Intel (buf, v32); + face.p (i) := Integer (v32); + end loop; + -- 2/ Portal connection : object name is stored; + -- access must be found later + Read_String (buf, face_invar.connect_name); + -- 3/ Skin + GL.IO.Get_Byte (buf, v8); + face.skin := Skin_Type'Val (v8); + -- 4/ Mirror + GL.IO.Get_Byte (buf, v8); + face.mirror := Boolean'Val (v8); + -- 5/ Alpha + Read_Double (buf, face.alpha); + -- 6/ Colour + case face.skin is + when colour_only | coloured_texture => + Read_Double (buf, face.colour.red); + Read_Double (buf, face.colour.green); + Read_Double (buf, face.colour.blue); + when others => + null; + end case; + -- 7/ Material + case face.skin is + when material_only | material_texture => + Read_Material_Float_vector (face.material.ambient); + Read_Material_Float_vector (face.material.diffuse); + Read_Material_Float_vector (face.material.specular); + Read_Material_Float_vector (face.material.emission); + Read_Float (face.material.shininess); + when others => + null; + end case; + -- 8/ Texture : texture name is stored; + -- id must be found later + Read_String (buf, face_invar.texture_name); + GL.IO.Get_Byte (buf, v8); + face.whole_texture := Boolean'Val (v8); + GL.IO.Get_Byte (buf, v8); + face.repeat_U := Positive'Val (v8); + GL.IO.Get_Byte (buf, v8); + face.repeat_V := Positive'Val (v8); + if not face.whole_texture then + Read_Map_idx_pair_array (face.texture_edge_map); + end if; + end Read_face; + test_signature : String (signature_obj'Range); + ID : Ident; + begin + String'Read (s, test_signature); + if test_signature /= signature_obj then + raise Bad_data_format; + end if; + GL.IO.Attach_Stream (b => buf, stm => s); + Read_String (buf, ID); + -- Read the object's dimensions, create object, read its contents + Read_Intel (buf, mp32); + Read_Intel (buf, mf32); + o := new Object_3D (Integer (mp32), Integer (mf32)); + o.ID := ID; + for p in o.Point'Range loop + Read_Point_3D (o.Point (p)); + end loop; + for f in o.face'Range loop + Read_face (o.face (f), o.face_invariant (f)); + end loop; + Read_Point_3D (o.Centre); + for i in Matrix_33'Range (1) loop + for j in Matrix_33'Range (2) loop + Read_Double (buf, o.rotation (i, j)); + end loop; + end loop; + -- !! sub - objects : skipped !! + -- Main operation done! + end Read; + + procedure Write ( + s : in Ada.Streams.Stream_IO.Stream_Access; + o : in Object_3D +) + is + + procedure Write_Intel is new Write_Intel_x86_number (s, U16); + procedure Write_Intel is new Write_Intel_x86_number (s, U32); + + procedure Write_Float (n : in GL.C_Float) is + m : I32; e : I16; + begin + Split (n, m, e); + Write_Intel (Cvt (m)); + Write_Intel (Cvt (e)); + end Write_Float; + + procedure Write_Material_Float_vector (mfv : in GL.Material_Float_vector) is + begin + for i in mfv'Range loop + Write_Float (mfv (i)); + end loop; + end Write_Material_Float_vector; + + procedure Write_Point_3D (p : in Point_3D) is + begin + for i in p'Range loop + Write_Double (s, p (i)); + end loop; + end Write_Point_3D; + + procedure Write_Map_idx_pair_array (m : in Map_idx_pair_array) is + begin + for i in m'Range loop + Write_Double (s, m (i).U); + Write_Double (s, m (i).V); + end loop; + end Write_Map_idx_pair_array; + + procedure Write_face (face : Face_type; face_invar : Face_invariant_type) is + begin + -- 1/ Points + for i in face.p'Range loop + Write_Intel (U32 (face.p (i))); + end loop; + -- 2/ Portal connection : object name is stored + if face.connecting = null then + Write_String (s, empty); + else + Write_String (s, face.connecting.ID); + end if; + -- 3/ Skin + U8'Write (s, Skin_Type'Pos (face.skin)); + -- 4/ Mirror + U8'Write (s, Boolean'Pos (face.mirror)); + -- 5/ Alpha + Write_Double (s, face.alpha); + -- 6/ Colour + case face.skin is + when colour_only | coloured_texture => + Write_Double (s, face.colour.red); + Write_Double (s, face.colour.green); + Write_Double (s, face.colour.blue); + when others => + null; + end case; + -- 7/ Material + case face.skin is + when material_only | material_texture => + Write_Material_Float_vector (face.material.ambient); + Write_Material_Float_vector (face.material.diffuse); + Write_Material_Float_vector (face.material.specular); + Write_Material_Float_vector (face.material.emission); + Write_Float (face.material.shininess); + when others => + null; + end case; + -- 8/ Texture : texture name is stored + if face.texture = null_image then + -- Maybe a texture name has been given with Texture_name_hint, + -- but was not yet attached to a GL ID number through Rebuild_Links + Write_String (s, face_invar.texture_name); + else + -- Usual way : We can get the texture name associated to the + -- GL ID number; name is stored by GLOBE_3D.Textures. + Write_String (s, Textures.Texture_name (face.texture, False)); + end if; + U8'Write (s, Boolean'Pos (face.whole_texture)); + U8'Write (s, Positive'Pos (face.repeat_U)); + U8'Write (s, Positive'Pos (face.repeat_V)); + if not face.whole_texture then + Write_Map_idx_pair_array (face.texture_edge_map); + end if; + end Write_face; + + begin + String'Write (s, signature_obj); + Write_String (s, o.ID); + Write_Intel (U32 (o.Max_points)); + Write_Intel (U32 (o.Max_faces)); + for p in o.Point'Range loop + Write_Point_3D (o.Point (p)); + end loop; + for f in o.face'Range loop + Write_face (o.face (f), o.face_invariant (f)); + end loop; + Write_Point_3D (o.Centre); + for i in Matrix_33'Range (1) loop + for j in Matrix_33'Range (2) loop + Write_Double (s, o.rotation (i, j)); + end loop; + end loop; + -- !! sub - objects : skipped !! + -- Main operation done! + end Write; + + generic + type Anything is private; + extension : String; + animal : String; + with procedure Read ( + s : in Ada.Streams.Stream_IO.Stream_Access; + a : out Anything +); + procedure Load_generic (name_in_resource : String; a : out Anything); + + procedure Load_generic (name_in_resource : String; a : out Anything) is + name_ext : constant String := name_in_resource & extension; + + procedure Try (zif : in out Zip.Zip_info; name : String) is + use UnZip.Streams; + fobj : Zipped_File_Type; + begin -- Try + Load_if_needed (zif, name); + Open (fobj, zif, name_ext); + Read (Stream (fobj), a); + Close (fobj); + exception + when Zip.File_name_not_found => + raise; + when e:others => + Raise_Exception ( + Exception_Identity (e), + Exception_Message (e) & "" on "" & animal & "" : "" & name_ext +); + end Try; + begin + begin + Try (zif_level, To_String (level_data_name)); + exception + when Zip.File_name_not_found | + Zip.Zip_file_open_Error => + -- Not found in level - specific pack + Try (zif_global, To_String (global_data_name));" +procedure Load_Internal is,"new Load_generic ( + Anything => p_Object_3D, + extension => object_extension, + animal => ""object"", + Read => Read +); + + procedure Load (name_in_resource : String; o : out p_Object_3D) + renames Load_Internal; + + procedure Load_file (file_name : String; o : out p_Object_3D) is + use Ada.Streams.Stream_IO; + f : File_Type; + begin + Open (f, in_file, file_name); + Read (Stream (f), o); + Close (f); + end Load_file; + + procedure Save_file (file_name : String; o : in Object_3D'Class) is + use Ada.Streams.Stream_IO; + f : File_Type; + begin + Create (f, out_file, file_name); + Write (Stream (f), Object_3D (o)); + -- ^ endian - proof and floating - point hardware neutral; + -- using stream attribute would be machine - specific. + Close (f); + end Save_file; + + procedure Save_file (o : in Object_3D'Class) is + begin + Save_file (Trim (o.ID, Right) & object_extension, o); + end Save_file; + + ------------- + -- BSP I/O -- + ------------- + + -- Write a BSP tree to a stream + + procedure Write ( + s : in Ada.Streams.Stream_IO.Stream_Access; + tree : in BSP.p_BSP_node +) + is + procedure Write_Intel is new Write_Intel_x86_number (s, U32); + use BSP; + + n : Natural := 0; + + procedure Numbering (node : p_BSP_node) is + begin + if node /= null then + n := n + 1; + node.node_id := n; + Numbering (node.front_child); + Numbering (node.back_child); + end if; + end Numbering; + + procedure Save_node (node : p_BSP_node) is + begin + if node /= null then + Write_Intel (U32 (node.node_id)); + if node.front_child = null then + Write_Intel (U32' (0)); + if node.front_leaf = null then + Write_String (s, empty); + else + Write_String (s, node.front_leaf.ID); + end if; + else + Write_Intel (U32 (node.front_child.node_id)); + end if; + if node.back_child = null then + Write_Intel (U32' (0)); + if node.back_leaf = null then + Write_String (s, empty); + else + Write_String (s, node.back_leaf.ID); + end if; + else + Write_Intel (U32 (node.back_child.node_id)); + end if; + for i in node.normal'Range loop + Write_Double (s, node.normal (i)); + end loop; + Write_Double (s, node.distance); + -- + Save_node (node.front_child); + Save_node (node.back_child); + end if; + end Save_node; + + begin + Numbering (tree); -- fill the node_id's + String'Write (s, signature_bsp); -- header + Write_Intel (U32 (n)); -- give the number of nodes first + Save_node (tree); + end Write; + + -- Write a BSP tree to a file + + procedure Save_file (file_name : String; tree : in BSP.p_BSP_node) is + use Ada.Streams.Stream_IO; + f : File_Type; + begin + if Index (file_name, ""."")=0 then + Create (f, out_file, file_name & BSP_extension); + else + Create (f, out_file, file_name); + end if; + Write (Stream (f), tree); + Close (f); + end Save_file; + + procedure Load ( + name_in_resource : in String; + referred : in Map_of_Visuals; + tree : out BSP.p_BSP_node +) + is + + function Find_object (ID : Ident; tolerant : Boolean) return p_Object_3D is + begin + if ID = empty then + return null; + else + return p_Object_3D ( + Visuals_Mapping.Element ( + Container => Visuals_Mapping.Map (referred), + Key => Ada.Strings.Unbounded.To_Unbounded_String (ID) +) +); + end if; + exception + when Constraint_Error => + -- GNAT gives also the message: + -- no element available because key not in map + if tolerant then + return null; + else + Raise_Exception ( + Missing_object_in_BSP'Identity, + ""Object not found : ["" & Trim (ID, Right) & ']' +); + end if; + end Find_object; + + procedure Read ( + s : in Ada.Streams.Stream_IO.Stream_Access; + tree : out BSP.p_BSP_node +) + is + use BSP; + buf : GL.IO.Input_buffer; + procedure Read_Intel is new Read_Intel_x86_number (U32); + + test_signature : String (signature_bsp'Range); + n, j, k : U32; + ID : Ident; + tol : constant Boolean := False; + begin + String'Read (s, test_signature); + if test_signature /= signature_bsp then + raise Bad_data_format; + end if; + GL.IO.Attach_Stream (b => buf, stm => s); + Read_Intel (buf, n); + if n < 1 then + tree := null; + return; + end if; + declare + -- We put all the new - born nodes into a farm with numbered boxes, + -- because only the numbers are stored in the BSP file. + -- Once the nodes are linked together through accesses (pointers), + -- we can forget the farm and let the tree float .. . + farm : array (0 .. n) of p_BSP_Node; + begin + farm (0) := null; + for i in 1 .. n loop + farm (i) := new BSP_Node; + end loop; + for i in 1 .. n loop + Read_Intel (buf, j); -- node_id + farm (j).node_id := Integer (j); + Read_Intel (buf, k); + farm (j).front_child := farm (k); + if k = 0 then -- it is a front leaf - > associate object + Read_String (buf, ID); + farm (j).front_leaf := Find_object (ID, tol); + end if; + Read_Intel (buf, k); + farm (j).back_child := farm (k); + if k = 0 then -- it is a back leaf - > associate object + Read_String (buf, ID); + farm (j).back_leaf := Find_object (ID, tol); + end if; + -- The node's geometric information (a plane): + for ii in farm (j).normal'Range loop + Read_Double (buf, farm (j).normal (ii)); + end loop; + Read_Double (buf, farm (j).distance); + end loop; + tree := farm (1);" +"procedure Deallocate is new Ada.Unchecked_Deallocation (Visual'Class, p_Visual);","begin + Destroy (o.all); + Deallocate (o); + end Free; + + function skinned_Geometrys (o : Visual) return GL.Skinned_Geometry.skinned_Geometrys is + (GL.Skinned_Geometry.null_skinned_Geometrys); + + function Width (o : Visual'class) return Real is + (Bounds (o).Box.X_Extent.Max - Bounds (o).Box.X_Extent.Min); + + function Height (o : Visual'class) return Real is + (Bounds (o).Box.Y_Extent.Max - Bounds (o).Box.Y_Extent.Min); + + function Depth (o : Visual'class) return Real is + (Bounds (o).Box.Z_Extent.Max - Bounds (o).Box.Z_Extent.Min); + + -- 'Object_3D' + -- + + -- object validation + -- + + procedure Check_object (o : Object_3D) is + + use G3DM; + + procedure Check_faces is + + procedure Check (f, v : Integer) is + pragma Inline (Check); + begin + if v < 0 or else v > o.Max_points then + Raise_Exception (bad_vertex_number'Identity, + o.ID & "" face ="" & Integer'Image (f) & + "" vertex ="" & Integer'Image (v)); + end if; + end Check; + + procedure Check_duplicate (f, Pn1, Pn2 : Integer) is + pragma Inline (Check_duplicate); + begin + -- Skip ""dead"" edge (triangle), 30 - Dec - 2001 + if Pn1 = 0 or else Pn2 = 0 then + return; + end if; + -- Detect same point number + if Pn1 = Pn2 then + Raise_Exception (duplicated_vertex'Identity, + o.ID & "" in face "" & Integer'Image (f)); + end if; + -- Detect same point coordinates (tolerated in an object, + -- although inefficient, but harms as vertex of the same face!) + + if Almost_zero (Norm2 (o.Point (Pn1) - o.Point (Pn2))) then + Raise_Exception (duplicated_vertex_location'Identity, + o.ID & "" in face "" & Integer'Image (f)); + end if; + end Check_duplicate; + + begin + for fa in o.face'Range loop + for edge_num in 1 .. 4 loop + Check (fa, o.face (fa).P (edge_num)); + for other_edge in edge_num + 1 .. 4 loop + Check_duplicate (fa, o.face (fa).P (edge_num), + o.face (fa).P (other_edge)); + end loop; + end loop; + end loop; -- fa + end Check_faces; + + begin + Check_faces; + end Check_object; + + -------------------------------------------- + -- Object initialization (1x in its life) -- + -------------------------------------------- + + overriding procedure Pre_calculate (o : in out Object_3D) is + + use G3DM; + + N : Vector_3D; + length_N : Real; + + procedure Calculate_face_invariants ( + fa : Face_type; + fi : out Face_invariant_type + ) is + l : Natural := 0; + quadri_edge : array (fa.P'Range) of Natural; + ex_U, ex_V : Real; + begin + l := 0; + for qe in fa.P'Range loop + if fa.P (qe) /= 0 then + l := l + 1; + quadri_edge (l) := qe; -- if triangle, ""map"" edge on a quadri + fi.P_compact (l) := fa.P (qe); + end if; + end loop; + if l in Edge_count then + fi.last_edge := l; + else + Raise_Exception (bad_edge_number'Identity, o.ID); + end if; + -- * Face invariant : Textured face : extremities + for e in 1 .. l loop + if fa.whole_texture then + ex_U := Real (fa.repeat_U); + ex_V := Real (fa.repeat_V); + case quadri_edge (e) is + when 1 => fi.UV_extrema (e) := (0.0, 0.0); -- bottom, left 4 --< --3 + when 2 => fi.UV_extrema (e) := (ex_U, 0.0); -- bottom, right | | + when 3 => fi.UV_extrema (e) := (ex_U, ex_V); -- top, right 1 --> --2 + when 4 => fi.UV_extrema (e) := (0.0, ex_V); -- top, left + when others => null; + end case; + else + -- Just copy the mapping, but in compact form for triangles : + fi.UV_extrema (e) := fa.texture_edge_map (quadri_edge (e)); + end if; + end loop; + -- * Face invariant : Normal of unrotated face + N := (0.0, 0.0, 0.0); + case fi.last_edge is + when 3 => + Add_Normal_of_3p (o, + fi.P_compact (1), + fi.P_compact (2), + fi.P_compact (3), + N + ); + when 4 => + Add_Normal_of_3p (o, fa.P (1), fa.P (2), fa.P (4), N); + -- We sum other normals for not perfectly flat faces, + -- in order to have a convenient average .. . + Add_Normal_of_3p (o, fa.P (2), fa.P (3), fa.P (1), N); + Add_Normal_of_3p (o, fa.P (3), fa.P (4), fa.P (2), N); + Add_Normal_of_3p (o, fa.P (4), fa.P (1), fa.P (3), N); + end case; + length_N := Norm (N); + if Almost_zero (length_N) then + if strict_geometry then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + raise zero_summed_normal; + pragma Warnings (On, ""this code can never be executed and has been deleted""); + else + fi.normal := N; -- 0 vector ! + end if; + else + fi.normal := (1.0 / length_N) * N; + end if; + end Calculate_face_invariants; + + adjacent_faces : array (o.Point'Range) of Natural := (others => 0); + pf : Natural; + length : Real; + + begin -- Pre_calculate + if full_check_objects then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Check_object (o); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + + for i in o.face'Range loop + begin + -- Geometry + Calculate_face_invariants (o.face (i), o.Face_Invariant (i)); + -- Disable blending when alphas are = 1 + case o.face (i).skin is + when material_only | material_texture => + o.Face_Invariant (i).blending := Is_to_blend (o.face (i).material); + when colour_only | coloured_texture | texture_only => + o.Face_Invariant (i).blending := Is_to_blend (o.face (i).alpha); + when invisible => + o.Face_Invariant (i).blending := False; + end case; + o.transparent := o.transparent or else o.Face_Invariant (i).blending; + exception + when zero_summed_normal => + Raise_Exception (zero_summed_normal'Identity, + o.ID & "" face ="" & Integer'Image (i));" +procedure Display_one (o : in out Object_3D) is,"-- Display only this object and not connected objects + -- out : object will be initialized if not yet + + -- + + -- + -- Display face routine which is optimized to produce a shorter list + -- of GL commands. Runs slower then the original Display face routine + -- yet needs to be executed only once. + -- + -- Uwe R. Zimmer, July 2011 + -- + package Display_face_optimized is + procedure Display_face (First_Face : Boolean; fa : Face_type; fi : in out Face_invariant_type); + private + Previous_face : Face_type; + Previous_face_Invariant : Face_invariant_type; + end Display_face_optimized; + + package body Display_face_optimized is + + use GL.Materials; + + procedure Display_face (First_Face : Boolean; fa : Face_type; fi : in out Face_invariant_type) is + + blending_hint : Boolean; + + begin -- Display_face + + if fa.skin = invisible then + Previous_face := fa; + Previous_face_Invariant := fi; + return; + end if; + + -------------- + -- Material -- + -------------- + + if First_Face + or else Previous_face.skin = invisible + or else fa.skin /= Previous_face.skin + or else (fa.skin = Previous_face.skin + and then fa.material /= Previous_face.material) + then + case fa.skin is + when material_only | material_texture => + Disable (COLOR_MATERIAL); + Set_Material (fa.material); + when others => + Set_Material (GL.Materials.neutral_material); + end case; + end if; + + ------------ + -- Colour -- + ------------ + + if First_Face + or else Previous_face.skin = invisible + or else fa.skin /= Previous_face.skin + or else (fa.skin = Previous_face.skin + and then (fa.colour /= Previous_face.colour + or else fa.alpha /= Previous_face.alpha)) + then + case fa.skin is + when material_only | material_texture => + null; -- done above + when colour_only | coloured_texture => + Enable (COLOR_MATERIAL); + ColorMaterial (FRONT_AND_BACK, AMBIENT_AND_DIFFUSE); + Color ( + red => fa.colour.Red, + green => fa.colour.Green, + blue => fa.colour.Blue, + alpha => fa.alpha + ); + when texture_only => + Disable (COLOR_MATERIAL); + when invisible => + null; + end case; + end if; + + ------------- + -- Texture -- + ------------- + + if is_textured (fa.skin) then + G3DT.Check_2D_texture (fa.texture, blending_hint); + if blending_hint then + fi.blending := True; + -- 13 - Oct - 2006 : override the decision made at Pre_calculate. + -- If texture data contains an alpha layer, we switch + -- on transparency. + end if; + end if; + + if First_Face + or else Previous_face.skin = invisible + or else fa.skin /= Previous_face.skin + or else (fa.skin = Previous_face.skin + and then fa.texture /= Previous_face.texture) + then + case fa.skin is + when texture_only | coloured_texture | material_texture => + Enable (TEXTURE_2D); + GL.BindTexture (GL.TEXTURE_2D, GL.Uint (Image_ID'Pos (fa.texture) + 1)); + -- ^ superfluous ?!! + when colour_only | material_only => + Disable (TEXTURE_2D); + when invisible => + null; + end case; + end if; + + ----------------------------- + -- Blending / transparency -- + ----------------------------- + + if First_Face + or else Previous_face.skin = invisible + or else fi.blending /= Previous_face_Invariant.blending + then + if fi.blending then + Enable (BLEND); -- See 4.1.7 Blending + BlendFunc (sfactor => SRC_ALPHA, + dfactor => ONE_MINUS_SRC_ALPHA); + -- Disable (DEPTH_TEST); + -- Disable (CULL_FACE); + else + Disable (BLEND); + -- Enable (DEPTH_TEST); + -- Enable (CULL_FACE); + -- CullFace (BACK); + end if; + end if; + + ------------- + -- Drawing -- + ------------- + + case fi.last_edge is + when 3 => GL_Begin (TRIANGLES); + when 4 => GL_Begin (QUADS); + end case; + + for i in 1 .. fi.last_edge loop + if is_textured (fa.skin) then + TexCoord (fi.UV_extrema (i).U, fi.UV_extrema (i).V); + end if; + Normal (o.edge_vector (fi.P_compact (i))); + Vertex (o.Point (fi.P_compact (i))); + end loop; + + GL_End; + + Previous_face := fa; + Previous_face_Invariant := fi; + end Display_face; + + end Display_face_optimized; + + procedure Display_normals is + + use G3DM; + + C : Vector_3D; + + begin + GL.Color (0.5, 0.5, 1.0, 1.0); + -- show pseudo (average) normals at edges : + for e in o.Point'Range loop + Arrow (o.Point (e), arrow_inflator * o.edge_vector (e)); + end loop; + GL.Color (1.0, 1.0, 0.5, 1.0); + -- show normals of faces : + for f in o.face'Range loop + C := (0.0, 0.0, 0.0); + for i in 1 .. o.Face_Invariant (f).last_edge loop + C := C + o.Point (o.Face_Invariant (f).P_compact (i)); + end loop; + C := (1.0 / Real (o.Face_Invariant (f).last_edge)) * C; + Arrow (C, arrow_inflator * o.Face_Invariant (f).normal); + end loop; + end Display_normals; + + use G3DM; + + begin -- Display_one + + if not o.pre_calculated then + Pre_calculate (o); + end if; + + GL.BindBuffer (GL.ARRAY_BUFFER, 0); -- disable 'vertex buffer objects' + GL.BindBuffer (GL.ELEMENT_ARRAY_BUFFER, 0); -- disable 'vertex buffer objects' indices + + -- gl.disableClientState (gl.TEXTURE_COORD_ARRAY); + -- gl.disable (ALPHA_TEST); + GL.Enable (LIGHTING); + + GL.PushMatrix; -- 26 - May - 2006 : instead of rotating/translating back + GL.Translate (o.Centre); + Multiply_GL_Matrix (o.rotation); + + -- List preparation phase + case o.List_Status is + when No_List | Is_List => + null; + + when Generate_List => + o.List_Id := Integer (GL.GenLists (1)); + GL.NewList (GL.Uint (o.List_Id), COMPILE_AND_EXECUTE); + end case; + + -- Execution phase + case o.List_Status is + when No_List => + for f in o.face'Range loop + Display_face_optimized.Display_face (True, o.face (f), o.Face_Invariant (f)); + -- We mimic the old Display_face with redundant color, material, etc. + -- instructions by passing True for First_Face. + end loop; + when Generate_List => + for f in o.face'Range loop + Display_face_optimized.Display_face (f = o.face'First, o.face (f), o.Face_Invariant (f)); + end loop; + + when Is_List => GL.CallList (GL.Uint (o.List_Id)); + end case; + + -- Close list + case o.List_Status is + when No_List | Is_List => null; + + when Generate_List => + GL.EndList; + if GL.Get_Error = OUT_OF_MEMORY then + o.List_Status := No_List; + else + o.List_Status := Is_List; + end if; + end case; + + if show_normals then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + GL.Disable (GL.LIGHTING); + GL.Disable (GL.TEXTURE_2D); + Display_normals; + GL.Enable (GL.LIGHTING); -- mmmh .. . + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + + GL.PopMatrix; -- 26 - May - 2006 : instead of rotating/translating back + -- GL.Rotate (o.auto_rotation (2), 0.0, 0.0, - 1.0); + -- GL.Rotate (o.auto_rotation (1), 0.0, - 1.0, 0.0); + -- GL.Rotate (o.auto_rotation (0), - 1.0, 0.0, 0.0); + + -- GL.Translate ( - o.centre); + end Display_one; + + overriding procedure Display (o : in out Object_3D; + clip : Clipping_data) is + + use GLOBE_3D.Portals; + + procedure Display_clipped (o : in out Object_3D'Class; + clip_area : Clipping_area; + portal_depth : Natural) is + + procedure Try_portal (f : Positive) is + + use G3DM; + + dp : Real; + plane_to_eye : Vector_3D; -- vector from any point in plane to the eye + bounding_of_face, intersection_clip_and_face : Clipping_area; + success, non_empty_intersection : Boolean; + + begin + -- Culling #1 : check if portal is in vield of view's ""dead angle"" + dp := o.Face_Invariant (f).normal * clip.view_direction; + if dp < clip.max_dot_product then + -- Culling #2 : check if we are on the right side of the portal + -- NB : ignores o.auto_rotation ! + plane_to_eye := + clip.Eye_Position - + (o.Point (o.Face_Invariant (f).P_compact (1)) + o.Centre) + ; + dp := plane_to_eye * o.Face_Invariant (f).normal; + -- dp = signed distance to the plane + if dp > 0.0 then + -- Culling #3 : clipping rectangle + Find_bounding_box (o, f, bounding_of_face, success); + if success then + Intersect (clip_area, bounding_of_face, + intersection_clip_and_face, non_empty_intersection); + else + -- in doubt, draw with the present clipping + intersection_clip_and_face := clip_area; + non_empty_intersection := True; + end if; + if non_empty_intersection then + -- Recursion here : + Display_clipped ( + o => o.face (f).connecting.all, + clip_area => intersection_clip_and_face, + portal_depth => portal_depth + 1 + ); + end if; + end if; + end if; + end Try_portal; + + begin -- Display_clipped + if not o.pre_calculated then + Pre_calculate (o); + end if; + -- + -- a/ Display connected objects which are visible through o's faces + -- This is where recursion happens + if (not filter_portal_depth) or else -- filter_portal_depth : test/debug + portal_depth <= 6 + then + for f in o.face'Range loop + if o.face (f).connecting /= null and then + not o.Face_Invariant (f).portal_seen + -- ^ prevents infinite recursion on rare cases where + -- object A or B is not convex, and A and B see each other + -- and the culling by clipping cannot stop the recursion + -- (e.g. origin2.proc, tomb.proc) + -- + -- NB : drawing [different parts of] the same object several times + -- is right, since portions can be seen through different portals, + -- but going more than once through the same portal is wrong + then + o.Face_Invariant (f).portal_seen := True; + Try_portal (f); + -- ^ recursively calls Display_clipped for + -- objects visible through face f. + end if; + end loop; + end if; + -- b/ Display the object itself + if (not filter_portal_depth) or else -- filter_portal_depth : test/debug + (portal_depth = 1 or else portal_depth = 5) + then + -- The graphical clipping (Scissor) gives various effects + -- - almost no speedup on the ATI Radeon 9600 Pro (hardware) + -- - factor : ~ Sqrt (clipped surface ratio) with software GL + if portal_depth > 0 then + GL.Enable (GL.SCISSOR_TEST); + GL.Scissor (x => GL.Int (clip_area.X1), + y => GL.Int (clip_area.Y1), + width => GL.Sizei (clip_area.X2 - clip_area.X1 + 1), + height => GL.Sizei (clip_area.Y2 - clip_area.Y1 + 1)); + else + GL.Disable (GL.SCISSOR_TEST); + end if; + info_b_ntl2 := info_b_ntl2 + 1; + info_b_ntl3 := Natural'Max (portal_depth, info_b_ntl3); + Display_one (o); + end if; + if show_portals and then portal_depth > 0 then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Draw_boundary (clip.main_clipping, clip_area); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end Display_clipped; + + procedure Reset_portal_seen (o : in out Object_3D'Class) is + begin + for f in o.face'Range loop + if o.Face_Invariant (f).portal_seen then + o.Face_Invariant (f).portal_seen := False; + Reset_portal_seen (o.face (f).connecting.all); + end if; + end loop; + end Reset_portal_seen; + + begin + info_b_ntl2 := 0; -- count amount of objects displayed, not distinct + info_b_ntl3 := 0; -- records max depth + Display_clipped (o, clip_area => clip.main_clipping, portal_depth => 0); + Reset_portal_seen (o); + end Display; + + overriding procedure Destroy (o : in out Object_3D) is + + ol : p_Object_3D_list := o.sub_objects; + + begin + while ol /= null loop + Free (p_Visual (ol.all.objc)); + ol := ol.all.next; + end loop; + end Destroy; + + overriding procedure set_Alpha (o : in out Object_3D; Alpha : GL.Double) is + + begin + for f in o.face'Range loop + o.face (f).alpha := Alpha; + end loop; + end set_Alpha; + + overriding function is_Transparent (o : Object_3D) return Boolean is + + begin + return o.transparent; + end is_Transparent; + + overriding function face_Count (o : Object_3D) return Natural is + + begin + return o.Max_faces; + end face_Count; + + overriding function Bounds (o : Object_3D) return GL.Geometry.Bounds_record is + + begin + return o.Bounds; + end Bounds; + + -- Lighting support. + -- + + -- lights : array (Light_ident) of Light_definition; + light_defined : array (Light_ident) of Boolean := (others => False); + + procedure Define (which : Light_ident; as : Light_definition) is + + id : constant GL.LightIDEnm := GL.LightIDEnm'Val (which - 1); + + begin + -- lights (which) := as; + Light (id, POSITION, as.position); + Light (id, AMBIENT, as.ambient); + Light (id, DIFFUSE, as.diffuse); + Light (id, SPECULAR, as.specular); + light_defined (which) := True; + end Define; + + procedure Switch_lights (on : Boolean) is + + begin + for l in Light_ident loop + Switch_light (l, on); + end loop; + end Switch_lights; + + function Server_id (which : Light_ident) return GL.ServerCapabilityEnm is + + begin + return GL.ServerCapabilityEnm'Val (GL.ServerCapabilityEnm'Pos (GL.LIGHT0) + which - 1); + end Server_id; + + procedure Switch_light (which : Light_ident; on : Boolean) is + + begin + if light_defined (which) then + if on then + GL.Enable (Server_id (which)); + else + GL.Disable (Server_id (which)); + end if; + end if; + end Switch_light; + + function Is_light_switched (which : Light_ident) return Boolean is + + begin + return Boolean'Val (GL.IsEnabled (Server_id (which))); + end Is_light_switched; + + procedure Reverse_light_switch (which : Light_ident) is + + begin + Switch_light (which, not Is_light_switched (which)); + end Reverse_light_switch; + + prec_a360 : constant := 10000; + r_prec_a360 : constant := 10000.0; + i_r_prec_a360 : constant := 1.0 / r_prec_a360; + + procedure Angles_modulo_360 (v : in out Vector_3D) is + + begin + for i in v'Range loop + v (i) := + GL.Double (Integer (r_prec_a360 * v (i)) mod (360 * prec_a360)) + * i_r_prec_a360; + end loop; + end Angles_modulo_360; + + ------------------ + -- Resource I/O -- + ------------------ + + procedure Load_if_needed (zif : in out Zip.Zip_info; name : String) is + + begin + if not Zip.Is_loaded (zif) then + begin + Zip.Load (zif, name); + exception + when Zip.Zip_file_open_Error => -- Try with lower case : + Zip.Load (zif, To_Lower (name));" +"procedure sort is new Ada.Containers.Generic_Array_Sort (Positive,","Visual_Geometry, + Visual_Geometries); + use GL.Skins, GL.Geometry, GL.Skinned_Geometry; + + current_Visual : p_Visual; + + begin + if geometry_Count > 1 then + sort (All_Geometries (1 .. geometry_Count)); + end if; + + GL.PushMatrix; + + for Each in 1 .. geometry_Count loop + + if All_Geometries (Each).Geometry.Skin /= current_Skin then + current_Skin := All_Geometries (Each).Geometry.Skin; + Enable (current_Skin.all); + GL.Errors.log; + end if; + + if All_Geometries (Each).Geometry.Veneer /= null then + Enable (All_Geometries (Each).Geometry.Veneer.all); + GL.Errors.log; + end if; + + if All_Geometries (Each).Visual = current_Visual then + Draw (All_Geometries (Each).Geometry.Geometry.all); + GL.Errors.log; + else + GL.PopMatrix; + GL.PushMatrix; + GL.Translate (All_Geometries (Each).Visual.all.Centre); + Multiply_GL_Matrix (All_Geometries (Each).Visual.all.rotation); + + Draw (All_Geometries (Each).Geometry.Geometry.all); + GL.Errors.log; + + current_Visual := All_Geometries (Each).Visual; + end if; + + end loop; + + GL.PopMatrix;" +"-- procedure sort is new Ada.Containers.Generic_Array_Sort (Positive,","procedure sort is new Ada.Containers.Generic_Array_Sort (Positive, + GLOBE_3D.p_Visual, + GLOBE_3D.Visual_array); + begin + for Each in 1 .. transparent_Count loop -- pre - calculate each visuals Centre in camera space. + all_Transparents (Each).all.Centre_Camera_Space := the_Camera.World_Rotation + * (all_Transparents (Each).all.Centre - the_Camera.Clipper.Eye_Position); + end loop; + + if transparent_Count > 1 then + sort (all_Transparents (1 .. transparent_Count)); + end if; + + GL.Depth_Mask (GL_False); -- make depth buffer read - only, for correct transparency + + Enable (LIGHTING); -- ensure lighting is enabled for G3D.Display of transparents (obsolete). + Enable (BLEND); + BlendFunc (sfactor => ONE, + dfactor => ONE_MINUS_SRC_ALPHA); + + for Each_Transparency in 1 .. transparent_Count loop + declare + the_Visual : Visual'Class renames all_Transparents (Each_Transparency).all; + visual_Geometrys : constant GL.Skinned_Geometry.skinned_Geometrys := skinned_Geometrys (the_Visual); -- tbd : apply ogl state sorting here ? + begin + Display (the_Visual, the_Camera.Clipper); + GL.Errors.log; + + for Each_Geometry in visual_Geometrys'Range loop + declare + use GL.Skins, GL.Geometry; + the_Geometry : GL.Skinned_Geometry.Skinned_Geometry_t renames visual_Geometrys (Each_Geometry); + begin + + if the_Geometry.Skin /= current_Skin then + current_Skin := the_Geometry.Skin; + Enable (current_Skin.all); + GL.Errors.log; + end if; + + if the_Geometry.Veneer /= null then + Enable (the_Geometry.Veneer.all); + GL.Errors.log; + end if; + + GL.PushMatrix; + + GL.Translate (the_Visual.Centre); + Multiply_GL_Matrix (the_Visual.rotation); + + Draw (the_Geometry.Geometry.all); + GL.Errors.log; + + GL.PopMatrix;" +"function to_Window is new Ada.Unchecked_Conversion (System.Address, GLOBE_3D.p_Window);","begin + return GLUT.Windows.Window_view (to_Window (GetWindowData)); + end current_Window; + + procedure Name_is (Self : in out Window; Now : String) is + + begin + Self.Name := To_Unbounded_String (Now); + end Name_is; + + function Name (Self : Window) return String is (To_String (Self.Name)); + + function is_Closed (Self : Window) return Boolean is (Self.is_Closed); + + procedure Prepare_default_lighting (Self : in out Window; + fact : GL.C_Float) is + + proto_light : G3D.Light_definition := (position => (0.0, 500.0, 0.0, 1.0), + ambient => (0.3, 0.3, 0.3, fact), + diffuse => (0.9, 0.9, 0.9, fact), + specular => (0.05, 0.05, 0.01, fact)); + begin + GL.Enable (GL.LIGHTING); + + G3D.Define (1, proto_light); + Self.frontal_light := proto_light; + + proto_light.diffuse := (0.5, 0.9, 0.5, fact); + G3D.Define (2, proto_light); + + proto_light.diffuse := (0.2, 0.0, 0.9, fact); + proto_light.specular := (1.0, 1.0, 1.0, fact); + G3D.Define (3, proto_light); + + proto_light.position := (-3.0, 4.0, 10.0, 1.0); + G3D.Define (4, proto_light); + + proto_light.position := (3.0, -4.0, 10.0, 1.0); + proto_light.ambient := (0.6, 0.6, 0.6, 0.1); + G3D.Define (5, proto_light); + + proto_light.ambient := (0.6, 0.0, 0.0, 0.1); + G3D.Define (6, proto_light); + + proto_light.ambient := (0.0, 0.6, 0.0, 0.1); + G3D.Define (7, proto_light); + + proto_light.ambient := (0.0, 0.0, 0.6, 0.1); + G3D.Define (8, proto_light); + + G3D.Switch_lights (True); + + G3D.Switch_light (2, False); + G3D.Switch_light (3, False); + G3D.Switch_light (4, False); + G3D.Switch_light (5, False); + G3D.Switch_light (6, False); + G3D.Switch_light (7, False); + G3D.Switch_light (8, False); + + end Prepare_default_lighting; + + procedure Clear_modes is + + begin + Disable (BLEND); + Disable (LIGHTING); + Disable (AUTO_NORMAL); + Disable (NORMALIZE); + Disable (DEPTH_TEST); + end Clear_modes; + + procedure Reset_for_3D (Self : in out Window'Class) is + + begin + pragma Unreferenced (Self); + MatrixMode (MODELVIEW); -- (tbd : still needed ?) . .. The matrix generated by GLU.Perspective is multipled by the current matrix + ShadeModel (SMOOTH); -- GL's default is SMOOTH, vs FLAT + -- ShadeModel (FLAT); -- GL's default is SMOOTH, vs FLAT + + ClearColor (0.0, 0.0, 0.0, 0.0); -- Specifies clear values for color buffer (s) + ClearAccum (0.0, 0.0, 0.0, 0.0); -- Specifies clear values for the accumulation buffer + end Reset_for_3D; + + procedure enable_Viewport_and_Perspective (Self : in out Window'Class) is -- tbd : move projection matrix to 'window resize'. + + begin + Viewport (0, 0, Self.main_size_x, Self.main_size_y); + + MatrixMode (PROJECTION); + LoadIdentity; + + GLU.Perspective (fovy => Self.Camera.FOVy, -- field of view angle (deg) in the y direction + aspect => Self.Camera.Aspect, -- x/y aspect ratio + zNear => Self.Camera.near_plane_Distance, -- distance from the viewer to the near clipping plane + zFar => Self.Camera.far_plane_Distance); -- distance from the viewer to the far clipping plane + + Get (GL.PROJECTION_MATRIX, Self.Camera.Projection_Matrix (1, 1)'Unchecked_Access); -- Get the current PROJECTION matrix from OpenGL + + Self.Camera.Projection_Matrix := Transpose (Self.Camera.Projection_Matrix); + + MatrixMode (MODELVIEW); -- The matrix generated by GLU.Perspective is multipled by the current matrix + end enable_Viewport_and_Perspective; + + procedure set_Size (Self : in out Window'Class; width, height : Integer) is + + use G3D; + use REF; + + half_fov_max_rads : Real; + Tan_of_half_fov_max_rads : Real; + + begin + Self.main_size_x := GL.Sizei (width); + Self.main_size_y := GL.Sizei (height); + + Self.Camera.Clipper.main_clipping.X1 := 0; + Self.Camera.Clipper.main_clipping.Y1 := 0; + Self.Camera.Clipper.main_clipping.X2 := width - 1; + Self.Camera.Clipper.main_clipping.Y2 := height - 1; + + Self.Camera.Aspect := GL.Double (Self.main_size_x) / GL.Double (Self.main_size_y); + half_fov_max_rads := 0.5 * Self.Camera.FOVy * deg2rad; + + Tan_of_half_fov_max_rads := Tan (half_fov_max_rads); + + Self.Camera.near_plane_Height := Self.Camera.near_plane_Distance * Tan_of_half_fov_max_rads; + Self.Camera.near_plane_Width := Self.Camera.near_plane_Height * Self.Camera.Aspect; + + Self.Camera.far_plane_Height := Self.Camera.far_plane_Distance * Tan_of_half_fov_max_rads; + Self.Camera.far_plane_Width := Self.Camera.far_plane_Height * Self.Camera.Aspect; + + if Self.Camera.Aspect > 1.0 then -- x side angle broader than y side angle + half_fov_max_rads := Arctan (Self.Camera.Aspect * Tan_of_half_fov_max_rads); + end if; + + Self.Camera.Clipper.max_dot_product := Sin (half_fov_max_rads); + + end set_Size; + + -- Procedures passed to GLUT: + -- Window_Resize, Keyboard, Motion, Menu, Mouse, Display + + procedure Window_Resize (width, height : Integer) is + + the_Window : constant GLUT.Windows.Window_view := current_Window; + + begin + the_Window.all.forget_mouse := 5; + set_Size (the_Window.all, width, height); + Reset_for_3D (the_Window.all); + end Window_Resize; + + procedure Menu (value : Integer) is + + begin + case value is + when 1 => -- GLUT.GameModeString (Full_Screen_Mode); + GLUT.FullScreen; + -- res := GLUT.EnterGameMode; + GLUT.SetCursor (GLUT.CURSOR_NONE); + current_Window.all.forget_mouse := 10; + current_Window.all.full_screen := True; + when 2 => null; -- GLUT_exit; + when others => null; + end case; + end Menu; + pragma Unreferenced (Menu); + + procedure Display_status (Self : in out Window; + sec : GLOBE_3D.Real) is + + use G3D, G3D.REF; + + light_info : String (1 .. 8); + + begin + PushMatrix; + + Disable (LIGHTING); + Disable (TEXTURE_2D); + + Color (red => 0.7, + green => 0.7, + blue => 0.6); + + GLUT_2D.Text_output ((1.0, 0.0, 0.0), "" (x)"", GLUT_2D.Times_Roman_24); + GLUT_2D.Text_output ((0.0, 1.0, 0.0), "" (y)"", GLUT_2D.Times_Roman_24); + GLUT_2D.Text_output ((0.0, 0.0, 1.0), "" (z)"", GLUT_2D.Times_Roman_24); + + GLUT_2D.Text_output (0, 50, Self.main_size_x, Self.main_size_y, + ""Eye : "" & Coords (Self.Camera.Clipper.Eye_Position), + GLUT_2D.Helvetica_10); + + GLUT_2D.Text_output (0, 60, Self.main_size_x, Self.main_size_y, + ""View direction : "" & Coords (Self.Camera.Clipper.view_direction), + GLUT_2D.Helvetica_10); + + for i in light_info'Range loop + + if Is_light_switched (i) then + light_info (i) := Character'Val (Character'Pos ('0') + i); + else + light_info (i) := 'x'; + end if; + end loop; + + GLUT_2D.Text_output (0, 70, Self.main_size_x, Self.main_size_y, ""Lights : ("" & light_info & ')', GLUT_2D.Helvetica_10); + + if sec > 0.0 then + GLUT_2D.Text_output (0, 130, Self.main_size_x, Self.main_size_y, ""FPS : "" & Integer'Image (Integer (1.0 / sec)), GLUT_2D.Helvetica_10); + end if; + + if Self.is_capturing_Video then + GLUT_2D.Text_output (0, 150, Self.main_size_x, Self.main_size_y, ""*recording*"", GLUT_2D.Helvetica_10); + end if; + + PopMatrix; + + end Display_status; + + function Frames_per_second (Self : Window) return Float is (Float (1.0 / (Self.Average * 0.001))); + + procedure Graphic_display (Self : in out Window'Class; + Extras : GLOBE_3D.Visual_array := GLOBE_3D.null_Visuals) is + + use G3D; + + begin + G3D.render (Self.Objects (1 .. Self.object_Count) & Extras, Self.Camera); + + if Self.Show_Status then + Display_status (Self, Self.Average * 0.001); + end if; + end Graphic_display; + + procedure Fill_screen (Self : in out Window'Class; + Extras : GLOBE_3D.Visual_array := GLOBE_3D.null_Visuals) is + + procedure Display is + + begin + Graphic_display (Self, Extras); + end Display; + + package SAA is new GLOBE_3D.Software_Anti_Aliasing (Display); + begin + + case Self.Smoothing is + + when Software => + SAA.Set_Quality (SAA.Q3); + for SAA_Phase in 1 .. SAA.Anti_Alias_phases loop + SAA.Display_with_Anti_Aliasing (SAA_Phase); + end loop; + + when Hardware => + Enable (MULTISAMPLE_ARB); -- (if not done yet) + + -- ClearColor (0.0, 0.0, 0.0, 1.0); -- Specifies clear values for color buffer (s) + -- ClearColor (0.15, 0.4, 0.15, 1.0); -- Specifies clear values for color buffer (s) -- tbd : make clear color user - settable + ClearColor (0.0, 0.0, 0.0, 1.0); -- Specifies clear values for color buffer (s) -- tbd : make clear color user - settable + ClearAccum (0.0, 0.0, 0.0, 0.0); -- Specifies clear values for the accumulation buffer + + Graphic_display (Self, Extras); + Flush; + + when None => + Graphic_display (Self, Extras); + Flush; + end case; + + GLUT.SwapBuffers; + end Fill_screen; + + procedure Reset_eye (Self : in out Window'Class) is + + begin + Self.Camera.Clipper.Eye_Position := (0.0, 5.0, 4.0); + Self.Camera.World_Rotation := GLOBE_3D.Id_33; + end Reset_eye; + + function Image (Date : Ada.Calendar.Time) return String; + -- Proxy for Ada 2005 Ada.Calendar.Formatting.Image + + procedure Main_Operations (Self : access Window; + time_Step : G3D.Real; + Extras : GLOBE_3D.Visual_array := GLOBE_3D.null_Visuals) is + + use G3D, G3D.REF, Game_Control; + + elaps, time_now : Integer; + gx, gy : GL.Double; -- mouse movement since last call + seconds : GL.Double; -- seconds since last image + alpha_correct : Boolean; + attenu_t, attenu_r : Real; + + begin + if not Self.all.is_Visible or else Self.all.is_Closed then + return; + end if; + + enable_Viewport_and_Perspective (Self.all); -- nb : must be done prior to setting frustum planes (when using GL.frustums.current_Planes) + + -- Control of lighting + -- + -- self.frontal_light.position := (GL.Float (self.Camera.Clipper.eye_Position (0)), + -- GL.Float (self.Camera.Clipper.eye_Position (1)), + -- GL.Float (self.Camera.Clipper.eye_Position (2)), + -- 1.0); + -- G3D.Define (1, self.frontal_light); + + for c in n1 .. n8 loop + if Self.all.game_command (c) then + Reverse_light_switch (1 + Command'Pos (c) - Command'Pos (n1)); + end if; + end loop; + + -- Display screen + -- + Fill_screen (Self.all, Extras); + + -- Timer management + -- + time_now := GLUT.Get (GLUT.ELAPSED_TIME); -- Number of milliseconds since GLUT.Init + + if Self.all.new_scene then + Self.all.new_scene := False; + elaps := 0; + else + elaps := time_now - Self.all.last_time; + end if; + + Self.all.last_time := time_now; + Self.all.Average := 0.0; + + for i in reverse Self.all.sample'First + 1 .. Self.all.sample'Last loop + Self.all.sample (i) := Self.all.sample (i - 1); + Self.all.Average := Self.all.Average + Real (Self.all.sample (i)); + end loop; + + Self.all.sample (Self.all.sample'First) := elaps; + + Self.all.Average := Self.all.Average + Real (elaps); + Self.all.Average := Self.all.Average / Real (Self.all.sample'Length); + + seconds := Real (elaps) * 0.001; + attenu_t := Real'Min (0.96, Real'Max (0.04, 1.0 - seconds * 4.0)); + attenu_r := attenu_t ** 0.5; + + -- Game control management + -- + Self.all.game_command := no_command; + + Game_Control.Append_Commands (size_x => Integer (Self.all.main_size_x), + size_y => Integer (Self.all.main_size_y), + warp_mouse => Self.all.full_screen, + c => Self.all.game_command, + gx => gx, + gy => gy, + Keyboard => Self.all.Keyboard'Access, + Mouse => Self.all.Mouse'Access); + + if Self.all.forget_mouse > 0 then -- mouse coords disturbed by resize + gx := 0.0; + gy := 0.0; + Self.all.forget_mouse := Self.all.forget_mouse - 1; + end if; + + if Self.all.game_command (interrupt_game) then + null; -- GLUT_exit; -- tbd : how to handle this best ? + end if; + + alpha_correct := False; + + if Self.all.game_command (special_plus) then + Self.all.Alpha := Self.all.Alpha + seconds; alpha_correct := True; + end if; + if Self.all.game_command (special_minus) then + Self.all.Alpha := Self.all.Alpha - seconds; alpha_correct := True; + end if; + + if alpha_correct then + if Self.all.Alpha < 0.0 then + Self.all.Alpha := 0.0; + elsif Self.all.Alpha > 1.0 then + Self.all.Alpha := 1.0; + end if; + + for Each in 1 .. Self.all.object_Count loop + set_Alpha (Self.all.Objects (Each).all, Self.all.Alpha); + end loop; + end if; + + -- Camera/Eye - nb : camera movement is done after rendering, so camera is in a state ready for the next frame. + -- - (important for Impostors) + + -- Rotating the eye + + Actors.Rotation (Self.all.Camera, + gc => Self.all.game_command, + gx => gx, + gy => gy, + unitary_change => seconds, + deceleration => attenu_r, + time_step => time_Step); + + -- Moving the eye + + Actors.Translation (Self.all.Camera, + gc => Self.all.game_command, + gx => gx, + gy => gy, + unitary_change => seconds, + deceleration => attenu_t, + time_step => time_Step); + + if Self.all.game_command (n0) then + Reset_eye (Self.all); + end if; + + Self.all.Camera.Clipper.view_direction := Transpose (Self.all.Camera.World_Rotation) * (0.0, 0.0, -1.0); + + -- update camera frustum + -- + MatrixMode (MODELVIEW); + Set_GL_Matrix (Self.all.Camera.World_Rotation); + Translate (-Self.all.Camera.Clipper.Eye_Position (0), -Self.all.Camera.Clipper.Eye_Position (1), -Self.all.Camera.Clipper.Eye_Position (2)); + + Self.all.Camera.frustum_Planes := GL.Frustums.Current_Planes; -- tbd : getting frustum planes from camera, might be quicker, + -- set_frustum_Planes (Self.Camera); -- but 'set_frustum_Planes' seems buggy :/. + + -- video management + -- + if Self.all.game_command (video) then + if Self.all.is_capturing_Video then + GL.IO.Stop_Capture; + Self.all.is_capturing_Video := False; + else + GL.IO.Start_Capture (AVI_Name => To_String (Self.all.Name) & ""."" & Image (Ada.Calendar.Clock) & "".avi"", + frame_rate => 8); -- Integer (self.Frames_per_second)); + Self.all.is_capturing_Video := True; + end if; + end if; + + if Self.all.is_capturing_Video then + GL.IO.Capture_Frame; + end if; + + -- photo management + -- + if Self.all.game_command (photo) then + GL.IO.Screenshot (Name => To_String (Self.all.Name) & ""."" & Image (Ada.Calendar.Clock) & "".bmp""); + end if; + + end Main_Operations; + + procedure Close_Window is + + begin + current_Window.all.is_Closed := True; + end Close_Window; + + procedure Update_Visibility (State : Integer) is + + begin + -- ada.text_io.put_line (""in update_Visibility callback state : "" & integer'image (State)); + -- + -- tbd : this callback is not being called when a window is iconicised !! + + current_Window.all.is_Visible := not (State = GLUT.HIDDEN or else State = GLUT.FULLY_COVERED); + end Update_Visibility; + + procedure Start_GLUTs (Self : in out Window) is + + use GLUT; + + function to_Address is new Ada.Unchecked_Conversion (GLOBE_3D.p_Window, System.Address); + + GLUT_options : GLUT.Unsigned := GLUT.DOUBLE or GLUT.RGBA or GLUT.ALPHA or GLUT.DEPTH; + + begin + if Self.Smoothing = Hardware then + GLUT_options := GLUT_options or GLUT.MULTISAMPLE; + end if; + + InitDisplayMode (GLUT_options); + + set_Size (Self, 500, 400); + + InitWindowSize (Integer (Self.main_size_x), Integer (Self.main_size_y)); + InitWindowPosition (120, 120); + + Self.glut_Window := CreateWindow (""GLOBE_3D/GLUT Window""); + + if Self.glut_Window = 0 then + raise GLUT_Problem; + end if; + + GLUT.CloseFunc (Close_Window'Access); + GLUT.ReshapeFunc (Window_Resize'Access); + GLUT.WindowStatusFunc (Update_Visibility'Access); + GLUT.SetWindowData (to_Address (GLOBE_3D.Window'Class (Self)'Unchecked_Access)); + + GLUT.Devices.Initialize; + + -- if CreateMenu (Menu'Access) = 0 then -- tdb : deferred + -- raise GLUT_Problem; + -- end if; + + -- AttachMenu (MIDDLE_BUTTON); + + -- AddMenuEntry ("" * Full Screen"", 1); + -- AddMenuEntry (""--> Exit (Esc)"", 2); + + end Start_GLUTs; + + procedure Start_GLs (Self : in out Window) is + + fog_colour : GL.Light_Float_vector := (0.2, 0.2, 0.2, 0.1); + + begin + + Clear_modes; + Prepare_default_lighting (Self, 0.9); + + if Self.foggy then + Enable (FOG); + Fogfv (FOG_COLOR, fog_colour (0)'Unchecked_Access); + Fogf (FOG_DENSITY, 0.02); + end if; + + Reset_for_3D (Self); + + if Self.Smoothing = Hardware then + Enable (MULTISAMPLE_ARB); + Enable (SAMPLE_COVERAGE_ARB); -- Hope it helps switching on the AA .. . + end if; + + end Start_GLs; + + procedure Initialize is + + begin + GLUT.Init; + GLUT.SetOption (GLUT.GLUT_RENDERING_CONTEXT, GLUT.GLUT_USE_CURRENT_CONTEXT); + GLUT.SetOption (GLUT.ACTION_ON_WINDOW_CLOSE, ACTION_CONTINUE_EXECUTION); + end Initialize; + + procedure Define (Self : in out Window) is + + begin + Start_GLUTs (Self); -- Initialize the GLUT things + Start_GLs (Self); -- Initialize the (Open)GL things + Reset_eye (Self); + + Freshen (Self, 0.02); -- do an initial freshen, to initialise Camera, etc. + end Define; + + procedure Destroy (Self : in out Window) is + + begin + DestroyWindow (Self.glut_Window); + end Destroy; + + overriding procedure Enable (Self : in out Window) is + + begin + GLUT.SetWindow (Self.glut_Window); + -- opengl.glx.glXMakeCurrent; + end Enable; + + overriding procedure Freshen (Self : in out Window; + time_Step : G3D.Real; + Extras : GLOBE_3D.Visual_array := GLOBE_3D.null_Visuals) is + + begin + Enable (Self); -- for multi - window operation. + Main_Operations (Self'Access, time_Step, Extras); + end Freshen; + + -- traits + -- + + function Smoothing (Self : Window) return Smoothing_method is (Self.Smoothing); + + procedure Smoothing_is (Self : in out Window; + Now : Smoothing_method) is + + begin + Self.Smoothing := Now; + end Smoothing_is; + + procedure Add (Self : in out Window; the_Object : GLOBE_3D.p_Visual) is + + begin + Self.object_Count := Self.object_Count + 1; + Self.Objects (Self.object_Count) := the_Object.all'Access; + end Add; + + procedure Rid (Self : in out Window; the_Object : GLOBE_3D.p_Visual) is + + use G3D; + + begin + for Each in 1 .. Self.object_Count loop + + if Self.Objects (Each) = the_Object then + + if Each /= Self.object_Count then + Self.Objects (Each .. Self.object_Count - 1) := Self.Objects (Each + 1 .. Self.object_Count); + end if; + + Self.object_Count := Self.object_Count - 1; + return; + end if; + + end loop; + + raise no_such_Object; + end Rid; + + function Object_Count (Self : Window) return Natural is (Self.object_Count); + + -- status display + -- + + function Show_Status (Self : Window) return Boolean is (Self.Show_Status); + + procedure Show_Status (Self : in out Window; + Show : Boolean := True) is + + begin + Self.Show_Status := Show; + end Show_Status; + + -- Devices + -- + + function Keyboard (Self : access Window'Class) return Devices.p_Keyboard is (Self.all.Keyboard'Access); + + function Mouse (Self : access Window'Class) return Devices.p_Mouse is (Self.all.Mouse'Access); + + -- Proxy for Ada 2005 Ada.Calendar.Formatting.Image + function Image (Date : Ada.Calendar.Time) return String is + + use Ada.Calendar; + + subtype Sec_int is Long_Integer; -- must contain 86_400 + + m, s : Sec_int; + + begin + s := Sec_int (Seconds (Date)); + m := s / 60; + + declare + -- + 100 : trick for obtaining 0x + sY : constant String := Integer'Image (Year (Date)); + sM : constant String := Integer'Image (Month (Date) + 100); + sD : constant String := Integer'Image (Day (Date) + 100); + shr : constant String := Sec_int'Image (m / 60 + 100); + smn : constant String := Sec_int'Image (m mod 60 + 100); + ssc : constant String := Sec_int'Image (s mod 60 + 100); + + begin + return + sY (sY'Last - 3 .. sY'Last) & '-' & -- not Year 10'000 compliant. + sM (sM'Last - 1 .. sM'Last) & '-' & + sD (sD'Last - 1 .. sD'Last) & + "" "" & + shr (shr'Last - 1 .. shr'Last) & '.' & + smn (smn'Last - 1 .. smn'Last) & '.' & + ssc (ssc'Last - 1 .. ssc'Last);" +function New_List_Id return List_Ids;,"private + Available_List_Id : List_Ids := List_Ids'First; + end List_Id_Generator; + package body List_Id_Generator is + function New_List_Id return List_Ids is + begin + Available_List_Id := Available_List_Id + 1; + return Available_List_Id - 1; + end New_List_Id; + end List_Id_Generator; + -- + function Image (r : Real) return String is + s : String (1 .. 10); + begin + RIO.Put (s, r, 4, 0); + return s; + exception + when Ada.Text_IO.Layout_Error => + return Real'Image (r); + end Image; + function Coords (p : Point_3D) return String is + begin + return ' (' & Image (p (0)) & + ', ' & Image (p (1)) & + ', ' & Image (p (2)) & + ')'; + end Coords; + + -- normal support + -- + procedure Add_Normal_of_3p (o : in Object_3d'Class; + Pn0, Pn1, Pn2 : in Integer; + N : in out Vector_3D) is + use GL, G3dm; + function Params return String is + begin + return + "" Object : "" & Trim (o.id, right) & + "" Pn0="" & Integer'Image (Pn0) & + "" Pn1="" & Integer'Image (Pn1) & + "" Pn2="" & Integer'Image (Pn2); + end Params; + N_contrib : Vector_3D; + begin + if Pn0=0 or Pn1=0 or Pn2=0 then return; end if; + N_contrib := (o.point (Pn1) - o.point (Pn0))* (o.point (Pn2) - o.point (Pn0)) ; + if strict_geometry and then Almost_zero (Norm2 (N_contrib)) then + raise_exception (zero_normal'Identity, + Params & + "" P0="" & Coords (o.point (Pn0)) & + "" P1="" & Coords (o.point (Pn1)) & + "" P2="" & Coords (o.point (Pn2)) & + "" Nc="" & Coords (N_contrib) +); + end if; + N := N + N_contrib; + exception + when e : others => + raise_exception ( + Exception_Identity (e), + Exception_Message (e) & Params +); + end Add_Normal_of_3p; + + -- blending support + -- + function Is_to_blend (m : GL.Double) return Boolean is + use GL, G3DM; + begin + return not Almost_zero (m - 1.0); + end Is_to_blend; + function Is_to_blend (m : GL.Float) return Boolean is + use GL, G3DM; + begin + return not Almost_zero (m - 1.0); + end Is_to_blend; + function Is_to_blend (m : GL.Material_Float_vector) return Boolean is + begin + return Is_to_blend (m (3)); + end Is_to_blend; + function Is_to_blend (m : GL.Materials.Material_type) return Boolean is + begin + return + Is_to_blend (m.ambient) or + Is_to_blend (m.diffuse) or + Is_to_blend (m.specular); + -- m.emission, m.shininess not relevant + end Is_to_blend; + -- material support + -- + procedure Set_Material (m : GL.Materials.Material_type) is + use GL; + begin + Material (FRONT_AND_BACK, AMBIENT, m.ambient); + Material (FRONT_AND_BACK, DIFFUSE, m.diffuse); + Material (FRONT_AND_BACK, SPECULAR, m.specular); + Material (FRONT_AND_BACK, EMISSION, m.emission); + Material (FRONT_AND_BACK, SHININESS, m.shininess); + end Set_Material; + -- 'Visual' + -- + procedure free (o : in out p_Visual) + is + procedure deallocate is new ada.unchecked_deallocation (Visual'Class, p_Visual); + begin + destroy (o.all); + deallocate (o); + end free; + function skinned_Geometrys (o : in Visual) return GL.skinned_geometry.skinned_Geometrys + is + begin + return GL.skinned_geometry.null_skinned_Geometrys; + end skinned_Geometrys; + function Width (o : in Visual'class) return Real + is + begin + return bounds (o).box.X_Extent.Max - bounds (o).box.X_Extent.Min; + end Width; + function Height (o : in Visual'class) return Real + is + begin + return bounds (o).box.Y_Extent.Max - bounds (o).box.Y_Extent.Min; + end Height; + function Depth (o : in Visual'class) return Real + is + begin + return bounds (o).box.Z_Extent.Max - bounds (o).box.Z_Extent.Min; + end Depth; + -- 'Object_3D' + -- + -- object validation + -- + procedure Check_object (o : Object_3D) is + use G3DM; + procedure Check_faces is + procedure Check (f, v : Integer) is + pragma Inline (Check); + begin + if v < 0 or else v > o.max_points then + raise_exception (bad_vertex_number'Identity, + o.id & "" face="" & Integer'Image (f) & + "" vertex="" & Integer'Image (v)); + end if; + end Check; + procedure Check_duplicate (f, Pn1, Pn2 : Integer) is + pragma Inline (Check_duplicate); + begin + -- Skip ""dead"" edge (triangle), 30 - Dec - 2001 + if Pn1=0 or else Pn2=0 then return; end if; + -- Detect same point number + if Pn1=Pn2 then + raise_exception (duplicated_vertex'Identity, + o.id & "" in face "" & Integer'Image (f)); + end if; + -- Detect same point coordinates (tolerated in an object, + -- although inefficient, but harms as vertex of the same face!) + if Almost_zero (Norm2 (o.point (Pn1) - o.point (Pn2))) then + raise_exception (duplicated_vertex_location'Identity, + o.id & "" in face "" & Integer'Image (f)); + end if; + end Check_duplicate; + begin + for fa in o.face'Range loop + for edge_num in 1 .. 4 loop + Check (fa, o.face (fa).P (edge_num)); + for other_edge in edge_num + 1 .. 4 loop + Check_duplicate (fa, o.face (fa).P (edge_num), + o.face (fa).P (other_edge)); + end loop; + end loop; + end loop; -- fa + end Check_faces; + begin + Check_faces; + end Check_object; + -------------------------------------------- + -- Object initialization (1x in its life) -- + -------------------------------------------- + procedure Pre_calculate (o : in out Object_3D) is + use GL, G3DM; + N : Vector_3D; + length_N : Real; + procedure Calculate_face_invariants ( + fa : in Face_type; + fi : out Face_invariant_type +) is + l : Natural := 0; + quadri_edge : array (fa.P'Range) of Natural; + ex_U, ex_V : Real; + begin + l := 0; + for qe in fa.P'Range loop + if fa.P (qe) /= 0 then + l := l + 1; + quadri_edge (l) := qe; -- if triangle, ""map"" edge on a quadri + fi.P_compact (l) := fa.P (qe); + end if; + end loop; + if l in Edge_count then + fi.last_edge := l; + else + raise_exception (bad_edge_number'Identity, o.id); + end if; + -- * Face invariant : Textured face : extremities + for e in 1 .. l loop + if fa.whole_texture then + ex_U := Real (fa.repeat_U); + ex_V := Real (fa.repeat_V); + case quadri_edge (e) is + when 1 => fi.UV_extrema (e) := (0.0, 0.0); -- bottom, left 4 --< --3 + when 2 => fi.UV_extrema (e) := (ex_U, 0.0); -- bottom, right | | + when 3 => fi.UV_extrema (e) := (ex_U, ex_V); -- top, right 1 --> --2 + when 4 => fi.UV_extrema (e) := (0.0, ex_V); -- top, left + when others => null; + end case; + else + -- Just copy the mapping, but in compact form for triangles: + fi.UV_extrema (e) := fa.texture_edge_map (quadri_edge (e)); + end if; + end loop; + -- * Face invariant : Normal of unrotated face + N := (0.0, 0.0, 0.0); + case fi.last_edge is + when 3 => + Add_Normal_of_3p (o, + fi.P_compact (1), + fi.P_compact (2), + fi.P_compact (3), + N +); + when 4 => + Add_Normal_of_3p (o, fa.P (1), fa.P (2), fa.P (4), N); + -- We sum other normals for not perfectly flat faces, + -- in order to have a convenient average .. . + Add_Normal_of_3p (o, fa.P (2), fa.P (3), fa.P (1), N); + Add_Normal_of_3p (o, fa.P (3), fa.P (4), fa.P (2), N); + Add_Normal_of_3p (o, fa.P (4), fa.P (1), fa.P (3), N); + end case; + length_N := Norm (N); + if Almost_zero (length_N) then + if strict_geometry then + raise zero_summed_normal; + else + fi.normal := N; -- 0 vector ! + end if; + else + fi.normal := (1.0 / length_N) * N; + end if; + end Calculate_face_invariants; + adjacent_faces : array (o.point'Range) of Natural := (others => 0); + pf : Natural; + length : Real; + begin --Pre_calculate + if full_check_objects then Check_object (o); end if; + for i in o.face'Range loop + begin + -- Geometry + Calculate_face_invariants (o.face (i), o.face_invariant (i)); + -- Disable blending when alphas are = 1 + case o.face (i).skin is + when material_only | material_texture => + o.face_invariant (i).blending := Is_to_blend (o.face (i).material); + when colour_only | coloured_texture | texture_only => + o.face_invariant (i).blending := Is_to_blend (o.face (i).alpha); + when invisible => + o.face_invariant (i).blending := False; + end case; + o.transparent := o.transparent or o.face_invariant (i).blending; + exception + when zero_summed_normal => + raise_exception (zero_summed_normal'Identity, + o.id & "" face="" & Integer'Image (i));" +procedure Display_one (o : in out Object_3D) is,"-- Display only this object and not connected objects + -- out : object will be initialized if not yet + -- + -- + -- Display face routine which is optimized to produce a shorter list + -- of GL commands. Runs slower then the original Display face routine + -- yet needs to be executed only once. + -- + -- Uwe R. Zimmer, July 2011 + -- + package Display_face_optimized is + procedure Display_face (First_Face : Boolean; fa : Face_type; fi : in out Face_invariant_type); + private + Previous_face : Face_type; + Previous_face_Invariant : Face_invariant_type; + end Display_face_optimized; + package body Display_face_optimized is + use GL.Materials; + procedure Display_face (First_Face : Boolean; fa : Face_type; fi : in out Face_invariant_type) is + use GL; + blending_hint : Boolean; + begin -- Display_face + if fa.skin = invisible then + Previous_face := fa; + Previous_face_Invariant := fi; + return; + end if; + -------------- + -- Material -- + -------------- + if First_Face + or else Previous_face.skin = invisible + or else fa.skin /= Previous_face.skin + or else (fa.skin = Previous_face.skin + and then fa.material /= Previous_face.material) then + case fa.skin is + when material_only | material_texture => + Disable (COLOR_MATERIAL); + Set_Material (fa.material); + when others => + Set_Material (GL.Materials.neutral_material); + end case; + end if; + ------------ + -- Colour -- + ------------ + if First_Face + or else Previous_face.skin = invisible + or else fa.skin /= Previous_face.skin + or else (fa.skin = Previous_face.skin + and then (fa.colour /= Previous_face.colour + or else fa.alpha /= Previous_face.alpha)) then + case fa.skin is + when material_only | material_texture => + null; -- done above + when colour_only | coloured_texture => + Enable (COLOR_MATERIAL); + ColorMaterial (FRONT_AND_BACK, AMBIENT_AND_DIFFUSE); + Color (red => fa.colour.red, + green => fa.colour.green, + blue => fa.colour.blue, + alpha => fa.alpha); + when texture_only => + Disable (COLOR_MATERIAL); + when invisible => + null; + end case; + end if; + ------------- + -- Texture -- + ------------- + if First_Face + or else Previous_face.skin = invisible + or else fa.skin /= Previous_face.skin + or else (fa.skin = Previous_face.skin + and then fa.texture /= Previous_face.texture) then + case fa.skin is + when texture_only | coloured_texture | material_texture => + Enable (TEXTURE_2D); + G3DT.Check_2D_texture (fa.texture, blending_hint); + GL.BindTexture (GL.TEXTURE_2D, GL.Uint (Image_id'Pos (fa.texture) + 1)); + -- ^ superfluous ?!! + if blending_hint then + fi.blending := True; + -- 13 - Oct - 2006 : override decision made at Pre_calculate + -- if texture data contains an alpha layer + end if; + when colour_only | material_only => + Disable (TEXTURE_2D); + when invisible => + null; + end case; + end if; + ----------------------------- + -- Blending / transparency -- + ----------------------------- + if First_Face + or else Previous_face.skin = invisible + or else fi.blending /= Previous_face_Invariant.blending then + if fi.blending then + Enable (BLEND); -- See 4.1.7 Blending + BlendFunc (sfactor => SRC_ALPHA, + dfactor => ONE_MINUS_SRC_ALPHA); + -- Disable (DEPTH_TEST); + -- Disable (CULL_FACE); + else + Disable (BLEND); + -- Enable (DEPTH_TEST); + -- Enable (CULL_FACE); + -- CullFace (BACK); + end if; + end if; + ------------- + -- Drawing -- + ------------- + case fi.last_edge is + when 3 => GL_Begin (TRIANGLES); + when 4 => GL_Begin (QUADS); + end case; + for i in 1 .. fi.last_edge loop + if is_textured (fa.skin) then + TexCoord (fi.UV_extrema (i).U, fi.UV_extrema (i).V); + end if; + Normal (o.edge_vector (fi.P_compact (i))); + Vertex (o.point (fi.P_compact (i))); + end loop; + GL_End; + Previous_face := fa; + Previous_face_Invariant := fi; + end Display_face; + end Display_face_optimized; + -- + procedure Display_face (fa : Face_type; fi : in out Face_invariant_type) is + use GL; + blending_hint : Boolean; + begin -- Display_face + if fa.skin = invisible then + return; + end if; + -------------- + -- Material -- + -------------- + case fa.skin is + when material_only | material_texture => + Disable (COLOR_MATERIAL); + Set_Material (fa.material); + neutral_material_already_set := False; + when others => + -- Avoid setting again and again the neutral material + if not neutral_material_already_set then + Set_Material (GL.Materials.neutral_material); + neutral_material_already_set := True; + end if; + end case; + ------------ + -- Colour -- + ------------ + case fa.skin is + when material_only | material_texture => + null; -- done above + when colour_only | coloured_texture => + Enable (COLOR_MATERIAL); + ColorMaterial (FRONT_AND_BACK, AMBIENT_AND_DIFFUSE); + Color ( + red => fa.colour.red, + green => fa.colour.green, + blue => fa.colour.blue, + alpha => fa.alpha +); + when texture_only => + Disable (COLOR_MATERIAL); + when invisible => + null; + end case; + ------------- + -- Texture -- + ------------- + case fa.skin is + when texture_only | coloured_texture | material_texture => + Enable (TEXTURE_2D); + G3DT.Check_2D_texture (fa.texture, blending_hint); + GL.BindTexture (GL.TEXTURE_2D, GL.Uint (Image_id'Pos (fa.texture) + 1)); + -- ^ superfluous ?!! + if blending_hint then + fi.blending := True; + -- 13 - Oct - 2006 : override decision made at Pre_calculate + -- if texture data contains an alpha layer + end if; + when colour_only | material_only => + Disable (TEXTURE_2D); + when invisible => + null; + end case; + ----------------------------- + -- Blending / transparency -- + ----------------------------- + if fi.blending then + Enable (BLEND); -- See 4.1.7 Blending + BlendFunc (sfactor => SRC_ALPHA, + dfactor => ONE_MINUS_SRC_ALPHA); + -- Disable (DEPTH_TEST); + -- Disable (CULL_FACE); + else + Disable (BLEND); + -- Enable (DEPTH_TEST); + -- Enable (CULL_FACE); + -- CullFace (BACK); + end if; + ------------- + -- Drawing -- + ------------- + case fi.last_edge is + when 3 => GL_Begin (TRIANGLES); + when 4 => GL_Begin (QUADS); + end case; + for i in 1 .. fi.last_edge loop + if is_textured (fa.skin) then + TexCoord (fi.UV_extrema (i).U, fi.UV_extrema (i).V); + end if; + Normal (o.edge_vector (fi.P_compact (i))); + Vertex (o.point (fi.P_compact (i))); + end loop; + GL_End; + end Display_face; + procedure Display_normals is + use GL, G3DM; + C : Vector_3D; + begin + GL.Color (0.5, 0.5, 1.0, 1.0); + -- show pseudo (average) normals at edges: + for e in o.point'Range loop + Arrow (o.point (e), arrow_inflator * o.edge_vector (e)); + end loop; + GL.Color (1.0, 1.0, 0.5, 1.0); + -- show normals of faces: + for f in o.face'Range loop + C := (0.0, 0.0, 0.0); + for i in 1 .. o.face_invariant (f).last_edge loop + C := C + o.point (o.face_invariant (f).P_compact (i)); + end loop; + C := (1.0/Real (o.face_invariant (f).last_edge)) * C; + Arrow (C, arrow_inflator * o.face_invariant (f).normal); + end loop; + end Display_normals; + use GL, G3DM; + begin -- Display_one + if not o.pre_calculated then + Pre_calculate (o); + end if; + GL.bindBuffer (gl.ARRAY_BUFFER, 0); -- disable 'vertex buffer objects' + GL.bindBuffer (gl.ELEMENT_ARRAY_BUFFER, 0); -- disable 'vertex buffer objects' indices + -- GL.disableClientState (gl.TEXTURE_COORD_ARRAY); + -- GL.disable (ALPHA_TEST); + GL.enable (Lighting); + GL.PushMatrix; -- 26 - May - 2006 : instead of rotating/translating back + GL.Translate (o.centre); + Multiply_GL_Matrix (o.rotation); + -- List preparation phase + case o.List_Status is + when No_list | Is_List => null; + when Generate_List => + o.List_Id := List_Id_Generator.New_List_Id; + GL.NewList (GL.uint (o.List_Id), COMPILE_AND_EXECUTE); + end case; + -- Execution phase + case o.List_Status is + when No_list => + for f in o.face'Range loop + Display_face (o.face (f), o.face_invariant (f)); + end loop; + when Generate_List => + for f in o.face'Range loop + Display_face_optimized.Display_face (f = o.face'First, o.face (f), o.face_invariant (f)); + end loop; + when Is_List => GL.CallList (GL.uint (o.List_Id)); + end case; + -- Close list + case o.List_Status is + when No_list | Is_List => null; + when Generate_List => + GL.EndList; + if GL.GetError = OUT_OF_MEMORY then + o.List_Status := No_List; + else + o.List_Status := Is_List; + end if; + end case; + if show_normals then + GL.Disable (GL.LIGHTING); + GL.Disable (GL.TEXTURE_2D); + Display_normals; + GL.Enable (GL.LIGHTING); -- mmmh .. . + end if; + GL.PopMatrix; -- 26 - May - 2006 : instead of rotating/translating back + -- GL.Rotate (o.auto_rotation (2), 0.0, 0.0, - 1.0); + -- GL.Rotate (o.auto_rotation (1), 0.0, - 1.0, 0.0); + -- GL.Rotate (o.auto_rotation (0), - 1.0, 0.0, 0.0); + -- GL.Translate ( - o.centre); + end Display_one; + procedure Display ( + o : in out Object_3D; + clip : in Clipping_data +) + is + use GLOBE_3D.Portals; + procedure Display_clipped ( + o : in out Object_3D'Class; + clip_area : in Clipping_area; + portal_depth : in Natural +) + is + procedure Try_portal (f : Positive) is + use G3DM, GL; + dp : Real; + plane_to_eye : Vector_3D; -- vector from any point in plane to the eye + bounding_of_face, intersection_clip_and_face : Clipping_area; + success, non_empty_intersection : Boolean; + begin + -- Culling #1 : check if portal is in vield of view's ""dead angle"" + dp := o.face_invariant (f).normal * clip.view_direction; + if dp < clip.max_dot_product then + -- Culling #2 : check if we are on the right side of the portal + -- NB : ignores o.auto_rotation ! + plane_to_eye := + clip.eye_position - + (o.point (o.face_invariant (f).P_compact (1)) + o.centre) + ; + dp := plane_to_eye * o.face_invariant (f).normal; + -- dp = signed distance to the plane + if dp > 0.0 then + -- Culling #3 : clipping rectangle + Find_bounding_box (o, f, bounding_of_face, success); + if success then + Intersect (clip_area, bounding_of_face, + intersection_clip_and_face, non_empty_intersection); + else + -- in doubt, draw with the present clipping + intersection_clip_and_face := clip_area; + non_empty_intersection := True; + end if; + if non_empty_intersection then + -- Recursion here: + Display_clipped ( + o => o.face (f).connecting.all, + clip_area => intersection_clip_and_face, + portal_depth => portal_depth + 1 +); + end if; + end if; + end if; + end Try_portal; + begin -- Display_clipped + if not o.pre_calculated then + Pre_calculate (o); + end if; + -- + -- a/ Display connected objects which are visible through o's faces + -- This is where recursion happens + if (not filter_portal_depth) or else -- filter_portal_depth : test/debug + portal_depth <= 6 + then + for f in o.face'Range loop + if o.face (f).connecting /= null and then + not o.face_invariant (f).portal_seen + -- ^ prevents infinite recursion on rare cases where + -- object A or B is not convex, and A and B see each other + -- and the culling by clipping cannot stop the recursion + -- (e.g. origin2.proc, tomb.proc) + -- + -- NB : drawing [different parts of] the same object several times + -- is right, since portions can be seen through different portals, + -- but going more than once through the same portal is wrong + then + o.face_invariant (f).portal_seen := True; + Try_portal (f); + -- ^ recursively calls Display_clipped for + -- objects visible through face f. + end if; + end loop; + end if; + -- b/ Display the object itself + if (not filter_portal_depth) or else -- filter_portal_depth : test/debug + (portal_depth = 1 or portal_depth = 5) + then + -- The graphical clipping (Scissor) gives various effects + -- - almost no speedup on the ATI Radeon 9600 Pro (hardware) + -- - factor : ~ Sqrt (clipped surface ratio) with software GL + if portal_depth > 0 then + GL.Enable (GL.SCISSOR_TEST); + GL.Scissor ( + x => GL.Int (clip_area.x1), + y => GL.Int (clip_area.y1), + width => GL.SizeI (clip_area.x2 - clip_area.x1 + 1), + height => GL.SizeI (clip_area.y2 - clip_area.y1 + 1) +); + else + GL.Disable (GL.SCISSOR_TEST); + end if; + info_b_ntl2 := info_b_ntl2 + 1; + info_b_ntl3 := Natural'Max (portal_depth, info_b_ntl3); + Display_one (o); + end if; + if show_portals and then portal_depth > 0 then + Draw_boundary (clip.main_clipping, clip_area); + end if; + end Display_clipped; + procedure Reset_portal_seen (o : in out Object_3D'Class) is + begin + for f in o.face'Range loop + if o.face_invariant (f).portal_seen then + o.face_invariant (f).portal_seen := False; + Reset_portal_seen (o.face (f).connecting.all); + end if; + end loop; + end Reset_portal_seen; + begin + info_b_ntl2 := 0; -- count amount of objects displayed, not distinct + info_b_ntl3 := 0; -- records max depth + Display_clipped (o, clip_area => clip.main_clipping, portal_depth => 0); + Reset_portal_seen (o); + end Display; + procedure Destroy (o : in out Object_3D) is + ol : p_Object_3D_list := o.sub_objects; + begin + while ol /= null loop + Free (p_Visual (ol.objc)); + ol := ol.next; + end loop; + end Destroy; + procedure set_Alpha (o : in out Object_3D; Alpha : in GL.Double) is + begin + for f in o.face'Range loop + o.face (f).alpha := Alpha; + end loop; + end set_Alpha; + function is_Transparent (o : in Object_3D) return Boolean is + begin + return o.transparent; + end is_Transparent; + function face_Count (o : in Object_3D) return Natural is + begin + return o.Max_faces; + end face_Count; + function Bounds (o : in Object_3D) return GL.geometry.Bounds_record is + begin + return o.Bounds; + end Bounds; + -- Lighting support. + -- + -- lights : array (Light_ident) of Light_definition; + light_defined : array (Light_ident) of Boolean := (others => False); + procedure Define (which : Light_ident; as : Light_definition) is + id : constant GL.LightIDEnm := GL.LightIDEnm'Val (which - 1); + use GL; + begin + -- lights (which) := as; + Light (id, POSITION, as.position); + Light (id, AMBIENT, as.ambient); + Light (id, DIFFUSE, as.diffuse); + Light (id, SPECULAR, as.specular); + light_defined (which) := True; + end Define; + procedure Switch_lights (on : Boolean) is + begin + for l in Light_ident loop + Switch_light (l, on); + end loop; + end Switch_lights; + function Server_id (which : Light_ident) return GL.ServerCapabilityEnm is + begin + return GL.ServerCapabilityEnm'Val (GL.ServerCapabilityEnm'Pos (GL.LIGHT0) + which - 1); + end Server_id; + procedure Switch_light (which : Light_ident; on : Boolean) is + begin + if light_defined (which) then + if on then + GL.Enable (Server_id (which)); + else + GL.Disable (Server_id (which)); + end if; + end if; + end Switch_light; + function Is_light_switched (which : Light_ident) return Boolean is + begin + return Boolean'Val (GL.IsEnabled (Server_id (which))); + end Is_light_switched; + procedure Reverse_light_switch (which : Light_ident) is + begin + Switch_light (which, not Is_light_switched (which)); + end Reverse_light_switch; + prec_a360 : constant := 10000; + r_prec_a360 : constant := 10000.0; + i_r_prec_a360 : constant := 1.0 / r_prec_a360; + procedure Angles_modulo_360 (v : in out Vector_3D)is + use GL; + begin + for i in v'Range loop + v (i) := + GL.Double (Integer (r_prec_a360 * v (i)) mod (360*prec_a360)) + * i_r_prec_a360; + end loop; + end Angles_modulo_360; + ------------------ + -- Resource I/O -- + ------------------ + procedure Load_if_needed (zif : in out Zip.Zip_info; name : String) is + begin + if not Zip.Is_loaded (zif) then + begin + Zip.Load (zif, name); + exception + when Zip.Zip_file_open_error => -- Try with lower case: + Zip.Load (zif, To_Lower (name));" +"procedure sort is new Ada.Containers.Generic_Array_Sort (Positive,","visual_geometry, + visual_geometrys); + use GL.Skins, GL.Geometry, GL.Skinned_Geometry; + current_Visual : p_Visual; + begin + if geometry_Count > 1 then + sort (all_Geometrys (1 .. geometry_Count)); + end if; + GL.PushMatrix; + for Each in 1 .. geometry_Count loop + if all_Geometrys (Each).Geometry.Skin /= current_Skin then + current_Skin := all_Geometrys (Each).Geometry.Skin; + enable (current_Skin.all); + GL.Errors.log; + end if; + if all_Geometrys (Each).Geometry.Veneer /= null then + enable (all_Geometrys (Each).Geometry.Veneer.all); + GL.Errors.log; + end if; + if all_Geometrys (Each).Visual = current_Visual then + draw (all_Geometrys (Each).Geometry.Geometry.all); + GL.Errors.log; + else + GL.PopMatrix; + GL.PushMatrix; + GL.Translate (all_Geometrys (Each).Visual.centre); + Multiply_GL_Matrix (all_Geometrys (Each).Visual.rotation); + draw (all_Geometrys (Each).Geometry.Geometry.all); + GL.Errors.log; + current_Visual := all_Geometrys (Each).Visual; + end if; + end loop; + GL.PopMatrix;" +"--procedure sort is new Ada.Containers.Generic_Array_Sort (Positive,","procedure sort is new Ada.Containers.Generic_Array_Sort (Positive, + globe_3d.p_Visual, + globe_3d.Visual_array); + begin + for Each in 1 .. transparent_Count loop -- pre - calculate each visuals Centre in camera space. + all_Transparents (Each).Centre_camera_space := the_Camera.world_Rotation + * (all_Transparents (Each).Centre - the_Camera.Clipper.eye_Position); + end loop; + if transparent_Count > 1 then + sort (all_Transparents (1 .. transparent_Count)); + end if; + GL.depthMask (gl_False); -- make depth buffer read - only, for correct transparency + Enable (LIGHTING); -- ensure lighting is enabled for G3D.Display of transparents (obsolete). + Enable (BLEND); + BlendFunc (sfactor => ONE, + dfactor => ONE_MINUS_SRC_ALPHA); + for Each in 1 .. transparent_Count loop + declare + the_Visual : Visual'Class renames all_Transparents (Each).all; + visual_Geometrys : constant GL.skinned_geometry.skinned_Geometrys := skinned_Geometrys (the_visual); -- tbd : apply ogl state sorting here ? + begin + display (the_Visual, the_Camera.clipper); + GL.Errors.log; + for Each in visual_Geometrys'Range loop + declare + use GL.Skins, GL.Geometry; + the_Geometry : GL.skinned_geometry.skinned_Geometry renames visual_Geometrys (Each); + begin + if the_Geometry.Skin /= current_Skin then + current_Skin := the_Geometry.Skin; + enable (current_Skin.all); + GL.Errors.log; + end if; + if the_Geometry.Veneer /= null then + enable (the_Geometry.Veneer.all); + GL.Errors.log; + end if; + GL.PushMatrix; + GL.Translate (the_Visual.centre); + Multiply_GL_Matrix (the_Visual.rotation); + draw (the_Geometry.Geometry.all); + GL.Errors.log; + GL.PopMatrix;" +"procedure Dispose is new Ada.Unchecked_Deallocation (Texture_info_array, p_Texture_info_array);","----------------------------------- + -- 2) Fast access through a name -- + ----------------------------------- + + package Texture_Name_Mapping is new Ada.Containers.Hashed_Maps + (Key_Type => Ada.Strings.Unbounded.Unbounded_String, + Element_Type => Image_ID, + Hash => Ada.Strings.Unbounded.Hash, + Equivalent_Keys => Ada.Strings.Unbounded.""=""); + + type Texture_2d_infos_type is record + tex : p_Texture_info_array; + map : Texture_Name_Mapping.Map; + last_entry_in_use : Image_ID; + end record; + + empty_texture_2d_infos : constant Texture_2d_infos_type := + (null, + Texture_Name_Mapping.Empty_Map, + null_image +); + + Texture_2d_Infos : Texture_2d_infos_type := empty_texture_2d_infos; + + ----------------------------- + -- Load_texture (internal) -- + ----------------------------- + + procedure Load_texture_2D (id : Image_ID; blending_hint : out Boolean) is + tex_name : constant String := Trim (Texture_2d_Infos.tex.all (id).name, Right); + + procedure Try (zif : in out Zip.Zip_info; name : String) is + use UnZip.Streams; + ftex : Zipped_File_Type; + procedure Try_a_type (tex_name_ext : String; format : GL.IO.Supported_format) is + begin + Open (ftex, zif, tex_name_ext); + GL.IO.Load (Stream (ftex), format, Image_ID'Pos (id) + 1, blending_hint); + Close (ftex); + exception + when Zip.File_name_not_found => + raise; + when e : others => + Raise_Exception ( + Exception_Identity (e), + Exception_Message (e) & "" on texture : "" & tex_name_ext); + end Try_a_type; + begin -- Try + Load_if_needed (zif, name); + Try_a_type (tex_name & "".TGA"", GL.IO.TGA); + exception + when Zip.File_name_not_found => + Try_a_type (tex_name & "".BMP"", GL.IO.BMP); + end Try; + begin + begin + Try (zif_level, To_String (level_data_name)); + exception + when Zip.File_name_not_found | + Zip.Zip_file_open_Error => + -- Not found in level - specific pack + Try (zif_global, To_String (global_data_name));" +"procedure deallocate is new ada.unchecked_Deallocation (Impostor'Class, p_Impostor);","begin + destroy (o.all); + deallocate (o);" +procedure Display (o : in out tri_Mesh;,"clip : in Clipping_data) + is + begin + null; + end Display; + + procedure set_Vertices (Self : in out tri_Mesh; To : access GL.geometry.GL_vertex_Array) + is + use GL.Buffer.vertex, GL.Geometry, GL.Geometry.vbo; + + the_Geometry : GL.geometry.vbo.vbo_Geometry renames GL.geometry.vbo.vbo_Geometry (self.skinned_geometry.Geometry.all); + begin + the_Geometry.Vertices := to_Buffer (To, usage => GL.static_draw); -- tbd : check usage + the_Geometry.vertex_Count := GL.SizeI (To'Length); + + the_Geometry.Bounds := Bounds (To.all);" +procedure Skin_is (o : in out tri_Mesh; Now : in GL.skins.p_Skin),"is + begin + o.skinned_Geometry.Skin := Now; + o.skinned_Geometry.Veneer := Now.all.new_Veneer (for_geometry => o.skinned_Geometry.Geometry.all);" +procedure dummy is begin null; end;,"-- 'vertex_cache_optimise' is based on algorithm descibed here . .. http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html + -- + procedure vertex_cache_optimise (Vertices : in out GL.geometry.GL_Vertex_array; Indices : in out GL.geometry.vertex_Id_array) + is + use GL, GL.Geometry; + + --subtype vertex_Id is Positive; + subtype triangle_Id is positive_uInt; + + type triangle_Indices is array (Positive range <>) of triangle_Id; + + function Indices_Index (the_Face : in positive_uInt; the_Vertex : in positive_uInt) return positive_uInt + is + begin + return 3 * (the_Face - 1) + the_Vertex;" +"procedure free is new ada.unchecked_deallocation (vco_vertex_Array, access_vco_vertex_Array);","num_Faces : constant positive_uInt := indices'Length / 3; + vco_Vertices : access_vco_vertex_Array := new vco_vertex_Array; -- can be very large, so create in the heap + vco_Triangles : array (1 .. num_Faces) of vco_Triangle; + + type LRU_Cache is array (Natural range <>) of GL.geometry.vertex_Id; + + the_LRU_Cache : LRU_Cache (0 .. MaxSizeVertexCache - 1); + LRU_Cache_last : Integer := - 1; + + procedure add_recent_Vertices_to_LRU_Cache (v1, v2, v3 : in GL.geometry.vertex_Id) + is + prior_Cache : LRU_Cache := the_LRU_Cache (0 .. LRU_Cache_last); + begin + the_LRU_Cache (0) := v1; + the_LRU_Cache (1) := v2; + the_LRU_Cache (2) := v3; + + LRU_Cache_last := 2; + + for Each in prior_Cache'Range loop + + if not (prior_Cache (Each) = v1 + or else prior_Cache (Each) = v2 + or else prior_Cache (Each) = v3) + then + LRU_Cache_last := LRU_Cache_last + 1; + the_LRU_Cache (LRU_Cache_last) := prior_Cache (Each); + end if; + + end loop; + + end add_recent_Vertices_to_LRU_Cache; + + function tri_Score_of (triangle_Id : in positive_uInt) return GL.Double + is + use GL; + the_Triangle : vco_Triangle renames vco_Triangles (triangle_Id); + + Base : positive_uInt := positive_uInt (triangle_Id - 1) * 3; + v1_Id : GL.geometry.vertex_Id renames Indices (base + 1); + v2_Id : GL.geometry.vertex_Id renames Indices (base + 2); + v3_Id : GL.geometry.vertex_Id renames Indices (base + 3); + + Score : GL.Double; + begin + Score := vco_Vertices (v1_Id).Score; + Score := Score + vco_Vertices (v2_Id).Score; + Score := Score + vco_Vertices (v3_Id).Score; + + return Score; + end tri_Score_of; + + best_Triangle : triangle_Id; + best_Triangle_score : GL.Double := GL.Double'First; + + new_face_Indices : GL.geometry.vertex_Id_array (Indices'Range); -- the resulting optimised triangle indices. + -- new_face_Indices : triangle_vertex_Indices (o.Face_Indices'Range); -- the resulting optimised triangle indices. + -- -- new_face_Indices_last : Natural := new_face_Indices'first - 1; + begin + --put_Line (""start optimise !""); + + -- combined pass's : - increments the counter of the number of triangles that use each vertex + -- - adds the triangle to the vertex's triangle list, for each vertex. + -- + for Each in 1 .. num_Faces loop + declare + procedure add_face_Vertex (which_vertex : positive_uInt) + is + the_Vertex : vco_Vertex renames vco_Vertices (Indices ((Each - 1) * 3 + which_vertex)); + begin + the_Vertex.tri_Count := the_Vertex.tri_Count + 1; + the_Vertex.Triangles (the_Vertex.tri_Count) := triangle_Id (Each); + + the_Vertex.tri_Count_unadded := the_Vertex.tri_Count; + exception + when constraint_Error => + put_Line (""vco_Triangles max exceeded . .. increase Max_triangles_per_vertex !!""); + raise;" +"procedure deallocate is new ada.unchecked_Deallocation (Impostor'Class, p_Impostor);","begin + if o /= null then + destroy (o.all); + end if; + + deallocate (o);" +"procedure deallocate is new ada.unchecked_Deallocation (Impostor'Class, p_Impostor);","begin + if o /= null then + destroy (o.all); + end if; + + deallocate (o);" +function target_camera_Distance (o : in Impostor'Class) return Real,"is + begin + return o.target_camera_Distance;" +procedure Display (o : in out Impostor; clip : in Clipping_data),"is + begin + null; -- actual display is done by the renderer (ie glut.Windows), which requests all skinned Geometry's + -- and then applies 'gl state' sorting for performance, before drawing. + end Display; + + procedure set_Alpha (o : in out Impostor; Alpha : in GL.Double) + is + begin + null; -- tbd" +procedure Display (o : in out Sprite;,"clip : in Clipping_data) + is + begin + null; -- actual display is done by the renderer (ie glut.Windows), which requests all skinned Geometry's + -- and then applies 'gl state' sorting for performance, before drawing. + end Display; + + procedure set_Alpha (o : in out Sprite; Alpha : in GL.Double) + is + begin + null; -- tbd" +procedure Display (o : in out tri_Mesh;,"clip : in Clipping_data) + is + begin + null; + end Display; + + procedure set_Vertices (Self : in out tri_Mesh; To : access GL.geometry.GL_vertex_Array) + is + use GL.Geometry, GL.Geometry.primal; + + the_Geometry : GL.geometry.primal.primal_Geometry + renames GL.geometry.primal.primal_Geometry (self.skinned_geometry.Geometry.all); + begin + the_Geometry.set_Vertices (to => To);" +procedure Skin_is (o : in out tri_Mesh; Now : in GL.skins.p_Skin),"is + begin + o.skinned_Geometry.Skin := Now; + o.skinned_Geometry.Veneer := Now.all.new_Veneer (for_geometry => o.skinned_Geometry.Geometry.all);" +function Intel_nb is new Intel_x86_number (Unsigned_16);,"function Intel_nb is new Intel_x86_number (Unsigned_32); + + -- Put numbers with correct endianess as bytes + + generic + type Number is mod <>; -- range <> in Ada83 version (fake Interfaces) + size : Positive; + function Intel_x86_buffer (n : Number) return Byte_Buffer; + + function Intel_x86_buffer (n : Number) return Byte_Buffer is + + b : Byte_Buffer (1 .. size); + m : Number := n; + + begin + for i in b'Range loop + b (i) := Unsigned_8 (m and 255); + m := m / 256; + end loop; + return b; + end Intel_x86_buffer; + + function Intel_bf is new Intel_x86_buffer (Unsigned_16, 2); + function Intel_bf is new Intel_x86_buffer (Unsigned_32, 4); + + ------------------- + -- PK signatures -- + ------------------- + + function PK_signature (buf : Byte_Buffer; code : Unsigned_8) return Boolean is + (buf (1 .. 4) = (16#50#, 16#4B#, code, code + 1)); -- PK12, PK34, . .. + + procedure PK_signature (buf : in out Byte_Buffer; code : Unsigned_8) is + + begin + buf (1 .. 4) := (16#50#, 16#4B#, code, code + 1); -- PK12, PK34, . .. + end PK_signature; + + ------------------------------------------------------- + -- PKZIP file header, as in central directory - PK12 -- + ------------------------------------------------------- + + procedure Read_and_check (stream : Zipstream_Class; + header : out Central_File_Header) is + + chb : Byte_Buffer (1 .. 46); + + begin + BlockRead (stream, chb); + + if not PK_signature (chb, 1) then + raise bad_central_header; + end if; + + header := (made_by_version => Intel_nb (chb (5 .. 6)), + short_info => + (needed_extract_version => Intel_nb (chb (7 .. 8)), + bit_flag => Intel_nb (chb (9 .. 10)), + zip_type => Intel_nb (chb (11 .. 12)), + file_timedate => Zip_Streams.Calendar.Convert (Unsigned_32'(Intel_nb (chb (13 .. 16)))), + dd => + (crc_32 => Intel_nb (chb (17 .. 20)), + compressed_size => Intel_nb (chb (21 .. 24)), + uncompressed_size => Intel_nb (chb (25 .. 28))), + filename_length => Intel_nb (chb (29 .. 30)), + extra_field_length => Intel_nb (chb (31 .. 32))), + comment_length => Intel_nb (chb (33 .. 34)), + disk_number_start => Intel_nb (chb (35 .. 36)), + internal_attributes => Intel_nb (chb (37 .. 38)), + external_attributes => Intel_nb (chb (39 .. 42)), + local_header_offset => Intel_nb (chb (43 .. 46))); + + end Read_and_check; + + procedure Write (stream : Zipstream_Class; + header : Central_File_Header) is + + chb : Byte_Buffer (1 .. 46); + + begin + PK_signature (chb, 1); + + chb (5 .. 6) := Intel_bf (header.made_by_version); + chb (7 .. 8) := Intel_bf (header.short_info.needed_extract_version); + chb (9 .. 10) := Intel_bf (header.short_info.bit_flag); + chb (11 .. 12) := Intel_bf (header.short_info.zip_type); + chb (13 .. 16) := Intel_bf (Zip_Streams.Calendar.Convert (header.short_info.file_timedate)); + chb (17 .. 20) := Intel_bf (header.short_info.dd.crc_32); + chb (21 .. 24) := Intel_bf (header.short_info.dd.compressed_size); + chb (25 .. 28) := Intel_bf (header.short_info.dd.uncompressed_size); + chb (29 .. 30) := Intel_bf (header.short_info.filename_length); + chb (31 .. 32) := Intel_bf (header.short_info.extra_field_length); + chb (33 .. 34) := Intel_bf (header.comment_length); + chb (35 .. 36) := Intel_bf (header.disk_number_start); + chb (37 .. 38) := Intel_bf (header.internal_attributes); + chb (39 .. 42) := Intel_bf (header.external_attributes); + chb (43 .. 46) := Intel_bf (header.local_header_offset); + + BlockWrite (stream.all, chb); + end Write; + + ----------------------------------------------------------------------- + -- PKZIP local file header, in front of every file in archive - PK34 -- + ----------------------------------------------------------------------- + + procedure Read_and_check (stream : Zipstream_Class; + header : out Local_File_Header) is + + lhb : Byte_Buffer (1 .. 30); + + begin + BlockRead (stream, lhb); + + if not PK_signature (lhb, 3) then + raise bad_local_header; + end if; + + header := + (needed_extract_version => Intel_nb (lhb (5 .. 6)), + bit_flag => Intel_nb (lhb (7 .. 8)), + zip_type => Intel_nb (lhb (9 .. 10)), + file_timedate => Zip_Streams.Calendar.Convert (Unsigned_32'(Intel_nb (lhb (11 .. 14)))), + dd => + (crc_32 => Intel_nb (lhb (15 .. 18)), + compressed_size => Intel_nb (lhb (19 .. 22)), + uncompressed_size => Intel_nb (lhb (23 .. 26))), + filename_length => Intel_nb (lhb (27 .. 28)), + extra_field_length => Intel_nb (lhb (29 .. 30))); + + end Read_and_check; + + procedure Write (stream : Zipstream_Class; + header : Local_File_Header) is + + lhb : Byte_Buffer (1 .. 30); + + begin + PK_signature (lhb, 3); + + lhb (5 .. 6) := Intel_bf (header.needed_extract_version); + lhb (7 .. 8) := Intel_bf (header.bit_flag); + lhb (9 .. 10) := Intel_bf (header.zip_type); + lhb (11 .. 14) := Intel_bf (Zip_Streams.Calendar.Convert (header.file_timedate)); + lhb (15 .. 18) := Intel_bf (header.dd.crc_32); + lhb (19 .. 22) := Intel_bf (header.dd.compressed_size); + lhb (23 .. 26) := Intel_bf (header.dd.uncompressed_size); + lhb (27 .. 28) := Intel_bf (header.filename_length); + lhb (29 .. 30) := Intel_bf (header.extra_field_length); + + BlockWrite (stream.all, lhb); + end Write; + + ------------------------------------------- + -- PKZIP end - of - central - directory - PK56 -- + ------------------------------------------- + + procedure Copy_and_check (buffer : Byte_Buffer; + the_end : out End_of_Central_Dir) is + + begin + if not PK_signature (buffer, 5) then + raise bad_end; + end if; + + the_end := + (disknum => Intel_nb (buffer (5 .. 6)), + disknum_with_start => Intel_nb (buffer (7 .. 8)), + disk_total_entries => Intel_nb (buffer (9 .. 10)), + total_entries => Intel_nb (buffer (11 .. 12)), + central_dir_size => Intel_nb (buffer (13 .. 16)), + central_dir_offset => Intel_nb (buffer (17 .. 20)), + main_comment_length => Intel_nb (buffer (21 .. 22)), + offset_shifting => 0); -- Assuming single zip archive here + + end Copy_and_check; + + procedure Read_and_check (stream : Zipstream_Class; + the_end : out End_of_Central_Dir) is + + eb : Byte_Buffer (1 .. 22); + + begin + BlockRead (stream, eb); + Copy_and_check (eb, the_end); + end Read_and_check; + + -- Some explanations - GdM 2001 + + -- The idea is that the .ZIP can be appended to an .EXE, for + -- self - extracting purposes. So, the most general infos are + -- at the end, and we crawl back for more precise infos: + -- 1) end - of - central directory + -- 2) central directory + -- 3) zipped files + + procedure Load (stream : Zipstream_Class; + the_end : out End_of_Central_Dir) is + + end_buffer : Byte_Buffer (1 .. 22); + min_end_start : Ada.Streams.Stream_IO.Count; + + use Ada.Streams.Stream_IO; + + max_comment : constant := 65_535; + + begin + -- 20 - Jun - 2001 : abandon search below min_end_start + -- - read about max comment length in appnote + + if Size (stream) <= max_comment then + min_end_start := 1; + else + min_end_start := Ada.Streams.Stream_IO.Count (Size (stream)) - max_comment; + end if; + + -- Yes, we must _search_ for it .. . + -- because PKWARE put a variable - size comment _after_ it 8 - ( + + for i in reverse min_end_start .. Ada.Streams.Stream_IO.Count (Size (stream)) - 21 loop + Zip_Streams.Set_Index (stream, Positive (i)); + begin + for j in end_buffer'Range loop + Byte'Read (stream, end_buffer (j)); + -- 20 - Jun - 2001 : useless to read more if 1st character is not 'P' + if j = end_buffer'First and then + end_buffer (j) /= Character'Pos ('P') + then + raise bad_end; + end if; + end loop; + Copy_and_check (end_buffer, the_end); + -- at this point, the buffer was successfully read + -- (no exception raised). + the_end.offset_shifting := + -- This is the real position of the end - of - central - directory block. + Unsigned_32 (Zip_Streams.Index (stream) - 22) + - + -- This is the theoretical position of the end - of - central - directory, + -- block. Should coincide with the real position if the zip file + -- is not appended. + ( + 1 + + the_end.central_dir_offset + + the_end.central_dir_size + ); + return; -- the_end found and filled - > exit + exception + when bad_end => + if i > min_end_start then + null; -- we will try 1 index before .. . + else + raise; -- definitely no ""end - of - central - directory"" here + end if;" +procedure Init_Buffers;,"package Decryption is + procedure Set_mode (crypted : Boolean); + function Get_mode return Boolean; + procedure Init (passwrd : String; crc_check : Unsigned_32); + procedure Decode (b : in out Unsigned_8); + pragma Inline (Decode); + end Decryption; + + procedure Read_raw_byte (bt : out Unsigned_8); + pragma Inline (Read_raw_byte); + + package Bit_buffer is + procedure Init; + -- Read at least n bits into the bit buffer, returns the n first bits + function Read (n : Natural) return Integer; + pragma Inline (Read); + function Read_U32 (n : Natural) return Unsigned_32; + pragma Inline (Read_U32); + -- Inverts (NOT operator) the result before masking by n bits + function Read_inverted (n : Natural) return Integer; + pragma Inline (Read_inverted); + -- Dump n bits no longer needed from the bit buffer + procedure Dump (n : Natural); + pragma Inline (Dump); + procedure Dump_to_byte_boundary; + function Read_and_dump (n : Natural) return Integer; + pragma Inline (Read_and_dump); + function Read_and_dump_U32 (n : Natural) return Unsigned_32; + pragma Inline (Read_and_dump_U32); + end Bit_buffer; + + procedure Flush (x : Natural); -- directly from slide to output stream + + procedure Flush_if_full (W : in out Integer; unflushed : in out Boolean); + pragma Inline (Flush_if_full); + + procedure Flush_if_full (W : in out Integer); + pragma Inline (Flush_if_full); + + procedure Copy (distance, copy_length : Natural; + index : in out Natural); + pragma Inline (Copy); + + procedure Copy_or_zero (distance, copy_length : Natural; + index : in out Natural; + unflushed : in out Boolean); + pragma Inline (Copy_or_zero); + + procedure Delete_output; -- an error has occured (bad compressed data) + + end UnZ_IO; + + package UnZ_Meth is + procedure Copy_stored; + procedure Unshrink; + subtype Reduction_factor is Integer range 1 .. 4; + procedure Unreduce (factor : Reduction_factor); + procedure Explode (literal_tree, slide_8_KB : Boolean); + deflate_e_mode : Boolean := False; + procedure Inflate; + procedure Bunzip2; -- Nov - 2009 + end UnZ_Meth; + + ------------------------------ + -- Bodies of UnZ_* packages -- + ------------------------------ + package body UnZ_IO is + + -- Centralize buffer initialisations - 29 - Jun - 2001 + + procedure Init_Buffers is + begin + UnZ_Glob.inpos := 0; -- Input buffer position + UnZ_Glob.readpos := -1; -- Nothing read + UnZ_Glob.slide_index := 0; + UnZ_Glob.reachedsize := 0; + UnZ_Glob.effective_writes := 0; + UnZ_Glob.Zip_EOF := False; + Zip.CRC.Init (UnZ_Glob.crc32val); + Bit_buffer.Init; + end Init_Buffers; + + procedure Read_buffer is + begin + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put (""[Read_buffer .. .""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + if UnZ_Glob.reachedsize > UnZ_Glob.compsize + 2 then + -- + 2 : last code is smaller than requested! + UnZ_Glob.readpos := UnZ_Glob.inbuf'Length; + -- Simulates reading - > no blocking + UnZ_Glob.Zip_EOF := True; + else + begin + Zip.BlockRead ( + stream => zip_file, + buffer => UnZ_Glob.inbuf, + actually_read => UnZ_Glob.readpos + ); + exception + when others => -- I/O error + UnZ_Glob.readpos := UnZ_Glob.inbuf'Length; + -- Simulates reading - > CRC error + UnZ_Glob.Zip_EOF := True;" +procedure Init is,"begin + B := 0; + K := 0; + end Init; + + procedure Need (n : Natural) is + pragma Inline (Need); + bt : Zip.Byte; + begin + while K < n loop + Read_raw_byte (bt); + B := B or Shift_Left (Unsigned_32 (bt), K); + K := K + 8; + end loop; + end Need; + + procedure Dump (n : Natural) is + begin + B := Shift_Right (B, n); + K := K - n; + end Dump; + + procedure Dump_to_byte_boundary is + begin + Dump (K mod 8); + end Dump_to_byte_boundary; + + function Read_U32 (n : Natural) return Unsigned_32 is + begin + Need (n); + return B and (Shift_Left (1, n) - 1); + end Read_U32; + + function Read_inverted (n : Natural) return Integer is + begin + Need (n); + return Integer ((not B) and (Shift_Left (1, n) - 1)); + end Read_inverted; + + function Read (n : Natural) return Integer is + begin + return Integer (Read_U32 (n)); + end Read; + + function Read_and_dump (n : Natural) return Integer is + res : Integer; + begin + res := Read (n); + Dump (n); + return res; + end Read_and_dump; + + function Read_and_dump_U32 (n : Natural) return Unsigned_32 is + res : Unsigned_32; + begin + res := Read_U32 (n); + Dump (n); + return res; + end Read_and_dump_U32; + + end Bit_buffer; + + procedure Flush (x : Natural) is + use Zip, UnZip, Ada.Streams; + user_aborting : Boolean; + begin + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put (""[Flush .. .""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + begin + case mode is + when write_to_binary_file => + BlockWrite (Ada.Streams.Stream_IO.Stream (out_bin_file).all, UnZ_Glob.slide (0 .. x - 1)); + when write_to_text_file => + Zip.Write_as_text ( + UnZ_IO.out_txt_file, UnZ_Glob.slide (0 .. x - 1), UnZ_IO.last_char + ); + when write_to_memory => + for i in 0 .. x - 1 loop + output_memory_access.all (UnZ_Glob.uncompressed_index) := + Ada.Streams.Stream_Element (UnZ_Glob.slide (i)); + UnZ_Glob.uncompressed_index := UnZ_Glob.uncompressed_index + 1; + end loop; + when just_test => + null; + end case; + exception + when others => + raise UnZip.Write_Error;" +procedure Delete_output is -- an error has occured (bad compressed data),"begin + if no_trace then -- if there is a trace, we are debugging + case mode is -- and want to keep the malformed file + when write_to_binary_file => + Ada.Streams.Stream_IO.Delete (UnZ_IO.out_bin_file); + when write_to_text_file => + Ada.Text_IO.Delete (UnZ_IO.out_txt_file); + when others => + null; + end case; + end if; + end Delete_output; + + end UnZ_IO; + + package body UnZ_Meth is + + --------[ Method : Unshrink ] -------- + + -- Original in Pascal written by Christian Ghisler. + + Max_Code : constant := 8192; + Max_Stack : constant := 8192; + Initial_Code_Size : constant := 9; + Maximum_Code_Size : constant := 13; + First_Entry : constant := 257; + + -- Rest of slide=write buffer =766 bytes + + Write_Max : constant := wsize - 3 * (Max_Code - 256) - Max_Stack - 2; + + Previous_Code : array (First_Entry .. Max_Code) of Integer; + Actual_Code : array (First_Entry .. Max_Code) of Zip.Byte; + + Next_Free : Integer; -- Next free code in trie + Write_Ptr : Integer; -- Pointer to output buffer + + Writebuf : Zip.Byte_Buffer (0 .. Write_Max); -- Write buffer + + procedure Unshrink_Flush is + use Zip, UnZip, Ada.Streams, Ada.Streams.Stream_IO; + user_aborting : Boolean; + begin + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put (""[Unshrink_Flush]""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + begin + case mode is + when write_to_binary_file => + BlockWrite (Stream (UnZ_IO.out_bin_file).all, Writebuf (0 .. Write_Ptr - 1)); + when write_to_text_file => + Zip.Write_as_text (UnZ_IO.out_txt_file, Writebuf (0 .. Write_Ptr - 1), UnZ_IO.last_char); + when write_to_memory => + for I in 0 .. Write_Ptr - 1 loop + output_memory_access.all (UnZ_Glob.uncompressed_index) := + Stream_Element (Writebuf (I)); + UnZ_Glob.uncompressed_index := UnZ_Glob.uncompressed_index + 1; + end loop; + when just_test => + null; + end case; + exception + when others => + raise UnZip.Write_Error;" +procedure Clear_Leaf_Nodes is,"Pc : Integer; -- previous code + Act_Max_Code : Integer; -- max code to be searched for leaf nodes + + begin + Act_Max_Code := Next_Free - 1; + for I in First_Entry .. Act_Max_Code loop + Previous_Code (I) := + Integer (Unsigned_32 (Previous_Code (I)) or 16#8000#); + end loop; + + for I in First_Entry .. Act_Max_Code loop + Pc := Previous_Code (I) mod 16#8000#; + if Pc > 256 then + Previous_Code (Pc) := Previous_Code (Pc) mod 16#8000#; + end if; + end loop; + + -- Build new free list + Pc := -1; + Next_Free := -1; + for I in First_Entry .. Act_Max_Code loop + -- Either free before or marked now + if (Unsigned_32 (Previous_Code (I)) and 16#C000#) /= 0 then + -- Link last item to this item + if Pc = -1 then + Next_Free := I; + else + Previous_Code (Pc) := -I; + end if; + Pc := I; + end if; + end loop; + + if Pc /= -1 then + Previous_Code (Pc) := -Act_Max_Code - 1; + end if; + + end Clear_Leaf_Nodes; + + procedure Unshrink is + Incode : Integer; -- Code read in + Last_Incode : Integer; + Last_Outcode : Zip.Byte; + Code_Size : Integer := Initial_Code_Size; -- Actual code size (9 .. 13) + Stack : Zip.Byte_Buffer (0 .. Max_Stack); -- Stack for output + Stack_Ptr : Integer := Max_Stack; + New_Code : Integer; -- Save new normal code read + + Code_for_Special : constant := 256; + Code_Increase_size : constant := 1; + Code_Clear_table : constant := 2; + + S : UnZip.File_size_type := UnZ_Glob.uncompsize; + -- Fix Jan - 2009 : replaces a remaining bits counter as Unsigned_*32* .. . + + procedure Read_Code is + pragma Inline (Read_Code); + begin + Incode := UnZ_IO.Bit_buffer.Read_and_dump (Code_Size); + end Read_Code; + + begin + Previous_Code := (others => 0); + Actual_Code := (others => 0); + Stack := (others => 0); + Writebuf := (others => 0); + + if UnZ_Glob.compsize = Unsigned_32'Last then + -- Compressed Size was not in header! + raise UnZip.Not_supported; + elsif UnZ_Glob.uncompsize = 0 then + return; -- compression of a 0 - file with Shrink.pas + end if; + + -- initialize free codes list + + for I in Previous_Code'Range loop + Previous_Code (I) := -(I + 1); + end loop; + + Next_Free := First_Entry; + Write_Ptr := 0; + + Read_Code; + Last_Incode := Incode; + Last_Outcode := Zip.Byte (Incode); + Write_Byte (Last_Outcode); + S := S - 1; + + while S > 0 and then not UnZ_Glob.Zip_EOF loop + Read_Code; + if Incode = Code_for_Special then + Read_Code; + case Incode is + when Code_Increase_size => + Code_Size := Code_Size + 1; + if some_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put ( + ""[LZW code size - >"" & Integer'Image (Code_Size) & ']' + ); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + if Code_Size > Maximum_Code_Size then + raise Zip.Zip_file_Error; + end if; + when Code_Clear_table => + Clear_Leaf_Nodes; + when others => + raise Zip.Zip_file_Error; + end case; + + else -- Normal code + New_Code := Incode; + if Incode < 256 then -- Simple char + Last_Outcode := Zip.Byte (Incode); + Write_Byte (Last_Outcode); + S := S - 1; + else + if Previous_Code (Incode) < 0 then + Stack (Stack_Ptr) := Last_Outcode; + Stack_Ptr := Stack_Ptr - 1; + Incode := Last_Incode; + end if; + while Incode > 256 loop + -- Test added 11 - Dec - 2007 for situations + -- happening on corrupt files: + if Stack_Ptr < Stack'First or else + Incode > Actual_Code'Last + then + raise Zip.Zip_file_Error; + end if; + Stack (Stack_Ptr) := Actual_Code (Incode); + Stack_Ptr := Stack_Ptr - 1; + Incode := Previous_Code (Incode); + end loop; + + Last_Outcode := Zip.Byte (Incode mod 256); + Write_Byte (Last_Outcode); + + for I in Stack_Ptr + 1 .. Max_Stack loop + Write_Byte (Stack (I)); + end loop; + S := S - UnZip.File_size_type (Max_Stack - Stack_Ptr + 1); + + Stack_Ptr := Max_Stack; + end if; + Incode := Next_Free; + if Incode <= Max_Code then + Next_Free := -Previous_Code (Incode); + -- Next node in free list + Previous_Code (Incode) := Last_Incode; + Actual_Code (Incode) := Last_Outcode; + end if; + Last_Incode := New_Code; + end if; + end loop; + if some_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put (""[ Unshrink main loop finished ]""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + Unshrink_Flush; + end Unshrink; + + --------[ Method : Unreduce ] -------- + + procedure Unreduce (factor : Reduction_factor) is + + -- Original slide limit : 16#4000# + DLE_code : constant := 144; + subtype Symbol_range is Integer range 0 .. 255; + subtype Follower_range is Integer range 0 .. 63; -- Appnote : <= 32 ! + Followers : array (Symbol_range, Follower_range) of Symbol_range := + (others => (others => 0)); + Slen : array (Symbol_range) of Follower_range; + + -- Bits taken by (x - 1) mod 256: + B_Table : constant array (Symbol_range) of Integer := + (0 => 8, + 1 .. 2 => 1, + 3 .. 4 => 2, + 5 .. 8 => 3, + 9 .. 16 => 4, + 17 .. 32 => 5, + 33 .. 64 => 6, + 65 .. 128 => 7, + 129 .. 255 => 8); + + procedure LoadFollowers is + list_followers : constant Boolean := some_trace; + procedure Show_symbol (S : Symbol_range) is + begin + if S in 32 .. 254 then + Ada.Text_IO.Put (Character'Val (S)); + else + Ada.Text_IO.Put ('{' & Symbol_range'Image (S) & '}'); + end if; + end Show_symbol; + begin + for X in reverse Symbol_range loop + Slen (X) := UnZ_IO.Bit_buffer.Read_and_dump (6); + if list_followers then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Show_symbol (X); + Ada.Text_IO.Put ("" - > ("" & Integer'Image (Slen (X)) & "") ""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + for I in 0 .. Slen (X) - 1 loop + Followers (X, I) := UnZ_IO.Bit_buffer.Read_and_dump (8); + if list_followers then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Show_symbol (Followers (X, I)); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end loop; + if list_followers then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.New_Line; + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end loop; + end LoadFollowers; + + unreduce_length, + char_read, + last_char : Integer := 0; + -- ^ some := 0 are useless, just to calm down ObjectAda 7.2.2 + S : UnZip.File_size_type := UnZ_Glob.uncompsize; + -- number of bytes left to decompress + unflushed : Boolean := True; + maximum_AND_mask : constant Unsigned_32 := Shift_Left (1, 8 - factor) - 1; + + procedure Out_byte (b : Zip.Byte) is + begin + S := S - 1; + UnZ_Glob.slide (UnZ_Glob.slide_index) := b; + UnZ_Glob.slide_index := UnZ_Glob.slide_index + 1; + UnZ_IO.Flush_if_full (UnZ_Glob.slide_index, unflushed); + end Out_byte; + + V : Unsigned_32 := 0; + type State_type is (normal, length_a, length_b, distance); + state : State_type := normal; + + begin + LoadFollowers; + + while S > 0 and then not UnZ_Glob.Zip_EOF loop + + -- 1/ Probabilistic expansion + if Slen (last_char) = 0 then + -- follower set is empty for this character + char_read := UnZ_IO.Bit_buffer.Read_and_dump (8); + elsif UnZ_IO.Bit_buffer.Read_and_dump (1) = 0 then + char_read := Followers ( + last_char, + UnZ_IO.Bit_buffer.Read_and_dump (B_Table (Slen (last_char))) + ); + else + char_read := UnZ_IO.Bit_buffer.Read_and_dump (8); + end if; + + -- 2/ Expand the resulting Zip.Byte into repeated sequences + case state is + + when normal => + if char_read = DLE_code then + -- >> Next will be a DLE + state := length_a; + else + -- >> A single char + Out_byte (Zip.Byte (char_read)); + end if; + + when length_a => + if char_read = 0 then + -- >> DLE_code & 0 - > was just the Zip.Byte coded DLE_code + Out_byte (DLE_code); + state := normal; + else + V := Unsigned_32 (char_read); + unreduce_length := Integer (V and maximum_AND_mask); + -- The remaining bits of V will be used for the distance + if unreduce_length = Integer (maximum_AND_mask) then + state := length_b; + -- >> length must be completed before reading distance + else + state := distance; + end if; + end if; + + when length_b => + unreduce_length := unreduce_length + char_read; + state := distance; + + when distance => + unreduce_length := unreduce_length + 3; + S := S - UnZip.File_size_type (unreduce_length); + + UnZ_IO.Copy_or_zero ( + distance => char_read + 1 + Integer (Shift_Right (V, 8 - factor) * 2**8), + copy_length => unreduce_length, + index => UnZ_Glob.slide_index, + unflushed => unflushed + ); + state := normal; + + end case; + + last_char := char_read; -- store character for next iteration + end loop; + + UnZ_IO.Flush (UnZ_Glob.slide_index); + end Unreduce; + + --------[ Method : Explode ] -------- + + -- C code by info - zip group, translated to Pascal by Christian Ghisler + -- based on unz51g.zip + + use UnZip.Decompress.Huffman; + + procedure Get_Tree (L : out Length_array) is + I, K, J, B : Unsigned_32; + N : constant Unsigned_32 := L'Length; + L_Idx : Integer := L'First; + Bytebuf : Zip.Byte; + + begin + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""Begin UnZ_Expl.Get_tree""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + + UnZ_IO.Read_raw_byte (Bytebuf); + I := Unsigned_32 (Bytebuf) + 1; + K := 0; + + loop + UnZ_IO.Read_raw_byte (Bytebuf); + J := Unsigned_32 (Bytebuf); + B := (J and 16#0F#) + 1; + J := (J and 16#F0#) / 16 + 1; + if K + J > N then + raise Zip.Zip_file_Error; + end if; + + loop + L (L_Idx) := Natural (B); + L_Idx := L_Idx + 1; + K := K + 1; + J := J - 1; + exit when J = 0; + end loop; + + I := I - 1; + exit when I = 0; + end loop; + + if K /= N then + raise Zip.Zip_file_Error; + end if; + + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""End UnZ_Expl.Get_tree""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end Get_Tree; + + procedure Explode_Lit ( -- method with 3 trees + Needed : Integer; + Tb, Tl, Td : p_Table_list; + Bb, Bl, Bd : Integer + ) + is + S : Unsigned_32; + E, N, D : Integer; + + W : Integer := 0; + Ct : p_HufT_table; -- current table + Ci : Natural; -- current index + unflushed : Boolean := True; -- true while slide not yet unflushed + + begin + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""Begin Explode_lit""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + + UnZ_IO.Bit_buffer.Init; + + S := UnZ_Glob.uncompsize; + while S > 0 and then not UnZ_Glob.Zip_EOF loop + if UnZ_IO.Bit_buffer.Read_and_dump (1) /= 0 then -- 1 : Litteral + S := S - 1; + Ct := Tb.all.table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (Bb); + + loop + E := Ct.all (Ci).extra_bits; + exit when E <= 16; + + if E = invalid then + raise Zip.Zip_file_Error; + end if; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + E := E - 16; + Ct := Ct.all (Ci).next_table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (E); + end loop; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + UnZ_Glob.slide (W) := Zip.Byte (Ct.all (Ci).n); + W := W + 1; + UnZ_IO.Flush_if_full (W, unflushed); + + else -- 0 : Copy + D := UnZ_IO.Bit_buffer.Read_and_dump (Needed); + Ct := Td.all.table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (Bd); + + loop + E := Ct.all (Ci).extra_bits; + exit when E <= 16; + + if E = invalid then + raise Zip.Zip_file_Error; + end if; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + E := E - 16; + Ct := Ct.all (Ci).next_table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (E); + end loop; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + D := D + Ct.all (Ci).n; + + Ct := Tl.all.table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (Bl); + + loop + E := Ct.all (Ci).extra_bits; + exit when E <= 16; + + if E = invalid then + raise Zip.Zip_file_Error; + end if; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + E := E - 16; + Ct := Ct.all (Ci).next_table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (E); + end loop; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + + N := Ct.all (Ci).n; + if E /= 0 then + N := N + UnZ_IO.Bit_buffer.Read_and_dump (8); + end if; + S := S - Unsigned_32 (N); + + UnZ_IO.Copy_or_zero ( + distance => D, + copy_length => N, + index => W, + unflushed => unflushed + ); + + end if; + end loop; + + UnZ_IO.Flush (W); + if UnZ_Glob.Zip_EOF then + raise UnZip.Read_Error; + end if; + + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""End Explode_lit""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end Explode_Lit; + + procedure Explode_Nolit ( -- method with 2 trees + Needed : Integer; + Tl, Td : p_Table_list; + Bl, Bd : Integer + ) + is + S : Unsigned_32; + E, N, D : Integer; + W : Integer := 0; + Ct : p_HufT_table; -- current table + Ci : Natural; -- current index + unflushed : Boolean := True; -- true while slide not yet unflushed + + begin + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""Begin Explode_nolit""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + + UnZ_IO.Bit_buffer.Init; + S := UnZ_Glob.uncompsize; + while S > 0 and then not UnZ_Glob.Zip_EOF loop + if UnZ_IO.Bit_buffer.Read_and_dump (1) /= 0 then -- 1 : Litteral + S := S - 1; + UnZ_Glob.slide (W) := + Zip.Byte (UnZ_IO.Bit_buffer.Read_and_dump (8)); + W := W + 1; + UnZ_IO.Flush_if_full (W, unflushed); + else -- 0 : Copy + D := UnZ_IO.Bit_buffer.Read_and_dump (Needed); + Ct := Td.all.table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (Bd); + + loop + E := Ct.all (Ci).extra_bits; + exit when E <= 16; + + if E = invalid then + raise Zip.Zip_file_Error; + end if; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + E := E - 16; + Ct := Ct.all (Ci).next_table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (E); + end loop; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + + D := D + Ct.all (Ci).n; + Ct := Tl.all.table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (Bl); + + loop + E := Ct.all (Ci).extra_bits; + exit when E <= 16; + + if E = invalid then + raise Zip.Zip_file_Error; + end if; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + E := E - 16; + Ct := Ct.all (Ci).next_table; + Ci := UnZ_IO.Bit_buffer.Read_inverted (E); + end loop; + + UnZ_IO.Bit_buffer.Dump (Ct.all (Ci).bits); + + N := Ct.all (Ci).n; + if E /= 0 then + N := N + UnZ_IO.Bit_buffer.Read_and_dump (8); + end if; + S := S - Unsigned_32 (N); + + UnZ_IO.Copy_or_zero ( + distance => D, + copy_length => N, + index => W, + unflushed => unflushed + ); + + end if; + end loop; + + UnZ_IO.Flush (W); + if UnZ_Glob.Zip_EOF then + raise UnZip.Read_Error; + end if; + + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""End Explode_nolit""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + + end Explode_Nolit; + + procedure Explode (literal_tree, slide_8_KB : Boolean) is + + Tb, Tl, Td : p_Table_list; + Bb, Bl, Bd : Integer; + L : Length_array (0 .. 255); + huft_incomplete : Boolean; + + cp_length_2_trees : + constant Length_array (0 .. 63) := + (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65); + + cp_length_3_trees : + constant Length_array (0 .. 63) := + (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66); + + cp_dist_4KB : + constant Length_array (0 .. 63) := + (1, 65, 129, 193, 257, 321, 385, 449, 513, 577, 641, 705, + 769, 833, 897, 961, 1025, 1089, 1153, 1217, 1281, 1345, 1409, 1473, + 1537, 1601, 1665, 1729, 1793, 1857, 1921, 1985, 2049, 2113, 2177, + 2241, 2305, 2369, 2433, 2497, 2561, 2625, 2689, 2753, 2817, 2881, + 2945, 3009, 3073, 3137, 3201, 3265, 3329, 3393, 3457, 3521, 3585, + 3649, 3713, 3777, 3841, 3905, 3969, 4033); + + cp_dist_8KB : + constant Length_array (0 .. 63) := + (1, 129, 257, 385, 513, 641, 769, 897, 1025, 1153, 1281, + 1409, 1537, 1665, 1793, 1921, 2049, 2177, 2305, 2433, 2561, 2689, + 2817, 2945, 3073, 3201, 3329, 3457, 3585, 3713, 3841, 3969, 4097, + 4225, 4353, 4481, 4609, 4737, 4865, 4993, 5121, 5249, 5377, 5505, + 5633, 5761, 5889, 6017, 6145, 6273, 6401, 6529, 6657, 6785, 6913, + 7041, 7169, 7297, 7425, 7553, 7681, 7809, 7937, 8065); + + extra : + constant Length_array (0 .. 63) := (0 .. 62 => 0, 63 => 8); + + begin + Bl := 7; + if UnZ_Glob.compsize > 200000 then + Bd := 8; + else + Bd := 7; + end if; + + if literal_tree then + Bb := 9; + Get_Tree (L); + begin + HufT_build (L, 256, empty, empty, Tb, Bb, huft_incomplete); + if huft_incomplete then + HufT_free (Tb); + raise Zip.Zip_file_Error; + end if; + exception + when others => + raise Zip.Zip_file_Error;" +procedure Copy_stored is,"size : constant UnZip.File_size_type := UnZ_Glob.compsize; + read_in, absorbed : UnZip.File_size_type; + begin + absorbed := 0; + if UnZ_IO.Decryption.Get_mode then + absorbed := 12; + end if; + while absorbed < size loop + read_in := size - absorbed; + if read_in > wsize then + read_in := wsize; + end if; + begin + for I in 0 .. read_in - 1 loop + UnZ_IO.Read_raw_byte (UnZ_Glob.slide (Natural (I))); + end loop; + exception + when others => + raise UnZip.Read_Error;" +"procedure Inflate_stored_block is -- Actually, nothing to inflate","N : Integer; + begin + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""Begin Inflate_stored_block""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + UnZ_IO.Bit_buffer.Dump_to_byte_boundary; + + -- Get the block length and its complement + N := UnZ_IO.Bit_buffer.Read_and_dump (16); + if N /= Integer ( + (not UnZ_IO.Bit_buffer.Read_and_dump_U32 (16)) + and 16#ffff#) + then + raise Zip.Zip_file_Error; + end if; + while N > 0 and then not UnZ_Glob.Zip_EOF loop + -- Read and output the non - compressed data + N := N - 1; + UnZ_Glob.slide (UnZ_Glob.slide_index) := + Zip.Byte (UnZ_IO.Bit_buffer.Read_and_dump (8)); + UnZ_Glob.slide_index := UnZ_Glob.slide_index + 1; + UnZ_IO.Flush_if_full (UnZ_Glob.slide_index); + end loop; + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""End Inflate_stored_block""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end Inflate_stored_block; + + -- Copy lengths for literal codes 257 .. 285 + + copy_lengths_literal : Length_array (0 .. 30) := + (3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0); + + -- Extra bits for literal codes 257 .. 285 + + extra_bits_literal : Length_array (0 .. 30) := + (0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, invalid, invalid); + + -- Copy offsets for distance codes 0 .. 29 (30 .. 31 : deflate_e) + + copy_offset_distance : constant Length_array (0 .. 31) := + (1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 32769, 49153); + + -- Extra bits for distance codes + + extra_bits_distance : constant Length_array (0 .. 31) := + (0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14); + + max_dist : Integer := 29; -- changed to 31 for deflate_e + + procedure Inflate_fixed_block is + Tl, -- literal/length code table + Td : p_Table_list; -- distance code table + Bl, Bd : Integer; -- lookup bits for tl/bd + huft_incomplete : Boolean; + + -- length list for HufT_build (literal table) + L : constant Length_array (0 .. 287) := + (0 .. 143 => 8, 144 .. 255 => 9, 256 .. 279 => 7, 280 .. 287 => 8); + + begin + if some_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""Begin Inflate_fixed_block""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + + -- make a complete, but wrong code set + Bl := 7; + HufT_build ( + L, 257, copy_lengths_literal, extra_bits_literal, + Tl, Bl, huft_incomplete + ); + + -- Make an incomplete code set + Bd := 5; + begin + HufT_build ( + (0 .. max_dist => 5), 0, + copy_offset_distance, extra_bits_distance, + Td, Bd, huft_incomplete + ); + if huft_incomplete then + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line ( + ""td is incomplete, pointer=null : "" & + Boolean'Image (Td = null) + ); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end if; + exception + when huft_out_of_memory | huft_error => + HufT_free (Tl); + raise Zip.Zip_file_Error;" +procedure Inflate_dynamic_block is,"bit_order : constant array (0 .. 18) of Natural := + (16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15); + + Lbits : constant := 9; + Dbits : constant := 6; + + current_length : Natural; + defined, number_of_lengths : Natural; + + Tl, -- literal/length code tables + Td : p_Table_list; -- distance code tables + + CTE : p_HufT; -- current table element + + Bl, Bd : Integer; -- lookup bits for tl/bd + Nb : Natural; -- number of bit length codes + Nl : Natural; -- number of literal length codes + Nd : Natural; -- number of distance codes + + -- literal/length and distance code lengths + Ll : Length_array (0 .. 288 + 32 - 1) := (others => 0); + + huft_incomplete : Boolean; + + procedure Repeat_length_code (amount : Natural) is + begin + if defined + amount > number_of_lengths then + raise Zip.Zip_file_Error; + end if; + for c in reverse 1 .. amount loop + Ll (defined) := current_length; + defined := defined + 1; + end loop; + end Repeat_length_code; + + begin + if some_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (""Begin Inflate_dynamic_block""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + + -- Read in table lengths + Nl := 257 + UnZ_IO.Bit_buffer.Read_and_dump (5); + Nd := 1 + UnZ_IO.Bit_buffer.Read_and_dump (5); + Nb := 4 + UnZ_IO.Bit_buffer.Read_and_dump (4); + + if Nl > 288 or else Nd > 32 then + raise Zip.Zip_file_Error; + end if; + + -- Read in bit - length - code lengths. + -- The rest, Ll (Bit_Order (Nb .. 18)), is already = 0 + for J in 0 .. Nb - 1 loop + Ll (bit_order (J)) := UnZ_IO.Bit_buffer.Read_and_dump (3); + end loop; + + -- Build decoding table for trees --single level, 7 bit lookup + Bl := 7; + begin + HufT_build ( + Ll (0 .. 18), 19, empty, empty, Tl, Bl, huft_incomplete + ); + if huft_incomplete then + HufT_free (Tl); + raise Zip.Zip_file_Error; + end if; + exception + when others => + raise Zip.Zip_file_Error;" +procedure Inflate is,"is_last_block : Boolean; + blocks : Positive := 1; + begin + if deflate_e_mode then + copy_lengths_literal (28) := 3; -- instead of 258 + extra_bits_literal (28) := 16; -- instead of 0 + max_dist := 31; + end if; + loop + Inflate_Block (is_last_block); + exit when is_last_block; + blocks := blocks + 1; + end loop; + UnZ_IO.Flush (UnZ_Glob.slide_index); + UnZ_Glob.slide_index := 0; + if some_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put (""# blocks:"" & Integer'Image (blocks)); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end Inflate; + + --------[ Method : BZip2 ] -------- + + procedure Bunzip2 is + type BZ_Buffer is array (Natural range <>) of Interfaces.Unsigned_8; + procedure Read (b : out BZ_Buffer) is + begin + for i in b'Range loop + exit when UnZ_Glob.Zip_EOF; + UnZ_IO.Read_raw_byte (b (i)); + end loop; + end Read; + procedure Write (b : BZ_Buffer) is + begin + for i in b'Range loop + UnZ_Glob.slide (UnZ_Glob.slide_index) := b (i); + UnZ_Glob.slide_index := UnZ_Glob.slide_index + 1; + UnZ_IO.Flush_if_full (UnZ_Glob.slide_index); + end loop; + end Write; + package My_BZip2 is new BZip2 + (Buffer => BZ_Buffer, + check_CRC => False, -- Already done by UnZ_IO + Read => Read, + Write => Write + ); + begin + My_BZip2.Decompress; + UnZ_IO.Flush (UnZ_Glob.slide_index); + end Bunzip2; + + end UnZ_Meth; + + procedure Process (descriptor : out Zip.Headers.Data_descriptor) + is + start : Integer; + b : Unsigned_8; + dd_buffer : Zip.Byte_Buffer (1 .. 30); + begin + UnZ_IO.Bit_buffer.Dump_to_byte_boundary; + UnZ_IO.Read_raw_byte (b); + if b = 75 then -- 'K' ('P' is before, Java/JAR bug!) + dd_buffer (1) := 80; + dd_buffer (2) := 75; + start := 3; + else + dd_buffer (1) := b; -- hopefully = 80 + start := 2; + end if; + for i in start .. 16 loop + UnZ_IO.Read_raw_byte (dd_buffer (i)); + end loop; + Zip.Headers.Copy_and_check (dd_buffer, descriptor); + end Process; + + tolerance_wrong_password : constant := 4; -- after that, error ! + work_index : Ada.Streams.Stream_IO.Positive_Count; + use Zip, UnZ_Meth; + + begin -- Decompress_Data + output_memory_access := null; + -- ^ this is an 'out' parameter, we have to set it anyway + case mode is + when write_to_binary_file => + Ada.Streams.Stream_IO.Create (UnZ_IO.out_bin_file, Ada.Streams.Stream_IO.Out_File, output_file_name, + Form => To_String (Zip.Form_For_IO_Open_N_Create)); + when write_to_text_file => + Ada.Text_IO.Create (UnZ_IO.out_txt_file, Ada.Text_IO.Out_File, output_file_name, + Form => To_String (Zip.Form_For_IO_Open_N_Create)); + when write_to_memory => + output_memory_access := new + Ada.Streams.Stream_Element_Array ( + 1 .. Ada.Streams.Stream_Element_Offset (hint.uncompressed_size) + ); + UnZ_Glob.uncompressed_index := output_memory_access'First; + when just_test => + null; + end case; + + UnZ_Glob.compsize := hint.compressed_size; + -- 2008 : from TT's version: + -- Avoid wraparound in read_buffer, when File_size_type'Last is given + -- as hint.compressed_size (unknown size) + if UnZ_Glob.compsize > File_size_type'Last - 2 then + UnZ_Glob.compsize := File_size_type'Last - 2; + end if; + UnZ_Glob.uncompsize := hint.uncompressed_size; + UnZ_IO.Init_Buffers; + UnZ_IO.Decryption.Set_mode (encrypted); + if encrypted then + work_index := Ada.Streams.Stream_IO.Positive_Count (Zip_Streams.Index (zip_file)); + password_passes : for p in 1 .. tolerance_wrong_password loop + begin + UnZ_IO.Decryption.Init (To_String (password), hint.crc_32); + exit password_passes; -- the current password fits, then go on! + exception + when Wrong_password => + if p = tolerance_wrong_password then + raise; + end if; -- alarm! + if get_new_password /= null then + get_new_password (password); -- ask for a new one + end if;" +procedure Decompress is,"max_groups : constant := 6; + max_alpha_size : constant := 258; + max_code_len : constant := 23; + group_size : constant := 50; + max_selectors : constant := 2 + (900_000 / group_size); + + sub_block_size : constant := 100_000; + + type Length_array is array (Integer range <>) of Natural; + + block_randomized : Boolean := False; + block_size : Natural; + + use Interfaces; + + type Tcardinal_array is array (Integer range <>) of Unsigned_32; + type Pcardinal_array is access Tcardinal_array; + procedure Dispose is new Ada.Unchecked_Deallocation (Tcardinal_array, Pcardinal_array); + tt : Pcardinal_array; + tt_count : Natural; + + rle_run_left : Natural := 0; + rle_run_data : Unsigned_8 := 0; + decode_available : Natural := Natural'Last; + block_origin : Natural := 0; + read_data : Unsigned_8 := 0; + bits_available : Natural := 0; + inuse_count : Natural; + seq_to_unseq : array (0 .. 255) of Natural; + global_alpha_size : Natural; + group_count : Natural; + -- + selector_count : Natural; + selector, selector_mtf : array (0 .. max_selectors) of Unsigned_8; + -- + type Alpha_U32_array is array (0 .. max_alpha_size) of Unsigned_32; + type Alpha_Nat_array is array (0 .. max_alpha_size) of Natural; + + len : array (0 .. max_groups) of Alpha_Nat_array; + global_limit, + global_base, + global_perm : array (0 .. max_groups) of Alpha_U32_array; + -- + minlens : Length_array (0 .. max_groups); + cftab : array (0 .. 257) of Natural; + -- + end_reached : Boolean := False; + + in_buf : Buffer (1 .. input_buffer_size); + in_idx : Natural := in_buf'Last + 1; + + function Read_byte return Unsigned_8 is + res : Unsigned_8; + begin + if in_idx > in_buf'Last then + Read (in_buf); + in_idx := in_buf'First; + end if; + res := in_buf (in_idx); + in_idx := in_idx + 1; + return res; + end Read_byte; + + procedure hb_create_decode_tables (limit, base, perm : in out Alpha_U32_array; + length : Alpha_Nat_array; + min_len, max_len : Natural; + alpha_size : Integer) is + + pp, idx : Integer; + vec : Unsigned_32; + + begin + pp := 0; + for i in min_len .. max_len loop + for j in 0 .. alpha_size - 1 loop + if length (j) = i then + perm (pp) := Unsigned_32 (j); + pp := pp + 1; + end if; + end loop; + end loop; + for i in 0 .. max_code_len - 1 loop + base (i) := 0; + limit (i) := 0; + end loop; + for i in 0 .. alpha_size - 1 loop + idx := length (i) + 1; + base (idx) := base (idx) + 1; + end loop; + for i in 1 .. max_code_len - 1 loop + base (i) := base (i) + base (i - 1); + end loop; + vec := 0; + for i in min_len .. max_len loop + vec := vec + base (i + 1) - base (i); + limit (i) := vec - 1; + vec := vec * 2; + end loop; + for i in min_len + 1 .. max_len loop + base (i) := (limit (i - 1) + 1) * 2 - base (i); + end loop; + end hb_create_decode_tables; + + procedure Init is + magic : String (1 .. 3); + b : Unsigned_8; + begin + -- Read the magic. + for i in magic'Range loop + b := Read_byte; + magic (i) := Character'Val (b); + end loop; + if magic /= ""BZh"" then + raise bad_header_magic; + end if; + -- Read the block size and allocate the working array. + b := Read_byte; + block_size := Natural (b) - Character'Pos ('0'); + tt := new Tcardinal_array (0 .. block_size * sub_block_size); + end Init; + + function get_bits (n : Natural) return Unsigned_8 is + Result_get_bits : Unsigned_8; + data : Unsigned_8; + begin + if n > bits_available then + data := Read_byte; + Result_get_bits := Shift_Right (read_data, 8 - n) or Shift_Right (data, 8 - (n - bits_available)); + read_data := Shift_Left (data, n - bits_available); + bits_available := bits_available + 8; + else + Result_get_bits := Shift_Right (read_data, 8 - n); + read_data := Shift_Left (read_data, n); + end if; + bits_available := bits_available - n; + return Result_get_bits; + end get_bits; + + function get_bits_32 (n : Natural) return Unsigned_32 is + begin + return Unsigned_32 (get_bits (n)); + end get_bits_32; + + function get_boolean return Boolean is + begin + return Boolean'Val (get_bits (1)); + end get_boolean; + + function get_byte return Unsigned_8 is + begin + return get_bits (8); + end get_byte; + + function get_cardinal24 return Unsigned_32 is + begin + return Shift_Left (get_bits_32 (8), 16) or Shift_Left (get_bits_32 (8), 8) or get_bits_32 (8); + end get_cardinal24; + + function get_cardinal return Unsigned_32 is + begin + return Shift_Left (get_bits_32 (8), 24) or + Shift_Left (get_bits_32 (8), 16) or + Shift_Left (get_bits_32 (8), 8) or + get_bits_32 (8); + end get_cardinal; + + -- Receive the mapping table. To save space, the inuse set is stored in pieces + -- of 16 bits. First 16 bits are stored which pieces of 16 bits are used, then + -- the pieces follow. + procedure receive_mapping_table is + inuse16 : array (0 .. 15) of Boolean; + --* inuse : array (0 .. 255) of Boolean; -- for dump purposes + begin + inuse16 := (others => False); + -- Receive the first 16 bits which tell which pieces are stored. + for i in 0 .. 15 loop + inuse16 (i) := get_boolean; + end loop; + -- Receive the used pieces. + --* inuse := (others => False); + inuse_count := 0; + for i in 0 .. 15 loop + if inuse16 (i) then + for j in 0 .. 15 loop + if get_boolean then + --* inuse (16*i + j) := True; + seq_to_unseq (inuse_count) := 16 * i + j; + inuse_count := inuse_count + 1; + end if; + end loop; + end if; + end loop; + end receive_mapping_table; + + -- Receives the selectors. + procedure receive_selectors is + j : Unsigned_8; + begin + group_count := Natural (get_bits (3)); + selector_count := Natural (Shift_Left (get_bits_32 (8), 7) or get_bits_32 (7)); + for i in 0 .. selector_count - 1 loop + j := 0; + while get_boolean loop + j := j + 1; + if j > 5 then + raise data_error; + end if; + end loop; + selector_mtf (i) := j; + end loop; + end receive_selectors; + + -- Undo the MTF values for the selectors. + procedure undo_mtf_values is + pos : array (0 .. max_groups) of Natural; + v, tmp : Natural; + begin + for w in 0 .. group_count - 1 loop + pos (w) := w; + end loop; + for i in 0 .. selector_count - 1 loop + v := Natural (selector_mtf (i)); + tmp := pos (v); + while v /= 0 loop + pos (v) := pos (v - 1); + v := v - 1; + end loop; + pos (0) := tmp; + selector (i) := Unsigned_8 (tmp); + end loop; + end undo_mtf_values; + + procedure receive_coding_tables is + curr : Natural; + begin + for t in 0 .. group_count - 1 loop + curr := Natural (get_bits (5)); + for i in 0 .. global_alpha_size - 1 loop + loop + if curr not in 1 .. 20 then + raise data_error; + end if; + exit when not get_boolean; + if get_boolean then + curr := curr - 1; + else + curr := curr + 1; + end if; + end loop; + len (t) (i) := curr; + end loop; + end loop; + end receive_coding_tables; + + -- Builds the Huffman tables. + procedure make_hufftab is + minlen, maxlen : Natural; + begin + for t in 0 .. group_count - 1 loop + minlen := 32; + maxlen := 0; + for i in 0 .. global_alpha_size - 1 loop + if len (t) (i) > maxlen then + maxlen := len (t) (i); + end if; + if len (t) (i) < minlen then + minlen := len (t) (i); + end if; + end loop; + hb_create_decode_tables (global_limit (t), global_base (t), global_perm (t), len (t), + minlen, maxlen, global_alpha_size); + minlens (t) := minlen; + end loop; + end make_hufftab; + + ------------------------- + -- MTF - Move To Front -- + ------------------------- + + procedure receive_mtf_values is + -- + mtfa_size : constant := 4096; + mtfl_size : constant := 16; + mtfbase : array (0 .. 256 / mtfl_size - 1) of Natural; + mtfa : array (0 .. mtfa_size - 1) of Natural; + -- + procedure init_mtf is + k : Natural := mtfa_size - 1; + begin + for i in reverse 0 .. 256 / mtfl_size - 1 loop + for j in reverse 0 .. mtfl_size - 1 loop + mtfa (k) := i * mtfl_size + j; + k := k - 1; + end loop; + mtfbase (i) := k + 1; + end loop; + end init_mtf; + -- + group_pos, group_no : Integer; + gminlen, gsel : Natural; + -- + function get_mtf_value return Unsigned_32 is + zn : Natural; + zvec : Unsigned_32; + begin + if group_pos = 0 then + group_no := group_no + 1; + group_pos := group_size; + gsel := Natural (selector (group_no)); + gminlen := minlens (gsel); + end if; + group_pos := group_pos - 1; + zn := gminlen; + zvec := get_bits_32 (zn); + while zvec > global_limit (gsel) (zn) loop + zn := zn + 1; + zvec := Shift_Left (zvec, 1) or get_bits_32 (1); + end loop; + return global_perm (gsel) (Natural (zvec - global_base (gsel) (zn))); + end get_mtf_value; + -- + procedure move_mtf_block is + j, k : Natural; + begin + k := mtfa_size; + for i in reverse 0 .. 256 / mtfl_size - 1 loop + j := mtfbase (i); + mtfa (k - 16 .. k - 1) := mtfa (j .. j + 15); + k := k - 16; + mtfbase (i) := k; + end loop; + end move_mtf_block; + -- + run_b : constant := 1; + t : Natural; + next_sym : Unsigned_32; + es : Natural; + n, nn : Natural; + p, q : Natural; -- indexes mtfa + u, v : Natural; -- indexes mtfbase + lno, off : Natural; + begin -- receive_mtf_values + group_no := -1; + group_pos := 0; + t := 0; + cftab := (others => 0); + init_mtf; + next_sym := get_mtf_value; + -- + while Natural (next_sym) /= inuse_count + 1 loop + if next_sym <= run_b then + es := 0; + n := 0; + loop + es := es + Natural (Shift_Left (next_sym + 1, n)); + n := n + 1; + next_sym := get_mtf_value; + exit when next_sym > run_b; + end loop; + n := seq_to_unseq (mtfa (mtfbase (0))); + cftab (n) := cftab (n) + es; + if t + es > sub_block_size * block_size then + raise data_error; + end if; + while es > 0 loop + tt.all (t) := Unsigned_32 (n); + es := es - 1; + t := t + 1; + end loop; + else + nn := Natural (next_sym - 1); + if nn < mtfl_size then + -- Avoid the costs of the general case. + p := mtfbase (0); + q := p + nn; + n := mtfa (q); + loop + mtfa (q) := mtfa (q - 1); + q := q - 1; + exit when q = p; + end loop; + mtfa (q) := n; + else + -- General case. + lno := nn / mtfl_size; + off := nn mod mtfl_size; + p := mtfbase (lno); + q := p + off; + n := mtfa (q); + while q /= p loop + mtfa (q) := mtfa (q - 1); + q := q - 1; + end loop; + u := mtfbase'First; + v := u + lno; + loop + mtfa (mtfbase (v)) := mtfa (mtfbase (v - 1) + mtfl_size - 1); + v := v - 1; + mtfbase (v) := mtfbase (v) - 1; + exit when v = u; + end loop; + mtfa (mtfbase (v)) := n; + if mtfbase (v) = 0 then + move_mtf_block; + end if; + end if; + cftab (seq_to_unseq (n)) := cftab (seq_to_unseq (n)) + 1; + tt.all (t) := Unsigned_32 (seq_to_unseq (n)); + t := t + 1; + if t > sub_block_size * block_size then + raise data_error; + end if; + next_sym := get_mtf_value; + end if; + end loop; + tt_count := t; + -- Setup cftab to facilitate generation of T^ ( - 1). + t := 0; + for i in 0 .. 256 loop + nn := cftab (i); + cftab (i) := t; + t := t + nn; + end loop; + end receive_mtf_values; + + procedure detransform is + a : Unsigned_32; + p, q, r, i255 : Natural; + begin + a := 0; + p := tt'First; + q := p + tt_count; + while p /= q loop + i255 := Natural (tt.all (p) and 16#ff#); + r := cftab (i255); + cftab (i255) := cftab (i255) + 1; + tt.all (r) := tt.all (r) or a; + a := a + 256; + p := p + 1; + end loop; + end detransform; + + -- Cyclic redundancy check to verify uncompressed block data integrity + + package CRC is + + procedure Init (CRC_Value : out Unsigned_32); + function Final (CRC_Value : Unsigned_32) return Unsigned_32; + procedure Update (CRC_Value : in out Unsigned_32; val : Unsigned_8); + pragma Inline (Update); + + end CRC; + + package body CRC is + + CRC32_Table : + constant array (Unsigned_32'(0) .. 255) of Unsigned_32 := ( + 16#00000000#, 16#04c11db7#, 16#09823b6e#, 16#0d4326d9#, + 16#130476dc#, 16#17c56b6b#, 16#1a864db2#, 16#1e475005#, + 16#2608edb8#, 16#22c9f00f#, 16#2f8ad6d6#, 16#2b4bcb61#, + 16#350c9b64#, 16#31cd86d3#, 16#3c8ea00a#, 16#384fbdbd#, + 16#4c11db70#, 16#48d0c6c7#, 16#4593e01e#, 16#4152fda9#, + 16#5f15adac#, 16#5bd4b01b#, 16#569796c2#, 16#52568b75#, + 16#6a1936c8#, 16#6ed82b7f#, 16#639b0da6#, 16#675a1011#, + 16#791d4014#, 16#7ddc5da3#, 16#709f7b7a#, 16#745e66cd#, + 16#9823b6e0#, 16#9ce2ab57#, 16#91a18d8e#, 16#95609039#, + 16#8b27c03c#, 16#8fe6dd8b#, 16#82a5fb52#, 16#8664e6e5#, + 16#be2b5b58#, 16#baea46ef#, 16#b7a96036#, 16#b3687d81#, + 16#ad2f2d84#, 16#a9ee3033#, 16#a4ad16ea#, 16#a06c0b5d#, + 16#d4326d90#, 16#d0f37027#, 16#ddb056fe#, 16#d9714b49#, + 16#c7361b4c#, 16#c3f706fb#, 16#ceb42022#, 16#ca753d95#, + 16#f23a8028#, 16#f6fb9d9f#, 16#fbb8bb46#, 16#ff79a6f1#, + 16#e13ef6f4#, 16#e5ffeb43#, 16#e8bccd9a#, 16#ec7dd02d#, + 16#34867077#, 16#30476dc0#, 16#3d044b19#, 16#39c556ae#, + 16#278206ab#, 16#23431b1c#, 16#2e003dc5#, 16#2ac12072#, + 16#128e9dcf#, 16#164f8078#, 16#1b0ca6a1#, 16#1fcdbb16#, + 16#018aeb13#, 16#054bf6a4#, 16#0808d07d#, 16#0cc9cdca#, + 16#7897ab07#, 16#7c56b6b0#, 16#71159069#, 16#75d48dde#, + 16#6b93dddb#, 16#6f52c06c#, 16#6211e6b5#, 16#66d0fb02#, + 16#5e9f46bf#, 16#5a5e5b08#, 16#571d7dd1#, 16#53dc6066#, + 16#4d9b3063#, 16#495a2dd4#, 16#44190b0d#, 16#40d816ba#, + 16#aca5c697#, 16#a864db20#, 16#a527fdf9#, 16#a1e6e04e#, + 16#bfa1b04b#, 16#bb60adfc#, 16#b6238b25#, 16#b2e29692#, + 16#8aad2b2f#, 16#8e6c3698#, 16#832f1041#, 16#87ee0df6#, + 16#99a95df3#, 16#9d684044#, 16#902b669d#, 16#94ea7b2a#, + 16#e0b41de7#, 16#e4750050#, 16#e9362689#, 16#edf73b3e#, + 16#f3b06b3b#, 16#f771768c#, 16#fa325055#, 16#fef34de2#, + 16#c6bcf05f#, 16#c27dede8#, 16#cf3ecb31#, 16#cbffd686#, + 16#d5b88683#, 16#d1799b34#, 16#dc3abded#, 16#d8fba05a#, + 16#690ce0ee#, 16#6dcdfd59#, 16#608edb80#, 16#644fc637#, + 16#7a089632#, 16#7ec98b85#, 16#738aad5c#, 16#774bb0eb#, + 16#4f040d56#, 16#4bc510e1#, 16#46863638#, 16#42472b8f#, + 16#5c007b8a#, 16#58c1663d#, 16#558240e4#, 16#51435d53#, + 16#251d3b9e#, 16#21dc2629#, 16#2c9f00f0#, 16#285e1d47#, + 16#36194d42#, 16#32d850f5#, 16#3f9b762c#, 16#3b5a6b9b#, + 16#0315d626#, 16#07d4cb91#, 16#0a97ed48#, 16#0e56f0ff#, + 16#1011a0fa#, 16#14d0bd4d#, 16#19939b94#, 16#1d528623#, + 16#f12f560e#, 16#f5ee4bb9#, 16#f8ad6d60#, 16#fc6c70d7#, + 16#e22b20d2#, 16#e6ea3d65#, 16#eba91bbc#, 16#ef68060b#, + 16#d727bbb6#, 16#d3e6a601#, 16#dea580d8#, 16#da649d6f#, + 16#c423cd6a#, 16#c0e2d0dd#, 16#cda1f604#, 16#c960ebb3#, + 16#bd3e8d7e#, 16#b9ff90c9#, 16#b4bcb610#, 16#b07daba7#, + 16#ae3afba2#, 16#aafbe615#, 16#a7b8c0cc#, 16#a379dd7b#, + 16#9b3660c6#, 16#9ff77d71#, 16#92b45ba8#, 16#9675461f#, + 16#8832161a#, 16#8cf30bad#, 16#81b02d74#, 16#857130c3#, + 16#5d8a9099#, 16#594b8d2e#, 16#5408abf7#, 16#50c9b640#, + 16#4e8ee645#, 16#4a4ffbf2#, 16#470cdd2b#, 16#43cdc09c#, + 16#7b827d21#, 16#7f436096#, 16#7200464f#, 16#76c15bf8#, + 16#68860bfd#, 16#6c47164a#, 16#61043093#, 16#65c52d24#, + 16#119b4be9#, 16#155a565e#, 16#18197087#, 16#1cd86d30#, + 16#029f3d35#, 16#065e2082#, 16#0b1d065b#, 16#0fdc1bec#, + 16#3793a651#, 16#3352bbe6#, 16#3e119d3f#, 16#3ad08088#, + 16#2497d08d#, 16#2056cd3a#, 16#2d15ebe3#, 16#29d4f654#, + 16#c5a92679#, 16#c1683bce#, 16#cc2b1d17#, 16#c8ea00a0#, + 16#d6ad50a5#, 16#d26c4d12#, 16#df2f6bcb#, 16#dbee767c#, + 16#e3a1cbc1#, 16#e760d676#, 16#ea23f0af#, 16#eee2ed18#, + 16#f0a5bd1d#, 16#f464a0aa#, 16#f9278673#, 16#fde69bc4#, + 16#89b8fd09#, 16#8d79e0be#, 16#803ac667#, 16#84fbdbd0#, + 16#9abc8bd5#, 16#9e7d9662#, 16#933eb0bb#, 16#97ffad0c#, + 16#afb010b1#, 16#ab710d06#, 16#a6322bdf#, 16#a2f33668#, + 16#bcb4666d#, 16#b8757bda#, 16#b5365d03#, 16#b1f740b4# + ); + + procedure Update (CRC_Value : in out Unsigned_32; val : Unsigned_8) is + begin + CRC_Value := + CRC32_Table (16#FF# and (Shift_Right (CRC_Value, 24) xor Unsigned_32 (val))) + xor + Shift_Left (CRC_Value, 8); + end Update; + + procedure Init (CRC_Value : out Unsigned_32) is + begin + CRC_Value := 16#FFFF_FFFF#; + end Init; + + function Final (CRC_Value : Unsigned_32) return Unsigned_32 is + begin + return not CRC_Value; + end Final; + + end CRC; + + compare_final_CRC : Boolean := False; + stored_blockcrc, mem_stored_blockcrc, computed_crc : Unsigned_32; + + -- Decode a new compressed block. + function decode_block return Boolean is + magic : String (1 .. 6); + begin + for i in 1 .. 6 loop + magic (i) := Character'Val (get_byte); + end loop; + if magic = ""1AY&SY"" then + if check_CRC then + if compare_final_CRC then + null; -- initialisation is delayed until the rle buffer is empty + else + CRC.Init (computed_crc); -- Initialize for next block. + end if; + end if; + stored_blockcrc := get_cardinal; + block_randomized := get_boolean; + block_origin := Natural (get_cardinal24); + -- Receive the mapping table. + receive_mapping_table; + global_alpha_size := inuse_count + 2; + -- Receive the selectors. + receive_selectors; + -- Undo the MTF values for the selectors. + undo_mtf_values; + -- Receive the coding tables. + receive_coding_tables; + -- Build the Huffman tables. + make_hufftab; + -- Receive the MTF values. + receive_mtf_values; + -- Undo the Burrows Wheeler transformation. + detransform; + decode_available := tt_count; + return True; + elsif magic = Character'Val (16#17#) & ""rE8P"" & Character'Val (16#90#) then + return False; + else + raise bad_block_magic; + end if; + end decode_block; + + next_rle_idx : Integer := -2; + buf : Buffer (1 .. output_buffer_size); + last : Natural; + + procedure Read is + shorten : Natural := 0; + + procedure rle_read is + rle_len : Natural; + data : Unsigned_8; + idx : Integer := buf'First; + count : Integer := buf'Length; + -- + procedure rle_write is + pragma Inline (rle_write); + begin + loop + buf (idx) := data; + idx := idx + 1; + count := count - 1; + rle_len := rle_len - 1; + if check_CRC then + CRC.Update (computed_crc, data); + if rle_len = 0 and then compare_final_CRC then + if CRC.Final (computed_crc) /= mem_stored_blockcrc then + raise block_crc_check_failed; + end if; + compare_final_CRC := False; + CRC.Init (computed_crc); -- Initialize for next block. + end if; + end if; + exit when rle_len = 0 or else count = 0; + end loop; + end rle_write; + -- + -- handle extreme cases of data of length 1, 2 + input_dried : exception; + -- + -- Make next_rle_idx index to the next decoded byte. + -- If next_rle_idx did index to the last + -- byte in the current block, decode the next block. + -- + procedure consume_rle is + pragma Inline (consume_rle); + begin + next_rle_idx := Integer (Shift_Right (tt.all (next_rle_idx), 8)); + decode_available := decode_available - 1; + if decode_available = 0 then + compare_final_CRC := True; + mem_stored_blockcrc := stored_blockcrc; + -- ^ There might be a new block when last block's + -- rle is finally emptied. + -- + -- ** New block + if decode_block then + next_rle_idx := Natural (Shift_Right (tt.all (block_origin), 8)); + else + next_rle_idx := -1; + end_reached := True; + end if; + -- ** + if end_reached then + raise input_dried; + end if; + end if; + end consume_rle; + -- + function rle_byte return Unsigned_8 is + pragma Inline (rle_byte); + begin + return Unsigned_8 (tt.all (next_rle_idx) and 16#FF#); + end rle_byte; + -- + function rle_possible return Boolean is + pragma Inline (rle_possible); + begin + return decode_available > 0 and then data = rle_byte; + end rle_possible; + -- + begin -- rle_read + rle_len := rle_run_left; + data := rle_run_data; + if block_randomized then + raise randomized_not_yet_implemented; + end if; + if rle_len /= 0 then + rle_write; + if count = 0 then + shorten := 0; + rle_run_data := data; + rle_run_left := rle_len; + return; + end if; + end if; + begin + -- The big loop + loop + if decode_available = 0 or else end_reached then + exit; + end if; + rle_len := 1; + data := rle_byte; + consume_rle; + if rle_possible then + rle_len := rle_len + 1; + consume_rle; + if rle_possible then + rle_len := rle_len + 1; + consume_rle; + if rle_possible then + consume_rle; + rle_len := rle_len + Natural (rle_byte) + 1; + consume_rle; + end if; + end if; + end if; + rle_write; + exit when count = 0; + end loop; + exception + when input_dried => rle_write;" +procedure Dispose is new,"Ada.Unchecked_Deallocation (String, p_String); + + procedure Dispose is new + Ada.Unchecked_Deallocation (Ada.Streams.Stream_Element_Array, + p_Stream_Element_Array); + + procedure Dispose is new + Ada.Unchecked_Deallocation (UnZip_Stream_Type, + Zipped_File_Type); + + -------------------------------------------------- + -- *The* internal 1 - file unzipping procedure. -- + -- Input must be _open_ and won't be _closed_ ! -- + -------------------------------------------------- + + procedure UnZipFile (zip_file : Zip_Streams.Zipstream_Class; + header_index : in out Ada.Streams.Stream_IO.Positive_Count; + mem_ptr : out p_Stream_Element_Array; + password : in out Ada.Strings.Unbounded.Unbounded_String; + hint_comp_size : File_size_type; -- Added 2007 for .ODS files + cat_uncomp_size : File_size_type) is + + work_index : Ada.Streams.Stream_IO.Positive_Count := header_index; + local_header : Zip.Headers.Local_File_Header; + data_descriptor_present : Boolean; + encrypted : Boolean; + method : PKZip_method; + use Ada.Streams.Stream_IO, Zip, Zip_Streams; + begin + begin + Zip_Streams.Set_Index (zip_file, Positive (header_index)); + declare + TempStream : constant Zipstream_Class := zip_file; + begin + Zip.Headers.Read_and_check (TempStream, local_header);" +"procedure Dispose is new Ada.Unchecked_Deallocation (Dir_node, p_Dir_node);","procedure Dispose is new Ada.Unchecked_Deallocation (String, p_String); + + package Binary_tree_rebalancing is + procedure Rebalance (root : in out p_Dir_node); + end Binary_tree_rebalancing; + + package body Binary_tree_rebalancing is + + ------------------------------------------------------------------- + -- Tree Rebalancing in Optimal Time and Space -- + -- QUENTIN F. STOUT and BETTE L. WARREN -- + -- Communications of the ACM September 1986 Volume 29 Number 9 -- + ------------------------------------------------------------------- + -- http://www.eecs.umich.edu/~qstout/pap/CACM86.pdf + -- + -- Translated by (New) P2Ada v. 15 - Nov - 2006 + + procedure Tree_to_vine (root : p_Dir_node; size : out Integer) is + -- transform the tree with pseudo - root + -- ""root^"" into a vine with pseudo - root + -- node ""root^"", and store the number of + -- nodes in ""size"" + + vine_tail, remainder, temp : p_Dir_node; + + begin + vine_tail := root; + remainder := vine_tail.all.right; + size := 0; + while remainder /= null loop + if remainder.all.left = null then + -- move vine - tail down one: + vine_tail := remainder; + remainder := remainder.all.right; + size := size + 1; + else + -- rotate: + temp := remainder.all.left; + remainder.all.left := temp.all.right; + temp.all.right := remainder; + remainder := temp; + vine_tail.all.right := temp; + end if; + end loop; + end Tree_to_vine; + + procedure Vine_to_tree (root : p_Dir_node; size_given : Integer) is + -- convert the vine with ""size"" nodes and pseudo - root + -- node ""root^"" into a balanced tree + leaf_count : Integer; + size : Integer := size_given; + + procedure Compression (Dir_Root : p_Dir_node; count : Integer) is + -- compress ""count"" spine nodes in the tree with pseudo - root ""root^"" + scanner, child : p_Dir_node; + begin + scanner := Dir_Root; + for i in 1 .. count loop + child := scanner.all.right; + scanner.all.right := child.all.right; + scanner := scanner.all.right; + child.all.right := scanner.all.left; + scanner.all.left := child; + end loop; + end Compression; + + -- Returns n - 2 ** Integer (Float'Floor (log (Float (n)) / log (2.0))) + -- without Float - Point calculation and rounding errors with too short floats + function Remove_leading_binary_1 (n : Integer) return Integer is + x : Integer := 2**16; -- supposed maximum + begin + if n < 1 then + return n; + end if; + while n mod x = n loop + x := x / 2; + end loop; + return n mod x; + end Remove_leading_binary_1; + + begin -- Vine_to_tree + leaf_count := Remove_leading_binary_1 (size + 1); + Compression (root, leaf_count); -- create deepest leaves + -- use Perfect_leaves instead for a perfectly balanced tree + size := size - leaf_count; + while size > 1 loop + Compression (root, size / 2); + size := size / 2; + end loop; + end Vine_to_tree; + + procedure Rebalance (root : in out p_Dir_node) is + -- Rebalance the binary search tree with root ""root.all"", + -- with the result also rooted at ""root.all"". + -- Uses the Tree_to_vine and Vine_to_tree procedures. + pseudo_root : p_Dir_node; + size : Integer; + begin + pseudo_root := new Dir_node (name_len => 0); + pseudo_root.all.right := root; + Tree_to_vine (pseudo_root, size); + Vine_to_tree (pseudo_root, size); + root := pseudo_root.all.right; + Dispose (pseudo_root); + end Rebalance; + + end Binary_tree_rebalancing; + + -- 19 - Jun - 2001 : Enhanced file name identification + -- a) when case insensitive - > all UPPER (current) + -- b) '\' and '/' identified - > all '/' (new) + + function Normalize (s : String; case_sensitive : Boolean) return String is + sn : String (s'Range); + begin + if case_sensitive then + sn := s; + else + sn := Ada.Characters.Handling.To_Upper (s); + end if; + for i in sn'Range loop + if sn (i) = '\' then + sn (i) := '/'; + end if; + end loop; + return sn; + end Normalize; + + ------------------------------------------------------------- + -- Load Zip_info from a stream containing the .zip archive -- + ------------------------------------------------------------- + + procedure Load (info : out Zip_info; + from : Zip_Streams.Zipstream_Class; + case_sensitive : Boolean := False) is + + procedure Insert (dico_name : String; -- UPPER if case - insensitive search + file_name : String; + file_index : Ada.Streams.Stream_IO.Positive_Count; + comp_size, + uncomp_size : File_size_type; + crc_32 : Unsigned_32; + date_time : Time; + method : PKZip_method; + unicode_file_name : Boolean; + node : in out p_Dir_node) is + + begin + if node = null then + node := new Dir_node' + ((name_len => file_name'Length, + left => null, + right => null, + dico_name => dico_name, + file_name => file_name, + file_index => file_index, + comp_size => comp_size, + uncomp_size => uncomp_size, + crc_32 => crc_32, + date_time => date_time, + method => method, + unicode_file_name => unicode_file_name + ) + ); + elsif dico_name > node.all.dico_name then + Insert (dico_name, file_name, file_index, comp_size, uncomp_size, crc_32, date_time, method, unicode_file_name, node.all.right); + elsif dico_name < node.all.dico_name then + Insert (dico_name, file_name, file_index, comp_size, uncomp_size, crc_32, date_time, method, unicode_file_name, node.all.left); + else + raise Duplicate_name; + end if; + end Insert; + + the_end : Zip.Headers.End_of_Central_Dir; + header : Zip.Headers.Central_File_Header; + p : p_Dir_node := null; + zip_info_already_loaded : exception; + main_comment : p_String; + use Ada.Streams, Ada.Streams.Stream_IO; + begin -- Load Zip_info + if info.loaded then + raise zip_info_already_loaded; + end if; -- 15 - Apr - 2002 + Zip.Headers.Load (from, the_end); + -- We take the opportunity to read the main comment, which is right + -- after the end - of - central - directory block. + main_comment := new String (1 .. Integer (the_end.main_comment_length)); + String'Read (from, main_comment.all); + -- Process central directory: + Zip_Streams.Set_Index ( + from, + Positive ( + 1 + + the_end.offset_shifting + the_end.central_dir_offset + ) + ); + + for i in 1 .. the_end.total_entries loop + Zip.Headers.Read_and_check (from, header); + declare + this_name : String (1 .. Natural (header.short_info.filename_length)); + begin + String'Read (from, this_name); + -- Skip extra field and entry comment. + Zip_Streams.Set_Index ( + from, Positive ( + Ada.Streams.Stream_IO.Count (Zip_Streams.Index (from)) + + Ada.Streams.Stream_IO.Count ( + header.short_info.extra_field_length + + header.comment_length + )) + ); + -- Now the whole i_th central directory entry is behind + Insert (dico_name => Normalize (this_name, case_sensitive), + file_name => Normalize (this_name, True), + file_index => Ada.Streams.Stream_IO.Count + (1 + header.local_header_offset + the_end.offset_shifting), + comp_size => header.short_info.dd.compressed_size, + uncomp_size => header.short_info.dd.uncompressed_size, + crc_32 => header.short_info.dd.crc_32, + date_time => header.short_info.file_timedate, + method => Method_from_code (header.short_info.zip_type), + unicode_file_name => + (header.short_info.bit_flag and + Zip.Headers.Language_Encoding_Flag_Bit) /= 0, + node => p); + -- Since the files are usually well ordered, the tree as inserted + -- is very unbalanced; we need to rebalance it from time to time + -- during loading, otherwise the insertion slows down dramatically + -- for zip files with plenty of files - converges to + -- O (total_entries ** 2) .. . + if i mod 256 = 0 then + Binary_tree_rebalancing.Rebalance (p); + end if;" +procedure Dispose is new,"Ada.Unchecked_Deallocation (HufT_table, p_HufT_table); + procedure Dispose is new + Ada.Unchecked_Deallocation (Table_list, p_Table_list); + + current : p_Table_list; + tcount : Natural; -- just a stat. Idea : replace table_list with an array + + begin + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put (""[HufT_Free .. . ""); + tcount := 0; + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + while tl /= null loop + Dispose (tl.all.table); -- destroy the Huffman table + current := tl; + tl := tl.all.next; + Dispose (current); -- destroy the current node + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + tcount := tcount + 1; + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end loop; + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put_Line (Integer'Image (tcount) & "" tables]""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + end HufT_free; + + -- Build huffman table from code lengths given by array b + + procedure HufT_build (b : Length_array; + s : Integer; + d, e : Length_array; + tl : out p_Table_list; + m : in out Integer; + huft_incomplete : out Boolean) + is + use Interfaces; + + b_max : constant := 16; + b_maxp1 : constant := b_max + 1; + + -- bit length count table + count : array (0 .. b_maxp1) of Integer := (others => 0); + + f : Integer; -- i repeats in table every f entries + g : Integer; -- max. code length + i, -- counter, current code + j : Integer; -- counter + kcc : Integer; -- number of bits in current code + + c_idx, v_idx : Natural; -- array indices + + current_table_ptr : p_HufT_table := null; + current_node_ptr : p_Table_list := null; -- curr. node for the curr. table + new_node_ptr : p_Table_list; -- new node for the new table + + new_entry : HufT; -- table entry for structure assignment + + u : array (0 .. b_max) of p_HufT_table; -- table stack + + n_max : constant := 288; + -- values in order of bit length + v : array (0 .. n_max) of Integer := (others => 0); + el_v, el_v_m_s : Integer; + + w : Natural := 0; -- bits before this table + + offset, code_stack : array (0 .. b_maxp1) of Integer; + + table_level : Integer := -1; + bits : array (Integer'(-1) .. b_maxp1) of Integer; + -- ^bits (table_level) = # bits in table of level table_level + + y : Integer; -- number of dummy codes added + z : Natural := 0; -- number of entries in current table + el : Integer; -- length of eob code=code 256 + + no_copy_length_array : constant Boolean := d'Length = 0 or else e'Length = 0; + + begin + if full_trace then + pragma Warnings (Off, ""this code can never be executed and has been deleted""); + Ada.Text_IO.Put (""[HufT_Build .. .""); + pragma Warnings (On, ""this code can never be executed and has been deleted""); + end if; + tl := null; + + if b'Length > 256 then -- set length of EOB code, if any + el := b (256); + else + el := b_max; + end if; + + -- Generate counts for each bit length + + for k in b'Range loop + if b (k) > b_max then + -- m := 0; -- GNAT 2005 doesn't like it (warning). + raise huft_error; + end if; + count (b (k)) := count (b (k)) + 1; + end loop; + + if count (0) = b'Length then + m := 0; + huft_incomplete := False; -- spotted by Tucker Taft, 19 - Aug - 2004 + return; -- complete + end if; + + -- Find minimum and maximum length, bound m by those + + j := 1; + while j <= b_max and then count (j) = 0 loop + j := j + 1; + end loop; + kcc := j; + if m < j then + m := j; + end if; + i := b_max; + while i > 0 and then count (i) = 0 loop + i := i - 1; + end loop; + g := i; + if m > i then + m := i; + end if; + + -- Adjust last length count to fill out codes, if needed + + y := Integer (Shift_Left (Unsigned_32'(1), j)); -- y := 2 ** j; + while j < i loop + y := y - count (j); + if y < 0 then + raise huft_error; + end if; + y := y * 2; + j := j + 1; + end loop; + + y := y - count (i); + if y < 0 then + raise huft_error; + end if; + count (i) := count (i) + y; + + -- Generate starting offsets into the value table for each length + + offset (1) := 0; + j := 0; + for idx in 2 .. i loop + j := j + count (idx - 1); + offset (idx) := j; + end loop; + + -- Make table of values in order of bit length + + for idx in b'Range loop + j := b (idx); + if j /= 0 then + v (offset (j)) := idx - b'First; + offset (j) := offset (j) + 1; + end if; + end loop; + + -- Generate huffman codes and for each, make the table entries + + code_stack (0) := 0; + i := 0; + v_idx := v'First; + bits (-1) := 0; + + -- go through the bit lengths (kcc already is bits in shortest code) + for k in kcc .. g loop + + for am1 in reverse 0 .. count (k) - 1 loop -- a counts codes of length k + + -- here i is the huffman code of length k bits for value v (v_idx) + while k > w + bits (table_level) loop + + w := w + bits (table_level); -- Length of tables to this position + table_level := table_level + 1; + z := g - w; -- Compute min size table <= m bits + if z > m then + z := m; + end if; + j := k - w; + f := Integer (Shift_Left (Unsigned_32'(1), j)); -- f := 2 ** j; + if f > am1 + 2 then -- Try a k - w bit table + f := f - (am1 + 2); + c_idx := k; + loop -- Try smaller tables up to z bits + j := j + 1; + exit when j >= z; + f := f * 2; + c_idx := c_idx + 1; + exit when f - count (c_idx) <= 0; + f := f - count (c_idx); + end loop; + end if; + + if w + j > el and then w < el then + j := el - w; -- Make EOB code end at table + end if; + if w = 0 then + j := m; -- Fix : main table always m bits! + end if; + z := Integer (Shift_Left (Unsigned_32'(1), j)); -- z := 2 ** j; + bits (table_level) := j; + + -- Allocate and link new table + + begin + current_table_ptr := new HufT_table (0 .. z); + new_node_ptr := new Table_list'(current_table_ptr, null); + exception + when Storage_Error => + raise huft_out_of_memory;" +procedure Translation_inst is new Limited_Translation (No_Limitation);,"procedure Translation (actor : in out GLOBE_3D.Camera; + gc : Game_Control.Command_set; + gx, gy : GLOBE_3D.Real; + unitary_change : GLOBE_3D.Real; + deceleration : GLOBE_3D.Real; + time_step : GLOBE_3D.Real) renames Translation_inst; + + procedure Rotation (actor : in out GLOBE_3D.Camera; + gc : Game_Control.Command_set; + gx, gy : GLOBE_3D.Real; + unitary_change : GLOBE_3D.Real; + deceleration : GLOBE_3D.Real; + time_step : GLOBE_3D.Real) is + + incremental_rotation : Vector_3D := (0.0, 0.0, 0.0); + + begin + Abstract_rotation (gc, gx, gy, + unitary_change, deceleration, incremental_rotation, time_step, + actor.rotation_Speed); + actor.rotation := actor.rotation + incremental_rotation; + if actor.compose_rotations then + actor.World_Rotation := + XYZ_rotation (incremental_rotation) * actor.World_Rotation; + Re_Orthonormalize (actor.World_Rotation); + else + declare + r : Vector_3D renames actor.rotation; + -- We need to turn around the axes in this order : Y, X, Z + begin + actor.World_Rotation := + XYZ_rotation (0.0, 0.0, r (2)) * -- 3) turn around the nose + XYZ_rotation (r (0), 0.0, 0.0) * -- 2) lift or lower the head + XYZ_rotation (0.0, r (1), 0.0); -- 1) pivotate around the feet" +procedure Texture_is (Self : in sprite.p_Sprite; Now : in GL.textures.Object;,"texture_Transform_s : in GL.textures.texture_Transform; + texture_Transform_t : in GL.textures.texture_Transform) + is + use GL.Textures, GL.Skins, GL.Geometry.vbo; + + the_skinned_Geometry : GL.skinned_Geometry.skinned_Geometry_t renames self.skinned_geometrys (1); + + the_Skin : p_Skin_unlit_textured_vbo := new Skin_unlit_textured_vbo' (texture => Now); + the_Vertices : GL.geometry.GL_vertex_Array renames vbo_Geometry (the_skinned_Geometry.Geometry.all).Vertices.get; + texture_Coords : GL.textures.p_Coordinate_2D_array := to_texture_Coordinates_xz (the_Vertices, texture_Transform_s, + texture_Transform_t); + begin + the_skinned_Geometry.Skin := the_Skin.all'Access; + the_skinned_Geometry.Veneer := the_Skin.all.new_Veneer (for_geometry => the_skinned_Geometry.Geometry.all); + + declare + use GL.Buffer.texture_coords; + the_Veneer : GL.skins.Veneer_unlit_textured_vbo'Class renames GL.skins.Veneer_unlit_textured_vbo'Class (the_skinned_Geometry.Veneer.all); + begin + the_Veneer.texture_Coordinates := to_Buffer (texture_Coords, usage => GL.STATIC_DRAW);" +procedure initialise,"is + begin + the_vertex_Buffer := GL.Buffer.vertex.to_Buffer (object_points'Access, usage => GL.STATIC_DRAW); + + declare + piece_Id : Piece; + begin + for i in reverse 1 .. nb_faces loop + case i is + when 178 .. 237 => piece_Id := silver_Metal; + when 260 .. 315 => piece_Id := black_Cockpit; + when 740 .. 779 => piece_Id := Black; + when 860 .. 865 | + 936 .. 941 => piece_Id := black_front_Air; + when 316 .. 391 => piece_Id := Copper; + when 780 .. 803 => piece_Id := fire_Engine; + when 392 => piece_Id := nose_Cone; + when others => piece_Id := Remains; + end case; + + indices_Count (piece_Id) := indices_Count (piece_Id) + 1; + the_Indices (piece_Id) (positive_uInt (indices_Count (piece_Id))) := vertex_Id (object_faces (i, 1)); + + indices_Count (piece_Id) := indices_Count (piece_Id) + 1; + the_Indices (piece_Id) (positive_uInt (indices_Count (piece_Id))) := vertex_Id (object_faces (i, 2)); + + indices_Count (piece_Id) := indices_Count (piece_Id) + 1; + the_Indices (piece_Id) (positive_uInt (indices_Count (piece_Id))) := vertex_Id (object_faces (i, 3)); + end loop;" +"procedure deallocate is new ada.unchecked_Deallocation (Primitive'Class, p_Primitive);","begin + destroy (Self.all); + deallocate (Self);" +procedure Get_pixel is,"begin + case iBits is + when 32 => -- BGRA + Get_Byte (stream_buf, pix (pix'First + 2)); + Get_Byte (stream_buf, pix (pix'First + 1)); + Get_Byte (stream_buf, pix (pix'First)); + Get_Byte (stream_buf, pix (pix'First + 3)); + when 24 => -- BGR + Get_Byte (stream_buf, pix (pix'First + 2)); + Get_Byte (stream_buf, pix (pix'First + 1)); + Get_Byte (stream_buf, pix (pix'First)); + when 8 => -- Grey + Get_Byte (stream_buf, pix (pix'First)); + when others => + null; + end case; + end Get_pixel; + + tmp : GL.Ubyte; + + begin -- RLE_Pixel + if RLE_pixels_remaining = 0 then -- load RLE code + Get_Byte (stream_buf, tmp); + Get_pixel; + RLE_pixels_remaining := GL.Ubyte'Pos (tmp and 16#7F#); + is_run_packet := (tmp and 16#80#) /= 0; + if is_run_packet then + case iBits is + when 32 => + pix_mem (1 .. 4) := pix; + when 24 => + pix_mem (1 .. 3) := pix; + when 8 => + pix_mem (1 .. 1) := pix; + when others => + null; + end case; + end if; + else + if is_run_packet then + case iBits is + when 32 => + pix := pix_mem (1 .. 4); + when 24 => + pix := pix_mem (1 .. 3); + when 8 => + pix := pix_mem (1 .. 1); + when others => + null; + end case; + else + Get_pixel; + end if; + RLE_pixels_remaining := RLE_pixels_remaining - 1; + end if; + end RLE_Pixel; + + -- ============= + -- getRGBA + + -- Reads in RGBA data for a 32bit image. + -- ============= + + procedure getRGBA (buffer : out Byte_Array) is + i : Integer := buffer'First; + begin + if RLE then + while i <= buffer'Last - 3 loop + RLE_Pixel (32, buffer (i .. i + 3)); + i := i + 4; + end loop; + else + while i <= buffer'Last - 3 loop + -- TGA is stored in BGRA, make it RGBA + Get_Byte (stream_buf, buffer (i + 2)); + Get_Byte (stream_buf, buffer (i + 1)); + Get_Byte (stream_buf, buffer (i)); + Get_Byte (stream_buf, buffer (i + 3)); + i := i + 4; + end loop; + end if; + the_Image.tex_Format := GL.RGBA; + the_Image.tex_pixel_Format := GL.RGBA; + end getRGBA; + + -- ============= + -- getRGB + + -- Reads in RGB data for a 24bit image. + -- ============= + + procedure getRGB (buffer : out Byte_Array) is + i : Integer := buffer'First; + begin + if RLE then + while i <= buffer'Last - 2 loop + RLE_Pixel (24, buffer (i .. i + 2)); + i := i + 3; + end loop; + else + while i <= buffer'Last - 2 loop + -- TGA is stored in BGR, make it RGB + Get_Byte (stream_buf, buffer (i + 2)); + Get_Byte (stream_buf, buffer (i + 1)); + Get_Byte (stream_buf, buffer (i)); + i := i + 3; + end loop; + end if; + the_Image.tex_Format := GL.RGB; + the_Image.tex_pixel_Format := GL.RGB; + end getRGB; + + -- ============= + -- getGray + + -- Gets the grayscale image data. Used as an alpha channel. + -- ============= + + procedure getGray (buffer : out Byte_Array) is + begin + if RLE then + for b in buffer'Range loop + RLE_Pixel (8, buffer (b .. b)); + end loop; + else + for b in buffer'Range loop + Get_Byte (stream_buf, buffer (b)); + end loop; + end if; + the_Image.tex_Format := GL.LUMINANCE; -- ALPHA + the_Image.tex_pixel_Format := GL.LUMINANCE; + end getGray; + + -- ============= + -- getData + + -- Gets the image data for the specified bit depth. + -- ============= + + procedure getData (iBits : Integer; buffer : out Byte_Array) is + begin + Attach_Stream (stream_buf, S); + case iBits is + when 32 => + getRGBA (buffer); + the_Image.blending_hint := True; + when 24 => + getRGB (buffer); + the_Image.blending_hint := False; + when 8 => + getGray (buffer); + the_Image.blending_hint := True; + when others => null; + end case; + end getData; + + TGA_type : Byte_Array (0 .. 3); + info : Byte_Array (0 .. 5); + dummy : Byte_Array (1 .. 8); + + Image_Bits : Integer; + Image_Type : Integer; + + begin -- to_TGA_Image + Byte_Array'Read (S, TGA_type); -- read in colormap info and image type + Byte_Array'Read (S, dummy); -- seek past the header and useless info + Byte_Array'Read (S, info); + + if TGA_type (1) /= GL.Ubyte'Val (0) then + Raise_Exception ( + TGA_Unsupported_Image_Type'Identity, + ""TGA : palette not supported, please use BMP"" + ); + end if; + + -- Image type: + -- 1=8 - bit palette style + -- 2=Direct [A]RGB image + -- 3=grayscale + -- 9=RLE version of Type 1 + -- 10=RLE version of Type 2 + -- 11=RLE version of Type 3 + + Image_Type := GL.Ubyte'Pos (TGA_type (2)); + RLE := Image_Type >= 9; + if RLE then + Image_Type := Image_Type - 8; + RLE_pixels_remaining := 0; + end if; + if Image_Type /= 2 and then Image_Type /= 3 then + Raise_Exception ( + TGA_Unsupported_Image_Type'Identity, + ""TGA type ="" & Integer'Image (Image_Type) + ); + end if; + + the_Image.Width := GL.Ubyte'Pos (info (0)) + GL.Ubyte'Pos (info (1)) * 256; + the_Image.Height := GL.Ubyte'Pos (info (2)) + GL.Ubyte'Pos (info (3)) * 256; + Image_Bits := GL.Ubyte'Pos (info (4)); + + the_Image.size := the_Image.Width * the_Image.Height; + + -- 30 - Apr - 2006 : dimensions not power of two allowed, but discouraged in the docs. + -- + -- -- make sure dimension is a power of 2 + -- if not (checkSize (imageWidth) and checkSize (imageHeight)) then + -- raise TGA_BAD_DIMENSION; + -- end if; + + -- make sure we are loading a supported TGA_type + if Image_Bits /= 32 and then Image_Bits /= 24 and then Image_Bits /= 8 then + raise TGA_Unsupported_Bits_per_pixel; + end if; + + -- Allocation + the_Image.Data := new Byte_Array (0 .. (Image_Bits / 8) * the_Image.size - 1); + getData (Image_Bits, the_Image.Data.all); + + return the_Image; + end To_TGA_Image; + + function To_TGA_Image (Filename : String) return Image is + + f : File_Type; + the_Image : Image; + + begin + begin + Open (f, In_File, Filename); + exception + when Name_Error => Raise_Exception (File_Not_Found'Identity, "" file name:"" & Filename);" +procedure i_Load_TGA is new Load_XXX (Stream_Loader => Load_TGA);,"procedure Load_TGA (Name : String; Id : Integer; blending_hint : out Boolean) renames i_Load_TGA; + + -- BMP + + procedure Load_BMP (S : Ada.Streams.Stream_IO.Stream_Access; -- Input data stream + Id : Integer; -- Id is the texture identifier to bind to + blending_hint : out Boolean) is -- has the image blending / transparency /alpha ? + + imageData : Byte_Array_Ptr := null; + stream_buf : Input_buffer; + + subtype Y_Loc is Natural range 0 .. 4095; + subtype X_Loc is Natural range 0 .. 4095; + + -- 256 - col types + + subtype Color_Type is GL.Ubyte; + + type RGB_Color_Bytes is + record + Red : Color_Type; + Green : Color_Type; + Blue : Color_Type; + end record; + + type Color_Palette is array (Color_Type) of RGB_Color_Bytes; + + Palette : Color_Palette; + + ---------------------------------------------------- + -- BMP format I/O -- + -- -- + -- Rev 1.5 10 - May - 2006 GdM : added 4 - bit support -- + -- Rev 1.4 11/02/99 RBS -- + -- -- + ---------------------------------------------------- + -- Coded by G. de Montmollin + + -- Code additions, changes, and corrections by Bob Sutton + -- + -- Remarks expanded and altered + -- Provided for scanline padding in data stream + -- Corrected stream reading for images exceeding screen size. + -- Provided selectable trim modes for oversize images + -- Procedures originally Read_BMP_dimensions now Read_BMP_Header + -- Some exceptions added + -- + -- Rev 1.2 RBS. Added variable XY screen location for BMP + -- Rev 1.3 RBS. Added image inversion & reversal capability + -- Rev 1.4 RBS. Activated LOCATE centering / clipping options + -- + -- This version presumes that the infile is a new style, 256 color bitmap. + -- The Bitmap Information Header structure (40 bytes) is presumed + -- instead of the pre - Windows 3.0 Bitmap Core Header Structure (12 Bytes) + -- Pos 15 (0EH), if 28H, is valid BIH structure. If 0CH, is BCH structure. + + procedure Read_BMP_Header (S : Stream_Access; + width : out X_Loc; + height : out Y_Loc; + image_bits : out Integer; + offset : out U32) is + + fsz : U32; + ih : U32; + w, dummy16 : U16; + n : U32; + Str2 : String (1 .. 2); + Str4 : String (1 .. 4); + Str20 : String (1 .. 20); + + -- Get numbers with correct trucmuche endian, to ensure + -- correct header loading on some non - Intel machines + + generic + type Number is mod <>; -- range <> in Ada83 version (fake Interfaces) + procedure Read_Intel_x86_number (n : out Number); + + procedure Read_Intel_x86_number (n : out Number) is + b : GL.Ubyte; + m : Number := 1; + begin + n := 0; + for i in 1 .. Number'Size / 8 loop + GL.Ubyte'Read (S, b); + n := n + m * Number (b); + m := m * 256; + end loop; + end Read_Intel_x86_number; + + procedure Read_Intel is new Read_Intel_x86_number (U16); + procedure Read_Intel is new Read_Intel_x86_number (U32); + + begin + -- First 14 bytes is file header structure. + -- Pos= 1, read 2 bytes, file signature word + String'Read (S, Str2); + if Str2 /= ""BM"" then + raise Not_BMP_format; + end if; + -- Pos= 3, read the file size + Read_Intel (fsz); + -- Pos= 7, read four bytes, unknown + String'Read (S, Str4); + -- Pos= 11, read four bytes offset, file top to bitmap data. + -- For 256 colors, this is usually 36 04 00 00 + Read_Intel (offset); + -- Pos= 15. The beginning of Bitmap information header. + -- Data expected : 28H, denoting 40 byte header + Read_Intel (ih); + -- Pos= 19. Bitmap width, in pixels. Four bytes + Read_Intel (n); + width := X_Loc (n); + -- Pos= 23. Bitmap height, in pixels. Four bytes + Read_Intel (n); + height := Y_Loc (n); + -- Pos= 27, skip two bytes. Data is number of Bitmap planes. + Read_Intel (dummy16); -- perform the skip + -- Pos= 29, Number of bits per pixel + -- Value 8, denoting 256 color, is expected + Read_Intel (w); + if w /= 8 and then w /= 4 and then w /= 1 then + raise BMP_Unsupported_Bits_per_Pixel; + end if; + image_bits := Integer (w); + -- Pos= 31, read four bytees + Read_Intel (n); -- Type of compression used + if n /= 0 then + raise Unsupported_compression; + end if; + + -- Pos= 35 (23H), skip twenty bytes + String'Read (S, Str20); -- perform the skip + + -- Pos= 55 (36H), - start of palette + end Read_BMP_Header; + + procedure Load_BMP_Palette (S : Stream_Access; + Image_Bits : Integer; + BMP_Palette : out Color_Palette) is + + dummy : GL.Ubyte; + mc : constant Color_Type := (2**Image_Bits) - 1; + + begin + for DAC in 0 .. mc loop + GL.Ubyte'Read (S, BMP_Palette (DAC).Blue); + GL.Ubyte'Read (S, BMP_Palette (DAC).Green); + GL.Ubyte'Read (S, BMP_Palette (DAC).Red); + GL.Ubyte'Read (S, dummy); + end loop; + end Load_BMP_Palette; + + -- Load image only from stream (after having read header and palette!) + + procedure Load_BMP_Image (S : Stream_Access; + width : X_Loc; + height : Y_Loc; + Buffer : in out Byte_Array; + BMP_bits : Integer; + BMP_Palette : Color_Palette) is + + idx : Natural; + b01, b : GL.Ubyte := 0; + pair : Boolean := True; + bit : Natural range 0 .. 7 := 0; + -- + x3 : Natural; -- idx + x*3 (each pixel takes 3 bytes) + x3_max : Natural; + -- + procedure Fill_palettized is + pragma Inline (Fill_palettized); + begin + Buffer (x3) := Ubyte (BMP_Palette (b).Red); + Buffer (x3 + 1) := Ubyte (BMP_Palette (b).Green); + Buffer (x3 + 2) := Ubyte (BMP_Palette (b).Blue); + end Fill_palettized; + -- + begin + Attach_Stream (stream_buf, S); + for y in 0 .. height - 1 loop + idx := y * width * 3; -- GL destination picture is 24 bit + x3 := idx; + x3_max := idx + (width - 1) * 3; + case BMP_bits is + when 1 => -- B/W + while x3 <= x3_max loop + if bit = 0 then + Get_Byte (stream_buf, b01); + end if; + b := (b01 and 16#80#) / 16#80#; + Fill_palettized; + b01 := b01 * 2; -- cannot overflow. + if bit = 7 then + bit := 0; + else + bit := bit + 1; + end if; + x3 := x3 + 3; + end loop; + when 4 => -- 16 colour image + while x3 <= x3_max loop + if pair then + Get_Byte (stream_buf, b01); + b := (b01 and 16#F0#) / 16#10#; + else + b := (b01 and 16#0F#); + end if; + pair := not pair; + Fill_palettized; + x3 := x3 + 3; + end loop; + when 8 => -- 256 colour image + while x3 <= x3_max loop + Get_Byte (stream_buf, b); + Fill_palettized; + x3 := x3 + 3; + end loop; + when others => + null; + end case; + end loop; + end Load_BMP_Image; + + Width : X_Loc; + Height : Y_Loc; + offset : U32; + BMP_bits, imagebits : Integer; + BMP_Size : Integer; + BMP_tex_format : GL.TexFormatEnm; + BMP_tex_pixel_format : GL.TexPixelFormatEnm; + + begin + Read_BMP_Header (S, Width, Height, BMP_bits, offset); + imagebits := 24; + blending_hint := False; -- no blending with BMP's + BMP_tex_format := GL.RGB; + BMP_tex_pixel_format := GL.RGB; + Load_BMP_Palette (S, BMP_bits, Palette); + + BMP_Size := Width * Height; + + -- Allocation + imageData := new Byte_Array (0 .. (imagebits / 8) * BMP_Size - 1); + + Load_BMP_Image + (S, Width, Height, imageData.all, + BMP_bits, Palette); + + Insert_into_GL (id => Id, + Insert_Size => BMP_Size, + width => Width, + height => Height, + texFormat => BMP_tex_format, + texPixelFormat => BMP_tex_pixel_format, + image_p => imageData + ); + + -- release our data, its been uploaded to the GL system + Free (imageData); + + end Load_BMP; + + procedure i_Load_BMP is new Load_XXX (Stream_Loader => Load_BMP); + + procedure Load_BMP (Name : String; Id : Integer; blending_hint : out Boolean) renames i_Load_BMP; + + procedure Load (name : String; -- file name + format : Supported_format; -- expected file format + ID : Integer; -- ID is the texture identifier to bind to + blending_hint : out Boolean) is -- has blending / transparency /alpha ? + + begin + case format is + when BMP => Load_BMP (name, ID, blending_hint); + when TGA => Load_TGA (name, ID, blending_hint); + end case; + end Load; + + procedure Load (s : Ada.Streams.Stream_IO.Stream_Access; -- input data stream (e.g. Unzip.Streams) + format : Supported_format; -- expected file format + ID : Integer; -- ID is the texture identifier to bind to + blending_hint : out Boolean) is -- has blending / transparency /alpha ? + + begin + case format is + when BMP => Load_BMP (s, ID, blending_hint); + when TGA => Load_TGA (s, ID, blending_hint); + end case; + end Load; + + ------------- + -- Outputs -- + ------------- + + generic + type Number is mod <>; + s : Stream_Access; + procedure Write_Intel_x86_number (n : Number); + + procedure Write_Intel_x86_number (n : Number) is + m : Number := n; + bytes : constant Integer := Number'Size / 8; + begin + for i in 1 .. bytes loop + U8'Write (s, U8 (m mod 256)); + m := m / 256; + end loop; + end Write_Intel_x86_number; + + procedure Write_raw_BGR_frame (s : Stream_Access; width, height : Natural) is + -- 4 - byte padding for .bmp/.avi formats is the same as GL's default + -- padding : see glPixelStore, GL_[UN]PACK_ALIGNMENT = 4 as initial value. + -- http://www.opengl.org/sdk/docs/man/xhtml/glPixelStore.xml + -- + padded_row_size : constant Positive := + 4 * Integer (C_Float'Ceiling (C_Float (width) * 3.0 / 4.0)); + -- (in bytes) + -- + type Temp_bitmap_type is array (Natural range <>) of aliased GL.Ubyte; + PicData : Temp_bitmap_type (0 .. (padded_row_size + 4) * (height + 4) - 1); + -- No dynamic allocation needed! + -- The ""+ 4"" are there to avoid parity address problems when GL writes + -- to the buffer. + type loc_pointer is new GL.pointer; + function Cvt is new Ada.Unchecked_Conversion (System.Address, loc_pointer); + -- This method is functionally identical as GNAT's Unrestricted_Access + -- but has no type safety (cf GNAT Docs) + pragma No_Strict_Aliasing (loc_pointer); -- recommended by GNAT 2005 + + pPicData : loc_pointer; + data_max : constant Integer := padded_row_size * height - 1; + begin + pPicData := Cvt (PicData (0)'Address); + GL.ReadPixels ( + 0, 0, + GL.Sizei (width), GL.Sizei (height), + GL.BGR, + GL.GL_UNSIGNED_BYTE, + GL.pointer (pPicData) + ); + if workaround_possible then + declare + use Ada.Streams; + SE_Buffer : Stream_Element_Array (0 .. Stream_Element_Offset (PicData'Last)); + for SE_Buffer'Address use PicData'Address; + pragma Import (Ada, SE_Buffer); + begin + Ada.Streams.Write (s.all, SE_Buffer (0 .. Stream_Element_Offset (data_max)));" +"function Cvt is new Ada.Unchecked_Conversion (System.Address, GL_IntPointer);","-- This method is functionally identical as GNAT's Unrestricted_Access + -- but has no type safety (cf GNAT Docs) + pragma No_Strict_Aliasing (GL_IntPointer); -- recommended by GNAT 2005+ + + begin + -- Größe des Viewports abfragen --> Spätere Bildgrößenangaben + GL.GetIntegerv (GL.VIEWPORT, GL.intPointer (Cvt (Screenshot_Viewport (0)'Address))); + + -- Initialisieren der Daten des Headers + FileHeader.bfType := 16#4D42#; -- 'BM' + FileHeader.bfOffBits := Bitmap_Info_Header'Size / 8 + Bitmap_File_Header'Size / 8; + + -- Schreiben der Bitmap - Informationen + FileInfo.biSize := Bitmap_Info_Header'Size / 8; + FileInfo.biWidth := I32 (Screenshot_Viewport (2)); + FileInfo.biHeight := I32 (Screenshot_Viewport (3)); + FileInfo.biPlanes := 1; + FileInfo.biBitCount := 24; + FileInfo.biCompression := 0; + FileInfo.biSizeImage := + U32 ( + -- 4 - byte padding for .bmp/.avi formats + 4 * Integer (C_Float'Ceiling (C_Float (FileInfo.biWidth) * 3.0 / 4.0)) * + Integer (FileInfo.biHeight) + ); + + -- Größenangabe auch in den Header übernehmen + FileHeader.bfSize := FileHeader.bfOffBits + FileInfo.biSizeImage; + + -- Und den ganzen Müll in die Datei schieben ; - ) + -- Moderne Leute nehmen dafür auch Streams . .. + Create (f, Out_File, Name); + declare + procedure Write_Intel is new Write_Intel_x86_number (U16, Stream (f)); + procedure Write_Intel is new Write_Intel_x86_number (U32, Stream (f)); + function Cvt is new Ada.Unchecked_Conversion (I32, U32); + + begin + -- ** Only for Intel endianess : ** -- + -- BITMAPFILEHEADER'Write (Stream (F), FileHeader); + -- BITMAPINFOHEADER'Write (Stream (F), FileInfo); + -- + -- ** Endian - safe : ** -- + Write_Intel (FileHeader.bfType); + Write_Intel (FileHeader.bfSize); + Write_Intel (FileHeader.bfReserved1); + Write_Intel (FileHeader.bfReserved2); + Write_Intel (FileHeader.bfOffBits); + -- + Write_Intel (FileInfo.biSize); + Write_Intel (Cvt (FileInfo.biWidth)); + Write_Intel (Cvt (FileInfo.biHeight)); + Write_Intel (FileInfo.biPlanes); + Write_Intel (FileInfo.biBitCount); + Write_Intel (FileInfo.biCompression); + Write_Intel (FileInfo.biSizeImage); + Write_Intel (Cvt (FileInfo.biXPelsPerMeter)); + Write_Intel (Cvt (FileInfo.biYPelsPerMeter)); + Write_Intel (FileInfo.biClrUsed); + Write_Intel (FileInfo.biClrImportant); + -- + Write_raw_BGR_frame (Stream (f), Integer (Screenshot_Viewport (2)), Integer (Screenshot_Viewport (3))); + Close (f); + exception + when others => + Close (f); + raise;" +procedure Normalise (the_Plane : in out Plane) is,"use GL_Double_EF; + inv_Magnitude : constant GL.Double := 1.0 / Sqrt (the_Plane (0) * the_Plane (0) + + the_Plane (1) * the_Plane (1) + + the_Plane (2) * the_Plane (2)); + begin + the_Plane := (0 => the_Plane (0) * inv_Magnitude, + 1 => the_Plane (1) * inv_Magnitude, + 2 => the_Plane (2) * inv_Magnitude, + 3 => the_Plane (3) * inv_Magnitude); + end Normalise; + + -- Bounds + -- + + function Max (L, R : Extent) return Extent is + (Min => GL.Double'Max (L.Min, R.Min), + Max => GL.Double'Max (L.Max, R.Max)); + + function Max (L, R : Axis_Aligned_Bounding_Box) return Axis_Aligned_Bounding_Box is + (X_Extent => Max (L.X_Extent, R.X_Extent), + Y_Extent => Max (L.Y_Extent, R.Y_Extent), + Z_Extent => Max (L.Z_Extent, R.Z_Extent)); + + function Max (L, R : Bounds_record) return Bounds_record is + (Sphere_Radius => GL.Double'Max (L.Sphere_Radius, R.Sphere_Radius), + Box => Max (L.Box, R.Box)); + + -- vertex_Id's + -- + + procedure Increment (Self : in out vertex_Id_array) is + + begin + for Each in Self'Range loop + Self (Each) := Self (Each) + 1; + end loop; + end Increment; + + procedure Decrement (Self : in out vertex_Id_array) is + + begin + for Each in Self'Range loop + Self (Each) := Self (Each) - 1; + end loop; + end Decrement; + + -- vertices + -- + + function Image (Self : GL_Vertex) return String is + ("" ("" & Double'Image (Self (0)) & Double'Image (Self (1)) & Double'Image (Self (2)) & "")""); + + function Bounds (Self : GL_Vertex_array) return GL.Geometry.Bounds_record is + + use GL_Double_EF; + the_Bounds : Bounds_record := null_Bounds; + max_Distance_2 : GL.Double := 0.0; -- current maximum distance squared. + + begin + for p in Self'Range loop + max_Distance_2 := GL.Double'Max (Self (p) (0) * Self (p) (0) + + Self (p) (1) * Self (p) (1) + + Self (p) (2) * Self (p) (2), + max_Distance_2); + + the_Bounds.Box := (X_Extent => (Min => GL.Double'Min (the_Bounds.Box.X_Extent.Min, Self (p) (0)), + Max => GL.Double'Max (the_Bounds.Box.X_Extent.Max, Self (p) (0))), + Y_Extent => (Min => GL.Double'Min (the_Bounds.Box.Y_Extent.Min, Self (p) (1)), + Max => GL.Double'Max (the_Bounds.Box.Y_Extent.Max, Self (p) (1))), + Z_Extent => (Min => GL.Double'Min (the_Bounds.Box.Z_Extent.Min, Self (p) (2)), + Max => GL.Double'Max (the_Bounds.Box.Z_Extent.Max, Self (p) (2)))); + end loop; + + the_Bounds.Sphere_Radius := Sqrt (max_Distance_2); + + return the_Bounds; + end Bounds; + + function Bounds (Given_Vertices : GL_Vertex_array; Given_Indices : vertex_Id_array) return GL.Geometry.Bounds_record is + + use GL_Double_EF; + the_Bounds : Bounds_record := null_Bounds; + max_Distance_2 : GL.Double := 0.0; -- current maximum distance squared. + + begin + for Each in Given_Indices'Range loop + declare + the_Point : GL_Vertex renames Given_Vertices (Given_Indices (Each)); + begin + max_Distance_2 := GL.Double'Max (the_Point (0) * the_Point (0) + + the_Point (1) * the_Point (1) + + the_Point (2) * the_Point (2), + max_Distance_2); + + the_Bounds.Box := (X_Extent => (Min => GL.Double'Min (the_Bounds.Box.X_Extent.Min, the_Point (0)), + Max => GL.Double'Max (the_Bounds.Box.X_Extent.Max, the_Point (0))), + Y_Extent => (Min => GL.Double'Min (the_Bounds.Box.Y_Extent.Min, the_Point (1)), + Max => GL.Double'Max (the_Bounds.Box.Y_Extent.Max, the_Point (1))), + Z_Extent => (Min => GL.Double'Min (the_Bounds.Box.Z_Extent.Min, the_Point (2)), + Max => GL.Double'Max (the_Bounds.Box.Z_Extent.Max, the_Point (2))));" +"procedure deallocate is new Ada.Unchecked_Deallocation (Geometry_t'Class, p_Geometry);","begin + destroy (Self.all); + deallocate (Self); + end Free; + + function Vertex_Normals (Self : Geometry_t'Class) return GL_Normals_Vertex_Id is + + begin + case primitive_Id (Self) is + when TRIANGLES => + declare + the_Vertices : GL_Vertex_array renames Vertices (Self); + the_Indices : vertex_Id_array renames Indices (Self); + the_Normals : GL_Normals_Vertex_Id (the_Vertices'Range); + + Triangle_Face_Count : constant Positive := the_Indices'Length / 3; + face_Normals : GL_Normals (1 .. Triangle_Face_Count); + + N : GL.Double_Vector_3D; + length_N : GL.Double; + + function vertex_Id_for (Face : Positive; point_Id : Positive) return vertex_Id is + (the_Indices (positive_uInt (3 * (Face - 1) + point_Id))); + + begin + -- Geometry (Normal of unrotated face) + -- + for each_Face in 1 .. Triangle_Face_Count loop + N := (the_Vertices (vertex_Id_for (each_Face, 2)) - the_Vertices (vertex_Id_for (each_Face, 1))) + * (the_Vertices (vertex_Id_for (each_Face, 3)) - the_Vertices (vertex_Id_for (each_Face, 1))); + length_N := Norm (N); + + case Almost_zero (length_N) is + when True => face_Normals (each_Face) := N; -- 0 vector ! + when False => face_Normals (each_Face) := (1.0 / length_N) * N; + end case; + end loop; + + -- Calculate normal at each vertex. + -- + declare + vertex_adjacent_faces_Count : array (the_Vertices'Range) of Natural := (others => 0); + the_Vertex : vertex_Id; + Vertex_Length : Double; + begin + + for p in the_Vertices'Range loop + the_Normals (p) := (0.0, 0.0, 0.0); + end loop; + + for f in 1 .. Triangle_Face_Count loop + for p in 1 .. 3 loop + the_Vertex := vertex_Id_for (f, p); + + vertex_adjacent_faces_Count (the_Vertex) := vertex_adjacent_faces_Count (the_Vertex) + 1; + the_Normals (the_Vertex) := the_Normals (the_Vertex) + face_Normals (f); + end loop; + end loop; + + for p in the_Vertices'Range loop + + Vertex_Length := Norm (the_Normals (p)); + + if not Almost_zero (Vertex_Length) then + the_Normals (p) := (1.0 / Vertex_Length) * the_Normals (p); + else + null; -- raise Constraint_Error; -- tbd : proper exception as usual. + end if; + end loop;" +function vanish_point_size_Min (Self : in Culler'Class) return Real,"is + begin + return self.vanish_point_size_Min;" +procedure vanish_point_size_Min_is (Self : in out Culler'Class; Now : in Real),"is + begin + self.vanish_point_size_Min := Now;" +procedure impostor_size_Min_is (Self : in out Culler'Class; Now : in Real),"is + begin + self.impostor_size_Min := Now;" +procedure frustum_culling_Enabled_is (Self : in out Culler'Class; Now : in Boolean),"is + begin + self.frustum_culling_Enabled := Now;" +function is_visible_for_plane (Which : in GL.frustums.plane_Id) return Boolean,"is + the_Site : Vector_3D renames the_Object.Centre; + plane_Distance : Real := Frustum (Which) (0) * the_Site (0) + + Frustum (Which) (1) * the_Site (1) + + Frustum (Which) (2) * the_Site (2) + + Frustum (Which) (3); + begin + return plane_Distance + the_Size > 0.0;" +"--procedure sort is new Ada.Containers.Generic_Array_Sort (Positive,","procedure sort is new Ada.Containers.Generic_Array_Sort (Positive, + impostor.p_Impostor, + impostor.p_Impostor_array); + begin + sort (the_Slot.Impostors (1 .. the_Slot.impostors_Count)); + + for Each in 1 .. num_Updates loop + the_slot.Impostors (Each).update (self.viewer.Camera'Access, self.texture_Pool'Unchecked_Access); + -- tbd : would 'flush' improve performance here ? + end loop;" +"procedure deallocate is new ada.unchecked_Deallocation (sprite_Set, sprite_Set_view);","Pad : sprite_Set_view := Self; + begin + destroy (Self.all); + deallocate (Pad);" +procedure Viewer_is (Self : in out Culler'Class; Now : p_Window),"is + begin + self.Viewer := Now.all'Access;" +procedure finalize_library is,"begin + E385 := E385 - 1; + E389 := E389 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""vehicle_interface__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""swarm_control__finalize_spec""); + begin + F2;" +procedure F3;,"pragma Import (Ada, F3, ""swarm_data__finalize_spec""); + begin + E376 := E376 - 1; + F3;" +procedure F4;,"pragma Import (Ada, F4, ""swarm_structures__finalize_spec""); + begin + F4;" +procedure F5;,"pragma Import (Ada, F5, ""vehicle_task_type__finalize_spec""); + begin + F5;" +procedure F6;,"pragma Import (Ada, F6, ""swarm_structures_base__finalize_spec""); + begin + E365 := E365 - 1; + F6;" +procedure F7;,"pragma Import (Ada, F7, ""graphics_structures__finalize_spec""); + begin + E305 := E305 - 1; + F7;" +procedure F8;,"pragma Import (Ada, F8, ""glut__windows__finalize_spec""); + begin + F8;" +procedure F9;,"pragma Import (Ada, F9, ""globe_3d__textures__finalize_body""); + begin + E256 := E256 - 1; + F9;" +procedure F10;,"pragma Import (Ada, F10, ""globe_3d__finalize_spec""); + begin + F10;" +procedure F11;,"pragma Import (Ada, F11, ""unzip__streams__finalize_spec""); + begin + F11;" +procedure F12;,"pragma Import (Ada, F12, ""zip_streams__finalize_spec""); + begin + F12;" +procedure F13;,"pragma Import (Ada, F13, ""glut__finalize_body""); + begin + E297 := E297 - 1; + F13;" +procedure F14;,"pragma Import (Ada, F14, ""gl__skins__finalize_spec""); + begin + F14;" +procedure F15;,"pragma Import (Ada, F15, ""gl__textures__finalize_spec""); + begin + F15;" +procedure F16;,"pragma Import (Ada, F16, ""gl__geometry__finalize_spec""); + begin + F16;" +procedure F17;,"pragma Import (Ada, F17, ""gl__buffer__finalize_spec""); + begin + F17;" +procedure F18;,"pragma Import (Ada, F18, ""barrier_type__finalize_spec""); + begin + F18;" +procedure F19;,"pragma Import (Ada, F19, ""system__tasking__protected_objects__entries__finalize_spec""); + begin + F19;" +procedure F20;,"pragma Import (Ada, F20, ""system__pool_global__finalize_spec""); + begin + F20;" +procedure F21;,"pragma Import (Ada, F21, ""ada__strings__unbounded__finalize_spec""); + begin + F21;" +procedure F22;,"pragma Import (Ada, F22, ""ada__text_io__finalize_spec""); + begin + F22;" +procedure F23;,"pragma Import (Ada, F23, ""system__storage_pools__subpools__finalize_spec""); + begin + F23;" +procedure F24;,"pragma Import (Ada, F24, ""system__finalization_masters__finalize_spec""); + begin + F24;" +procedure F25;,"pragma Import (Ada, F25, ""ada__streams__stream_io__finalize_spec""); + begin + F25;" +procedure F26;,"pragma Import (Ada, F26, ""system__file_io__finalize_body""); + begin + E135 := E135 - 1; + F26;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (C, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Exception_Tracebacks : Integer; + pragma Import (C, Exception_Tracebacks, ""__gl_exception_tracebacks""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Leap_Seconds_Support : Integer; + pragma Import (C, Leap_Seconds_Support, ""__gl_leap_seconds_support""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + System.Restrictions.Run_Time_Restrictions := + (Set => + (False, False, False, False, False, False, False, False, + False, False, False, False, False, False, False, False, + False, False, False, False, False, False, False, False, + False, False, False, False, False, False, False, False, + False, False, False, False, False, False, False, False, + False, False, False, False, False, False, False, False, + False, False, False, False, False, False, False, False, + False, False, False, False, False, False, False, False, + False, False, False, False, False, False, False, False, + False, False, False, False, False, True, False, False, + False, False, False, False, False, False, False, False, + False, False, False, False), + Value => (0, 0, 0, 0, 0, 0, 0, 0, 0, 0), + Violated => + (True, True, False, False, True, True, False, False, + True, False, False, True, True, True, True, False, + False, False, True, False, True, True, False, True, + True, False, True, True, True, True, False, True, + True, False, False, True, False, True, True, False, + True, True, True, True, False, True, True, True, + True, False, False, True, False, True, True, False, + True, False, False, True, True, True, True, True, + False, False, True, False, True, True, True, False, + True, True, False, True, True, True, True, False, + True, True, False, False, False, True, True, True, + True, True, True, False), + Count => (0, 0, 0, 1, 2, 1, 3, 2, 7, 0), + Unknown => (False, False, False, False, False, False, True, True, True, False)); + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Exception_Tracebacks := 1; + Detect_Blocking := 0; + Default_Stack_Size := -1; + Leap_Seconds_Support := 0; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E023 := E023 + 1; + System.Exceptions'Elab_Spec; + E025 := E025 + 1; + System.Soft_Links.Initialize'Elab_Body; + E019 := E019 + 1; + E011 := E011 + 1; + Ada.Containers'Elab_Spec; + E172 := E172 + 1; + Ada.Io_Exceptions'Elab_Spec; + E127 := E127 + 1; + Ada.Numerics'Elab_Spec; + E144 := E144 + 1; + Ada.Strings'Elab_Spec; + E166 := E166 + 1; + Interfaces.C'Elab_Spec; + E061 := E061 + 1; + Interfaces.C.Strings'Elab_Spec; + E159 := E159 + 1; + System.Os_Lib'Elab_Body; + E137 := E137 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E091 := E091 + 1; + Ada.Streams'Elab_Spec; + E126 := E126 + 1; + System.File_Control_Block'Elab_Spec; + E140 := E140 + 1; + System.Finalization_Root'Elab_Spec; + E129 := E129 + 1; + Ada.Finalization'Elab_Spec; + E124 := E124 + 1; + System.File_Io'Elab_Body; + E135 := E135 + 1; + Ada.Streams.Stream_Io'Elab_Spec; + E244 := E244 + 1; + System.Storage_Pools'Elab_Spec; + E191 := E191 + 1; + System.Finalization_Masters'Elab_Spec; + System.Finalization_Masters'Elab_Body; + E195 := E195 + 1; + System.Storage_Pools.Subpools'Elab_Spec; + E193 := E193 + 1; + Ada.Calendar'Elab_Spec; + Ada.Calendar'Elab_Body; + E279 := E279 + 1; + Ada.Calendar.Delays'Elab_Body; + E304 := E304 + 1; + Ada.Real_Time'Elab_Spec; + Ada.Real_Time'Elab_Body; + E054 := E054 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E131 := E131 + 1; + System.Assertions'Elab_Spec; + E150 := E150 + 1; + Ada.Strings.Maps'Elab_Spec; + E168 := E168 + 1; + Ada.Strings.Maps.Constants'Elab_Spec; + E171 := E171 + 1; + Ada.Strings.Unbounded'Elab_Spec; + E211 := E211 + 1; + System.Interrupt_Management.Operations'Elab_Body; + E393 := E393 + 1; + System.Pool_Global'Elab_Spec; + E187 := E187 + 1; + System.Random_Seed'Elab_Body; + E338 := E338 + 1; + System.Tasking.Initialization'Elab_Body; + E109 := E109 + 1; + System.Tasking.Protected_Objects'Elab_Body; + E119 := E119 + 1; + System.Tasking.Protected_Objects.Entries'Elab_Spec; + E121 := E121 + 1; + System.Tasking.Queuing'Elab_Body; + E117 := E117 + 1; + System.Tasking.Stages'Elab_Body; + E387 := E387 + 1; + System.Tasking.Async_Delays'Elab_Body; + E391 := E391 + 1; + Barrier_Type'Elab_Spec; + E380 := E380 + 1; + E269 := E269 + 1; + E103 := E103 + 1; + E367 := E367 + 1; + E156 := E156 + 1; + GL.BUFFER'ELAB_SPEC; + E201 := E201 + 1; + GL.IO'ELAB_SPEC; + GL.IO'ELAB_BODY; + E240 := E240 + 1; + E248 := E248 + 1; + GL.MATH'ELAB_BODY; + E219 := E219 + 1; + GL.GEOMETRY'ELAB_SPEC; + E209 := E209 + 1; + E291 := E291 + 1; + E180 := E180 + 1; + GL.ERRORS'ELAB_SPEC; + E178 := E178 + 1; + GL.TEXTURES'ELAB_SPEC; + GL.TEXTURES'ELAB_BODY; + E238 := E238 + 1; + GL.BUFFER.TEXTURE_COORDS'ELAB_SPEC; + GL.BUFFER.TEXTURE_COORDS'ELAB_BODY; + E205 := E205 + 1; + GL.SKINS'ELAB_SPEC; + GL.SKINS'ELAB_BODY; + E184 := E184 + 1; + E293 := E293 + 1; + GLUT'ELAB_BODY; + E297 := E297 + 1; + E295 := E295 + 1; + E142 := E142 + 1; + Graphics_Framerates'Elab_Body; + E302 := E302 + 1; + E309 := E309 + 1; + Quaternions'Elab_Body; + E311 := E311 + 1; + E360 := E360 + 1; + Vectors_2d'Elab_Spec; + E398 := E398 + 1; + Vectors_3d'Elab_Spec; + E313 := E313 + 1; + Rotations'Elab_Body; + E307 := E307 + 1; + Vectors_3d_Lf'Elab_Spec; + E395 := E395 + 1; + Vectors_4d'Elab_Spec; + E330 := E330 + 1; + Vectors_2d_I'Elab_Spec; + E399 := E399 + 1; + Vectors_2d_N'Elab_Spec; + E320 := E320 + 1; + Vectors_2d_P'Elab_Spec; + E400 := E400 + 1; + E397 := E397 + 1; + Zip_Streams'Elab_Spec; + Zip'Elab_Spec; + Zip_Streams'Elab_Body; + E277 := E277 + 1; + Zip.Headers'Elab_Spec; + E275 := E275 + 1; + Zip'Elab_Body; + E273 := E273 + 1; + E281 := E281 + 1; + Unzip'Elab_Spec; + Unzip.Decompress.Huffman'Elab_Spec; + E271 := E271 + 1; + Unzip'Elab_Body; + E265 := E265 + 1; + E267 := E267 + 1; + Unzip.Streams'Elab_Spec; + Unzip.Streams'Elab_Body; + E283 := E283 + 1; + GLOBE_3D'ELAB_SPEC; + GLOBE_3D.TEXTURES'ELAB_SPEC; + E252 := E252 + 1; + GLOBE_3D.MATH'ELAB_BODY; + E250 := E250 + 1; + GLOBE_3D.TEXTURES'ELAB_BODY; + E256 := E256 + 1; + GLOBE_3D'ELAB_BODY; + E161 := E161 + 1; + E254 := E254 + 1; + E356 := E356 + 1; + GLUT.DEVICES'ELAB_SPEC; + Game_Control'Elab_Spec; + E354 := E354 + 1; + Actors'Elab_Body; + E352 := E352 + 1; + GLUT.WINDOWS'ELAB_SPEC; + GLUT.WINDOWS'ELAB_BODY; + E350 := E350 + 1; + E348 := E348 + 1; + Graphics_Structures'Elab_Spec; + E305 := E305 + 1; + Graphics_Configuration'Elab_Spec; + E154 := E154 + 1; + E358 := E358 + 1; + E327 := E327 + 1; + E329 := E329 + 1; + Models'Elab_Spec; + Models'Elab_Body; + E325 := E325 + 1; + Graphics_Data'Elab_Spec; + E323 := E323 + 1; + E344 := E344 + 1; + Graphics_Opengl'Elab_Body; + E332 := E332 + 1; + Swarm_Structures_Base'Elab_Spec; + E365 := E365 + 1; + Swarm_Configurations'Elab_Spec; + E364 := E364 + 1; + Swarm_Configuration'Elab_Spec; + E362 := E362 + 1; + Vehicle_Task_Type'Elab_Spec; + Swarm_Structures'Elab_Spec; + E378 := E378 + 1; + Swarm_Data'Elab_Spec; + E376 := E376 + 1; + Swarm_Control'Elab_Spec; + E375 := E375 + 1; + Vehicle_Interface'Elab_Spec; + E389 := E389 + 1; + Vehicle_Task_Type'Elab_Body; + E385 := E385 + 1; + E402 := E402 + 1; + Callback_Procedures'Elab_Body; + E052 := E052 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_swarm""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + gnat_argc := argc; + gnat_argv := argv; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure Global_Registry_Handler,"(Registry : in out WP.Client.Registry'Class; + Id : Unsigned_32; + Name : String; + Version : Unsigned_32) is + begin + Interfaces.Append ((Name => +Name, Id => Id, Version => Version)); + + if Name = WP.Client.Compositor_Interface.Name then + Compositor.Bind (Registry, Id, Unsigned_32'Min (Version, 4)); + elsif Name = WP.Client.Shm_Interface.Name then + Shm.Bind (Registry, Id, Unsigned_32'Min (Version, 1)); + + if not Shm.Has_Proxy then + raise Wayland_Error with ""No shm""; + end if; + + Shm_Events.Subscribe (Shm); + elsif Name = WP.Client.Seat_Interface.Name then + declare + Seat : WP.Client.Seat renames Seats (Seat_Last_Index + 1).Seat; + begin + Seat.Bind (Registry, Id, Unsigned_32'Min (Version, 6)); + + if not Seat.Has_Proxy then + raise Wayland_Error with ""No seat""; + end if; + + Seat_Events.Subscribe (Seat); + + Seat_Last_Index := Seat_Last_Index + 1;" +procedure Wayland_Ada_Scanner is,"use type Ada.Containers.Count_Type; + use type Wayland_XML.Event_Child; + use type Wayland_XML.Request_Child; + + use all type Wayland_XML.Arg_Tag; + use all type Wayland_XML.Copyright_Tag; + use all type Wayland_XML.Description_Tag; + use all type Wayland_XML.Entry_Tag; + use all type Wayland_XML.Enum_Tag; + use all type Wayland_XML.Event_Tag; + use all type Wayland_XML.Request_Tag; + use all type Wayland_XML.Interface_Tag; + use all type Wayland_XML.Protocol_Tag; + + use all type Aida.Deepend.XML_DOM_Parser.Node_Kind_Id; + use all type Aida.Deepend.XML_DOM_Parser.Attribute; + use all type Aida.Deepend.XML_DOM_Parser.XML_Tag; + use all type Wayland_XML.Protocol_Child_Kind_Id; + use all type Wayland_XML.Interface_Child_Kind_Id; + use all type Wayland_XML.Event_Child_Kind_Id; + use all type Wayland_XML.Arg_Type_Attribute; + use all type Wayland_XML.Request_Child_Kind_Id; + use all type Wayland_XML.Enum_Child; + + package SF renames Ada.Strings.Fixed; + package SU renames Ada.Strings.Unbounded; + + package Unbounded_String_Vectors is new Ada.Containers.Vectors + (Index_Type => Positive, + Element_Type => SU.Unbounded_String, + ""="" => SU.""=""); + + function Trim (Value : String) return String is (SF.Trim (Value, Ada.Strings.Both)); + + function Is_Reserved_Keyword (Name : String) return Boolean is + (Name in ""Begin"" | ""End""); + + procedure Put + (File : Ada.Text_IO.File_Type; + Item : String) renames Ada.Text_IO.Put; + + procedure Put_Line + (File : Ada.Text_IO.File_Type; + Item : String) renames Ada.Text_IO.Put_Line; + + procedure Put_Line + (Item : String) renames Ada.Text_IO.Put_Line; + + procedure New_Line + (File : Ada.Text_IO.File_Type; + Spacing : Ada.Text_IO.Positive_Count := 1) renames Ada.Text_IO.New_Line; + + function ""+"" (Value : String) return SU.Unbounded_String renames SU.To_Unbounded_String; + function ""+"" (Value : SU.Unbounded_String) return String renames SU.To_String; + + XML_Exception : exception; + + procedure Create_Wayland_Spec_File (Enable_Comments : Boolean); + procedure Create_Wayland_Body_File; + + Protocol_Tag : Wayland_XML.Protocol_Tag_Ptr; + + function Is_Deprecated (Interface_Tag : Wayland_XML.Interface_Tag) return Boolean is + (Name (Interface_Tag) in ""wl_shell"" | ""wl_shell_surface""); + -- wl_shell[_surface] are deprecated and replaced by the xdg-shell protocol + + function Get_Protocol_Name (Name : String) return String is + (if Name = ""wayland"" then ""client"" else Name); + + package String_Maps is new Ada.Containers.Indefinite_Hashed_Maps + (Key_Type => String, + Element_Type => String, + Hash => Ada.Strings.Hash, + Equivalent_Keys => ""=""); + + procedure Generate_Code_For_Arg + (File : Ada.Text_IO.File_Type; + Interface_Tag : Wayland_XML.Interface_Tag; + Arg_Tag : Wayland_XML.Arg_Tag; + Max_Length : Natural; + Is_Last : Boolean; + Enum_Types : in out String_Maps.Map) + is + function Get_Enum_Type_Name return String is + Result : String := Enum (Arg_Tag); + begin + case SF.Count (Result, ""."") is + when 0 => + return Name (Interface_Tag) & ""_"" & Result; + when 1 => + Result (SF.Index (Result, ""."")) := '_'; + return Result; + when others => + raise XML_Exception; + end case; + end Get_Enum_Type_Name; + + Arg_Name : constant String + := Xml_Parser_Utils.Adaify_Variable_Name (Name (Arg_Tag)); + Arg_Type : constant String := + Xml_Parser_Utils.Arg_Type_As_String (Arg_Tag); + + Arg_Type_Name : constant String := + (if Exists_Enum (Arg_Tag) then + Xml_Parser_Utils.Adaify_Name (Get_Enum_Type_Name) + else + Arg_Type); + + Arg_Name_Aligned : constant String := SF.Head (Arg_Name, Max_Length, ' '); + begin + if Arg_Type_Name /= Arg_Type then + Enum_Types.Include (Arg_Type_Name, Arg_Type); + end if; + + if Is_Last then + Put (File, "" "" & Arg_Name_Aligned & "" : "" & Arg_Type_Name & "")""); + else + Put_Line (File, "" "" & Arg_Name_Aligned & "" : "" & Arg_Type_Name & "";""); + end if; + end Generate_Code_For_Arg; + + type Parameter is record + Name, Ada_Type : SU.Unbounded_String; + end record; + + type Parameter_Array is array (Positive range <>) of Parameter; + + type Subprogram_Kind is (Declaration, Implementation); + + Max_Line_Length : constant := 99; + Generate_Interfaces_For_Client : constant Boolean := True; + Unused_Padding_Name : constant String := ""Unused""; + + procedure Generate_Pretty_Code_For_Subprogram + (File : Ada.Text_IO.File_Type; + Kind : Subprogram_Kind; + Interface_Tag : aliased Wayland_XML.Interface_Tag; + Procedure_Name : String; + Return_Type : String; + Parameters : Parameter_Array := (1 .. 0 => <>)) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag)); + Ptr_Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag) & ""_Ptr""); + + Subprogram_Kind : constant String := (if Return_Type'Length > 0 then ""function"" else ""procedure""); + Return_String : constant String := (if Return_Type'Length > 0 then "" return "" & Return_Type else """"); + + Max_Name_Length : Natural := Name'Length; + + function Align (Value : String) return String is (SF.Head (Value, Max_Name_Length, ' ')); + + Last_Char : constant String := (if Kind = Declaration then "";"" else "" is""); + One_Line : Boolean; + begin + for Parameter of Parameters loop + Max_Name_Length := Natural'Max (Max_Name_Length, SU.Length (Parameter.Name)); + end loop; + + declare + Line_Length : Natural := Subprogram_Kind'Length + 8 + 2 * Name'Length + Procedure_Name'Length + Ptr_Name'Length + Return_String'Length + Last_Char'Length + 2 * Parameters'Length; + begin + for Parameter of Parameters loop + Line_Length := Line_Length + SU.Length (Parameter.Name) + SU.Length (Parameter.Ada_Type) + 3; + end loop; + + One_Line := Parameters'Length = 0 and Line_Length <= Max_Line_Length;" +procedure Identify_Protocol_Tag;,"procedure Identify_Protocol_Children; + + procedure Allocate_Space_For_Wayland_XML_Contents + (File_Name : String; + File_Contents : out Aida.Deepend.String_Ptr) + is + package IO renames Ada.Streams.Stream_IO; + + Size : constant Natural := Natural (Ada.Directories.Size (File_Name)); + File : IO.File_Type; + + subtype File_String is String (1 .. Size); + begin + IO.Open (File, IO.In_File, File_Name); + + File_Contents := new File_String; + File_String'Read (IO.Stream (File), File_Contents.all); + + IO.Close (File); + end Allocate_Space_For_Wayland_XML_Contents; + + Root_Node : Aida.Deepend.XML_DOM_Parser.Node_Ptr; + + procedure Parse_Contents (File_Contents : Aida.Deepend.String_Ptr) is + Call_Result : Aida.Call_Result; + begin + Aida.Deepend.XML_DOM_Parser.Parse + (File_Contents.all, Call_Result, Root_Node); + + if Call_Result.Has_Failed then + raise XML_Exception with Call_Result.Message; + else + Identify_Protocol_Tag; + Identify_Protocol_Children; + end if; + end Parse_Contents; + + procedure Identify_Protocol_Tag is + begin + if Root_Node.Id /= Node_Kind_Tag or else Name (Root_Node.Tag) /= ""protocol"" then + raise XML_Exception with ""Root node is not ""; + end if; + + if + Attributes (Root_Node.Tag).Length /= 1 or else + Name (Attributes (Root_Node.Tag) (1).all) /= ""name"" + then + raise XML_Exception with "" node has no name attribute""; + end if; + + Protocol_Tag := new Wayland_XML.Protocol_Tag; + Set_Name (Protocol_Tag.all, Value (Attributes (Root_Node.Tag) (1).all)); + end Identify_Protocol_Tag; + + procedure Identify_Protocol_Children is + function Identify_Copyright + (Node : not null Aida.Deepend.XML_DOM_Parser.Node_Ptr) + return not null Wayland_XML.Copyright_Ptr + is + Copyright_Tag : constant not null Wayland_XML.Copyright_Ptr + := new Wayland_XML.Copyright_Tag; + begin + if Child_Nodes (Node.Tag).Length = 1 then + if Child_Nodes (Node.Tag) (1).Id = Node_Kind_Text then + Set_Text + (Copyright_Tag.all, + Trim (Child_Nodes (Node.Tag) (1).Text.all)); + else + raise XML_Exception; + end if; + else + raise XML_Exception; + end if; + return Copyright_Tag; + end Identify_Copyright; + + function Identify_Description + (Node : not null Aida.Deepend.XML_DOM_Parser.Node_Ptr) + return not null Wayland_XML.Description_Tag_Ptr + is + Description_Tag : constant not null Wayland_XML.Description_Tag_Ptr + := new Wayland_XML.Description_Tag; + + Text : SU.Unbounded_String; + begin + if Attributes (Node.Tag).Length = 1 and then + Name (Attributes (Node.Tag) (1).all) = ""summary"" + then + Set_Summary (Description_Tag.all, Value (Attributes (Node.Tag) (1).all)); + else + raise XML_Exception with ""Expected tag 'description' to have 1 attribute 'summary'""; + end if; + + for Child of Child_Nodes (Node.Tag) loop + if Child.Id = Node_Kind_Text then + SU.Append (Text, Trim (Child.Text.all)); + elsif Child.Id /= Node_Kind_Comment then + raise XML_Exception with + ""Tag 'description' has unexpected child "" & Child.Id'Image; + end if; + end loop; + Set_Text (Description_Tag.all, +Text); + + return Description_Tag; + end Identify_Description; + + function Identify_Arg + (Node : not null Aida.Deepend.XML_DOM_Parser.Node_Ptr) + return not null Wayland_XML.Arg_Tag_Ptr + is + Arg_Tag : constant not null Wayland_XML.Arg_Tag_Ptr + := new Wayland_XML.Arg_Tag; + + procedure Iterate + (Tag : aliased Aida.Deepend.XML_DOM_Parser.XML_Tag) is + begin + for A of Attributes (Tag) loop + if Name (A.all) = ""name"" then + Set_Name (Arg_Tag.all, Value (A.all)); + elsif Name (A.all) = ""type"" then + Set_Type_Attribute (Arg_Tag.all, Value (A.all)); + elsif Name (A.all) = ""summary"" then + Set_Summary (Arg_Tag.all, Value (A.all)); + elsif Name (A.all) = ""interface"" then + Set_Interface_Attribute (Arg_Tag.all, Value (A.all)); + elsif Name (A.all) = ""allow-null"" then + if Value (A.all) = ""true"" then + Set_Allow_Null (Arg_Tag.all, True); + elsif Value (A.all) = ""false"" then + Set_Allow_Null (Arg_Tag.all, False); + else + raise XML_Exception with + ""Attribute 'allow-null' must be 'true' or 'false'""; + end if; + elsif Name (A.all) = ""enum"" then + Set_Enum (Arg_Tag.all, Value (A.all)); + else + raise XML_Exception; + end if; + end loop; + end Iterate; + begin + Iterate (Node.Tag); + + return Arg_Tag; + end Identify_Arg; + + function Identify_Request + (Node : not null Aida.Deepend.XML_DOM_Parser.Node_Ptr) + return not null Wayland_XML.Request_Tag_Ptr + is + Request_Tag : constant not null Wayland_XML.Request_Tag_Ptr + := new Wayland_XML.Request_Tag; + + procedure Iterate + (Tag : aliased Aida.Deepend.XML_DOM_Parser.XML_Tag) is + begin + for A of Attributes (Tag) loop + if Name (A.all) = ""name"" then + Set_Name (Request_Tag.all, Value (A.all)); + elsif Name (A.all) = ""type"" then + Set_Type_Attribute (Request_Tag.all, Value (A.all)); + elsif Name (A.all) = ""since"" then + declare + V : Integer; + Has_Failed : Boolean; + begin + Aida.To_Integer (Value (A.all), V, Has_Failed); + + if Has_Failed then + raise XML_Exception; + else + Set_Since + (Request_Tag.all, + Wayland_XML.Version_Number (V)); + end if;" +procedure Generate_Code_For_Opcodes is,"I : Integer := 0; + + procedure Generate_Code + (Request_Tag : aliased Wayland_XML.Request_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag) & ""_"" & + Wayland_XML.Name (Request_Tag)); + begin + if I = 0 then + New_Line (File); + end if; + Put_Line (File, "" "" & Name & "" : constant := "" & Aida.To_String (I) & "";""); + + I := I + 1; + end Generate_Code; + begin + Iterate_Over_Requests (Interface_Tag, Generate_Code'Access); + end Generate_Code_For_Opcodes; + + begin + Generate_Code_For_Opcodes; + -- Note: See git history for *_Since_Version constants + end Handle_Interface; + begin + Iterate_Over_Interfaces (Handle_Interface'Access); + end Generate_Code_For_Numeric_Constants; + + All_Types : Unbounded_String_Vectors.Vector; + + procedure Create_Wayland_Spec_File (Enable_Comments : Boolean) is + File : Ada.Text_IO.File_Type; + + procedure Create_Wl_Thin_Spec_File (Protocol_Name : String); + + procedure Generate_Code_For_Type_Declarations; + procedure Generate_Code_For_External_Proxies (Protocol_Name : String); + procedure Generate_Code_For_The_Interface_Constants; + procedure Generate_Code_For_Enum_Constants; + procedure Generate_Private_Code_For_Enum_Constants; + procedure Generate_Manually_Edited_Partial_Type_Declarations (Protocol_Name : String); + procedure Generate_Use_Type_Declarions (Package_Name : String); + procedure Generate_Manually_Edited_Code_For_Type_Definitions; + procedure Generate_Private_Code_For_The_Interface_Constants; + + procedure Create_File is + Protocol_Name : constant String := Get_Protocol_Name (Name (Protocol_Tag.all)); + Package_Name : constant String := Xml_Parser_Utils.Adaify_Name (Protocol_Name); + + Has_Enums : constant Boolean := + Protocol_Name in + ""client"" | + ""pointer_constraints_unstable_v1"" | + ""presentation_time"" | + ""xdg_decoration_unstable_v1"" | + ""xdg_shell""; + begin + Ada.Text_IO.Create + (File, Ada.Text_IO.Out_File, + ""wayland-protocols-"" & Protocol_Name & "".ads""); + + Put_Line (File, ""private with Wayland.Protocols.Thin_"" & Package_Name & "";""); + if Has_Enums then + New_Line (File); + Put_Line (File, ""with Wayland.Enums."" & Package_Name & "";""); + end if; + + if Protocol_Name = ""client"" then + null; + elsif Protocol_Name = ""xdg_decoration_unstable_v1"" then + New_Line (File); + Put_Line (File, ""with Wayland.Protocols.Client;""); + Put_Line (File, ""with Wayland.Protocols.Xdg_Shell;""); + else + New_Line (File); + Put_Line (File, ""with Wayland.Protocols.Client;""); + end if; + + New_Line (File); + Put_Line (File, ""package Wayland.Protocols."" & Package_Name & "" is""); + Put_Line (File, "" pragma Preelaborate;""); + + if Has_Enums then + New_Line (File); + Put_Line (File, "" use Wayland.Enums."" & Package_Name & "";""); + end if; + + if Protocol_Name = ""xdg_shell"" then + New_Line (File); + Put_Line (File, "" type State_Array is array (Positive range <>) of Xdg_Toplevel_State;""); + Put_Line (File, "" type Capability_Array is array (Positive range <>) of Xdg_Toplevel_Wm_Capabilities;""); + end if; + + Generate_Code_For_Type_Declarations; + Generate_Code_For_External_Proxies (Protocol_Name); + Generate_Code_For_The_Interface_Constants; + + if Generate_Interfaces_For_Client or Protocol_Name /= ""client"" then + New_Line (File); + Put_Line (File, "" procedure Initialize;""); + end if; + + if Protocol_Name = ""client"" then + Put_Line (File, """"); + Put_Line (File, "" function Bind""); + Put_Line (File, "" (Object : Registry;""); + Put_Line (File, "" Iface : Interface_Type;""); + Put_Line (File, "" Id : Unsigned_32;""); + Put_Line (File, "" Version : Unsigned_32) return Secret_Proxy;""); + end if; + + Generate_Manually_Edited_Partial_Type_Declarations (Protocol_Name); + + New_Line (File); + Put_Line (File, ""private""); + New_Line (File); + + Generate_Use_Type_Declarions (Package_Name); + Generate_Manually_Edited_Code_For_Type_Definitions; + + if Protocol_Name = ""client"" then + Put_Line (File, """"); + Put_Line (File, "" function Get_Proxy (Object : Surface) return Secret_Proxy is (Secret_Proxy (Object.Proxy));""); + Put_Line (File, "" function Get_Proxy (Object : Seat) return Secret_Proxy is (Secret_Proxy (Object.Proxy));""); + Put_Line (File, "" function Get_Proxy (Object : Shm) return Secret_Proxy is (Secret_Proxy (Object.Proxy));""); + Put_Line (File, "" function Get_Proxy (Object : Output) return Secret_Proxy is (Secret_Proxy (Object.Proxy));""); + Put_Line (File, "" function Get_Proxy (Object : Pointer) return Secret_Proxy is (Secret_Proxy (Object.Proxy));""); + Put_Line (File, "" function Get_Proxy (Object : Region) return Secret_Proxy is (Secret_Proxy (Object.Proxy));""); + elsif Protocol_Name = ""xdg_shell"" then + Put_Line (File, """"); + Put_Line (File, "" function Get_Proxy (Object : Xdg_Toplevel) return Secret_Proxy is (Secret_Proxy (Object.Proxy));""); + end if; + + Generate_Private_Code_For_The_Interface_Constants; + + Put_Line (File, """"); + Put_Line (File, ""end Wayland.Protocols."" & Package_Name & "";""); + + Ada.Text_IO.Close (File); + + ----------------------------------------------------------------------- + + -- TODO Do not generate file if there are no enum constants + Ada.Text_IO.Create + (File, Ada.Text_IO.Out_File, + ""wayland-enums-"" & Protocol_Name & "".ads""); + + Put_Line (File, ""package Wayland.Enums."" & Package_Name & "" is""); + Put_Line (File, "" pragma Preelaborate;""); + + Generate_Code_For_Enum_Constants; + + New_Line (File); + Put_Line (File, ""private""); + New_Line (File); + + Generate_Private_Code_For_Enum_Constants; + + Put_Line (File, ""end Wayland.Enums."" & Package_Name & "";""); + + Ada.Text_IO.Close (File); + + Ada.Text_IO.Create + (File, Ada.Text_IO.Out_File, + ""wayland-protocols-thin_"" & Protocol_Name & "".ads""); + + Put_Line (File, ""with Interfaces.C.Strings;""); + Put_Line (File, """"); + Put_Line (File, ""with Wayland.API;""); + if Has_Enums then + Put_Line (File, ""with Wayland.Enums."" & Package_Name & "";""); + end if; + + if Protocol_Name = ""client"" then + null; + elsif Protocol_Name = ""xdg_decoration_unstable_v1"" then + Put_Line (File, ""with Wayland.Protocols.Thin_Xdg_Shell;""); + else + Put_Line (File, ""with Wayland.Protocols.Thin_Client;""); + end if; + Put_Line (File, """"); + Put_Line (File, ""private package Wayland.Protocols.Thin_"" & Package_Name & "" is""); + Put_Line (File, "" pragma Preelaborate;""); + + if Has_Enums then + Put_Line (File, """"); + Put_Line (File, "" use Wayland.Enums."" & Package_Name & "";""); + end if; + + Put_Line (File, """"); + Put_Line (File, "" subtype chars_ptr is Interfaces.C.Strings.chars_ptr;""); + Put_Line (File, """"); + + Put_Line (File, "" subtype Interface_T is Wayland.API.Interface_T;""); + Put_Line (File, """"); + Put_Line (File, "" subtype Proxy_Ptr is Wayland.API.Proxy_Ptr;""); + Put_Line (File, "" subtype Interface_Ptr is Wayland.API.Interface_Ptr;""); + Put_Line (File, """"); + + Create_Wl_Thin_Spec_File (Protocol_Name); + + Put_Line (File, ""end Wayland.Protocols.Thin_"" & Package_Name & "";""); + + Ada.Text_IO.Close (File); + end Create_File; + + procedure Generate_Code_For_Type_Declarations is + procedure Handle_Interface + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + Put_Line (File, "" type "" & Name & "" is tagged limited private;""); + end Handle_Interface; + begin + New_Line (File); + Iterate_Over_Interfaces (Handle_Interface'Access); + end Generate_Code_For_Type_Declarations; + + procedure Generate_Code_For_External_Proxies (Protocol_Name : String) is + begin + if Protocol_Name = ""client"" then + Put_Line (File, """"); + Put_Line (File, "" function Get_Proxy (Object : Surface) return Secret_Proxy;""); + Put_Line (File, "" function Get_Proxy (Object : Seat) return Secret_Proxy;""); + Put_Line (File, "" function Get_Proxy (Object : Shm) return Secret_Proxy;""); + Put_Line (File, "" function Get_Proxy (Object : Output) return Secret_Proxy;""); + Put_Line (File, "" function Get_Proxy (Object : Pointer) return Secret_Proxy;""); + Put_Line (File, "" function Get_Proxy (Object : Region) return Secret_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" package Constructors is""); + Put_Line (File, "" function Set_Proxy (Proxy : Secret_Proxy) return Buffer;""); + Put_Line (File, "" function Set_Proxy (Proxy : Secret_Proxy) return Output;""); + Put_Line (File, "" function Set_Proxy (Proxy : Secret_Proxy) return Surface;""); + Put_Line (File, "" end Constructors;""); + elsif Protocol_Name = ""xdg_shell"" then + Put_Line (File, """"); + Put_Line (File, "" function Get_Proxy (Object : Xdg_Toplevel) return Secret_Proxy;""); + end if; + end Generate_Code_For_External_Proxies; + + procedure Generate_Code_For_The_Interface_Constants is + procedure Handle_Interface + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag) & ""_Interface""); + begin + Put_Line (File, "" "" & Name & "" : constant Interface_Type;""); + end Handle_Interface; + begin + New_Line (File); + Iterate_Over_Interfaces (Handle_Interface'Access); + end Generate_Code_For_The_Interface_Constants; + + function Get_Name (Entry_Tag : Wayland_XML.Entry_Tag) return String is + -- Just because some entries in wl_output.transform start with a digit :/ + Entry_Name : constant String := Name (Entry_Tag); + begin + return + (if Entry_Name in ""90"" | ""180"" | ""270"" then + ""Rotate_"" & Entry_Name + else + Xml_Parser_Utils.Adaify_Name (Entry_Name)); + end Get_Name; + + function Get_Max_Child_Length (Enum_Tag : aliased Wayland_XML.Enum_Tag) return Natural is + Result : Natural := 0; + begin + for Child of Wayland_XML.Entries (Enum_Tag) loop + Result := Natural'Max (Result, Get_Name (Child.Entry_Tag.all)'Length); + end loop; + + return Result; + end Get_Max_Child_Length; + + procedure Generate_Code_For_Enum_Constants is + procedure Handle_Interface + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + procedure Generate_Code (Enum_Tag : aliased Wayland_XML.Enum_Tag) is + Enum_Type_Name : constant String := Xml_Parser_Utils.Adaify_Name + (Name (Interface_Tag) & ""_"" & Name (Enum_Tag)); + + Is_Bitfield : constant Boolean := + Exists_Bitfield (Enum_Tag) and then Bitfield (Enum_Tag); + + Max_Length : constant Natural := + Natural'Max (Get_Max_Child_Length (Enum_Tag), Unused_Padding_Name'Length); + + procedure Generate_Summary_For_Entry + (Entry_Tag : Wayland_XML.Entry_Tag) + is + Summary_String : constant String := + (if Enable_Comments and Exists_Summary (Entry_Tag) then + Summary (Entry_Tag) + else """"); + begin + if Summary_String'Length > 0 then + Put_Line (File, "" -- "" & Summary_String); + end if; + end Generate_Summary_For_Entry; + + Count_components : Natural := 0; + + procedure Generate_Code_For_Entry_Component + (Entry_Tag : Wayland_XML.Entry_Tag) + is + Aligned_Name : constant String := + SF.Head (Get_Name (Entry_Tag), Max_Length, ' '); + + Value : constant Natural := Natural'Value (Value_As_String (Entry_Tag)); + begin + -- Ignore entry with value 0 because then all components of + -- the record are False + if Value = 0 then + return; + end if; + + Count_components := Count_components + 1; + + Put_Line (File, "" "" & Aligned_Name & "" : Boolean := False;""); + Generate_Summary_For_Entry (Entry_Tag); + end Generate_Code_For_Entry_Component; + + procedure Generate_Code_For_Entry + (Entry_Tag : Wayland_XML.Entry_Tag; + Is_First : Boolean; + Is_Last : Boolean) + is + Aligned_Name : constant String := Get_Name (Entry_Tag); + + Prefix : constant String := (if Is_First then """" else "" ""); + Suffix : constant String := (if Is_Last then "");"" else "",""); + begin + Put_Line (File, Prefix & Aligned_Name & Suffix); + Generate_Summary_For_Entry (Entry_Tag); + end Generate_Code_For_Entry; + begin + New_Line (File); + if Is_Bitfield then + Put_Line (File, "" type "" & Enum_Type_Name & "" is record""); + for Child of Wayland_XML.Entries (Enum_Tag) loop + Generate_Code_For_Entry_Component (Child.Entry_Tag.all); + end loop; + if Count_components < 32 then + declare + Aligned_Name : constant String := + SF.Head (Unused_Padding_Name, Max_Length, ' '); + begin + Put_Line (File, "" "" & Aligned_Name & "" : Unused_Type;"");" +procedure Generate_Private_Code_For_Enum_Constants is,"procedure Handle_Interface + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + procedure Generate_Code (Enum_Tag : aliased Wayland_XML.Enum_Tag) is + Enum_Type_Name : constant String := Xml_Parser_Utils.Adaify_Name + (Name (Interface_Tag) & ""_"" & Name (Enum_Tag)); + + Is_Bitfield : constant Boolean := + Exists_Bitfield (Enum_Tag) and then Bitfield (Enum_Tag); + + Max_Length : constant Natural := + Natural'Max (Get_Max_Child_Length (Enum_Tag), Unused_Padding_Name'Length); + + Count_Components : Natural := 0; + + procedure Generate_Code_For_Entry_Component + (Entry_Tag : Wayland_XML.Entry_Tag) + is + Aligned_Name : constant String := + SF.Head (Get_Name (Entry_Tag), Max_Length, ' '); + + type U32 is mod 2 ** 32 + with Size => 32; + + Value : constant U32 := U32'Value (Value_As_String (Entry_Tag)); + begin + -- Ignore entry with value 0 because then all components of + -- the record are False + if Value = 0 then + return; + end if; + + if (Value and (Value - 1)) /= 0 then + raise Constraint_Error with Value'Image & "" is not a power of two""; + end if; + + Count_Components := Count_Components + 1; + + declare + Bit : Natural := 0; + begin + while Value > 2 ** Bit loop + Bit := Bit + 1; + end loop; + + Put_Line (File, "" "" & Aligned_Name & + "" at 0 range "" & Trim (Bit'Image) & "" .. "" & Trim (Bit'Image) & "";"");" +procedure Generate_Prefix_Spec_Events is,"begin + Put_Line (File, """"); + Put_Line (File, "" generic""); + end Generate_Prefix_Spec_Events; + + procedure Generate_Suffix_Spec_Events (Name : String) is + begin + Put_Line (File, "" package "" & Name & ""_Events is""); + Put_Line (File, """"); + Put_Line (File, "" procedure Subscribe""); + Put_Line (File, "" (Object : aliased in out "" & Name & ""'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" end "" & Name & ""_Events;""); + end Generate_Suffix_Spec_Events; + + procedure Handle_Interface_Subprograms_Client + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Name in ""Compositor"" | ""Seat"" | ""Shm"" | ""Output"" | ""Data_Device_Manager"" then + Generate_Spec_Bind_Subprogram (Name); + end if; + + if Name = ""Display"" then + Put_Line (File, """"); + Put_Line (File, "" function Is_Connected (Object : Display) return Boolean renames Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Connect (Object : in out Display)""); + Put_Line (File, "" with Pre => not Object.Is_Connected;""); + Put_Line (File, "" -- Attempts connecting with the Wayland server""); + Put_Line (File, """"); + Put_Line (File, "" type Events_Status is (Has_Events, No_Events, Error);""); + Put_Line (File, """"); + Put_Line (File, "" type Events_Status_Array is array (Positive range <>) of Events_Status;""); + Put_Line (File, """"); + Put_Line (File, "" type File_Descriptor_Array is array (Positive range <>) of File_Descriptor;""); + Put_Line (File, """"); + Put_Line (File, "" function Check_For_Events""); + Put_Line (File, "" (Object : Display;""); + Put_Line (File, "" Timeout : Duration;""); + Put_Line (File, "" Descriptors : File_Descriptor_Array := (1 .. 0 => 0)) return Events_Status_Array""); + Put_Line (File, "" with Post => Check_For_Events'Result'Length = Descriptors'Length + 1;""); + Put_Line (File, """"); + Put_Line (File, "" function Flush (Object : Display) return Optional_Result""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, "" -- Send all buffered requests to the Wayland compositor""); + Put_Line (File, "" --""); + Put_Line (File, "" -- Returns the number of bytes sent if successful.""); + Put_Line (File, """"); + Put_Line (File, "" procedure Flush (Object : Display)""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, "" -- Send all buffered requests to the Wayland compositor""); + Put_Line (File, "" --""); + Put_Line (File, "" -- Raises Program_Error if flushing failed.""); + Put_Line (File, """"); + Put_Line (File, "" function Dispatch (Object : Display) return Optional_Result""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, "" -- Process incoming events""); + Put_Line (File, """"); + Put_Line (File, "" procedure Dispatch (Object : Display)""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, "" -- Process incoming events""); + Put_Line (File, "" --""); + Put_Line (File, "" -- Raises Program_Error if dispatching failed.""); + Put_Line (File, """"); + Put_Line (File, "" function Dispatch_Pending (Object : Display) return Optional_Result""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, "" -- Dispatch events on the default queue without reading from""); + Put_Line (File, "" -- the display's file descriptor""); + Put_Line (File, "" --""); + Put_Line (File, "" -- It does not attempt to read the display's file descriptor and simply""); + Put_Line (File, "" -- returns zero if the main queue is empty, i.e., it does not block.""); + Put_Line (File, "" --""); + Put_Line (File, "" -- Returns the number of dispatched events if successful.""); + Put_Line (File, """"); + Put_Line (File, "" function Prepare_Read (Object : Display) return Call_Result_Code""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, "" -- Prepare to read events from the display's file descriptor""); + Put_Line (File, """"); + Put_Line (File, "" function Read_Events (Object : Display) return Call_Result_Code""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Cancel_Read (Object : Display)""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, "" -- Cancel read intention on display's file descriptor""); + Put_Line (File, """"); + Put_Line (File, "" function Roundtrip (Object : Display) return Integer""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Roundtrip (Object : Display)""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Disconnect (Object : in out Display)""); + Put_Line (File, "" with Pre => Object.Is_Connected,""); + Put_Line (File, "" Post => not Object.Is_Connected;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Registry""); + Put_Line (File, "" (Object : Display;""); + Put_Line (File, "" Registry : in out Client.Registry'Class)""); + Put_Line (File, "" with Pre => Object.Is_Connected and not Registry.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" function Sync (Object : Display) return Callback'Class""); + Put_Line (File, "" with Pre => Object.Is_Connected;""); + elsif Name = ""Compositor"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Create_Surface (Object : Compositor;""); + Put_Line (File, "" Surface : in out Client.Surface'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Create_Region (Object : Compositor;""); + Put_Line (File, "" Region : in out Client.Region'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + elsif Name = ""Seat"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Pointer (Object : Seat;""); + Put_Line (File, "" Pointer : in out Client.Pointer'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and not Pointer.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Keyboard (Object : Seat;""); + Put_Line (File, "" Keyboard : in out Client.Keyboard'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and not Keyboard.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Touch (Object : Seat;""); + Put_Line (File, "" Touch : in out Client.Touch'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and not Touch.Has_Proxy;""); + elsif Name = ""Shm_Pool"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Create_Buffer (Object : Shm_Pool;""); + Put_Line (File, "" Offset : Natural;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural;""); + Put_Line (File, "" Stride : Natural;""); + Put_Line (File, "" Format : Shm_Format;""); + Put_Line (File, "" Buffer : in out Client.Buffer'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Resize (Object : Shm_Pool;""); + Put_Line (File, "" Size : Positive)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + elsif Name = ""Shm"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Create_Pool (Object : Shm;""); + Put_Line (File, "" File_Descriptor : Wayland.File_Descriptor;""); + Put_Line (File, "" Size : Positive;""); + Put_Line (File, "" Pool : in out Shm_Pool'Class);""); + elsif Name = ""Data_Offer"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Do_Accept (Object : Data_Offer;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Mime_Type : String)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Do_Not_Accept (Object : Data_Offer;""); + Put_Line (File, "" Serial : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Receive (Object : Data_Offer;""); + Put_Line (File, "" Mime_Type : String;""); + Put_Line (File, "" File_Descriptor : Wayland.File_Descriptor)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Finish (Object : Data_Offer)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Actions (Object : Data_Offer;""); + Put_Line (File, "" Dnd_Actions : Data_Device_Manager_Dnd_Action;""); + Put_Line (File, "" Preferred_Action : Data_Device_Manager_Dnd_Action)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + elsif Name = ""Data_Source"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Offer (Object : Data_Source;""); + Put_Line (File, "" Mime_Type : String)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Actions (Object : Data_Source;""); + Put_Line (File, "" Dnd_Actions : Data_Device_Manager_Dnd_Action)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + elsif Name = ""Data_Device"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Start_Drag (Object : Data_Device;""); + Put_Line (File, "" Source : Data_Source'Class;""); + Put_Line (File, "" Origin : Surface'Class;""); + Put_Line (File, "" Icon : Surface'Class;""); + Put_Line (File, "" Serial : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Source.Has_Proxy and Origin.Has_Proxy and Icon.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Selection (Object : Data_Device;""); + Put_Line (File, "" Source : Data_Source'Class;""); + Put_Line (File, "" Serial : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Source.Has_Proxy;""); + elsif Name = ""Data_Device_Manager"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Create_Data_Source (Object : Data_Device_Manager;""); + Put_Line (File, "" Source : in out Data_Source'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Data_Device (Object : Data_Device_Manager;""); + Put_Line (File, "" Seat : Client.Seat'Class;""); + Put_Line (File, "" Device : in out Data_Device'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Seat.Has_Proxy;""); + elsif Name = ""Surface"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Attach (Object : Surface;""); + Put_Line (File, "" Buffer : Client.Buffer'Class;""); + Put_Line (File, "" X, Y : Integer)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Damage (Object : Surface;""); + Put_Line (File, "" X, Y : Integer;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Frame (Object : Surface; Subject : in out Callback'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and not Subject.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Opaque_Region (Object : Surface;""); + Put_Line (File, "" Region : Client.Region'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Input_Region (Object : Surface;""); + Put_Line (File, "" Region : Client.Region'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Commit (Object : Surface)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Buffer_Transform (Object : Surface;""); + Put_Line (File, "" Transform : Output_Transform)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Buffer_Scale (Object : Surface;""); + Put_Line (File, "" Scale : Positive)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Damage_Buffer (Object : Surface;""); + Put_Line (File, "" X, Y : Integer;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + elsif Name = ""Pointer"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Cursor (Object : Pointer;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Surface : Client.Surface'Class;""); + Put_Line (File, "" Hotspot_X : Integer;""); + Put_Line (File, "" Hotspot_Y : Integer)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + elsif Name = ""Region"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Add (Object : Region;""); + Put_Line (File, "" X, Y : Integer;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Subtract (Object : Region;""); + Put_Line (File, "" X, Y : Integer;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + elsif Name = ""Subcompositor"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Subsurface (Object : Subcompositor;""); + Put_Line (File, "" Surface : Client.Surface'Class;""); + Put_Line (File, "" Parent : Client.Surface'Class;""); + Put_Line (File, "" Subsurface : in out Client.Subsurface'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Surface.Has_Proxy and Parent.Has_Proxy;""); + elsif Name = ""Subsurface"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Position (Object : Subsurface; X, Y : Integer)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Place_Above (Object : Subsurface;""); + Put_Line (File, "" Sibling : Surface'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Sibling.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Place_Below (Object : Subsurface;""); + Put_Line (File, "" Sibling : Surface'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Sibling.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Sync (Object : Subsurface)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Desync (Object : Subsurface)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + end if; + end Handle_Interface_Subprograms_Client; + + procedure Handle_Interface_Events_Client + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if not Exists_Events (Interface_Tag) then + return; + end if; + + Generate_Prefix_Spec_Events; + + if Name = ""Display"" then + Put_Line (File, "" with procedure Error""); + Put_Line (File, "" (Display : in out Client.Display'Class;""); + Put_Line (File, "" Code : Unsigned_32;""); + Put_Line (File, "" Message : String) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Delete_Id""); + Put_Line (File, "" (Display : in out Client.Display'Class;""); + Put_Line (File, "" Id : Unsigned_32) is null;""); + elsif Name = ""Registry"" then + Put_Line (File, "" with procedure Global_Object_Added""); + Put_Line (File, "" (Registry : in out Client.Registry'Class;""); + Put_Line (File, "" Id : Unsigned_32;""); + Put_Line (File, "" Name : String;""); + Put_Line (File, "" Version : Unsigned_32);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Global_Object_Removed""); + Put_Line (File, "" (Registry : in out Client.Registry'Class;""); + Put_Line (File, "" Id : Unsigned_32) is null;""); + elsif Name = ""Callback"" then + Put_Line (File, "" with procedure Done""); + Put_Line (File, "" (Callback : in out Client.Callback'Class;""); + Put_Line (File, "" Callback_Data : Unsigned_32);""); + elsif Name = ""Shm"" then + Put_Line (File, "" with procedure Format""); + Put_Line (File, "" (Shm : in out Client.Shm'Class;""); + Put_Line (File, "" Format : Shm_Format);""); + elsif Name = ""Buffer"" then + Put_Line (File, "" with procedure Release""); + Put_Line (File, "" (Buffer : in out Client.Buffer'Class);""); + elsif Name = ""Data_Offer"" then + Put_Line (File, "" with procedure Offer""); + Put_Line (File, "" (Data_Offer : in out Client.Data_Offer'Class;""); + Put_Line (File, "" Mime_Type : String) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Source_Actions""); + Put_Line (File, "" (Data_Offer : in out Client.Data_Offer'Class;""); + Put_Line (File, "" Source_Actions : Data_Device_Manager_Dnd_Action) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Action""); + Put_Line (File, "" (Data_Offer : in out Client.Data_Offer'Class;""); + Put_Line (File, "" Dnd_Action : Data_Device_Manager_Dnd_Action) is null;""); + elsif Name = ""Data_Source"" then + Put_Line (File, "" with procedure Target""); + Put_Line (File, "" (Data_Source : in out Client.Data_Source'Class;""); + Put_Line (File, "" Mime_Type : String) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Send""); + Put_Line (File, "" (Data_Source : in out Client.Data_Source'Class;""); + Put_Line (File, "" Mime_Type : String;""); + Put_Line (File, "" Fd : File_Descriptor) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Cancelled""); + Put_Line (File, "" (Data_Source : in out Client.Data_Source'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Performed""); + Put_Line (File, "" (Data_Source : in out Client.Data_Source'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Finished""); + Put_Line (File, "" (Data_Source : in out Client.Data_Source'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Action""); + Put_Line (File, "" (Data_Source : in out Client.Data_Source'Class;""); + Put_Line (File, "" Dnd_Action : Data_Device_Manager_Dnd_Action) is null;""); + elsif Name = ""Data_Device"" then + Put_Line (File, "" with procedure Data_Offer""); + Put_Line (File, "" (Data_Device : in out Client.Data_Device'Class;""); + Put_Line (File, "" Data_Offer : in out Client.Data_Offer) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Enter""); + Put_Line (File, "" (Data_Device : in out Client.Data_Device'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Surface : Client.Surface;""); + Put_Line (File, "" X, Y : Fixed;""); + Put_Line (File, "" Data_Offer : in out Client.Data_Offer) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Leave""); + Put_Line (File, "" (Data_Device : in out Client.Data_Device'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Motion""); + Put_Line (File, "" (Data_Device : in out Client.Data_Device'Class;""); + Put_Line (File, "" Time : Unsigned_32;""); + Put_Line (File, "" X, Y : Fixed) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Drop""); + Put_Line (File, "" (Data_Device : in out Client.Data_Device'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Selection""); + Put_Line (File, "" (Data_Device : in out Client.Data_Device'Class;""); + Put_Line (File, "" Data_Offer : in out Client.Data_Offer) is null;""); + elsif Name = ""Surface"" then + Put_Line (File, "" with procedure Enter""); + Put_Line (File, "" (Surface : in out Client.Surface'Class;""); + Put_Line (File, "" Output : Client.Output) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Leave""); + Put_Line (File, "" (Surface : in out Client.Surface'Class;""); + Put_Line (File, "" Output : Client.Output) is null;""); + elsif Name = ""Seat"" then + Put_Line (File, "" with procedure Seat_Capabilities""); + Put_Line (File, "" (Seat : in out Client.Seat'Class;""); + Put_Line (File, "" Capabilities : Seat_Capability) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Seat_Name""); + Put_Line (File, "" (Seat : in out Client.Seat'Class;""); + Put_Line (File, "" Name : String) is null;""); + elsif Name = ""Pointer"" then + Put_Line (File, "" with procedure Pointer_Enter""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Surface : Client.Surface;""); + Put_Line (File, "" Surface_X : Fixed;""); + Put_Line (File, "" Surface_Y : Fixed) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Pointer_Leave""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Surface : Client.Surface) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Pointer_Motion""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class;""); + Put_Line (File, "" Time : Unsigned_32;""); + Put_Line (File, "" Surface_X : Fixed;""); + Put_Line (File, "" Surface_Y : Fixed) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Pointer_Button""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Time : Unsigned_32;""); + Put_Line (File, "" Button : Unsigned_32;""); + Put_Line (File, "" State : Pointer_Button_State) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Pointer_Scroll""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class;""); + Put_Line (File, "" Time : Unsigned_32;""); + Put_Line (File, "" Axis : Pointer_Axis;""); + Put_Line (File, "" Value : Fixed) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Pointer_Frame""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Pointer_Scroll_Source""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class;""); + Put_Line (File, "" Axis_Source : Pointer_Axis_Source) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Pointer_Scroll_Stop""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class;""); + Put_Line (File, "" Time : Unsigned_32;""); + Put_Line (File, "" Axis : Pointer_Axis) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Pointer_Scroll_Discrete""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class;""); + Put_Line (File, "" Axis : Pointer_Axis;""); + Put_Line (File, "" Discrete : Integer) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Pointer_Scroll_Value120""); + Put_Line (File, "" (Pointer : in out Client.Pointer'Class;""); + Put_Line (File, "" Axis : Pointer_Axis;""); + Put_Line (File, "" Value120 : Integer) is null;""); + elsif Name = ""Keyboard"" then + Put_Line (File, "" with procedure Keymap""); + Put_Line (File, "" (Keyboard : in out Client.Keyboard'Class;""); + Put_Line (File, "" Format : Keyboard_Keymap_Format;""); + Put_Line (File, "" Fd : File_Descriptor;""); + Put_Line (File, "" Size : Unsigned_32) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Enter""); + Put_Line (File, "" (Keyboard : in out Client.Keyboard'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Surface : Client.Surface;""); + Put_Line (File, "" Keys : Unsigned_32_Array) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Leave""); + Put_Line (File, "" (Keyboard : in out Client.Keyboard'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Surface : Client.Surface) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Key""); + Put_Line (File, "" (Keyboard : in out Client.Keyboard'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Time : Unsigned_32;""); + Put_Line (File, "" Key : Unsigned_32;""); + Put_Line (File, "" State : Keyboard_Key_State) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Modifiers""); + Put_Line (File, "" (Keyboard : in out Client.Keyboard'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Mods_Depressed : Unsigned_32;""); + Put_Line (File, "" Mods_Latched : Unsigned_32;""); + Put_Line (File, "" Mods_Locked : Unsigned_32;""); + Put_Line (File, "" Group : Unsigned_32) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Repeat_Info""); + Put_Line (File, "" (Keyboard : in out Client.Keyboard'Class;""); + Put_Line (File, "" Rate : Integer;""); + Put_Line (File, "" Delay_V : Integer) is null;""); + elsif Name = ""Touch"" then + Put_Line (File, "" with procedure Down""); + Put_Line (File, "" (Touch : in out Client.Touch'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Time : Unsigned_32;""); + Put_Line (File, "" Surface : Client.Surface;""); + Put_Line (File, "" Id : Integer;""); + Put_Line (File, "" X, Y : Fixed) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Up""); + Put_Line (File, "" (Touch : in out Client.Touch'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Time : Unsigned_32;""); + Put_Line (File, "" Id : Integer) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Motion""); + Put_Line (File, "" (Touch : in out Client.Touch'Class;""); + Put_Line (File, "" Time : Unsigned_32;""); + Put_Line (File, "" Id : Integer;""); + Put_Line (File, "" X, Y : Fixed) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Frame""); + Put_Line (File, "" (Touch : in out Client.Touch'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Cancel""); + Put_Line (File, "" (Touch : in out Client.Touch'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Shape""); + Put_Line (File, "" (Touch : in out Client.Touch'Class;""); + Put_Line (File, "" Id : Integer;""); + Put_Line (File, "" Major : Fixed;""); + Put_Line (File, "" Minor : Fixed) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Orientation""); + Put_Line (File, "" (Touch : in out Client.Touch'Class;""); + Put_Line (File, "" Id : Integer;""); + Put_Line (File, "" Orientation : Fixed) is null;""); + elsif Name = ""Output"" then + Put_Line (File, "" with procedure Geometry""); + Put_Line (File, "" (Output : in out Client.Output'Class;""); + Put_Line (File, "" X, Y : Integer;""); + Put_Line (File, "" Physical_Width : Integer;""); + Put_Line (File, "" Physical_Height : Integer;""); + Put_Line (File, "" Subpixel : Output_Subpixel;""); + Put_Line (File, "" Make : String;""); + Put_Line (File, "" Model : String;""); + Put_Line (File, "" Transform : Output_Transform) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Mode""); + Put_Line (File, "" (Output : in out Client.Output'Class;""); + Put_Line (File, "" Flags : Output_Mode;""); + Put_Line (File, "" Width : Integer;""); + Put_Line (File, "" Height : Integer;""); + Put_Line (File, "" Refresh : Integer) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Done""); + Put_Line (File, "" (Output : in out Client.Output'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Scale""); + Put_Line (File, "" (Output : in out Client.Output'Class;""); + Put_Line (File, "" Factor : Integer) is null;""); + end if; + + Generate_Suffix_Spec_Events (Name); + end Handle_Interface_Events_Client; + + procedure Handle_Interface_Subprograms_Xdg_Shell + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Name in ""Xdg_Wm_Base"" then + Generate_Spec_Bind_Subprogram (Name); + end if; + + if Name = ""Xdg_Wm_Base"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Pong (Object : Xdg_Wm_Base; Serial : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Create_Positioner""); + Put_Line (File, "" (Object : Xdg_Wm_Base;""); + Put_Line (File, "" Positioner : in out Xdg_Shell.Xdg_Positioner'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Surface""); + Put_Line (File, "" (Object : Xdg_Wm_Base;""); + Put_Line (File, "" Window : Protocols.Client.Surface'Class;""); + Put_Line (File, "" Surface : in out Xdg_Shell.Xdg_Surface'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Window.Has_Proxy;""); + elsif Name = ""Xdg_Positioner"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Size""); + Put_Line (File, "" (Object : Xdg_Positioner;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Anchor_Rect""); + Put_Line (File, "" (Object : Xdg_Positioner;""); + Put_Line (File, "" X, Y : Integer;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Anchor""); + Put_Line (File, "" (Object : Xdg_Positioner;""); + Put_Line (File, "" Anchor : Xdg_Positioner_Anchor)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Gravity""); + Put_Line (File, "" (Object : Xdg_Positioner;""); + Put_Line (File, "" Gravity : Xdg_Positioner_Gravity)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Constraint_Adjustment""); + Put_Line (File, "" (Object : Xdg_Positioner;""); + Put_Line (File, "" Adjustment : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Offset""); + Put_Line (File, "" (Object : Xdg_Positioner;""); + Put_Line (File, "" X, Y : Integer)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Reactive (Object : Xdg_Positioner)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Parent_Size""); + Put_Line (File, "" (Object : Xdg_Positioner;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Parent_Configure""); + Put_Line (File, "" (Object : Xdg_Positioner;""); + Put_Line (File, "" Serial : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + elsif Name = ""Xdg_Surface"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Toplevel""); + Put_Line (File, "" (Object : Xdg_Surface;""); + Put_Line (File, "" Toplevel : in out Xdg_Shell.Xdg_Toplevel'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Popup""); + Put_Line (File, "" (Object : Xdg_Surface;""); + Put_Line (File, "" Parent : Xdg_Surface'Class;""); + Put_Line (File, "" Positioner : Xdg_Shell.Xdg_Positioner'Class;""); + Put_Line (File, "" Popup : in out Xdg_Shell.Xdg_Popup'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Window_Geometry""); + Put_Line (File, "" (Object : Xdg_Surface;""); + Put_Line (File, "" X, Y : Integer;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Ack_Configure""); + Put_Line (File, "" (Object : Xdg_Surface;""); + Put_Line (File, "" Serial : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + elsif Name = ""Xdg_Toplevel"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Parent""); + Put_Line (File, "" (Object : Xdg_Toplevel;""); + Put_Line (File, "" Parent : Xdg_Toplevel'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Parent.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Title (Object : Xdg_Toplevel; Value : String)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_App_Id (Object : Xdg_Toplevel; Value : String)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Show_Window_Menu""); + Put_Line (File, "" (Object : Xdg_Toplevel;""); + Put_Line (File, "" Seat : Protocols.Client.Seat'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" X, Y : Integer)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Move""); + Put_Line (File, "" (Object : Xdg_Toplevel;""); + Put_Line (File, "" Seat : Protocols.Client.Seat'Class;""); + Put_Line (File, "" Serial : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Resize""); + Put_Line (File, "" (Object : Xdg_Toplevel;""); + Put_Line (File, "" Seat : Protocols.Client.Seat'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Edges : Xdg_Toplevel_Resize_Edge)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Min_Size""); + Put_Line (File, "" (Object : Xdg_Toplevel;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Max_Size""); + Put_Line (File, "" (Object : Xdg_Toplevel;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Minimize (Object : Xdg_Toplevel)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Maximized (Object : Xdg_Toplevel; Enable : Boolean)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Fullscreen""); + Put_Line (File, "" (Object : Xdg_Toplevel;""); + Put_Line (File, "" Enable : Boolean)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Fullscreen""); + Put_Line (File, "" (Object : Xdg_Toplevel;""); + Put_Line (File, "" Enable : Boolean;""); + Put_Line (File, "" Output : Protocols.Client.Output'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Output.Has_Proxy;""); + elsif Name = ""Xdg_Popup"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Grab""); + Put_Line (File, "" (Object : Xdg_Popup;""); + Put_Line (File, "" Seat : Protocols.Client.Seat'Class;""); + Put_Line (File, "" Serial : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Seat.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Reposition""); + Put_Line (File, "" (Object : Xdg_Popup;""); + Put_Line (File, "" Positioner : Xdg_Shell.Xdg_Positioner'Class;""); + Put_Line (File, "" Token : Unsigned_32)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Positioner.Has_Proxy;""); + end if; + end Handle_Interface_Subprograms_Xdg_Shell; + + procedure Handle_Interface_Events_Xdg_Shell + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if not Exists_Events (Interface_Tag) then + return; + end if; + + Generate_Prefix_Spec_Events; + + if Name = ""Xdg_Wm_Base"" then + Put_Line (File, "" with procedure Ping""); + Put_Line (File, "" (Xdg_Wm_Base : in out Xdg_Shell.Xdg_Wm_Base'Class;""); + Put_Line (File, "" Serial : Unsigned_32);""); + elsif Name = ""Xdg_Surface"" then + Put_Line (File, "" with procedure Configure""); + Put_Line (File, "" (Xdg_Surface : in out Xdg_Shell.Xdg_Surface'Class;""); + Put_Line (File, "" Serial : Unsigned_32);""); + elsif Name = ""Xdg_Toplevel"" then + Put_Line (File, "" with procedure Configure""); + Put_Line (File, "" (Xdg_Toplevel : in out Xdg_Shell.Xdg_Toplevel'Class;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural;""); + Put_Line (File, "" States : State_Array);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Close""); + Put_Line (File, "" (Xdg_Toplevel : in out Xdg_Shell.Xdg_Toplevel'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Configure_Bounds""); + Put_Line (File, "" (Xdg_Toplevel : in out Xdg_Shell.Xdg_Toplevel'Class;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Capabilities""); + Put_Line (File, "" (Xdg_Toplevel : in out Xdg_Shell.Xdg_Toplevel'Class;""); + Put_Line (File, "" Capabilities : Capability_Array);""); + elsif Name = ""Xdg_Popup"" then + Put_Line (File, "" with procedure Configure""); + Put_Line (File, "" (Xdg_Popup : in out Xdg_Shell.Xdg_Popup'Class;""); + Put_Line (File, "" X, Y : Integer;""); + Put_Line (File, "" Width : Natural;""); + Put_Line (File, "" Height : Natural);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Popup_Done""); + Put_Line (File, "" (Xdg_Popup : in out Xdg_Shell.Xdg_Popup'Class) is null;""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Repositioned""); + Put_Line (File, "" (Xdg_Popup : in out Xdg_Shell.Xdg_Popup'Class;""); + Put_Line (File, "" Token : Unsigned_32) is null;""); + end if; + + Generate_Suffix_Spec_Events (Name); + end Handle_Interface_Events_Xdg_Shell; + + procedure Handle_Interface_Subprograms_Presentation_Time + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Name in ""Presentation"" then + Generate_Spec_Bind_Subprogram (Name); + end if; + + if Name = ""Presentation"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Feedback""); + Put_Line (File, "" (Object : Presentation;""); + Put_Line (File, "" Surface : Protocols.Client.Surface'Class;""); + Put_Line (File, "" Feedback : in out Presentation_Feedback'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Surface.Has_Proxy;""); + end if; + end Handle_Interface_Subprograms_Presentation_Time; + + procedure Handle_Interface_Events_Presentation_Time + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if not Exists_Events (Interface_Tag) then + return; + end if; + + Generate_Prefix_Spec_Events; + + if Name = ""Presentation"" then + Put_Line (File, "" with procedure Clock""); + Put_Line (File, "" (Presentation : in out Presentation_Time.Presentation'Class;""); + Put_Line (File, "" Id : Unsigned_32);""); + elsif Name = ""Presentation_Feedback"" then + Put_Line (File, "" with procedure Synchronized_Output""); + Put_Line (File, "" (Presentation_Feedback : in out Presentation_Time.Presentation_Feedback'Class;""); + Put_Line (File, "" Output : Protocols.Client.Output'Class);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Presented""); + Put_Line (File, "" (Presentation_Feedback : in out Presentation_Time.Presentation_Feedback'Class;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Refresh : Duration;""); + Put_Line (File, "" Counter : Unsigned_64;""); + Put_Line (File, "" Flags : Presentation_Feedback_Kind);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Discarded""); + Put_Line (File, "" (Presentation_Feedback : in out Presentation_Time.Presentation_Feedback'Class);""); + end if; + + Generate_Suffix_Spec_Events (Name); + end Handle_Interface_Events_Presentation_Time; + + procedure Handle_Interface_Subprograms_Viewporter + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Name in ""Viewporter"" then + Generate_Spec_Bind_Subprogram (Name); + end if; + + if Name = ""Viewporter"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Viewport""); + Put_Line (File, "" (Object : Viewporter;""); + Put_Line (File, "" Surface : Client.Surface'Class;""); + Put_Line (File, "" Viewport : in out Protocols.Viewporter.Viewport'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Surface.Has_Proxy;""); + elsif Name = ""Viewport"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Source""); + Put_Line (File, "" (Object : Viewport;""); + Put_Line (File, "" X, Y, Width, Height : Fixed)""); + Put_Line (File, "" with Pre => (X = -1.0 and Y = -1.0 and Width = -1.0 and Height = -1.0)""); + Put_Line (File, "" or (Width > 0.0 and Height > 0.0 and X >= 0.0 and Y >= 0.0);""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Destination""); + Put_Line (File, "" (Object : Viewport;""); + Put_Line (File, "" Width, Height : Integer)""); + Put_Line (File, "" with Pre => (Width = -1 and Height = -1) or (Width > 0 and Height > 0);""); + end if; + end Handle_Interface_Subprograms_Viewporter; + + procedure Handle_Interface_Subprogram_Idle_Inhibit + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Name in ""Idle_Inhibit_Manager_V1"" then + Generate_Spec_Bind_Subprogram (Name); + end if; + + if Name = ""Idle_Inhibit_Manager_V1"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Create_Inhibitor""); + Put_Line (File, "" (Object : Idle_Inhibit_Manager_V1;""); + Put_Line (File, "" Surface : Client.Surface'Class;""); + Put_Line (File, "" Inhibitor : in out Idle_Inhibitor_V1'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Surface.Has_Proxy;""); + elsif Name = ""Idle_Inhibitor_V1"" then + null; + end if; + end Handle_Interface_Subprogram_Idle_Inhibit; + + procedure Handle_Interface_Subprogram_Xdg_Decoration + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Name in ""Decoration_Manager_V1"" then + Generate_Spec_Bind_Subprogram (Name); + end if; + + if Name = ""Decoration_Manager_V1"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Toplevel_Decoration""); + Put_Line (File, "" (Object : Decoration_Manager_V1;""); + Put_Line (File, "" Toplevel : Xdg_Shell.Xdg_Toplevel'Class;""); + Put_Line (File, "" Decoration : in out Toplevel_Decoration_V1'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Toplevel.Has_Proxy;""); + elsif Name = ""Toplevel_Decoration_V1"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Mode""); + Put_Line (File, "" (Object : Toplevel_Decoration_V1;""); + Put_Line (File, "" Mode : Toplevel_Decoration_V1_Mode)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Unset_Mode (Object : Toplevel_Decoration_V1)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + end if; + end Handle_Interface_Subprogram_Xdg_Decoration; + + procedure Handle_Interface_Events_Xdg_Decoration + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if not Exists_Events (Interface_Tag) then + return; + end if; + + Generate_Prefix_Spec_Events; + + if Name = ""Toplevel_Decoration_V1"" then + Put_Line (File, "" with procedure Configure""); + Put_Line (File, "" (Decoration : in out Toplevel_Decoration_V1'Class;""); + Put_Line (File, "" Mode : Toplevel_Decoration_V1_Mode);""); + end if; + + Generate_Suffix_Spec_Events (Name); + end Handle_Interface_Events_Xdg_Decoration; + + procedure Handle_Interface_Subprogram_Relative_Pointer + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Name in ""Relative_Pointer_Manager_V1"" then + Generate_Spec_Bind_Subprogram (Name); + end if; + + if Name = ""Relative_Pointer_Manager_V1"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Get_Relative_Pointer""); + Put_Line (File, "" (Object : Relative_Pointer_Manager_V1;""); + Put_Line (File, "" Pointer : Client.Pointer'Class;""); + Put_Line (File, "" Relative : in out Relative_Pointer_V1'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Pointer.Has_Proxy;""); + elsif Name = ""Relative_Pointer_V1"" then + null; + end if; + end Handle_Interface_Subprogram_Relative_Pointer; + + procedure Handle_Interface_Events_Relative_Pointer + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if not Exists_Events (Interface_Tag) then + return; + end if; + + Generate_Prefix_Spec_Events; + + if Name = ""Relative_Pointer_V1"" then + Put_Line (File, "" with procedure Relative_Motion""); + Put_Line (File, "" (Pointer : in out Relative_Pointer_V1'Class;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Dx : Fixed;""); + Put_Line (File, "" Dy : Fixed;""); + Put_Line (File, "" Dx_Unaccel : Fixed;""); + Put_Line (File, "" Dy_Unaccel : Fixed);""); + end if; + + Generate_Suffix_Spec_Events (Name); + end Handle_Interface_Events_Relative_Pointer; + + procedure Handle_Interface_Subprogram_Pointer_Constraints + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Name in ""Pointer_Constraints_V1"" then + Generate_Spec_Bind_Subprogram (Name); + end if; + + if Name = ""Pointer_Constraints_V1"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Lock_Pointer""); + Put_Line (File, "" (Object : Pointer_Constraints_V1;""); + Put_Line (File, "" Surface : Client.Surface'Class;""); + Put_Line (File, "" Pointer : Client.Pointer'Class;""); + Put_Line (File, "" Region : Client.Region'Class;""); + Put_Line (File, "" Lifetime : Pointer_Constraints_V1_Lifetime;""); + Put_Line (File, "" Locked : in out Locked_Pointer_V1'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Surface.Has_Proxy and Pointer.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Confine_Pointer""); + Put_Line (File, "" (Object : Pointer_Constraints_V1;""); + Put_Line (File, "" Surface : Client.Surface'Class;""); + Put_Line (File, "" Pointer : Client.Pointer'Class;""); + Put_Line (File, "" Region : Client.Region'Class;""); + Put_Line (File, "" Lifetime : Pointer_Constraints_V1_Lifetime;""); + Put_Line (File, "" Confined : in out Confined_Pointer_V1'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Surface.Has_Proxy and Pointer.Has_Proxy;""); + elsif Name = ""Locked_Pointer_V1"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Cursor_Position_Hint""); + Put_Line (File, "" (Object : Locked_Pointer_V1;""); + Put_Line (File, "" X, Y : Fixed)""); + Put_Line (File, "" with Pre => Object.Has_Proxy;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Region""); + Put_Line (File, "" (Object : Locked_Pointer_V1;""); + Put_Line (File, "" Region : Client.Region'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Region.Has_Proxy;""); + elsif Name = ""Confined_Pointer_V1"" then + Put_Line (File, """"); + Put_Line (File, "" procedure Set_Region""); + Put_Line (File, "" (Object : Confined_Pointer_V1;""); + Put_Line (File, "" Region : Client.Region'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Region.Has_Proxy;""); + end if; + end Handle_Interface_Subprogram_Pointer_Constraints; + + procedure Handle_Interface_Events_Pointer_Constraints + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if not Exists_Events (Interface_Tag) then + return; + end if; + + Generate_Prefix_Spec_Events; + + if Name = ""Locked_Pointer_V1"" then + Put_Line (File, "" with procedure Locked""); + Put_Line (File, "" (Pointer : in out Locked_Pointer_V1'Class);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Unlocked""); + Put_Line (File, "" (Pointer : in out Locked_Pointer_V1'Class);""); + elsif Name = ""Confined_Pointer_V1"" then + Put_Line (File, "" with procedure Confined""); + Put_Line (File, "" (Pointer : in out Confined_Pointer_V1'Class);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Unconfined""); + Put_Line (File, "" (Pointer : in out Confined_Pointer_V1'Class);""); + end if; + + Generate_Suffix_Spec_Events (Name); + end Handle_Interface_Events_Pointer_Constraints; + + procedure Handle_Interface_Subprogram_Pointer_Gestures + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + procedure Print_Constructor (Name : String) is + begin + Put_Line (File, """"); + Put_Line (File, "" procedure Get_"" & Name & ""_Gesture""); + Put_Line (File, "" (Object : Pointer_Gestures_V1;""); + Put_Line (File, "" Pointer : Client.Pointer'Class;""); + Put_Line (File, "" Gesture : in out Pointer_Gesture_"" & Name & ""_V1'Class)""); + Put_Line (File, "" with Pre => Object.Has_Proxy and Pointer.Has_Proxy;""); + end Print_Constructor; + + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Name in ""Pointer_Gestures_V1"" then + Generate_Spec_Bind_Subprogram (Name); + end if; + + if Name in ""Pointer_Gestures_V1"" then + Print_Constructor (""Swipe""); + Print_Constructor (""Pinch""); + Print_Constructor (""Hold""); + end if; + end Handle_Interface_Subprogram_Pointer_Gestures; + + procedure Handle_Interface_Events_Pointer_Gestures + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if not Exists_Events (Interface_Tag) then + return; + end if; + + Generate_Prefix_Spec_Events; + + if Name = ""Pointer_Gesture_Swipe_V1"" then + Put_Line (File, "" with procedure Gesture_Begin""); + Put_Line (File, "" (Gesture : in out Pointer_Gesture_Swipe_V1'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Surface : Client.Surface;""); + Put_Line (File, "" Fingers : Unsigned_32);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Gesture_Update""); + Put_Line (File, "" (Gesture : in out Pointer_Gesture_Swipe_V1'Class;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Dx, Dy : Fixed);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Gesture_End""); + Put_Line (File, "" (Gesture : in out Pointer_Gesture_Swipe_V1'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Cancelled : Boolean);""); + elsif Name = ""Pointer_Gesture_Pinch_V1"" then + Put_Line (File, "" with procedure Gesture_Begin""); + Put_Line (File, "" (Gesture : in out Pointer_Gesture_Pinch_V1'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Surface : Client.Surface;""); + Put_Line (File, "" Fingers : Unsigned_32);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Gesture_Update""); + Put_Line (File, "" (Gesture : in out Pointer_Gesture_Pinch_V1'Class;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Dx, Dy : Fixed;""); + Put_Line (File, "" Scale : Fixed;""); + Put_Line (File, "" Rotation : Fixed);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Gesture_End""); + Put_Line (File, "" (Gesture : in out Pointer_Gesture_Pinch_V1'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Cancelled : Boolean);""); + elsif Name = ""Pointer_Gesture_Hold_V1"" then + Put_Line (File, "" with procedure Gesture_Begin""); + Put_Line (File, "" (Gesture : in out Pointer_Gesture_Hold_V1'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Surface : Client.Surface;""); + Put_Line (File, "" Fingers : Unsigned_32);""); + Put_Line (File, """"); + Put_Line (File, "" with procedure Gesture_End""); + Put_Line (File, "" (Gesture : in out Pointer_Gesture_Hold_V1'Class;""); + Put_Line (File, "" Serial : Unsigned_32;""); + Put_Line (File, "" Timestamp : Duration;""); + Put_Line (File, "" Cancelled : Boolean);""); + end if; + + Generate_Suffix_Spec_Events (Name); + end Handle_Interface_Events_Pointer_Gestures; + + procedure Handle_Interface_Common_Subprograms + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if Protocol_Name /= ""client"" or Name /= ""Display"" then + Generate_Spec_Destroy_Subprogram (Interface_Tag); + end if; + Generate_Spec_Utility_Functions (Name); + + if Protocol_Name /= ""client"" or Name /= ""Display"" then + Generate_Spec_User_Data_Subprogram (Name); + end if; + end Handle_Interface_Common_Subprograms; + + procedure Handle_Interface_Common_Events + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + if not Exists_Events (Interface_Tag) then + return; + end if; + + Generate_Prefix_Spec_Events; + Put_Line (File, "" -- FIXME Add generic `with procedure`'s here""); + Generate_Suffix_Spec_Events (Name); + end Handle_Interface_Common_Events; + begin + Iterate_Over_Interfaces (Handle_Interface_Common_Subprograms'Access); + + if Protocol_Name = ""client"" then + Iterate_Over_Interfaces (Handle_Interface_Subprograms_Client'Access); + Iterate_Over_Interfaces (Handle_Interface_Events_Client'Access); + elsif Protocol_Name = ""xdg_shell"" then + Iterate_Over_Interfaces (Handle_Interface_Subprograms_Xdg_Shell'Access); + Iterate_Over_Interfaces (Handle_Interface_Events_Xdg_Shell'Access); + elsif Protocol_Name = ""presentation_time"" then + Iterate_Over_Interfaces (Handle_Interface_Subprograms_Presentation_Time'Access); + Iterate_Over_Interfaces (Handle_Interface_Events_Presentation_Time'Access); + elsif Protocol_Name = ""viewporter"" then + Iterate_Over_Interfaces (Handle_Interface_Subprograms_Viewporter'Access); + elsif Protocol_Name = ""idle_inhibit_unstable_v1"" then + Iterate_Over_Interfaces (Handle_Interface_Subprogram_Idle_Inhibit'Access); + elsif Protocol_Name = ""xdg_decoration_unstable_v1"" then + Iterate_Over_Interfaces (Handle_Interface_Subprogram_Xdg_Decoration'Access); + Iterate_Over_Interfaces (Handle_Interface_Events_Xdg_Decoration'Access); + elsif Protocol_Name = ""relative_pointer_unstable_v1"" then + Iterate_Over_Interfaces (Handle_Interface_Subprogram_Relative_Pointer'Access); + Iterate_Over_Interfaces (Handle_Interface_Events_Relative_Pointer'Access); + elsif Protocol_Name = ""pointer_constraints_unstable_v1"" then + Iterate_Over_Interfaces (Handle_Interface_Subprogram_Pointer_Constraints'Access); + Iterate_Over_Interfaces (Handle_Interface_Events_Pointer_Constraints'Access); + elsif Protocol_Name = ""pointer_gestures_unstable_v1"" then + Iterate_Over_Interfaces (Handle_Interface_Subprogram_Pointer_Gestures'Access); + Iterate_Over_Interfaces (Handle_Interface_Events_Pointer_Gestures'Access); + else + Iterate_Over_Interfaces (Handle_Interface_Common_Events'Access); + end if; + end Generate_Manually_Edited_Partial_Type_Declarations; + + procedure Create_Wl_Thin_Spec_File (Protocol_Name : String) is + + procedure Generate_Code_For_Interface_Constants is + procedure Handle_Interface (Interface_Tag : aliased Wayland_XML.Interface_Tag) is + Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag) & ""_Interface""); + begin + if not Generate_Interfaces_For_Client and Protocol_Name = ""client"" then + Put_Line (File, "" "" & Name & "" : aliased constant Interface_T""); + Put_Line (File, "" with Import, Convention => C, External_Name => """""" & Wayland_XML.Name (Interface_Tag) & ""_interface"""";""); + New_Line (File); + else + Put_Line (File, "" "" & Name & "" : aliased constant Interface_T;""); + end if; + end Handle_Interface; + begin + Iterate_Over_Interfaces (Handle_Interface'Access); + end Generate_Code_For_Interface_Constants; + + procedure Generate_Private_Code_For_Interface_Constants is + type Partial_Match (Is_Match : Boolean) is record + case Is_Match is + when True => null; + when False => Index : Positive; + end case; + end record; + + type Match (Is_Match : Boolean) is record + case Is_Match is + when False => null; + when True => Index : Positive; + end case; + end record; + + function Contains_At_Index + (Index : Positive; + Vector, Sub_Vector : Unbounded_String_Vectors.Vector) return Partial_Match + is + use type SU.Unbounded_String; + begin + for Sub_Index in Sub_Vector.First_Index .. Sub_Vector.Last_Index loop + declare + Vector_Index : constant Positive := Index + (Sub_Index - Sub_Vector.First_Index); + begin + if Vector_Index > Vector.Last_Index or else Sub_Vector (Sub_Index) /= Vector (Vector_Index) then + return (Is_Match => False, Index => Sub_Index); + end if;" +procedure Generate_Code_For_Interface_Ptrs is,"procedure Handle_Interface (Interface_Tag : aliased Wayland_XML.Interface_Tag) is + Interface_Ptr_Name : constant String := + Xml_Parser_Utils.Adaify_Name (Name (Interface_Tag)) & ""_Ptr""; + begin + if Interface_Ptr_Name /= ""Display_Ptr"" then + Put_Line (File, "" type "" & Interface_Ptr_Name & "" is new Proxy_Ptr;""); + New_Line (File); + end if; + end Handle_Interface; + begin + Iterate_Over_Interfaces (Handle_Interface'Access); + end Generate_Code_For_Interface_Ptrs; + + procedure Generate_Code_For_Each_Interface is + + procedure Handle_Interface + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + procedure Generate_Code_For_Subprogram_Ptrs is + + procedure Generate_Code_For_Subprogram + (Event_Tag : aliased Wayland_XML.Event_Tag) + is + V : Wayland_XML.Event_Child_Vectors.Vector; + + Subprogram_Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Name (Interface_Tag) & ""_"" & Name (Event_Tag) & ""_Subprogram_Ptr""); + Interface_Name : constant String + := Xml_Parser_Utils.Adaify_Name (Name (Interface_Tag)); + begin + for Child of Wayland_XML.Children (Event_Tag) loop + if Child.Kind_Id = Child_Arg then + V.Append (Child); + end if; + end loop; + + declare + Max_Name_Length : Natural := Interface_Name'Length; + Dont_Care : String_Maps.Map; + begin + for Child of V loop + declare + Arg_Name : constant String + := Xml_Parser_Utils.Adaify_Variable_Name (Name (Child.Arg_Tag.all)); + begin + Max_Name_Length := Natural'Max (Max_Name_Length, Arg_Name'Length);" +procedure Generate_Code_For_Listener_Type_Definition is,"function Get_Name (Event_Tag : Wayland_XML.Event_Tag) return String is + (Xml_Parser_Utils.Adaify_Name (Name (Event_Tag))); + + Name_Length : Natural := 0; + + procedure Generate_Code_For_Record_Component + (Event_Tag : aliased Wayland_XML.Event_Tag) + is + Component_Name : constant String := Get_Name (Event_Tag); + + Component_Type_Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Name (Interface_Tag) & ""_"" & + Name (Event_Tag) & ""_Subprogram_Ptr""); + + Component_Name_Aligned : constant String := SF.Head (Component_Name & (if Is_Reserved_Keyword (Component_Name) then ""_F"" else """"), Name_Length, ' '); + + use type Wayland_XML.Version_Number; + begin + -- Patch out events from wl_output that exist since v4 because + -- the high level bindings assume v3 + if Wayland_XML.Name (Interface_Tag) = ""wl_output"" + and (Exists_Since (Event_Tag) and then Since (Event_Tag) >= 4) + then + return; + end if; + + Put_Line (File, "" "" & Component_Name_Aligned & "" : "" & Component_Type_Name & "";""); + end Generate_Code_For_Record_Component; + + Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag) & ""_Listener_T""); + Ptr_Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag) & ""_Listener_Ptr""); + begin + Put_Line (File, "" type "" & Name & "" is record""); + + for Child of Children (Interface_Tag) loop + if Child.Kind_Id = Child_Event then + declare + Arg_Name : constant String := Get_Name (Child.Event_Tag.all); + begin + Name_Length := Natural'Max (Name_Length, Arg_Name'Length + (if Is_Reserved_Keyword (Arg_Name) then 2 else 0));" +procedure Generate_Code_For_Add_Listener_Subprogram_Declaration is,"Ptr_Listener_Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag) & ""_Listener_Ptr""); + begin + Generate_Pretty_Code_For_Subprogram + (File, Declaration, Interface_Tag, ""Add_Listener"", ""Interfaces.C.int"", + ((+""Listener"", +Ptr_Listener_Name), + (+""Data"", +""Void_Ptr""))); + end Generate_Code_For_Add_Listener_Subprogram_Declaration; + + procedure Generate_Code_For_Set_User_Data_Subprogram_Declaration is + begin + Generate_Pretty_Code_For_Subprogram + (File, Declaration, Interface_Tag, ""Set_User_Data"", """", + (1 => (+""Data"", +""Void_Ptr""))); + end Generate_Code_For_Set_User_Data_Subprogram_Declaration; + + procedure Generate_Code_For_Get_User_Data_Subprogram_Declaration is + begin + Generate_Pretty_Code_For_Subprogram + (File, Declaration, Interface_Tag, ""Get_User_Data"", ""Void_Ptr""); + end Generate_Code_For_Get_User_Data_Subprogram_Declaration; + + procedure Generate_Code_For_Get_ID_Subprogram_Declaration is + begin + Generate_Pretty_Code_For_Subprogram + (File, Declaration, Interface_Tag, ""Get_ID"", ""Unsigned_32""); + end Generate_Code_For_Get_ID_Subprogram_Declaration; + + procedure Generate_Code_For_Get_Version_Subprogram_Declaration is + begin + Generate_Pretty_Code_For_Subprogram + (File, Declaration, Interface_Tag, ""Get_Version"", ""Unsigned_32""); + end Generate_Code_For_Get_Version_Subprogram_Declaration; + + procedure Generate_Code_For_Destroy_Subprogram_Declaration is + begin + Generate_Pretty_Code_For_Subprogram + (File, Declaration, Interface_Tag, ""Destroy"", """"); + end Generate_Code_For_Destroy_Subprogram_Declaration; + + procedure Generate_Code_For_Requests is + + procedure Generate_Code_For_Subprogram_Declaration + (Request_Tag : aliased Wayland_XML.Request_Tag) + is + procedure Generate_Comment (Text : String) is + Interval_Identifier : constant Xml_Parser_Utils.Interval_Identifier := Xml_Parser_Utils.Make (Text); + begin + for Interval of Interval_Identifier.Intervals loop + declare + Comment : constant String := Trim (Text (Interval.First .. Interval.Last)); + begin + if Comment'Length > 0 then + Put_Line (File, "" -- "" & Comment); + else + Put_Line (File, "" --""); + end if;" +"Put_Line (File, "" function Display_Connect return Display_Ptr;"");","Put_Line (File, """"); + Put_Line (File, "" procedure Display_Disconnect (This : in out Display_Ptr);""); + elsif Protocol_Name = ""xdg_decoration_unstable_v1"" then + Put_Line (File, "" use Wayland.Protocols.Thin_Xdg_Shell;""); + else + Put_Line (File, "" use Wayland.Protocols.Thin_Client;""); + end if; + Put_Line (File, """"); + Generate_Code_For_Interface_Constants; + if Generate_Interfaces_For_Client or Protocol_Name /= ""client"" then + New_Line (File); + Put_Line (File, "" procedure Initialize;""); + New_Line (File); + end if; + + Generate_Code_For_Interface_Ptrs; + Generate_Code_For_Each_Interface; + + if Generate_Interfaces_For_Client or Protocol_Name /= ""client"" then + Put_Line (File, ""private""); + New_Line (File); + + Generate_Private_Code_For_Interface_Constants; + New_Line (File); + end if; + end Create_Wl_Thin_Spec_File; + + procedure Generate_Use_Type_Declarions (Package_Name : String) is + procedure Handle_Interface (Interface_Tag : aliased Wayland_XML.Interface_Tag) is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + Put_Line (File, "" use type Thin."" & Name & ""_Ptr;""); + end Handle_Interface; + begin + Put_Line (File, "" package Thin renames Wayland.Protocols.Thin_"" & Package_Name & "";""); + Put_Line (File, """"); + Iterate_Over_Interfaces (Handle_Interface'Access); + end Generate_Use_Type_Declarions; + + procedure Generate_Manually_Edited_Code_For_Type_Definitions is + procedure Handle_Interface (Interface_Tag : aliased Wayland_XML.Interface_Tag) is + Name : constant String + := Xml_Parser_Utils.Adaify_Name (Wayland_XML.Name (Interface_Tag)); + begin + Put_Line (File, """"); + Put_Line (File, "" type "" & Name & "" is tagged limited record""); + Put_Line (File, "" Proxy : Thin."" & Name & ""_Ptr;""); + Put_Line (File, "" end record;""); + -- FIXME add Initialized : Boolean := Thin.Initialize; for Xdg_Wm_Base and Wp_Presentation + end Handle_Interface; + begin + Iterate_Over_Interfaces (Handle_Interface'Access); + end Generate_Manually_Edited_Code_For_Type_Definitions; + + procedure Generate_Private_Code_For_The_Interface_Constants is + procedure Handle_Interface (Interface_Tag : aliased Wayland_XML.Interface_Tag) is + Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag) & ""_Interface""); + begin + Put_Line (File, """"); + Put_Line (File, "" "" & Name & "" : constant Interface_Type :=""); + Put_Line (File, "" (My_Interface => Thin."" & Name & ""'Access);""); + end Handle_Interface; + begin + Iterate_Over_Interfaces (Handle_Interface'Access); + end Generate_Private_Code_For_The_Interface_Constants; + + begin + Create_File; + end Create_Wayland_Spec_File; + + procedure Create_Wayland_Body_File is + File : Ada.Text_IO.File_Type; + + procedure Create_Wl_Thin_Body_File; + + procedure Generate_Manually_Edited_Code (Protocol_Name : String); + + procedure Create_File is + Protocol_Name : constant String := Get_Protocol_Name (Name (Protocol_Tag.all)); + Package_Name : constant String := Xml_Parser_Utils.Adaify_Name (Protocol_Name); + begin + Ada.Text_IO.Create + (File, Ada.Text_IO.Out_File, + ""wayland-protocols-"" & Protocol_Name & "".adb""); + + -- TODO Do not import System.Address_To_Access_Conversions if + -- there are no generic *_Events packages + Put_Line (File, ""with System.Address_To_Access_Conversions;""); + New_Line (File); + + if Protocol_Name = ""client"" then + Put_Line (File, ""with Interfaces.C.Strings;""); + New_Line (File); + Put_Line (File, ""with Wayland.Posix;""); + elsif Protocol_Name in ""presentation_time"" | ""relative_pointer_unstable_v1"" then + Put_Line (File, ""with Ada.Unchecked_Conversion;""); + Put_Line (File, """"); + Put_Line (File, ""with Wayland.Protocols.Thin_Client;""); + elsif Protocol_Name = ""xdg_decoration_unstable_v1"" then + Put_Line (File, ""with Wayland.Protocols.Thin_Xdg_Shell;""); + else + Put_Line (File, ""with Wayland.Protocols.Thin_Client;""); + end if; + + New_Line (File); + Put_Line (File, ""package body Wayland.Protocols."" & Package_Name & "" is""); + New_Line (File); + + if Generate_Interfaces_For_Client or Protocol_Name /= ""client"" then + Put_Line (File, "" procedure Initialize renames Thin.Initialize;""); + Put_Line (File, """"); + end if; + + if Protocol_Name = ""client"" then + Put_Line (File, "" package body Constructors is""); + Put_Line (File, "" function Set_Proxy (Proxy : Secret_Proxy) return Buffer is""); + Put_Line (File, "" (Proxy => Thin.Buffer_Ptr (Proxy));""); + Put_Line (File, """"); + Put_Line (File, "" function Set_Proxy (Proxy : Secret_Proxy) return Output is""); + Put_Line (File, "" (Proxy => Thin.Output_Ptr (Proxy));""); + Put_Line (File, """"); + Put_Line (File, "" function Set_Proxy (Proxy : Secret_Proxy) return Surface is""); + Put_Line (File, "" (Proxy => Thin.Surface_Ptr (Proxy));""); + Put_Line (File, "" end Constructors;""); + Put_Line (File, """"); + end if; + + Generate_Manually_Edited_Code (Protocol_Name); + + Put_Line (File, ""end Wayland.Protocols."" & Package_Name & "";""); + + Ada.Text_IO.Close (File); + + ----------------------------------------------------------------------- + + Ada.Text_IO.Create + (File, Ada.Text_IO.Out_File, + ""wayland-protocols-thin_"" & Protocol_Name & "".adb""); + + Put_Line (File, ""with Ada.Unchecked_Conversion;""); + Put_Line (File, """"); + Put_Line (File, ""package body Wayland.Protocols.Thin_"" & Package_Name & "" is""); + Put_Line (File, """"); + + if Generate_Interfaces_For_Client or Protocol_Name /= ""client"" then + Put_Line (File, "" procedure Initialize is""); + Put_Line (File, "" begin""); + + Put_Line (File, "" Interface_Pointers :=""); + for Index in All_Types.First_Index .. All_Types.Last_Index loop + declare + Value : constant String := +All_Types (Index); + + Prefix : constant String := (if Index = All_Types.First_Index then ""("" else "" ""); + Suffix : constant String := (if Index = All_Types.Last_Index then "");"" else "",""); + begin + Put_Line (File, "" "" & Prefix & (if Value'Length > 0 then Xml_Parser_Utils.Adaify_Name (Value) & ""_Interface'Access"" else ""null"") & Suffix);" +"Put_Line (File, "" function Display_Connect return Display_Ptr is"");","Put_Line (File, "" begin""); + Put_Line (File, "" return Wayland.API.Display_Connect (Interfaces.C.Strings.Null_Ptr);""); + Put_Line (File, "" end Display_Connect;""); + Put_Line (File, """"); + Put_Line (File, "" procedure Display_Disconnect (This : in out Display_Ptr) is""); + Put_Line (File, "" use type Wayland.API.Display_Ptr;""); + Put_Line (File, "" begin""); + Put_Line (File, "" if This /= null then""); + Put_Line (File, "" Wayland.API.Display_Disconnect (This);""); + Put_Line (File, "" This := null;""); + Put_Line (File, "" end if;""); + Put_Line (File, "" end Display_Disconnect;""); + end if; + + Create_Wl_Thin_Body_File; + + Put_Line (File, """"); + Put_Line (File, ""end Wayland.Protocols.Thin_"" & Package_Name & "";""); + + Ada.Text_IO.Close (File); + end Create_File; + + procedure Create_Wl_Thin_Body_File is + + procedure Generate_Code_For_Protocol_Tag_Children is + procedure Handle_Interface + (Interface_Tag : aliased Wayland_XML.Interface_Tag) + is + procedure Generate_Code_For_Add_Listener_Subprogram_Implementations (Name : String) is + Ptr_Listener_Name : constant String := Name & ""_Listener_Ptr""; + begin + Generate_Pretty_Code_For_Subprogram + (File, Implementation, Interface_Tag, ""Add_Listener"", ""Interfaces.C.int"", + ((+""Listener"", +Ptr_Listener_Name), + (+""Data"", +""Void_Ptr""))); + Put_Line (File, "" begin""); + Put_Line (File, "" return Wayland.API.Proxy_Add_Listener""); + Put_Line (File, "" ("" & Name & "".all, Listener.all'Address, Data);""); + Put_Line (File, "" end "" & Name & ""_Add_Listener;""); + end Generate_Code_For_Add_Listener_Subprogram_Implementations; + + procedure Generate_Code_For_Set_User_Data_Subprogram_Implementations (Name : String) is + begin + Generate_Pretty_Code_For_Subprogram + (File, Implementation, Interface_Tag, ""Set_User_Data"", """", + (1 => (+""Data"", +""Void_Ptr""))); + Put_Line (File, "" begin""); + Put_Line (File, "" Wayland.API.Proxy_Set_User_Data ("" & Name & "".all, Data);""); + Put_Line (File, "" end "" & Name & ""_Set_User_Data;""); + end Generate_Code_For_Set_User_Data_Subprogram_Implementations; + + procedure Generate_Code_For_Get_User_Data_Subprogram_Implementations (Name : String) is + begin + Generate_Pretty_Code_For_Subprogram + (File, Implementation, Interface_Tag, ""Get_User_Data"", ""Void_Ptr""); + Put_Line (File, "" begin""); + Put_Line (File, "" return Wayland.API.Proxy_Get_User_Data ("" & Name & "".all);""); + Put_Line (File, "" end "" & Name & ""_Get_User_Data;""); + end Generate_Code_For_Get_User_Data_Subprogram_Implementations; + + procedure Generate_Code_For_Get_ID_Subprogram_Implementations (Name : String) is + begin + Generate_Pretty_Code_For_Subprogram + (File, Implementation, Interface_Tag, ""Get_ID"", ""Unsigned_32""); + Put_Line (File, "" begin""); + Put_Line (File, "" return Wayland.API.Proxy_Get_Id ("" & Name & "".all);""); + Put_Line (File, "" end "" & Name & ""_Get_ID;""); + end Generate_Code_For_Get_ID_Subprogram_Implementations; + + procedure Generate_Code_For_Get_Version_Subprogram_Implementations (Name : String) is + begin + Generate_Pretty_Code_For_Subprogram + (File, Implementation, Interface_Tag, ""Get_Version"", ""Unsigned_32""); + Put_Line (File, "" begin""); + Put_Line (File, "" return Wayland.API.Proxy_Get_Version ("" & Name & "".all);""); + Put_Line (File, "" end "" & Name & ""_Get_Version;""); + end Generate_Code_For_Get_Version_Subprogram_Implementations; + + procedure Generate_Code_For_Destroy_Subprogram_Implementations (Name : String) is + begin + Generate_Pretty_Code_For_Subprogram + (File, Implementation, Interface_Tag, ""Destroy"", """"); + Put_Line (File, "" begin""); + Put_Line (File, "" Wayland.API.Proxy_Destroy ("" & Name & "".all);""); + Put_Line (File, "" end "" & Name & ""_Destroy;""); + end Generate_Code_For_Destroy_Subprogram_Implementations; + + procedure Generate_Code_For_Requests is + + procedure Generate_Code_For_Subprogram_Implementation + (Request_Tag : aliased Wayland_XML.Request_Tag) + is + Request_Name : constant String := + Xml_Parser_Utils.Adaify_Name (Name (Request_Tag)); + + Subprogram_Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Name (Interface_Tag) & ""_"" & Request_Name); + Opcode : constant String := ""Constants."" & Subprogram_Name; + Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag)); + Ptr_Name : constant String + := Xml_Parser_Utils.Adaify_Name + (Wayland_XML.Name (Interface_Tag) & ""_Ptr""); + + procedure Generate_Arguments (Spaces : Natural; Null_Id : Boolean) is + use SF; + + function Get_Value (Child : Wayland_XML.Arg_Tag; Value : String) return String is + (if Exists_Enum (Child) then ""Convert ("" & Value & "")"" else Value); + + First_Element : Boolean := True; + begin + for Child of Children (Request_Tag) loop + if Child.Kind_Id = Child_Arg then + if not First_Element then + Put_Line (File, "",""); + end if; + First_Element := False; + if Type_Attribute (Child.Arg_Tag.all) /= Type_Object then + if Type_Attribute (Child.Arg_Tag.all) = Type_New_Id then + if Null_Id then + Put (File, Spaces * "" "" & ""0""); + end if; + else + Put (File, Spaces * "" "" & Get_Value (Child.Arg_Tag.all, Xml_Parser_Utils.Adaify_Variable_Name (Wayland_XML.Name (Child.Arg_Tag.all)))); + end if; + else + Put (File, Spaces * "" "" & ""Proxy_Ptr ("" & Get_Value (Child.Arg_Tag.all, Xml_Parser_Utils.Adaify_Variable_Name (Wayland_XML.Name (Child.Arg_Tag.all))) & "")""); + end if; + end if; + end loop; + end Generate_Arguments; + + procedure Generate_Code_Before_Arguments is + Interface_Name : constant String := Xml_Parser_Utils.Adaify_Name + (Xml_Parser_Utils.Find_Specified_Interface (Request_Tag)) & ""_Interface""; + begin + Put_Line (File, "" P : constant Proxy_Ptr :=""); + Put_Line (File, "" Wayland.API.Proxy_Marshal_Constructor""); + Put_Line (File, "" ("" & Name & "".all,""); + Put_Line (File, "" "" & Opcode & "",""); + Put_Line (File, "" "" & Interface_Name & ""'Access,""); + end Generate_Code_Before_Arguments; + + procedure Generate_Code_After_Arguments is + begin + Put_Line (File, "");""); + Put_Line (File, "" begin""); + Put_Line (File, "" return (if P /= null then P.all'Access else null);""); + Put_Line (File, "" end "" & Subprogram_Name & "";""); + end Generate_Code_After_Arguments; + + Enum_Types : String_Maps.Map; + + procedure Generate_Conversion_Code_For_Args is + procedure Generate_Convert (Cursor : String_Maps.Cursor) is + From : constant String := String_Maps.Key (Cursor); + To : constant String := String_Maps.Element (Cursor); + begin + Put_Line (File, "" function Convert is new Ada.Unchecked_Conversion""); + Put_Line (File, "" ("" & From & "", "" & To & "");""); + end Generate_Convert; + begin + Enum_Types.Iterate (Generate_Convert'Access); + end Generate_Conversion_Code_For_Args; + + V : Wayland_XML.Request_Child_Vectors.Vector; + + Max_Name_Length : Natural := Name'Length; + + function Align (Value : String) return String is (SF.Head (Value, Max_Name_Length, ' ')); + begin + Put_Line (File, """"); + if Xml_Parser_Utils.Is_New_Id_Argument_Present (Request_Tag) then + if Xml_Parser_Utils.Is_Interface_Specified (Request_Tag) then + declare + Return_Type : constant String := Xml_Parser_Utils.Adaify_Name + (Xml_Parser_Utils.Find_Specified_Interface (Request_Tag) & ""_Ptr""); + begin + Get_Max_Arg_Length (Request_Tag, V, Max_Name_Length); + + if Xml_Parser_Utils.Number_Of_Args (Request_Tag) > 1 then + Put_Line (File, "" function "" & Subprogram_Name); + Put_Line (File, "" ("" & Align (Name) & "" : "" & Ptr_Name & "";""); + + for Child of V loop + if Child.Kind_Id = Child_Arg then + Generate_Code_For_Arg + (File, + Interface_Tag, + Child.Arg_Tag.all, + Max_Name_Length, + Child = V.Last_Element, + Enum_Types); + end if; + end loop; + + Put_Line (File, "" return "" & Return_Type); + Put_Line (File, "" is""); + Generate_Conversion_Code_For_Args; + if not Enum_Types.Is_Empty then + Put_Line (File, """"); + end if; + else + if 27 + Subprogram_Name'Length + Name'Length + Ptr_Name'Length + Return_Type'Length <= Max_Line_Length then + Put_Line (File, "" function "" & Subprogram_Name & "" ("" & Name & "" : "" & Ptr_Name & "") return "" & Return_Type & "" is""); + else + Put_Line (File, "" function "" & Subprogram_Name); + Put_Line (File, "" ("" & Name & "" : "" & Ptr_Name & "") return "" & Return_Type); + Put_Line (File, "" is""); + end if; + end if; + Generate_Code_Before_Arguments; + Generate_Arguments (11, True); + Generate_Code_After_Arguments;" +procedure Print_Active_Map is,"C: Active_Clients.Cursor := Active_Clients.First(Active_Map); + EP_Image: ASU.Unbounded_String; + begin + Ada.Text_IO.Put_Line (""ACTIVE CLIENTS""); + Ada.Text_IO.Put_Line (""==============""); + + while Active_Clients.Has_Element(C) loop + EP_Image := ASU.To_Unbounded_String(LLU.Image(Active_Clients.Element + (C).Value.Client_EP)); + + Ada.Text_IO.Put_Line (ASU.To_String(Active_Clients.Element(C).Key) & + "" "" & + ASU.To_String(Format_EP(EP_Image)) & "" "" & + Time_Image(Active_Clients.Element(C).Value.Time)); + + Active_Clients.Next(C); + end loop; + ATI.New_Line; + end Print_Active_Map; + + procedure Print_Old_Map is + C: Old_Clients.Cursor := Old_Clients.First(Old_Map); + begin + Ada.Text_IO.Put_Line (""OLD CLIENTS""); + Ada.Text_IO.Put_Line (""===========""); + + while Old_Clients.Has_Element(C) loop + Ada.Text_IO.Put_Line (ASU.To_String(Old_Clients.Element(C).Key) & + "": "" & Time_Image(Old_Clients.Element(C).Value)); + + Old_Clients.Next(C); + end loop; + ATI.New_Line; + end Print_Old_Map; + + + function Client_To_Ban (Active_Map: Active_Clients.Map) return ASU.Unbounded_String is + + C: Active_Clients.Cursor := Active_Clients.First(Active_Map); + Min_Time: Ada.Calendar.Time; + Nick: ASU.Unbounded_String; + begin + Min_Time := Active_Clients.Element(C).Value.Time; + Nick := Active_Clients.Element(C).Key; + while Active_Clients.Has_Element(C) loop + + if Active_Clients.Element(C).Value.Time < Min_Time then + + Nick := Active_Clients.Element(C).Key; + + end if; + Active_Clients.Next(C); + end loop; + return Nick; + end Client_To_Ban; + + procedure Server_To_All (Comment: ASU.Unbounded_String; + O_Buffer: access LLU.Buffer_Type) is + + C: Active_Clients.Cursor := Active_Clients.First(Active_Map); + Nick: ASU.Unbounded_String := ASU.To_Unbounded_String(""Server""); + + begin + while Active_Clients.Has_Element(C) loop + + CM.Server_Message (Active_Clients.Element(C).Value.Client_EP, + Nick,Comment,O_Buffer); + + Active_Clients.Next(C); + end loop; + end Server_To_All; + + procedure Case_Init (I_Buffer: access LLU.Buffer_Type; + O_Buffer: access LLU.Buffer_Type) is + + Client_EP_Receive: LLU.End_Point_Type; + Client_EP_Handler: LLU.End_Point_Type; + Nick: ASU.Unbounded_String; + Ban_Nick: ASU.Unbounded_String; + Comment: ASU.Unbounded_String; + Logout_Time: Ada.Calendar.Time; + Client_Data: Data; + Accepted: Boolean; + Success: Boolean; + begin + + Client_EP_Receive := LLU.End_Point_Type'Input (I_Buffer); + Client_EP_Handler := LLU.End_Point_Type'Input (I_Buffer); + Nick := ASU.Unbounded_String'Input (I_Buffer); + + Active_Clients.Get(Active_Map,Nick,Client_Data,Success); + + if Success then + Accepted := False; + ATI.Put_Line(""INIT received from "" & ASU.To_String(Nick) + & "": IGNORED. nick already used""); + else + ATI.Put_Line(""INIT received from "" & ASU.To_String(Nick) + & "": ACCEPTED""); + begin + Accepted := True; + Client_Data.Client_EP := Client_EP_Handler; + Client_Data.Time := Ada.Calendar.Clock; + + Active_Clients.Put (Active_Map,Nick,Client_Data); + + exception + when Active_Clients.Full_Map => + + Ban_Nick := Client_To_Ban(Active_Map); + Logout_Time := Ada.Calendar.Clock; + + Old_Clients.Put (Old_Map,Ban_Nick,Logout_Time); + + Comment := ASU.To_Unbounded_String(ASU.To_String(Ban_Nick) + & "" banned for being idle too long""); + + Server_To_All (Comment,O_Buffer); + + Active_Clients.Delete (Active_Map,Ban_Nick,Success); + + Active_Clients.Put (Active_Map,Nick,Client_Data);" +procedure main is,"inputFname : unbounded_string; + outputFname : unbounded_string; + img : image; + processedImg :imageprocess.image; + userSelection : character; + + -- function which gets and validates file name + function getFilename(RWIndicator: in String) return Unbounded_String is + + inputFname : unbounded_string; + outputFname : unbounded_string; + ans: character; + outfp: file_type; + + begin + + -- hanldle file writing + if RWindicator = ""W"" then + + Put_Line (""Enter file name to write: ""); + get_line(outputFname); + + if exists(to_string(outputFname)) then + put_line(""File exists - overwrite (Y/N)? ""); + get(ans); + + if ans = 'Y' then + return outputFname; + else + put_line(""Exiting - image not saved""); + GNAT.OS_Lib.OS_Exit (0); + end if; + + end if; + + return outputFname; + + end if; + + --handle file reading + if RWindicator = ""R"" then + Put_Line (""Enter file name to read: ""); + get_line(inputFname); + + if not exists(to_string(inputFname)) then + put_line(""File does not exist: exiting - image not saved""); + GNAT.OS_Lib.OS_Exit (0); + end if; + + end if; + + return inputFname;" +function histEQUAL(img: in image) return image is,"equalImage : image; + type histArray is Array(1..256) of integer; + type CHIntArray is Array(1..256) of integer; + type cumuHistArray is Array(1..256) of Float; + type PDFArray is Array(1..256) of Float; + + cumuHistArray1 : cumuHistArray; + histArray1 : histArray; + PDFArray1 : PDFArray; + CHIntArray1 : CHIntArray; + totalPixels : integer; + + begin + + equalImage.dx := img.dx; + equalImage.dy := img.dy; + + --calculate the total number of pixels in the image + totalPixels := equalImage.dx * equalImage.dy; + + --create a histogram distribution array + for n in 1..256 loop + histArray1(n) := 0; + cumuHistArray1(n) := 0.0; + PDFArray1(n) := 0.0; + CHIntArray1(n) := 0; + end loop; + + for m in 1..256 loop + for i in 1..img.dx loop + for j in 1..img.dy loop + if img.pixel(i,j) = m then + histArray1(m) := histArray1(m) + 1; + end if; + end loop; + end loop; + end loop; + + --Populate Probability Density Arr + for m in 1..256 loop + PDFArray1(m) := (Float(histArray1(m))) / (Float(totalPixels)); + end loop; + + --Calculate Cumulative Histogram + cumuHistArray1(1) := PDFArray1(1); + for m in 2..256 loop + cumuHistArray1(m) := PDFArray1(m) + cumuHistArray1(m-1); + end loop; + + --multiply the CH by 255 and round, forming a new integer array + for m in 1..256 loop + CHIntArray1(m) := Integer(cumuHistArray1(m) * 255.0); + end loop; + + --map the new greyscale values to a histogram record + for i in 1..img.dx loop + for j in 1..img.dy loop + equalImage.pixel(i,j) := CHIntArray1(img.pixel(i,j)); + end loop; + end loop; + + return equalImage;" +procedure Remove_Target is,"use AAA.Strings; + begin + for I in Lines.First_Index .. Lines.Last_Index loop + declare + Line : constant String := Replace (Lines (I), "" "", """"); + begin + + if Armed and then Has_Prefix (Line, Target) then + Found := True; + Lines.Delete (I); + exit; + + elsif Has_Prefix (Line, ""[["") then + -- Detect a plain [[array]] with optional comment + Armed := + Line = Enter_Marker or else + Has_Prefix (Line, Enter_Marker & '#'); + + elsif Armed and then Line /= """" and then + Line (Line'First) /= '[' -- not a table or different array + then + -- We are seeing a different entry in the same array + -- entry; we can still remove our target if later found + -- in this entry. + null; + + elsif Line = """" or else Has_Prefix (Line, ""#"") then + -- We still can remove an entry found in this array entry + null; + + else + -- Any other sighting complicates matters and we won't + -- touch it. + Armed := False; + + -- TODO: be able to remove a table in the array named as + -- Entry, i.e., something like: + -- [[array]] + -- [array.entry] or [array.entry.etc] + -- etc + + -- Or, be able to remove something like + -- [[array]] + -- entry.field = ... + end if;" +procedure Remove_Empty_Arrays is,"-- This might probably be done with multiline regular expressions + + Deletable : Natural := 0; + -- Tracks how many empty lines we have seen since the last [[ + + Can_Delete : Boolean := True; + -- We can delete as long as we are only seeing empty lines + + use AAA.Strings; + begin + + -- Traverse lines backwards + + for I in reverse Lines.First_Index .. Lines.Last_Index loop + declare + Line : constant String := Replace (Lines (I), "" "", """"); + begin + if Can_Delete then + -- Look for empty lines or the opening [[array]] + if Line = """" then + Deletable := Deletable + 1; + + elsif + Line = Enter_Marker or else + Has_Prefix (Line, Enter_Marker & '#') + then + -- Now we can delete the empty [[array]] plus any + -- following empty lines. + for J in 0 .. Deletable loop -- 0 for the current line + Lines.Delete (I); + end loop; + + -- Restart, we can still delete previous entries + Deletable := 0; + + else + -- We found something else, so do not remove entry + Can_Delete := False; + Deletable := 0; + end if; + + else + -- Look for a [[ that starts another array entry. We + -- cannot rely on simply [ for tables, these could be + -- nested array tables. + if Has_Prefix (Line, ""[["") then + Can_Delete := True; + Deletable := 0; + -- We will look in next iterations for a precedent + -- empty array entry. + end if; + end if;" +procedure Day_02 is,"Mem: constant Memory.Block := Memory.Read_Comma_Separated; + M: aliased Intcode.Machine(Hi_Mem => Mem'Last); + + use type Memory.Value; + subtype Input is Memory.Value range 0..99; +begin + for Noun in Input'Range loop + for Verb in Input'Range loop + M.Mem := Mem; + M.Mem(16#1#) := Noun; + M.Mem(16#2#) := Verb; + declare + E: Intcode.Executor(M'Access); + begin + null; -- wait for E to terminate" +procedure Day_06 is,"subtype Name is String(1 .. 3); + You: constant Name := ""YOU""; + Santa: constant Name := ""SAN""; + + type Orbit is record + Self, Parent: Name; + end record; + + type Chain is array (Positive range <>) of Name; + + package Orbits is new Ada.Containers.Ordered_Maps( + Key_Type => Name, Element_Type => Orbit); + Locals: Orbits.Map; + + function Get(S: String) return Orbit is + begin + for I in S'Range loop + if S(I) = ')' then + return (Parent => S(S'First .. I - 1), Self => S(I + 1 .. S'Last)); + end if; + end loop; + raise Constraint_Error with ""orbit missing ')': "" & S; + end Get; + + function Count_Orbits(O: Orbit) return Positive is + E: constant Orbits.Cursor := Locals.Find(O.Parent); + use type Orbits.Cursor; + begin + if E = Orbits.No_Element then + return 1; -- only a direct orbit + else + return 1 + Count_Orbits(Orbits.Element(E)); + end if; + end Count_Orbits; + + function Ancestors(O: Orbit) return Chain is + Size : constant Natural := Count_Orbits(O) - 1; + C: Chain(1 .. Size); + Curr: Orbit := O; + begin + for I in C'Range loop + C(I) := Curr.Parent; + Curr := Locals.Element(Curr.Parent); + end loop; + return C; + end Ancestors; + +begin + while (not Ada.Text_IO.End_Of_File) loop + declare + O: constant Orbit := Get(Ada.Text_IO.Get_Line); + begin + Locals.Insert(Key => O.Self, New_Item => O);" +procedure Day_05 is,"package IO is new Ada.Text_IO.Integer_IO(Memory.Value); + Program_Name: constant String := Ada.Command_Line.Argument(1); + F: File_Type; +begin + Open(F, In_File, Program_Name); + declare + Mem: constant Memory.Block := Memory.Read_Comma_Separated(F); + M: aliased Intcode.Machine := + (Hi_Mem => Mem'Last, + Mem => Mem, + Aux_Mem => Intcode.Aux_Memory.Empty_Map, + Input => new Intcode.Port, + Output => new Intcode.Port); + Exec: Intcode.Executor(M'Access); + I: Memory.Value; + O: Intcode.Maybe_Memory_Value; + begin + Ada.Text_IO.Put(""? ""); + IO.Get(I); + M.Input.Put(I); + loop + M.Output.Get(O); + exit when not O.Present; + IO.Put(O.Value); + Ada.Text_IO.New_Line; + end loop;" +procedure Day_08 is,"function Count_Pixel(Within: Layer; Value: Pixel) return Natural is + Total: Natural := 0; + begin + for P of Within loop + if P = Value then Total := Total + 1; end if; + end loop; + return Total; + end Count_Pixel; + + package Layer_Vector is new Ada.Containers.Vectors( + Index_Type => Positive, Element_Type => Layer); + + All_Layers: Layer_Vector.Vector; + Least_Zeroed_Layer: Layer; + Zero_Count: Natural := Natural'Last; +begin + while not Ada.Text_IO.End_Of_File loop + declare + L: Layer; + Z: Natural; + begin + Get_Layer(L); + Z := Count_Pixel(Within => L, Value => '0'); + if Z < Zero_Count then + Zero_Count := Z; + Least_Zeroed_Layer := L; + end if; + All_Layers.Append(L);" +procedure Day_03 is,"type Point is record + X, Y: Integer; + end record; + + package Wire_Vec is new Ada.Containers.Vectors( + Index_Type => Natural, Element_Type => Point); + + procedure Append_Comma_Separated_Wire_Points(W: in out Wire_Vec.Vector) is + Curr: constant Point := W.Last_Element; + Dir: Character; + Distance: Natural; + begin + Ada.Text_IO.Get(Dir); + Ada.Integer_Text_IO.Get(Distance); + case Dir is + when 'U' => + for I in 1 .. Distance loop + W.Append(Point'(X => Curr.X, Y => Curr.Y + I)); + end loop; + when 'D' => + for I in 1 .. Distance loop + W.Append(Point'(X => Curr.X, Y => Curr.Y - I)); + end loop; + when 'R' => + for I in 1 .. Distance loop + W.Append(Point'(X => Curr.X + I, Y => Curr.Y)); + end loop; + when 'L' => + for I in 1 .. Distance loop + W.Append(Point'(X => Curr.X - I, Y => Curr.Y)); + end loop; + when others => + raise Ada.IO_Exceptions.Data_Error with Character'Image(Dir); + end case; + end Append_Comma_Separated_Wire_Points; + + function Read_Wire return Wire_Vec.Vector is + W: Wire_Vec.Vector; + Comma: Character; + begin + W.Append(Point'(0, 0)); + loop + Append_Comma_Separated_Wire_Points(W); + exit when Ada.Text_IO.End_Of_Line; + Ada.Text_IO.Get(Comma); + end loop; + return W; + end Read_Wire; + + -- only used in part 1 + -- function Manhattan(P: Point) return Natural is (abs(P.X) + abs(P.Y)); + + Wire_1: constant Wire_Vec.Vector := Read_Wire; + Wire_2: constant Wire_Vec.Vector := Read_Wire; + Min_Dist: Natural := Natural'Last; +begin + for I in Wire_1.First_Index .. Wire_1.Last_Index loop + declare + P: constant Point := Wire_1(I); + J: constant Wire_Vec.Extended_Index := Wire_2.Find_Index(P); + Dist: constant Natural := I + J; + begin + if J /= Wire_Vec.No_Index and Dist > 0 then + Min_Dist := Natural'Min(Min_Dist, Dist); + end if;" +procedure finalize_library is,"begin + E099 := E099 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__text_io__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""system__file_io__finalize_body""); + begin + E111 := E111 - 1; + F2;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (Ada, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + pragma Favor_Top_Level (No_Param_Proc); + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 0; + Default_Stack_Size := -1; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E025 := E025 + 1; + Ada.Containers'Elab_Spec; + E040 := E040 + 1; + Ada.Io_Exceptions'Elab_Spec; + E068 := E068 + 1; + Ada.Strings'Elab_Spec; + E052 := E052 + 1; + Ada.Strings.Maps'Elab_Spec; + E054 := E054 + 1; + Ada.Strings.Maps.Constants'Elab_Spec; + E058 := E058 + 1; + Interfaces.C'Elab_Spec; + E078 := E078 + 1; + System.Exceptions'Elab_Spec; + E027 := E027 + 1; + System.Object_Reader'Elab_Spec; + E080 := E080 + 1; + System.Dwarf_Lines'Elab_Spec; + E047 := E047 + 1; + System.Os_Lib'Elab_Body; + E072 := E072 + 1; + System.Soft_Links.Initialize'Elab_Body; + E021 := E021 + 1; + E013 := E013 + 1; + System.Traceback.Symbolic'Elab_Body; + E039 := E039 + 1; + E008 := E008 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E103 := E103 + 1; + Ada.Streams'Elab_Spec; + E101 := E101 + 1; + System.File_Control_Block'Elab_Spec; + E115 := E115 + 1; + System.Finalization_Root'Elab_Spec; + E114 := E114 + 1; + Ada.Finalization'Elab_Spec; + E112 := E112 + 1; + System.File_Io'Elab_Body; + E111 := E111 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E099 := E099 + 1; + E135 := E135 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_demovec""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + if gnat_argc = 0 then + gnat_argc := argc; + gnat_argv := argv; + end if; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure finalize_library is,"begin + E099 := E099 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__text_io__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""system__file_io__finalize_body""); + begin + E111 := E111 - 1; + F2;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (Ada, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + pragma Favor_Top_Level (No_Param_Proc); + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 0; + Default_Stack_Size := -1; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E025 := E025 + 1; + Ada.Containers'Elab_Spec; + E040 := E040 + 1; + Ada.Io_Exceptions'Elab_Spec; + E068 := E068 + 1; + Ada.Strings'Elab_Spec; + E052 := E052 + 1; + Ada.Strings.Maps'Elab_Spec; + E054 := E054 + 1; + Ada.Strings.Maps.Constants'Elab_Spec; + E058 := E058 + 1; + Interfaces.C'Elab_Spec; + E078 := E078 + 1; + System.Exceptions'Elab_Spec; + E027 := E027 + 1; + System.Object_Reader'Elab_Spec; + E080 := E080 + 1; + System.Dwarf_Lines'Elab_Spec; + E047 := E047 + 1; + System.Os_Lib'Elab_Body; + E072 := E072 + 1; + System.Soft_Links.Initialize'Elab_Body; + E021 := E021 + 1; + E013 := E013 + 1; + System.Traceback.Symbolic'Elab_Body; + E039 := E039 + 1; + E008 := E008 + 1; + Ada.Numerics'Elab_Spec; + E134 := E134 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E103 := E103 + 1; + Ada.Streams'Elab_Spec; + E101 := E101 + 1; + System.File_Control_Block'Elab_Spec; + E115 := E115 + 1; + System.Finalization_Root'Elab_Spec; + E114 := E114 + 1; + Ada.Finalization'Elab_Spec; + E112 := E112 + 1; + System.File_Io'Elab_Body; + E111 := E111 + 1; + Ada.Calendar'Elab_Spec; + Ada.Calendar'Elab_Body; + E142 := E142 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E099 := E099 + 1; + System.Random_Seed'Elab_Body; + E140 := E140 + 1; + E150 := E150 + 1; + E136 := E136 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_mainair""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + if gnat_argc = 0 then + gnat_argc := argc; + gnat_argv := argv; + end if; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +procedure finalize_library is,"begin + E099 := E099 - 1; + declare + procedure F1; + pragma Import (Ada, F1, ""ada__text_io__finalize_spec""); + begin + F1;" +procedure F2;,"pragma Import (Ada, F2, ""system__file_io__finalize_body""); + begin + E111 := E111 - 1; + F2;" +procedure Reraise_Library_Exception_If_Any;,"pragma Import (Ada, Reraise_Library_Exception_If_Any, ""__gnat_reraise_library_exception_if_any""); + begin + Reraise_Library_Exception_If_Any;" +procedure adafinal is,"procedure s_stalib_adafinal; + pragma Import (Ada, s_stalib_adafinal, ""system__standard_library__adafinal""); + + procedure Runtime_Finalize; + pragma Import (C, Runtime_Finalize, ""__gnat_runtime_finalize""); + + begin + if not Is_Elaborated then + return; + end if; + Is_Elaborated := False; + Runtime_Finalize; + s_stalib_adafinal; + end adafinal; + + type No_Param_Proc is access procedure; + pragma Favor_Top_Level (No_Param_Proc); + + procedure adainit is + Main_Priority : Integer; + pragma Import (C, Main_Priority, ""__gl_main_priority""); + Time_Slice_Value : Integer; + pragma Import (C, Time_Slice_Value, ""__gl_time_slice_val""); + WC_Encoding : Character; + pragma Import (C, WC_Encoding, ""__gl_wc_encoding""); + Locking_Policy : Character; + pragma Import (C, Locking_Policy, ""__gl_locking_policy""); + Queuing_Policy : Character; + pragma Import (C, Queuing_Policy, ""__gl_queuing_policy""); + Task_Dispatching_Policy : Character; + pragma Import (C, Task_Dispatching_Policy, ""__gl_task_dispatching_policy""); + Priority_Specific_Dispatching : System.Address; + pragma Import (C, Priority_Specific_Dispatching, ""__gl_priority_specific_dispatching""); + Num_Specific_Dispatching : Integer; + pragma Import (C, Num_Specific_Dispatching, ""__gl_num_specific_dispatching""); + Main_CPU : Integer; + pragma Import (C, Main_CPU, ""__gl_main_cpu""); + Interrupt_States : System.Address; + pragma Import (C, Interrupt_States, ""__gl_interrupt_states""); + Num_Interrupt_States : Integer; + pragma Import (C, Num_Interrupt_States, ""__gl_num_interrupt_states""); + Unreserve_All_Interrupts : Integer; + pragma Import (C, Unreserve_All_Interrupts, ""__gl_unreserve_all_interrupts""); + Detect_Blocking : Integer; + pragma Import (C, Detect_Blocking, ""__gl_detect_blocking""); + Default_Stack_Size : Integer; + pragma Import (C, Default_Stack_Size, ""__gl_default_stack_size""); + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Bind_Env_Addr : System.Address; + pragma Import (C, Bind_Env_Addr, ""__gl_bind_env_addr""); + + procedure Runtime_Initialize (Install_Handler : Integer); + pragma Import (C, Runtime_Initialize, ""__gnat_runtime_initialize""); + + Finalize_Library_Objects : No_Param_Proc; + pragma Import (C, Finalize_Library_Objects, ""__gnat_finalize_library_objects""); + Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + if Is_Elaborated then + return; + end if; + Is_Elaborated := True; + Main_Priority := -1; + Time_Slice_Value := -1; + WC_Encoding := 'b'; + Locking_Policy := ' '; + Queuing_Policy := ' '; + Task_Dispatching_Policy := ' '; + Priority_Specific_Dispatching := + Local_Priority_Specific_Dispatching'Address; + Num_Specific_Dispatching := 0; + Main_CPU := -1; + Interrupt_States := Local_Interrupt_States'Address; + Num_Interrupt_States := 0; + Unreserve_All_Interrupts := 0; + Detect_Blocking := 0; + Default_Stack_Size := -1; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + Runtime_Initialize (1); + + Finalize_Library_Objects := finalize_library'access; + + Ada.Exceptions'Elab_Spec; + System.Soft_Links'Elab_Spec; + System.Exception_Table'Elab_Body; + E025 := E025 + 1; + Ada.Containers'Elab_Spec; + E040 := E040 + 1; + Ada.Io_Exceptions'Elab_Spec; + E068 := E068 + 1; + Ada.Strings'Elab_Spec; + E052 := E052 + 1; + Ada.Strings.Maps'Elab_Spec; + E054 := E054 + 1; + Ada.Strings.Maps.Constants'Elab_Spec; + E058 := E058 + 1; + Interfaces.C'Elab_Spec; + E078 := E078 + 1; + System.Exceptions'Elab_Spec; + E027 := E027 + 1; + System.Object_Reader'Elab_Spec; + E080 := E080 + 1; + System.Dwarf_Lines'Elab_Spec; + E047 := E047 + 1; + System.Os_Lib'Elab_Body; + E072 := E072 + 1; + System.Soft_Links.Initialize'Elab_Body; + E021 := E021 + 1; + E013 := E013 + 1; + System.Traceback.Symbolic'Elab_Body; + E039 := E039 + 1; + E008 := E008 + 1; + Ada.Numerics'Elab_Spec; + E134 := E134 + 1; + Ada.Tags'Elab_Spec; + Ada.Tags'Elab_Body; + E103 := E103 + 1; + Ada.Streams'Elab_Spec; + E101 := E101 + 1; + System.File_Control_Block'Elab_Spec; + E115 := E115 + 1; + System.Finalization_Root'Elab_Spec; + E114 := E114 + 1; + Ada.Finalization'Elab_Spec; + E112 := E112 + 1; + System.File_Io'Elab_Body; + E111 := E111 + 1; + Ada.Calendar'Elab_Spec; + Ada.Calendar'Elab_Body; + E140 := E140 + 1; + Ada.Text_Io'Elab_Spec; + Ada.Text_Io'Elab_Body; + E099 := E099 + 1; + System.Random_Seed'Elab_Body; + E138 := E138 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_test""); + + function main + (argc : Integer; + argv : System.Address; + envp : System.Address) + return Integer + is + procedure Initialize (Addr : System.Address); + pragma Import (C, Initialize, ""__gnat_initialize""); + + procedure Finalize; + pragma Import (C, Finalize, ""__gnat_finalize""); + SEH : aliased array (1 .. 2) of Integer; + + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + if gnat_argc = 0 then + gnat_argc := argc; + gnat_argv := argv; + end if; + gnat_envp := envp; + + Initialize (SEH'Address); + adainit; + Ada_Main_Program; + adafinal; + Finalize; + return (gnat_exit_status);" +"function Get_Distance(C_act, C_oth : Coord) return Integer is","begin + return ((C_oth.x - C_act.x)**2 + (C_oth.y - C_act.y)**2);" +"function Get_Distance(AirC1,AirC2: Aircraft_Type) return Integer is","Cord1 : Coord := AirC1.Pos_Airplane; + Cord2 : Coord := AirC2.Pos_Airplane; + begin + return Get_Distance(Cord1,Cord2); + exception + when others => return -1;" +procedure Main is,"package GL_Double_IO is new Float_IO(GL.Types.Double); + use GL_Double_IO; + + package Natural_IO is new Integer_IO(Natural); + use Natural_IO; + + use GL.Types; + use GL.Types.Doubles; + use GL.Fixed.Matrix; + use GL.Buffers; + use type GL.Types.Double; + + package CRV is new Curve(Base_Real_Type => GL.Types.Double, + Dimension => 2); + + -- Constants + ------------ + + D : constant Gl.Types.Double := 4.0; -- Diameter of a drawn point + WINDOW_WIDTH : constant := 800; + WINDOW_HEIGHT : constant := 600; + + KNOTS_RULER_V_POS : constant Gl.Types.Double := GL.Types.Double(WINDOW_HEIGHT) - 50.0; + KNOTS_RULER_LEFT_COORDINATE : constant := 100.0; + KNOTS_RULER_RIGHT_COORDINATE : constant := GL.Types.Double(WINDOW_WIDTH) - 100.0; + + -- Types + -------- + + type Algorithm_Type is (DE_CASTELIJAU, DE_BOOR, CATMULL_ROM, LAGRANGE_EQUIDISTANT, LAGRANGE_CHEBYSHEV); + + subtype Num_Of_Control_Points_Type is Positive range 4 .. 99; -- Minumum 4 because of Catmull-Rom + subtype Num_Of_Knots_Type is Positive range 1 .. 99; + + type Test_Window is new Glfw.Windows.Window with record + + Control_Points : CRV.Control_Points_Array(1..Num_Of_Control_Points_Type'Last) := + (1 => (CRV.X => 10.0, CRV.Y => 100.0), + 2 => (CRV.X => 11.0, CRV.Y => 121.0), + 3 => (CRV.X => 15.0, CRV.Y => 225.0), + 4 => (CRV.X => 17.0, CRV.Y => 289.0), + 5 => (CRV.X => 20.0, CRV.Y => 400.0), + 6 => (CRV.X => 21.0, CRV.Y => 441.0), + 7 => (CRV.X => 22.0, CRV.Y => 484.0), + 8 => (CRV.X => 100.0, CRV.Y => 484.0), + 9 => (CRV.X => 150.0, CRV.Y => 484.0), + 10 => (CRV.X => 250.0, CRV.Y => 484.0), + others => (CRV.X => 0.0, CRV.Y => 0.0)); + + -- Note to self - this was bad idea to use static array of maximal size and a sepearte value to + -- represent it's actual size. + -- + Num_Of_Control_Points : Num_Of_Control_Points_Type := 10; + + Original_X, Original_Y : GL.Types.Double := 0.0; + Delta_X, Delta_Y : GL.Types.Double := 0.0; + + + Selected_Point, Hovered_Point : Natural := 0; + + Algorithm : Algorithm_Type := DE_CASTELIJAU; + + Help_Overlay_Required : Boolean := False; + + Display_Control_Polygon : Boolean := True; + + Knot_Values : CRV.Knot_Values_Array (1 .. Num_Of_Knots_Type'Last) := + (1 => 0.0, + 2 => 0.0, + 3 => 0.0, + 4 => 0.1, + 5 => 0.3, + 6 => 0.5, + 7 => 0.5, + 8 => 0.5, + 9 => 0.7, + 10 => 0.9, + 11 => 1.0, + 12 => 1.0, + 13 => 1.0, + others => 0.0); + + Num_Of_Knots : Num_Of_Knots_Type := 13; + + Selected_Knot, Hovered_Knot : Natural := 0; + + Hovered_Ruler : Boolean := False; + + end record; + + -- Fwd Declared Procedures and Functions + ------------------------------------ + function Calculate_Knot_H_Pos(Knot_Value : in CRV.Parametrization_Type) return GL.Types.Double; + function Calculate_Knot_Value(H_Pos : in Glfw.Input.Mouse.Coordinate) return CRV.Parametrization_Type; + + function Calculate_B_Spline_Degree return Integer; + procedure Uniformise_Knot_Vector(V : in out CRV.Knot_Values_Array; + Degree : in Integer); + + -- Overrides + --------------------------- + + overriding + procedure Init (Object : not null access Test_Window; + Width, Height : Glfw.Size; + Title : String; + Monitor : Glfw.Monitors.Monitor := Glfw.Monitors.No_Monitor; + Share : access Glfw.Windows.Window'Class := null); + + overriding + procedure Mouse_Position_Changed (Object : not null access Test_Window; + X, Y : Glfw.Input.Mouse.Coordinate); + overriding + procedure Mouse_Button_Changed (Object : not null access Test_Window; + Button : Glfw.Input.Mouse.Button; + State : Glfw.Input.Button_State; + Mods : Glfw.Input.Keys.Modifiers); + + overriding + procedure Key_Changed (Object : not null access Test_Window; + Key : Glfw.Input.Keys.Key; + Scancode : Glfw.Input.Keys.Scancode; + Action : Glfw.Input.Keys.Action; + Mods : Glfw.Input.Keys.Modifiers); + + -- Procedures and Functions + --------------------------- + + procedure Init (Object : not null access Test_Window; + Width, Height : Glfw.Size; + Title : String; + Monitor : Glfw.Monitors.Monitor := Glfw.Monitors.No_Monitor; + Share : access Glfw.Windows.Window'Class := null) is + Upcast : Glfw.Windows.Window_Reference + := Glfw.Windows.Window (Object.all)'Access; + begin + Upcast.Init (Width, Height, Title, Monitor, Share); + Object.Enable_Callback (Glfw.Windows.Callbacks.Mouse_Position); + Object.Enable_Callback (Glfw.Windows.Callbacks.Mouse_Button); + Object.Enable_Callback (Glfw.Windows.Callbacks.Key); + end Init; + + procedure Mouse_Position_Changed (Object : not null access Test_Window; + X, Y : Glfw.Input.Mouse.Coordinate) is + use GL.Types.Doubles; + + use type Glfw.Input.Button_State; + + subtype Knot_Index_Type is Positive range 1 .. Object.Num_Of_Knots; + + procedure Swap_Knots(Index_1, Index_2 : Knot_Index_Type) is + Temp : CRV.Parametrization_Type; + begin + Temp := Object.Knot_Values(Index_1); + Object.Knot_Values(Index_1) := Object.Knot_Values(Index_2); + Object.Knot_Values(Index_2) := temp;" +procedure Draw_Help_Overlay is separate;,"-- TODO: Postcondition - not hovered and selected at the same time + procedure Determine_Hovered_Object is separate; + + + function Calculate_B_Spline_Degree return Integer is + begin + return My_Window.Num_Of_Knots - My_Window.Num_Of_Control_Points - 1;" +procedure Uniformise_Knot_Vector(V : in out CRV.Knot_Values_Array;,"Degree : in Integer) is + begin + if V'Last >= 2*(Degree + 1) then + + V(V'First .. V'First + Degree) := (others => 0.0); + + for I in 1 .. V'Last - 2*(Degree + 1) loop + V(V'First + Degree + I) := CRV.Parametrization_Type( + Float(I) / + Float(V'Last - 2*(Degree + 1) + 1) + ); + end loop; + + V(V'Last - Degree .. V'Last) := (others => 1.0); + + end if;" +function Eval_Basis_Poly(J : in Interpolation_Nodes_Index_Type) return Base_Real_Type is,"D : constant Base_Real_Type := (Parametrization_Type'Last - Parametrization_Type'First) / Base_Real_Type(Control_Points'Length - 1); + + Numentator : Base_Real_Type := 1.0; + Denominator : Base_Real_Type := 1.0; + + begin + + for M in Control_Points'Range loop + + if M /= J then + Numentator := Numentator * ( T - Interpolation_Nodes(M) ); + + Denominator := Denominator * ( Interpolation_Nodes(J) - Interpolation_Nodes(M) ); + end if; + + end loop; + + return Numentator / Denominator; + + end Eval_Basis_Poly; + + begin + + for I in Control_Points'Range loop + + Result := Result + Control_Points(I) * Eval_Basis_Poly(I); + + end loop; + + return Result; + + end Eval_Lagrange; + + + function Make_Equidistant_Nodes( N : Positive ) return Interpolation_Nodes_Array is + + D : constant Base_Real_Type := (Parametrization_Type'Last - Parametrization_Type'First) / Base_Real_Type(N - 1); + Res : Interpolation_Nodes_Array(1..N); + + begin + + Res(Res'First) := Parametrization_Type'First; + + if N /= 1 then + + for I in Res'First + 1 .. Res'Last - 1 loop + + Res(I) := Parametrization_Type'First + D * Base_Real_Type(I-1); + + end loop; + + Res(Res'Last) := Parametrization_Type'Last; + + end if; + + return Res;" +procedure Draw_Help_Overlay is,"begin + + if Font_Loaded then + + GL.Toggles.Enable(GL.Toggles.Blend); + GL.Blending.Set_Blend_Func(GL.Blending.Src_Alpha, GL.Blending.One_Minus_Src_Alpha); + + declare + Token : Gl.Immediate.Input_Token := GL.Immediate.Start (Quads); + begin + Gl.Immediate.Set_Color (GL.Types.Colors.Color'(0.1, 0.1, 0.1, 0.9)); + + GL.Immediate.Add_Vertex(Token, Vector2'(0.0, 0.0 )); + GL.Immediate.Add_Vertex(Token, Vector2'(0.0, Double(WINDOW_HEIGHT))); + GL.Immediate.Add_Vertex(Token, Vector2'(Double(WINDOW_WIDTH), Double(WINDOW_HEIGHT))); + GL.Immediate.Add_Vertex(Token, Vector2'(Double(WINDOW_WIDTH), 0.0 ));" +procedure Print_Active_Map is,"C: Active_Clients.Cursor := Active_Clients.First(Active_Map); + EP_Image: ASU.Unbounded_String; + begin + Ada.Text_IO.Put_Line (""ACTIVE CLIENTS""); + Ada.Text_IO.Put_Line (""==============""); + + while Active_Clients.Has_Element(C) loop + + EP_Image := ASU.To_Unbounded_String(LLU.Image(Active_Clients.Element + (C).Value.Client_EP)); + + Ada.Text_IO.Put_Line (ASU.To_String(Active_Clients.Element(C).Key) & + "" "" & + ASU.To_String(Format_EP(EP_Image)) & "" "" & + Time_Image(Active_Clients.Element(C).Value.Time)); + + Active_Clients.Next(C); + end loop; + ATI.New_Line; + end Print_Active_Map; + + procedure Print_Old_Map is + C: Old_Clients.Cursor := Old_Clients.First(Old_Map); + begin + Ada.Text_IO.Put_Line (""OLD CLIENTS""); + Ada.Text_IO.Put_Line (""===========""); + + if not Old_Clients.Has_Element(C) then + ATI.Put_Line(""Old Clients not Found""); + end if; + + while Old_Clients.Has_Element(C) loop + Ada.Text_IO.Put_Line (ASU.To_String(Old_Clients.Element(C).Value.Nick) & + "": "" & Time_Image(Old_Clients.Element(C).Value.Time)); + + Old_Clients.Next(C); + end loop; + ATI.New_Line; + end Print_Old_Map; + + function Client_To_Ban (Active_Map: Active_Clients.Map) return ASU.Unbounded_String is + + C: Active_Clients.Cursor := Active_Clients.First(Active_Map); + Min_Time: Ada.Calendar.Time; + Nick: ASU.Unbounded_String; + begin + Min_Time := Active_Clients.Element(C).Value.Time; + Nick := Active_Clients.Element(C).Key; + while Active_Clients.Has_Element(C) loop + + if Active_Clients.Element(C).Value.Time < Min_Time then + + Min_Time := Active_Clients.Element(C).Value.Time; + Nick := Active_Clients.Element(C).Key; + + end if; + Active_Clients.Next(C); + end loop; + return Nick; + end Client_To_Ban; + + procedure Server_To_All (Comment: ASU.Unbounded_String; + O_Buffer: access LLU.Buffer_Type) is + + C: Active_Clients.Cursor := Active_Clients.First(Active_Map); + Nick: ASU.Unbounded_String := ASU.To_Unbounded_String(""Server""); + + begin + while Active_Clients.Has_Element(C) loop + + CM.Server_Message (Active_Clients.Element(C).Value.Client_EP, + Nick,Comment,O_Buffer); + + Active_Clients.Next(C); + end loop; + end Server_To_All; + + + -- CHAT CASES -- + + procedure Case_Init (I_Buffer: access LLU.Buffer_Type; + O_Buffer: access LLU.Buffer_Type) is + + Client_EP_Receive: LLU.End_Point_Type; + Client_EP_Handler: LLU.End_Point_Type; + Nick: ASU.Unbounded_String; + Ban_Nick: ASU.Unbounded_String; + Comment: ASU.Unbounded_String; + Client_Data: Data; + Old_Client: Old_Data; + Accepted: Boolean; + Success: Boolean; + Ban_Message: ASU.Unbounded_String; + begin + + Client_EP_Receive := LLU.End_Point_Type'Input (I_Buffer); + Client_EP_Handler := LLU.End_Point_Type'Input (I_Buffer); + Nick := ASU.Unbounded_String'Input (I_Buffer); + + Active_Clients.Get(Active_Map,Nick,Client_Data,Success); + + if Success then + Accepted := False; + ATI.Put_Line(""INIT received from "" & ASU.To_String(Nick) + & "": IGNORED. nick already used""); + else + ATI.Put_Line(""INIT received from "" & ASU.To_String(Nick) + & "": ACCEPTED""); + begin + Accepted := True; + Client_Data.Client_EP := Client_EP_Handler; + Client_Data.Time := Ada.Calendar.Clock; + + Old_Clients.Get(Old_Map,Nick_to_Integer(Nick),Old_Client,Success); + if Success then + Old_Clients.Delete (Old_Map,Nick_to_Integer(Nick),Success); + Comment := ASU.To_Unbounded_String(ASU.To_String(Nick) & + "" rejoins the chat""); + else + Comment := ASU.To_Unbounded_String(ASU.To_String(Nick) & + "" joins the chat""); + end if; + + Active_Clients.Put (Active_Map,Nick,Client_Data); + + -- Automatic := True + Send_To_Readers (True,Nick,Comment,O_Buffer); + + exception + when Active_Clients.Full_Map => + + Ban_Nick := Client_To_Ban(Active_Map); + Old_Client.Nick := Ban_Nick; + Old_Client.Time := Ada.Calendar.Clock; + + Old_Clients.Put (Old_Map,Nick_to_Integer(Ban_Nick),Old_Client); + + Ban_Message := ASU.To_Unbounded_String(ASU.To_String(Ban_Nick) + & "" banned for being idle too long""); + + Server_To_All (Ban_Message,O_Buffer); + + Active_Clients.Delete (Active_Map,Ban_Nick,Success); + + Active_Clients.Put (Active_Map,Nick,Client_Data); + + -- Automatic := True + Send_To_Readers (True,Nick,Comment,O_Buffer);" +procedure Unknown_Fail is,"result : Boolean; + + begin + result := Connect (""unknown"", 1_984); + Fail (Message => ""Exception expected""); + + exception + when Error : BaseXException => + null; + + end Unknown_Fail; + + procedure Port_Fail is + + result : Boolean; + + begin + result := Connect (""localhost"", 1_985); + Fail (Message => ""Exception expected""); + + exception + when Error : BaseXException => + null; + + end Port_Fail; + + procedure Connect_Auth is + + result : Boolean; + + begin + result := Connect (""localhost"", 1_984); + Assert (Condition => result = True, Message => ""Connect test""); + + result := Authenticate (""unknown"", ""test""); + Assert (Condition => result = False, Message => ""Auth test""); + + Close; + + end Connect_Auth; + + procedure Connect_Pass is + + result : Boolean; + + begin + result := Connect (""localhost"", 1_984); + Assert (Condition => result = True, Message => ""Connect test""); + + result := Authenticate (""admin"", ""admin""); + Assert (Condition => result = True, Message => ""Auth test""); + + Close; + + end Connect_Pass; + + procedure Execute_Test is + + result : Boolean; + + begin + result := Connect (""localhost"", 1_984); + Assert (Condition => result = True, Message => ""Connect test""); + + result := Authenticate (""admin"", ""admin""); + Assert (Condition => result = True, Message => ""Auth test""); + + declare + Response : String := Execute (""xquery 1+1""); + begin + Assert (Condition => Response = ""2"", Message => ""Execute test"");" +procedure Execute_Fail is,"result : Boolean; + + begin + result := Connect (""localhost"", 1_984); + Assert (Condition => result = True, Message => ""Connect test""); + + result := Authenticate (""admin"", ""admin""); + Assert (Condition => result = True, Message => ""Auth test""); + + declare + Response : String := Execute (""xquery unknown""); + begin + Fail (Message => ""Exception expected"");" +procedure Create_Drop is,"result : Boolean; + + begin + result := Connect (""localhost"", 1_984); + Assert (Condition => result = True, Message => ""Connect test""); + + result := Authenticate (""admin"", ""admin""); + Assert (Condition => result = True, Message => ""Auth test""); + + declare + Response : String := Create (""database"", ""Hello World!""); + begin + null;" +procedure Add_Test is,"result : Boolean; + + begin + result := Connect (""localhost"", 1_984); + Assert (Condition => result = True, Message => ""Connect test""); + + result := Authenticate (""admin"", ""admin""); + Assert (Condition => result = True, Message => ""Auth test""); + + declare + Response : String := Create (""database"", """"); + begin + null;" +procedure Replace_Test is,"result : Boolean; + + begin + result := Connect (""localhost"", 1_984); + Assert (Condition => result = True, Message => ""Connect test""); + + result := Authenticate (""admin"", ""admin""); + Assert (Condition => result = True, Message => ""Auth test""); + + declare + Response : String := Create (""database"", """"); + begin + null;" +procedure Query_Test is,"result : Boolean; + + begin + result := Connect (""localhost"", 1_984); + Assert (Condition => result = True, Message => ""Connect test""); + + result := Authenticate (""admin"", ""admin""); + Assert (Condition => result = True, Message => ""Auth test""); + + declare + Response : Query := CreateQuery (""1+1""); + V : String_Vectors.Vector; + begin + V := Response.Results; + Assert (Condition => V (0) = ""2"", Message => ""Query test""); + + Response.Close;" +procedure Query_Bind is,"result : Boolean; + + begin + result := Connect (""localhost"", 1_984); + Assert (Condition => result = True, Message => ""Connect test""); + + result := Authenticate (""admin"", ""admin""); + Assert (Condition => result = True, Message => ""Auth test""); + + declare + Response : Query := + CreateQuery + (""declare variable $name external; for $i in 1 to 1 return element { $name } { $i }""); + begin + Response.Bind (""name"", ""number"", """"); + declare + Res : String := Response.Execute; + begin + Assert + (Condition => Res = ""1"", + Message => ""Query bind"");" +procedure QueryExample is,"V: String_Vectors.Vector; + +begin + + if (Connect (""localhost"", 1_984) = False) then + Ada.Text_IO.Put_Line (""Connect failed.""); + return; + else + if (Authenticate (""admin"", ""admin"") = False) then + Ada.Text_IO.Put_Line (""Authenticate failed.""); + + Close; + return; + end if; + end if; + + declare + Response : Query := CreateQuery (""for $i in 1 to 10 return Text { $i }""); + begin + V := Response.Results; + for E of V loop + Put_Line (E); + end loop; + + Response.Close;" +procedure ExampleAdd is,"begin + + if (Connect (""localhost"", 1_984) = False) then + Ada.Text_IO.Put_Line (""Connect failed.""); + return; + else + if (Authenticate (""admin"", ""admin"") = False) then + Ada.Text_IO.Put_Line (""Authenticate failed.""); + + Close; + return; + end if; + end if; + + declare + Response : String := Execute (""create db database""); + begin + Ada.Text_IO.Put_Line (Response);" +procedure Example is,"begin + + if (Connect (""localhost"", 1_984) = False) then + Ada.Text_IO.Put_Line (""Connect failed.""); + return; + else + if (Authenticate (""admin"", ""admin"") = False) then + Ada.Text_IO.Put_Line (""Authenticate failed.""); + + Close; + return; + end if; + end if; + + declare + Response : String := Execute (""xquery 1 to 10""); + begin + Ada.Text_IO.Put_Line (Response);" +procedure QueryExample is,"begin + + if (Connect (""localhost"", 1_984) = False) then + Ada.Text_IO.Put_Line (""Connect failed.""); + return; + else + if (Authenticate (""admin"", ""admin"") = False) then + Ada.Text_IO.Put_Line (""Authenticate failed.""); + + Close; + return; + end if; + end if; + + declare + Response : Query := + CreateQuery + (""declare variable $name external; for $i in 1 to 10 return element { $name } { $i }""); + begin + Response.Bind (""name"", ""number"", """"); + Ada.Text_IO.Put_Line (Response.Execute); + Response.Close;" +procedure ExampleCreate is,"begin + + if (Connect (""localhost"", 1_984) = False) then + Ada.Text_IO.Put_Line (""Connect failed.""); + return; + else + if (Authenticate (""admin"", ""admin"") = False) then + Ada.Text_IO.Put_Line (""Authenticate failed.""); + + Close; + return; + end if; + end if; + + declare + Response : String := Create (""database"", ""Hello World!""); + begin + Ada.Text_IO.Put_Line (Response);" +procedure UART_429Disco is,"UART_Port: GPIO_Registers renames GPIOA; + UART_TX_Bit: constant Port_Bit_Number := 9; + UART_RX_Bit: constant Port_Bit_Number := 10; + + APB2_Frequency : constant := 90_000_000; -- Set by board support + Baud_Rate : constant := 115_200; + Ratio : constant := (APB2_Frequency + Baud_Rate / 2) / Baud_Rate; + --Ratio : constant := 128; + + Period: constant Time_Span := Milliseconds(10); + Now: Time := Clock; + + +begin + -- clock test + + --RCC.CFGR.HPRE := AHB_Prescaler_1; + --RCC.CFGR.PPRE2 := APB_Prescaler_2; + + + RCC.AHB1ENR.GPIOC := True; + RCC.CFGR.MCO2PRE := MCO_Prescaler_5; + RCC.CFGR.MCO2 := Clock_Output_2_SYSCLK; + + GPIOC.OTYPER(9) := Push_Pull_Type; + GPIOC.OSPEEDR(9) := Very_High_Speed; + GPIOC.AFR(9) := Alternate_Functions.SYS; + GPIOC.MODER(9) := Alternate_Mode; + + RCC.AHB1ENR.GPIOA := True; + + + RCC.APB2ENR.USART1 := True; + + RCC.APB2RSTR.USART1 := True; + + RCC.APB2RSTR.USART1 := False; + + + -- + + UART_Port.OTYPER(UART_TX_Bit) := Push_Pull_Type; + UART_Port.OSPEEDR(UART_TX_Bit) := Very_High_Speed; + UART_Port.PUPDR(UART_TX_Bit) := Pull_Down; + UART_Port.AFR(UART_TX_Bit) := Alternate_Functions.USART1; + UART_Port.MODER(UART_TX_Bit) := Alternate_Mode; + + UART_Port.OTYPER(UART_RX_Bit) := Push_Pull_Type; + UART_Port.OSPEEDR(UART_RX_Bit) := Very_High_Speed; + UART_Port.PUPDR(UART_RX_Bit) := No_Pull; + UART_Port.AFR(UART_RX_Bit) := Alternate_Functions.USART1; + UART_Port.MODER(UART_RX_Bit) := Alternate_Mode; + + -- UART initialisation (close to ST's HAL) + + USART1.CR1.UE := False; + + + declare + CR1: Control_Register_1 := USART1.CR1; + begin + CR1.M := Word_8_Bits; + CR1.PCE := False; + CR1.PS := Even_Parity; + CR1.TE := True; + CR1.RE := True; + CR1.OVER8 := False; + + USART1.CR1 := CR1;" +function Next_Sample_Pulse_And_Noise,"(Chan : in out Channel; + Sample_Rate : Positive) + return Sample + with Inline; + + function Next_Sample_Triangle + (Chan : in out Channel; + Sample_Rate : Positive) + return Sample + with Inline; + + procedure Process_Seq (This : in out Instance; + Chan_Id : Channel_ID); + + ----------------------- + -- Period_In_Samples -- + ----------------------- + + function Period_In_Samples (Sample_Rate : Positive; + Rate_In_Hertz : Frequency) + return Float + is (Float (Sample_Rate) / Float (Rate_In_Hertz)) + with Inline; + + --------------------------------- + -- Next_Sample_Pulse_And_Noise -- + --------------------------------- + + function Next_Sample_Pulse_And_Noise + (Chan : in out Channel; + Sample_Rate : Positive) + return Sample + is + Delta_Time : Float; + Width : Float; + Next_State : BLIT_State := Down; + begin + Chan.CSample_Nb := Chan.CSample_Nb + 1; + + -- If it is time, compute the next BLIT step + if Chan.Next_Impulse_Time <= Chan.CSample_Nb then + + if Chan.State = Up then + Width := Chan.Width; + else + Width := 1.0 - Chan.Width; + end if; + + Delta_Time := Period_In_Samples (Sample_Rate, Chan.Freq) * Width + + Chan.Next_Impulse_Phase; + + Chan.Next_Impulse_Time := Chan.Next_Impulse_Time + + Natural (Float'Floor (Delta_Time)); + + Chan.Next_Impulse_Phase := Delta_Time - Float'Floor (Delta_Time); + + case Chan.Mode is + when Pulse => + + -- Invert the state + Next_State := (if Chan.State = Up then Down else Up); + + when Noise_1 | Noise_2 => + + -- Next state depends on LFSR noise + declare + B0 : constant Unsigned_16 := Chan.LFSR and 1; + B1 : constant Unsigned_16 := Shift_Right (Chan.LFSR, 1) and 1; + B6 : constant Unsigned_16 := Shift_Right (Chan.LFSR, 6) and 1; + Feedback : Unsigned_16; + begin + if Chan.Mode = Noise_1 then + Feedback := B0 xor B1; + else + Feedback := B0 xor B6; + end if; + + Next_State := (if B0 = 0 then Down else Up); + + Chan.LFSR := Shift_Right (Chan.LFSR, 1); + + if (Feedback and 1) /= 0 then + Chan.LFSR := Chan.LFSR or 16#4000#; + else + Chan.LFSR := Chan.LFSR and not 16#4000#; + end if;" +function From_Sample is new To_Int (Int_T);,"begin + for Elt of Buffer loop + Elt := From_Sample (This.Next_Sample); + end loop; + end Next_Samples_Int; + + ----------------------- + -- Next_Samples_UInt -- + ----------------------- + + procedure Next_Samples_UInt (This : in out Instance; + Buffer : out Buffer_T) + is + function From_Sample is new To_UInt (UInt_T); + begin + for Elt of Buffer loop + Elt := From_Sample (This.Next_Sample); + end loop; + end Next_Samples_UInt; + + ----------------- + -- Process_Seq -- + ----------------- + + procedure Process_Seq (This : in out Instance; + Chan_Id : Channel_ID) + is + Chan : Channel renames This.Channels (Chan_Id); + begin + if Chan.Seq_Remaining_Ticks /= 0 then + Chan.Seq_Remaining_Ticks := Chan.Seq_Remaining_Ticks - 1; + end if; + + if Chan.Seq_Remaining_Ticks = 0 then + while Chan.Seq_Index in Chan.Seq'Range loop + declare + Cmd : Command renames Chan.Seq (Chan.Seq_Index); + begin + case Cmd.Kind is + + when Wait_Ticks => + Chan.Seq_Remaining_Ticks := Cmd.Ticks; + + when Wait_Note => + Chan.Seq_Remaining_Ticks := + Tick_Count ((60.0 / Float (Chan.BPM)) * + Float (Chan.Ticks_Per_Second) * + (case Cmd.Note is + when Large => 8.0, + when Long => 4.0, + when Double => 2.0, + when Whole => 1.0, + when Half => 0.5, + when Quarter => 0.25, + when N_8th => 0.125, + when N_16th => 0.0625, + when N_32nd => 0.0312, + when N_64th => 0.015625, + when N_128th => 0.0078125, + when N_256th => 0.0039062)); + + when Note_On => + Note_On (This, Chan_Id, Cmd.Freq); + + when Note_Off => + Note_Off (This, Chan_Id); + + when Set_Decay => + Set_Decay (This, Chan_Id, Cmd.Decay_Ticks); + + when Set_Sweep => + Set_Sweep (This, Chan_Id, + Cmd.Sweep, + Cmd.Sweep_Len, + Cmd.Sweep_Ticks); + + when Set_Volume => + Set_Volume (This, Chan_Id, Cmd.Vol); + + when Set_Mode => + Set_Mode (This, Chan_Id, Cmd.Mode); + + when Set_Width => + Set_Width (This, Chan_Id, Cmd.Width); + + end case;" +procedure tsp is,"package random_num is new ada.numerics.discrete_random (integer); + use random_num; + g : generator; + --total number of population + population_size : integer := 1000; + --length of gene = number of node + gene_length : integer := 15; + max_dist:integer := 40; + min_dist:integer := 10; + mutation_rate:integer:=100; + Task_number : integer; + Task_Load : integer; + type gene is array (integer range 1..gene_length) of integer range 1..gene_length; + type map_row is array (integer range 1..gene_length) of integer; + --use parent(i)(j) to access parent[i][j] + type container is array(integer range 1..population_size) of gene; + parent : container; + childarray :container; + --use map(i)(j) to access map[i][j] + map : array(integer range 1..gene_length) of map_row; + + fitness : array(integer range 1..population_size) of integer; + --generate random map + procedure generate_map is + begin + for i in 1..gene_length loop + for j in i..gene_length loop + map(i)(j) := (random(g) mod max_dist-min_dist+1)+min_dist; + map(j)(i) := map(i)(j); + if i=j then + map(i)(j) := 0; + end if; + end loop; + end loop; + end generate_map; + + --generate first generation + procedure generate_first is + rand_pos : integer; + temp :integer; + arr : gene; + begin + for i in 1..population_size loop + for j in 1..gene_length loop + arr(j):=j; + end loop; + for j in 1..gene_length loop + rand_pos := (random(g) mod (gene_length-j+1)) + 1; + parent(i)(j) := arr(rand_pos); + temp := arr(gene_length-j+1); + arr(gene_length-j+1) := arr(rand_pos); + arr(rand_pos) := temp; + end loop; + end loop; + end generate_first; + + function selection return integer is + sum : integer := 0; + rand : integer; + begin + for i in 1..population_size loop + sum:=sum+10000/fitness(i); + end loop; + rand := (random(g) mod sum) + 1; + sum := 0; + for i in 1..population_size loop + sum:=sum+10000/fitness(i); + if sum >= rand then + return i; + end if; + end loop; + return (population_size); + end selection; + + procedure crossover(c_i:integer) is + p:integer; + longest:integer:=1; + tmp:integer; + r1:integer; + r2:integer; + begin + p:=selection; + for i in 1..gene_length-1 loop + if map(parent(p)(i))(parent(p)(i+1)) > map(parent(p)(longest))(parent(p)(longest+1)) then + longest:=i; + end if; + end loop; + for i in 1..gene_length loop + if i + longest <= gene_length then + childarray(c_i)(i):=parent(p)(i+longest); + else + childarray(c_i)(i):=parent(p)((i+longest)mod gene_length); + end if; + end loop; + + if random(g) mod mutation_rate = 1 then + r1:=random(g) mod gene_length +1; + r2:=random(g) mod gene_length +1; + tmp:=childarray(c_i)(r1); + childarray(c_i)(r1):=childarray(c_i)(r2); + childarray(c_i)(r2):=tmp; + end if; + end crossover; + + procedure arrayAtoArrayB(A : in container;B : out container) is + begin + for i in 1 .. population_size loop + for j in 1 .. gene_length loop + B(i)(j) :=A(i)(j); + end loop; + end loop; + end arrayAtoArrayB; + + t_start:time; + t_end:time; + t_exe:duration; + package Duration_IO is new Fixed_IO(Duration); + + + + -------------------------------------------------------------- + + + task type T is + entry Compute_Fitness(i : integer); + end T; + + + task body T is + routine : integer; + loop_number : integer; + current_i : integer; + begin + + accept Compute_Fitness(i : integer) do + current_i := i-1; + end Compute_Fitness; + loop_number := (Task_Load*(current_i))+1; + for k in loop_number..(loop_number+Task_Load-1) loop + routine := 0; + for j in 1..(gene_length-1) loop + routine := routine + map(parent(k)(j))(parent(k)(j+1)); + end loop; + fitness(k) := routine; + delay(0.001); + end loop; + + end T; + + final_result :integer :=0; + n : integer :=0; + fit : integer :=1; + tmp :integer :=0; + result :integer :=0; + taskComplete : integer := 0; + best :integer:=5000; + end_condition:integer; + --------------------------- + + function condition return integer is + answer :integer :=0; + begin + for i in 1..(population_size-1) loop + fit := fitness(i); + if fitness(i+1)<=fitness(i) then + fit := fitness(i+1); + end if; + end loop; + if fitend_condition/4 then + mutation_rate := 75; + end if; + if n>end_condition/2 then + mutation_rate := 50; + end if; + if n>3*end_condition/4 then + mutation_rate := 10; + end if; + if n>=end_condition then + answer:=1; + else + answer:=0; + end if; + return answer; + end condition; + --------------------------- + generation:integer:=1; +begin + put(""End condition : ""); + get(end_condition); + put(""Number of threads : ""); + get(Task_number); + new_line; + Task_Load:= population_size/Task_number; + t_start:=clock; + reset(g); + generate_first; + generate_map; + ----------------------------- start find the route + Find_route: + loop + declare + Mul_Task : array(1..Task_number) of T; + begin + -------------------------------- + for i in 1..Task_number loop + Mul_Task(i).Compute_Fitness(i); + end loop; + + loop + taskComplete:=0; + for i in 1..Task_number loop + if Mul_Task(i)'Terminated then + taskComplete:=taskComplete+1; + end if; + end loop; + if taskComplete = Task_number then + exit; + end if; + end loop; + + result:=condition; + final_result := fit; + put(generation,5); + put("" th generation shortest length : ""); + put(final_result,3); + put("" Current shortest length : ""); + put(best,3); + new_line; + generation:=generation+1; + exit Find_route when result=1; + + --arrayAtoArrayB(parent,childarray); + for i in 1..population_size loop + --childgenerate; + crossover(i); + end loop; + arrayAtoArrayB(childarray,parent); + + ------------------------------------------" +"function Intel_32 is new Intel_x86_buffer( Unsigned_32, 4 );","function Intel_16( n: Unsigned_16 ) return Byte_buffer is + pragma Inline(Intel_16); + begin + return (Unsigned_8(n and 255), Unsigned_8(Shift_Right(n, 8))); + end Intel_16; + + -- 2.5.2 Byte Strings, 8-bit string length (BIFF2-BIFF5), p. 187 + function To_buf_8_bit_length(s: String) return Byte_buffer is + b: Byte_buffer(s'Range); + begin + if s'Length > 255 then -- length doesn't fit in a byte + raise Constraint_Error; + end if; + for i in b'Range loop + b(i):= Character'Pos(s(i)); + end loop; + return Unsigned_8(s'Length) & b; + end To_buf_8_bit_length; + + -- 2.5.2 Byte Strings, 16-bit string length (BIFF2-BIFF5), p. 187 + function To_buf_16_bit_length(s: String) return Byte_buffer is + b: Byte_buffer(s'Range); + begin + if s'Length > 2**16-1 then -- length doesn't fit in a 16-bit number + raise Constraint_Error; + end if; + for i in b'Range loop + b(i):= Character'Pos(s(i)); + end loop; + return Intel_16(s'Length) & b; + end To_buf_16_bit_length; + + -- -- 2.5.3 Unicode Strings, 16-bit string length (BIFF2-BIFF5), p. 17 + -- function To_buf_16_bit_length(s: Wide_String) return Byte_buffer is + -- b: Byte_buffer(1 .. 2 * s'Length); + -- j: Integer:= 1; + -- begin + -- if s'Length > 2**16-1 then -- length doesn't fit in a 16-bit number + -- raise Constraint_Error; + -- end if; + -- for i in s'Range loop + -- b(j) := Unsigned_8(Unsigned_32'(Wide_Character'Pos(s(i))) and 255); + -- b(j+1):= Unsigned_8(Shift_Right(Unsigned_32'(Wide_Character'Pos(s(i))), 8)); + -- j:= j + 2; + -- end loop; + -- return + -- Intel_16(s'Length) & + -- (1 => 1) & -- Character compression (ccompr): 1 = Uncompressed (16-bit characters) + -- b; + -- end To_buf_16_bit_length; + + -- Gives a byte sequence of an IEEE 64-bit number as if taken + -- from an Intel machine (i.e. with the same endianess). + -- + -- http://en.wikipedia.org/wiki/IEEE_754-1985#Double-precision_64_bit + -- + + package IEEE_LF is new IEEE_754.Generic_Double_Precision (Long_Float); + + function IEEE_Double_Intel_Portable(x: Long_Float) return Byte_buffer is + pragma Inline(IEEE_Double_Intel_Portable); + d : Byte_buffer(1..8); + -- + f64: constant IEEE_LF.Float_64:= IEEE_LF.To_IEEE(x); + begin + for i in d'Range loop + d(i):= f64(9-i); -- Order is reversed + end loop; + -- Fully tested in Test_IEEE.adb + return d; + end IEEE_Double_Intel_Portable; + + -- Just spit the bytes of the long float - fast way. + -- Of course this will work only on an Intel(-like) machine. We check this later. + subtype Byte_buffer_8 is Byte_buffer(0..7); + function IEEE_Double_Intel_Native is new + Ada.Unchecked_Conversion(Long_Float, Byte_buffer_8); + + x_test: constant Long_Float:= -12345.0e-67; + Can_use_native_IEEE: constant Boolean:= + IEEE_Double_Intel_Portable(x_test) = IEEE_Double_Intel_Native(x_test); + + function IEEE_Double_Intel(x: Long_Float) return Byte_buffer is + pragma Inline(IEEE_Double_Intel); + begin + if Can_use_native_IEEE then + return IEEE_Double_Intel_Native(x); -- Fast, non-portable + else + return IEEE_Double_Intel_Portable(x); -- Slower but portable + end if; + end IEEE_Double_Intel; + + -- Workaround for the severe xxx'Read xxx'Write performance + -- problems in the GNAT and ObjectAda compilers (as in 2009) + -- This is possible if and only if Byte = Stream_Element and + -- arrays types are both packed and aligned the same way. + -- + subtype Size_test_a is Byte_buffer(1..19); + subtype Size_test_b is Ada.Streams.Stream_Element_Array(1..19); + workaround_possible: constant Boolean:= + Size_test_a'Size = Size_test_b'Size and + Size_test_a'Alignment = Size_test_b'Alignment; + + procedure Block_Write( + stream : in out Ada.Streams.Root_Stream_Type'Class; + buffer : in Byte_buffer + ) + is + pragma Inline(Block_Write); + SE_Buffer : Stream_Element_Array (1 .. buffer'Length); + for SE_Buffer'Address use buffer'Address; + pragma Import (Ada, SE_Buffer); + begin + if workaround_possible then + Ada.Streams.Write(stream, SE_Buffer); + else + Byte_buffer'Write(stream'Access, buffer); + -- ^ This was 30x to 70x slower on GNAT 2009 + -- Test in the Zip-Ada project. + end if; + end Block_Write; + + ---------------- + -- Excel BIFF -- + ---------------- + + -- The original Modula-2 code counted on certain assumptions about + -- record packing & endianess. We write data without these assumptions. + + procedure WriteBiff( + xl : Excel_Out_Stream'Class; + biff_id: Unsigned_16; + data : Byte_buffer + ) + is + pragma Inline(WriteBiff); + begin + Block_Write(xl.xl_stream.all, Intel_16(biff_id)); + Block_Write(xl.xl_stream.all, Intel_16(Unsigned_16(data'Length))); + Block_Write(xl.xl_stream.all, data); + end WriteBiff; + + -- 5.8 BOF: Beginning of File, p.135 + procedure Write_BOF(xl : Excel_Out_Stream'Class) is + + function BOF_suffix return Byte_buffer is -- 5.8.1 Record BOF + begin + case xl.format is + when BIFF2 => + return empty_buffer; + when BIFF3 | BIFF4 => + return (0,0); -- Not used + -- when BIFF8 => + -- return (1,1,1,1); + end case; + end BOF_suffix; + + -- 0005H = Workbook globals + -- 0006H = Visual Basic module + -- 0010H = Sheet or dialogue (see SHEETPR, S5.97) + Sheet_or_dialogue: constant:= 16#10#; + -- 0020H = Chart + -- 0040H = Macro sheet + biff_record_identifier: constant array(Excel_type) of Unsigned_16:= + (BIFF2 => 16#0009#, + BIFF3 => 16#0209#, + BIFF4 => 16#0409# + -- BIFF8 => 16#0809# + ); + biff_version: constant array(Excel_type) of Unsigned_16:= + (BIFF2 => 16#0200#, + BIFF3 => 16#0300#, + BIFF4 => 16#0400# + -- BIFF8 => 16#0600# + ); + begin + WriteBiff(xl, + biff_record_identifier(xl.format), + Intel_16(biff_version(xl.format)) & + Intel_16(Sheet_or_dialogue) & + BOF_suffix + ); + end Write_BOF; + + -- 5.49 FORMAT (number format) + procedure WriteFmtStr (xl : Excel_Out_Stream'Class; s : String) is + begin + case xl.format is + when BIFF2 | BIFF3 => + WriteBiff(xl, 16#001E#, To_buf_8_bit_length(s)); + when BIFF4 => + WriteBiff(xl, 16#041E#, (0, 0) & To_buf_8_bit_length(s)); + -- when BIFF8 => + -- WriteBiff(xl, 16#041E#, (0, 0) & -- should be: format index used in other records + -- To_buf_8_bit_length(s)); + end case; + end WriteFmtStr; + + -- Write built-in number formats (internal) + procedure WriteFmtRecords (xl : Excel_Out_Stream'Class) is + sep_1000: constant Character:= ','; -- US format + sep_deci: constant Character:= '.'; -- US format + -- ^ If there is any evidence of an issue with those built-in separators, + -- we may make them configurable. NB: MS Excel 2002 and 2007 use only + -- the index of built-in formats and discards the strings for BIFF2, but not for BIFF3... + begin + -- 5.12 BUILTINFMTCOUNT + case xl.format is + when BIFF2 => + WriteBiff(xl, 16#001F#, Intel_16(Unsigned_16(last_built_in - 5))); + when BIFF3 => + WriteBiff(xl, 16#0056#, Intel_16(Unsigned_16(last_built_in - 3))); + when BIFF4 => + WriteBiff(xl, 16#0056#, Intel_16(Unsigned_16(last_built_in + 1))); + -- when BIFF8 => + -- null; + end case; + -- loop & case avoid omitting any choice + for n in Number_format_type'First .. last_custom loop + case n is + when general => WriteFmtStr(xl, ""General""); + when decimal_0 => WriteFmtStr(xl, ""0""); + when decimal_2 => WriteFmtStr(xl, ""0"" & sep_deci & ""00""); -- 'Comma' built-in style + when decimal_0_thousands_separator => + WriteFmtStr(xl, ""#"" & sep_1000 & ""##0""); + when decimal_2_thousands_separator => + WriteFmtStr(xl, ""#"" & sep_1000 & ""##0"" & sep_deci & ""00""); + when no_currency_0 => + if xl.format >= BIFF4 then + WriteFmtStr(xl, ""#"" & sep_1000 & ""##0;-#"" & sep_1000 & ""##0""); + end if; + when no_currency_red_0 => + if xl.format >= BIFF4 then + WriteFmtStr(xl, ""#"" & sep_1000 & ""##0;-#"" & sep_1000 & ""##0""); + -- [Red] doesn't go with non-English versions of Excel !! + end if; + when no_currency_2 => + if xl.format >= BIFF4 then + WriteFmtStr(xl, ""#"" & sep_1000 & ""##0"" & sep_deci & ""00;"" & + ""-#"" & sep_1000 & ""##0"" & sep_deci & ""00""); + end if; + when no_currency_red_2 => + if xl.format >= BIFF4 then + WriteFmtStr(xl, ""#"" & sep_1000 & ""##0"" & sep_deci & ""00;"" & + ""-#"" & sep_1000 & ""##0"" & sep_deci & ""00""); + end if; + when currency_0 => + WriteFmtStr(xl, ""$ #"" & sep_1000 & ""##0;$ -#"" & sep_1000 & ""##0""); + when currency_red_0 => + WriteFmtStr(xl, ""$ #"" & sep_1000 & ""##0;$ -#"" & sep_1000 & ""##0""); + -- [Red] doesn't go with non-English versions of Excel !! + when currency_2 => + WriteFmtStr(xl, ""$ #"" & sep_1000 & ""##0"" & sep_deci & ""00;"" & + ""$ -#"" & sep_1000 & ""##0"" & sep_deci & ""00""); + when currency_red_2 => + WriteFmtStr(xl, ""$ #"" & sep_1000 & ""##0"" & sep_deci & ""00;"" & + ""$ -#"" & sep_1000 & ""##0"" & sep_deci & ""00""); + when percent_0 => WriteFmtStr(xl, ""0%""); -- 'Percent' built-in style + when percent_2 => WriteFmtStr(xl, ""0"" & sep_deci & ""00%""); + when scientific => WriteFmtStr(xl, ""0"" & sep_deci & ""00E+00""); + when fraction_1 => + if xl.format >= BIFF3 then + WriteFmtStr(xl, ""#\ ?/?""); + end if; + when fraction_2 => + if xl.format >= BIFF3 then + WriteFmtStr(xl, ""#\ ??/??""); + end if; + when dd_mm_yyyy => WriteFmtStr(xl, ""dd/mm/yyyy""); + when dd_mmm_yy => WriteFmtStr(xl, ""dd/mmm/yy""); + when dd_mmm => WriteFmtStr(xl, ""dd/mmm""); + when mmm_yy => WriteFmtStr(xl, ""mmm/yy""); + when h_mm_AM_PM => WriteFmtStr(xl, ""h:mm\ AM/PM""); + when h_mm_ss_AM_PM => WriteFmtStr(xl, ""h:mm:ss\ AM/PM""); + when hh_mm => WriteFmtStr(xl, ""hh:mm""); + when hh_mm_ss => WriteFmtStr(xl, ""hh:mm:ss""); + when dd_mm_yyyy_hh_mm => WriteFmtStr(xl, ""dd/mm/yyyy\ hh:mm""); + when percent_0_plus => + WriteFmtStr(xl, ""+0%;-0%;0%""); + when percent_2_plus => + WriteFmtStr(xl, ""+0"" & sep_deci & ""00%;-0"" & sep_deci & ""00%;0"" & sep_deci & ""00%""); + when date_iso => WriteFmtStr(xl, ""yyyy\-mm\-dd""); + when date_h_m_iso => WriteFmtStr(xl, ""yyyy\-mm\-dd\ hh:mm""); + when date_h_m_s_iso => WriteFmtStr(xl, ""yyyy\-mm\-dd\ hh:mm:ss""); + -- !! Trouble: Excel (German Excel/French locale) writes yyyy, reads it, + -- understands it and translates it into aaaa, but is unable to + -- understand *our* yyyy + -- Same issue as [Red] vs [Rot] above. + end case; + end loop; + -- ^ Some formats in the original list caused problems, probably + -- because of regional placeholder symbols + case xl.format is + when BIFF2 => + for i in 1..6 loop + WriteFmtStr(xl, ""@""); + end loop; + when BIFF3 => + for i in 1..4 loop + WriteFmtStr(xl, ""@""); + end loop; + when BIFF4 => + null; + end case; + -- ^ Stuffing for having the same number of built-in and EW custom + end WriteFmtRecords; + + -- 5.35 DIMENSION + procedure Write_Dimensions(xl: Excel_Out_Stream'Class) is + -- sheet bounds: 0 2 Index to first used row + -- 2 2 Index to last used row, increased by 1 + -- 4 2 Index to first used column + -- 6 2 Index to last used column, increased by 1 + -- + -- Since our row / column counts are 1-based, no need to increase by 1. + sheet_bounds: constant Byte_buffer:= + Intel_16(0) & + Intel_16(Unsigned_16(xl.maxrow)) & + Intel_16(0) & + Intel_16(Unsigned_16(xl.maxcolumn)); + -- sheet_bounds_32_16: constant Byte_buffer:= + -- Intel_32(0) & + -- Intel_32(Unsigned_32(xl.maxrow)) & + -- Intel_16(0) & + -- Intel_16(Unsigned_16(xl.maxcolumn)); + begin + case xl.format is + when BIFF2 => + WriteBiff(xl, 16#0000#, sheet_bounds); + when BIFF3 | BIFF4 => + WriteBiff(xl, 16#0200#, sheet_bounds & (0,0)); + -- when BIFF8 => + -- WriteBiff(xl, 16#0200#, sheet_bounds_32_16 & (0,0)); + end case; + end Write_Dimensions; + + procedure Define_number_format( + xl : in out Excel_Out_Stream; + format : out Number_format_type; + format_string: in String + ) + is + begin + xl.number_fmt:= xl.number_fmt + 1; + format:= xl.number_fmt; + WriteFmtStr(xl, format_string); + end Define_number_format; + + procedure Write_Worksheet_header(xl : in out Excel_Out_Stream'Class) is + + procedure Define_style(fmt: Format_type; style_id: Unsigned_8) is + Base_Level: constant:= 255; + begin + WriteBiff(xl, + 16#0293#, + Intel_16(Unsigned_16(fmt) + 16#8000#) & style_id & Base_Level + ); + end Define_style; + -- + Comma_Style : constant:= 3; + Currency_Style : constant:= 4; + Percent_Style : constant:= 5; + font_for_styles, font_2, font_3 : Font_type; + -- + function Encoding_code return Unsigned_16 is -- 5.17 CODEPAGE, p. 145 + begin + case xl.encoding is + when Windows_CP_874 => return 874; + when Windows_CP_932 => return 932; + when Windows_CP_936 => return 936; + when Windows_CP_949 => return 949; + when Windows_CP_950 => return 950; + when Windows_CP_1250 => return 1250; + when Windows_CP_1251 => return 1251; + when Windows_CP_1252 => + case xl.format is + when BIFF2 .. BIFF3 => + return 16#8001#; + when BIFF4 => + return 1252; + end case; + when Windows_CP_1253 => return 1253; + when Windows_CP_1254 => return 1254; + when Windows_CP_1255 => return 1255; + when Windows_CP_1256 => return 1256; + when Windows_CP_1257 => return 1257; + when Windows_CP_1258 => return 1258; + when Windows_CP_1361 => return 1361; + when Apple_Roman => return 10000; + end case; + end Encoding_code; + -- + begin + Write_BOF(xl); + -- 5.17 CODEPAGE, p. 145 + case xl.format is + -- when BIFF8 => -- UTF-16 + -- WriteBiff(xl, 16#0042#, Intel_16(16#04B0#)); + when others => + WriteBiff(xl, 16#0042#, Intel_16(Encoding_code)); + end case; + -- 5.14 CALCMODE + WriteBiff(xl, 16#000D#, Intel_16(1)); -- 1 => automatic + -- 5.85 REFMODE + WriteBiff(xl, 16#000F#, Intel_16(1)); -- 1 => A1 mode + -- 5.28 DATEMODE + WriteBiff(xl, 16#0022#, Intel_16(0)); -- 0 => 1900; 1 => 1904 Date system + -- NB: the 1904 variant (Mac) is ignored by LibreOffice (<= 3.5), then wrong dates ! + -- + Define_font(xl,""Arial"", 10, xl.def_font); + Define_font(xl,""Arial"", 10, font_for_styles); -- Used by BIFF3+'s styles + Define_font(xl,""Calibri"", 10, font_2); -- Defined in BIFF3 files written by Excel 2002 + Define_font(xl,""Calibri"", 10, font_3); -- Defined in BIFF3 files written by Excel 2002 + WriteFmtRecords(xl); + -- 5.111 WINDOWPROTECT + WriteBiff(xl, 16#0019#, Intel_16(0)); + -- Define default format + Define_format(xl, xl.def_font, general, xl.def_fmt); + if xl.format >= BIFF3 then + -- Don't ask why we need the following useless formats, but it is as Excel 2002 + -- write formats. Additionally, the default format is turned into decimal_2 + -- when a file without those useless formats is opened in Excel (2002) ! + Define_format(xl, font_for_styles, general, xl.def_fmt); + Define_format(xl, font_for_styles, general, xl.def_fmt); + Define_format(xl, font_2, general, xl.def_fmt); + Define_format(xl, font_2, general, xl.def_fmt); + for i in 5..15 loop + Define_format(xl, xl.def_font, general, xl.def_fmt); + end loop; + -- Final default format index is the last changed xl.def_fmt + end if; + Use_default_format(xl); + -- Define formats for the BIFF3+ ""styles"": + Define_format(xl, font_for_styles, decimal_2, xl.cma_fmt); + Define_format(xl, font_for_styles, currency_0, xl.ccy_fmt); + Define_format(xl, font_for_styles, percent_0, xl.pct_fmt); + -- Define styles - 5.103 STYLE p. 212 + -- NB: - it is BIFF3+ (we cheat a bit if selected format is BIFF2). + -- - these ""styles"" seem to be a zombie feature of Excel 3 + -- - the whole purpose of including this is because format + -- buttons (%)(,) in Excel 95 through 2007 are using these styles; + -- if the styles are not defined, those buttons are not working + -- when an Excel Writer sheet is open in MS Excel. + Define_style(xl.cma_fmt, Comma_Style); + Define_style(xl.ccy_fmt, Currency_Style); + Define_style(xl.pct_fmt, Percent_Style); + xl.dimrecpos:= Index(xl); + Write_Dimensions(xl); + xl.is_created:= True; + end Write_Worksheet_header; + + type Font_or_Background is (for_font, for_background); + type Color_pair is array(Font_or_Background) of Unsigned_16; + auto_color: constant Color_pair:= + (16#7FFF#, -- system window text colour + 16#0019# -- system window background colour + ); + + color_code: constant array(Excel_type, Color_type) of Color_pair := + ( BIFF2 => + ( + black => (0, 0), + white => (1, 1), + red => (2, 2), + green => (3, 3), + blue => (4, 4), + yellow => (5, 5), + magenta => (6, 6), + cyan => (7, 7), + others => auto_color + ), + BIFF3 | BIFF4 => + (black => (8, 8), + white => (9, 9), + red => (10, 10), + green => (11, 11), + blue => (12, 12), + yellow => (13, 13), + magenta => (14, 14), + cyan => (15, 15), + dark_red => (16, 16), + dark_green => (17, 17), + dark_blue => (18, 18), + olive => (19, 19), + purple => (20, 20), + teal => (21, 21), + silver => (22, 22), + grey => (23, 23), + automatic => auto_color + ) + ); + + -- *** Exported procedures ********************************************** + + -- 5.115 XF - Extended Format + procedure Define_format( + xl : in out Excel_Out_Stream; + font : in Font_type; -- Default_font(xl), or given by Define_font + number_format : in Number_format_type; -- built-in, or given by Define_number_format + cell_format : out Format_type; + -- Optional parameters -- + horizontal_align : in Horizontal_alignment:= general_alignment; + border : in Cell_border:= no_border; + shaded : in Boolean:= False; -- Add a dotted background pattern + background_color : in Color_type:= automatic; + wrap_text : in Boolean:= False; + vertical_align : in Vertical_alignment:= bottom_alignment; + text_orient : in Text_orientation:= normal + ) + is + actual_number_format: Number_format_type:= number_format; + cell_is_locked: constant:= 1; + -- ^ Means actually: cell formula protection is possible, and enabled when sheet is protected. + procedure Define_BIFF2_XF is + border_bits, mask: Unsigned_8; + begin + border_bits:= 0; + mask:= 8; + for s in Cell_border_single loop + if border(s) then + border_bits:= border_bits + mask; + end if; + mask:= mask * 2; + end loop; + -- 5.115.2 XF Record Contents, p. 221 for BIFF3 + WriteBiff( + xl, + 16#0043#, -- XF code in BIFF2 + (Unsigned_8(font), + -- ^ Index to FONT record + 0, + -- ^ Not used + Number_format_type'Pos(actual_number_format) + 16#40# * cell_is_locked, + -- ^ Number format and cell flags + Horizontal_alignment'Pos(horizontal_align) + + border_bits + + Boolean'Pos(shaded) * 128 + -- ^ Horizontal alignment, border style, and background + ) + ); + end Define_BIFF2_XF; + + area_code: Unsigned_16; + + procedure Define_BIFF3_XF is + begin + -- 5.115.2 XF Record Contents, p. 221 for BIFF3 + WriteBiff( + xl, + 16#0243#, -- XF code in BIFF3 + (Unsigned_8(font), + -- ^ 0 - Index to FONT record + Number_format_type'Pos(actual_number_format), + -- ^ 1 - Number format and cell flags + cell_is_locked, + -- ^ 2 - XF_TYPE_PROT (5.115.1) + 16#FF# + -- ^ 3 - XF_USED_ATTRIB + ) & + Intel_16( + Horizontal_alignment'Pos(horizontal_align) + + Boolean'Pos(wrap_text) * 8 + ) & + -- ^ 4 - Horizontal alignment, text break, parent style XF + Intel_16(area_code) & + -- ^ 6 - XF_AREA_34 + ( Boolean'Pos(border(top_single)), + Boolean'Pos(border(left_single)), + Boolean'Pos(border(bottom_single)), + Boolean'Pos(border(right_single)) + ) + -- ^ 8 - XF_BORDER_34 - thin (=1) line; we could have other line styles: + -- Thin, Medium, Dashed, Dotted, Thick, Double, Hair + ); + end Define_BIFF3_XF; + + procedure Define_BIFF4_XF is + begin + -- 5.115.2 XF Record Contents, p. 222 for BIFF4 + WriteBiff( + xl, + 16#0443#, -- XF code in BIFF4 + (Unsigned_8(font), + -- ^ 0 - Index to FONT record + Number_format_type'Pos(actual_number_format), + -- ^ 1 - Number format and cell flags + cell_is_locked, 0, + -- ^ 2 - XF type, cell protection, and parent style XF + Horizontal_alignment'Pos(horizontal_align) + + Boolean'Pos(wrap_text) * 8 + + (Vertical_alignment'Pos(vertical_align) and 3) * 16 + + Text_orientation'Pos(text_orient) * 64, + -- ^ 4 - Alignment (hor & ver), text break, and text orientation + 16#FF# + -- ^ 3 - XF_USED_ATTRIB + ) & + -- ^ 4 - Horizontal alignment, text break, parent style XF + Intel_16(area_code) & + -- ^ 6 - XF_AREA_34 + ( Boolean'Pos(border(top_single)), + Boolean'Pos(border(left_single)), + Boolean'Pos(border(bottom_single)), + Boolean'Pos(border(right_single)) + ) + -- ^ 8 - XF_BORDER_34 - thin (=1) line; we could have other line styles: + -- Thin, Medium, Dashed, Dotted, Thick, Double, Hair + ); + end Define_BIFF4_XF; + + begin + -- 2.5.12 Patterns for Cell and Chart Background Area + -- This is for BIFF3+ + if shaded then + area_code:= + Boolean'Pos(shaded) * 17 + -- Sparse pattern, like BIFF2 ""shade"" + 16#40# * color_code(BIFF3, black)(for_background) + -- pattern colour + 16#800# * color_code(BIFF3, background_color)(for_background); -- pattern background + elsif background_color = automatic then + area_code:= 0; + else + area_code:= + 1 + -- Full pattern + 16#40# * color_code(BIFF3, background_color)(for_background) + -- pattern colour + 16#800# * color_code(BIFF3, background_color)(for_background); -- pattern background + end if; + case xl.format is + when BIFF2 => + case actual_number_format is + when general .. no_currency_2 => + null; + when currency_0 .. fraction_2 => + actual_number_format:= actual_number_format - 4; + when dd_mm_yyyy .. last_custom => + actual_number_format:= actual_number_format - 6; + when others => + null; + end case; + Define_BIFF2_XF; + when BIFF3 => + if actual_number_format in currency_0 .. last_custom then + actual_number_format:= actual_number_format - 4; + end if; + Define_BIFF3_XF; + when BIFF4 => + Define_BIFF4_XF; + -- when BIFF8 => + -- Define_BIFF8_XF; -- BIFF8: 16#00E0#, p. 224 + end case; + xl.xfs:= xl.xfs + 1; + cell_format:= Format_type(xl.xfs); + xl.xf_def(xl.xfs):= (font => font, numb => number_format); + end Define_format; + + procedure Header(xl : Excel_Out_Stream; page_header_string: String) is + begin + WriteBiff(xl, 16#0014#, To_buf_8_bit_length(page_header_string)); -- 5.55 p.180 + end Header; + + procedure Footer(xl : Excel_Out_Stream; page_footer_string: String) is + begin + WriteBiff(xl, 16#0015#, To_buf_8_bit_length(page_footer_string)); -- 5.48 p.173 + end Footer; + + procedure Left_Margin(xl : Excel_Out_Stream; inches: Long_Float) is + begin + WriteBiff(xl, 16#0026#, IEEE_Double_Intel(inches)); + end Left_Margin; + + procedure Right_Margin(xl : Excel_Out_Stream; inches: Long_Float) is + begin + WriteBiff(xl, 16#0027#, IEEE_Double_Intel(inches)); + end Right_Margin; + + procedure Top_Margin(xl : Excel_Out_Stream; inches: Long_Float) is + begin + WriteBiff(xl, 16#0028#, IEEE_Double_Intel(inches)); + end Top_Margin; + + procedure Bottom_Margin(xl : Excel_Out_Stream; inches: Long_Float) is + begin + WriteBiff(xl, 16#0029#, IEEE_Double_Intel(inches)); + end Bottom_Margin; + + procedure Margins(xl : Excel_Out_Stream; left, right, top, bottom: Long_Float) is + begin + Left_Margin(xl, left); + Right_Margin(xl, right); + Top_Margin(xl, top); + Bottom_Margin(xl, bottom); + end Margins; + + procedure Print_Row_Column_Headers(xl : Excel_Out_Stream) is + begin + WriteBiff(xl, 16#002A#, Intel_16(1)); -- 5.81 PRINTHEADERS p.199 + end Print_Row_Column_Headers; + + procedure Print_Gridlines(xl : Excel_Out_Stream) is + begin + WriteBiff(xl, 16#002B#, Intel_16(1)); -- 5.80 PRINTGRIDLINES p.199 + end Print_Gridlines; + + procedure Page_Setup( + xl : Excel_Out_Stream; + scaling_percents : Positive:= 100; + fit_width_with_n_pages : Natural:= 1; -- 0: as many as possible + fit_height_with_n_pages: Natural:= 1; -- 0: as many as possible + orientation : Orientation_choice:= portrait; + scale_or_fit : Scale_or_fit_choice:= scale + ) + is + begin + -- 5.73 PAGESETUP p.192 - this is BIFF4+ (cheat if xl.format below)! + WriteBiff(xl, + 16#00A1#, + Intel_16(0) & -- paper type undefined + Intel_16(Unsigned_16(scaling_percents)) & + Intel_16(1) & -- start page number + Intel_16(Unsigned_16(fit_width_with_n_pages)) & + Intel_16(Unsigned_16(fit_height_with_n_pages)) & + Intel_16(2 * Orientation_choice'Pos(orientation)) + ); + -- 5.97 SHEETPR p.207 - this is BIFF3+ (cheat if xl.format below) ! + -- NB: this field contains other informations, should be delayed + -- in case other preferences are to be set + WriteBiff(xl, + 16#0081#, + Intel_16(256 * Scale_or_fit_choice'Pos(scale_or_fit)) + ); + end Page_Setup; + + y_scale: constant:= 20; -- scaling to obtain character point (pt) units + + -- 5.31 DEFAULTROWHEIGHT + procedure Write_default_row_height ( + xl : Excel_Out_Stream; + height : Positive + ) + is + default_twips: constant Byte_buffer:= Intel_16(Unsigned_16(height * y_scale)); + options_flags: constant Byte_buffer:= (1,0); + -- 1 = Row height and default font height do not match + begin + case xl.format is + when BIFF2 => + WriteBiff(xl, 16#0025#, default_twips); + when BIFF3 | BIFF4 => + WriteBiff(xl, 16#0225#, options_flags & default_twips); + end case; + end Write_default_row_height; + + -- 5.32 DEFCOLWIDTH + procedure Write_default_column_width ( + xl : in out Excel_Out_Stream; + width : Positive) + is + begin + WriteBiff(xl, 16#0055#, Intel_16(Unsigned_16(width))); + xl.defcolwdth:= 256 * width; + end Write_default_column_width; + + procedure Write_column_width ( + xl : in out Excel_Out_Stream; + column : Positive; + width : Natural) + is + begin + Write_column_width(xl, column, column, width); + end Write_column_width; + + procedure Write_column_width( + xl : in out Excel_Out_Stream; + first_column, + last_column : Positive; + width : Natural + ) + is + begin + case xl.format is + when BIFF2 => + -- 5.20 COLWIDTH (BIFF2 only) + WriteBiff(xl, 16#0024#, + Unsigned_8(first_column-1) & + Unsigned_8(last_column-1) & + Intel_16(Unsigned_16(width * 256))); + when BIFF3 | BIFF4 => + -- 5.18 COLINFO (BIFF3+) + WriteBiff(xl, 16#007D#, + Intel_16(Unsigned_16(first_column-1)) & + Intel_16(Unsigned_16(last_column-1)) & + Intel_16(Unsigned_16(width * 256)) & + Intel_16(0) & -- Index to XF record (5.115) for default column formatting + Intel_16(0) & -- Option flags + (0,0) -- Not used + ); + for j in first_column .. last_column loop + xl.std_col_width(j):= False; + end loop; + end case; + end Write_column_width; + + -- 5.88 ROW + -- The OpenOffice documentation tells nice stories about row blocks, + -- but single ROW commands can also be put before in the data stream, + -- where the column widths are set. Excel saves with blocks of ROW + -- commands, most of them useless. + + procedure Write_row_height( + xl : Excel_Out_Stream; + row : Positive; + height : Natural + ) + is + row_info_base: Byte_buffer:= + Intel_16(Unsigned_16(row - 1)) & + Intel_16(0) & -- col. min. + Intel_16(255) & -- col. max. + Intel_16(Unsigned_16(height * y_scale)); + fDyZero: Unsigned_8:= 0; + begin + case xl.format is + when BIFF2 => + WriteBiff(xl, 16#0008#, + row_info_base & + (1..3 => 0) & + Intel_16(0) -- offset to data + ); + when BIFF3 | BIFF4 => + if height = 0 then -- proper hiding (needed with LibreOffice) + fDyZero:= 1; + row_info_base(row_info_base'Last - 1 .. row_info_base'Last):= + Intel_16(16#8000#); + end if; + WriteBiff(xl, 16#0208#, + row_info_base & + -- http://msdn.microsoft.com/en-us/library/dd906757(v=office.12).aspx + (0, 0, -- reserved1 (2 bytes): MUST be zero, and MUST be ignored. + 0, 0, -- unused1 (2 bytes): Undefined and MUST be ignored. + fDyZero * 32 + -- D - fDyZero (1 bit): row is hidden + 1 * 64 + -- E - fUnsynced (1 bit): row height was manually set + 0 * 128, -- F - fGhostDirty (1 bit): the row was formatted + 1) & -- reserved3 (1 byte): MUST be 1, and MUST be ignored + Intel_16(15) + -- ^ ixfe_val, then 4 bits. + -- If fGhostDirty is 0, ixfe_val is undefined and MUST be ignored. + ); + end case; + end Write_row_height; + + -- 5.45 FONT, p.171 + procedure Define_font( + xl : in out Excel_Out_Stream; + font_name : String; + height : Positive; + font : out Font_type; + style : Font_style:= regular; + color : Color_type:= automatic + ) + is + style_bits, mask: Unsigned_16; + begin + style_bits:= 0; + mask:= 1; + for s in Font_style_single loop + if style(s) then + style_bits:= style_bits + mask; + end if; + mask:= mask * 2; + end loop; + xl.fonts:= xl.fonts + 1; + if xl.fonts = 4 then + xl.fonts:= 5; + -- Anomaly! The font with index 4 is omitted in all BIFF versions. + -- Numbering is 0, 1, 2, 3, *5*, 6,... + end if; + case xl.format is + when BIFF2 => + WriteBiff(xl, 16#0031#, + Intel_16(Unsigned_16(height * y_scale)) & + Intel_16(style_bits) & + To_buf_8_bit_length(font_name) + ); + if color /= automatic then + -- 5.47 FONTCOLOR + WriteBiff(xl, 16#0045#, Intel_16(color_code(BIFF2, color)(for_font))); + end if; + when BIFF3 | BIFF4 => -- BIFF8 has 16#0031#, p. 171 + WriteBiff(xl, 16#0231#, + Intel_16(Unsigned_16(height * y_scale)) & + Intel_16(style_bits) & + Intel_16(color_code(BIFF3, color)(for_font)) & + To_buf_8_bit_length(font_name) + ); + end case; + font:= Font_type(xl.fonts); + end Define_font; + + procedure Jump_to_and_store_max(xl: in out Excel_Out_Stream; r, c: Integer) is + pragma Inline(Jump_to_and_store_max); + begin + if not xl.is_created then + raise Excel_stream_not_created; + end if; + Jump_to(xl, r, c); -- Store and check current position + if r > xl.maxrow then + xl.maxrow := r; + end if; + if c > xl.maxcolumn then + xl.maxcolumn := c; + end if; + end Jump_to_and_store_max; + + -- 2.5.13 Cell Attributes (BIFF2 only) + function Cell_attributes(xl: Excel_Out_Stream) return Byte_buffer is + begin + return + (Unsigned_8(xl.xf_in_use), + Unsigned_8(xl.xf_def(xl.xf_in_use).numb) + 16#40# * + Unsigned_8(xl.xf_def(xl.xf_in_use).font), + 0 + ); + end Cell_attributes; + + function Almost_zero(x: Long_Float) return Boolean is + begin + return abs x <= Long_Float'Model_Small; + end Almost_zero; + + -- Internal + -- + -- 5.71 NUMBER + procedure Write_as_double ( + xl : in out Excel_Out_Stream; + r, + c : Positive; + num : Long_Float + ) + is + pragma Inline(Write_as_double); + begin + Jump_to_and_store_max(xl, r, c); + case xl.format is + when BIFF2 => + WriteBiff(xl, 16#0003#, + Intel_16(Unsigned_16(r-1)) & + Intel_16(Unsigned_16(c-1)) & + Cell_attributes(xl) & + IEEE_Double_Intel(num) + ); + when BIFF3 | BIFF4 => + WriteBiff(xl, 16#0203#, + Intel_16(Unsigned_16(r-1)) & + Intel_16(Unsigned_16(c-1)) & + Intel_16(Unsigned_16(xl.xf_in_use)) & + IEEE_Double_Intel(num) + ); + end case; + Jump_to(xl, r, c+1); -- Store and check new position + end Write_as_double; + + -- Internal. This is BIFF2 only. BIFF format choice unchecked here. + -- + procedure Write_as_16_bit_unsigned ( + xl : in out Excel_Out_Stream; + r, + c : Positive; + num : Unsigned_16) + is + pragma Inline(Write_as_16_bit_unsigned); + begin + Jump_to_and_store_max(xl, r, c); + -- 5.60 INTEGER + WriteBiff(xl, 16#0002#, + Intel_16(Unsigned_16(r-1)) & + Intel_16(Unsigned_16(c-1)) & + Cell_attributes(xl) & + Intel_16(num) + ); + Jump_to(xl, r, c+1); -- Store and check new position + end Write_as_16_bit_unsigned; + + -- Internal. This is BIFF3+. BIFF format choice unchecked here. + -- + procedure Write_as_30_bit_signed ( + xl : in out Excel_Out_Stream; + r, + c : Positive; + num : Integer_32) + is + pragma Inline(Write_as_30_bit_signed); + RK_val: Unsigned_32; + RK_code: constant:= 2; -- Code for signed integer. See 2.5.5 RK Values + begin + if num >= 0 then + RK_val:= Unsigned_32(num) * 4 + RK_code; + else + RK_val:= (-Unsigned_32(-num)) * 4 + RK_code; + end if; + Jump_to_and_store_max(xl, r, c); + -- 5.87 RK + WriteBiff(xl, 16#027E#, + Intel_16(Unsigned_16(r-1)) & + Intel_16(Unsigned_16(c-1)) & + Intel_16(Unsigned_16(xl.xf_in_use)) & + Intel_32(RK_val) + ); + Jump_to(xl, r, c+1); -- Store and check new position + end Write_as_30_bit_signed; + + -- + -- Profile with floating-point number + -- + procedure Write ( + xl : in out Excel_Out_Stream; + r, + c : Positive; + num : Long_Float + ) + is + max_16_u: constant:= 2.0 ** 16 - 1.0; + min_30_s: constant:= -(2.0 ** 29); + max_30_s: constant:= 2.0 ** 29 - 1.0; + begin + case xl.format is + when BIFF2 => + if num >= 0.0 and then + num <= max_16_u and then + Almost_zero(num - Long_Float'Floor(num)) + then + Write_as_16_bit_unsigned(xl, r, c, Unsigned_16(Long_Float'Floor(num))); + else + Write_as_double(xl, r, c, num); + end if; + when BIFF3 | BIFF4 => + if num >= min_30_s and then + num <= max_30_s and then + Almost_zero(num - Long_Float'Floor(num)) + then + Write_as_30_bit_signed(xl, r, c, Integer_32(Long_Float'Floor(num))); + else + Write_as_double(xl, r, c, num); + end if; + end case; + end Write; + + -- + -- Profile with integer number + -- + procedure Write ( + xl : in out Excel_Out_Stream; + r, + c : Positive; + num : Integer) + is + begin + -- We use an integer representation (and small storage) if possible; + -- we need to use a floating-point in all other cases + case xl.format is + when BIFF2 => + if num in 0..2**16-1 then + Write_as_16_bit_unsigned(xl, r, c, Unsigned_16(num)); + else + Write_as_double(xl, r, c, Long_Float(num)); + end if; + when BIFF3 | BIFF4 => + if num in -2**29..2**29-1 then + Write_as_30_bit_signed(xl, r, c, Integer_32(num)); + else + Write_as_double(xl, r, c, Long_Float(num)); + end if; + end case; + end Write; + + -- -- Function taken from Wasabee.Encoding. + -- function ISO_8859_1_to_UTF_16(s: String) return Wide_String is + -- -- This conversion is a trivial 8-bit to 16-bit copy. + -- r: Wide_String(s'Range); + -- begin + -- for i in s'Range loop + -- r(i):= Wide_Character'Val(Character'Pos(s(i))); + -- end loop; + -- return r; + -- end ISO_8859_1_to_UTF_16; + + -- 5.63 LABEL + procedure Write ( + xl : in out Excel_Out_Stream; + r, + c : Positive; + str : String) + is + begin + Jump_to_and_store_max(xl, r, c); + if str'Length > 0 then + case xl.format is + when BIFF2 => + WriteBiff(xl, 16#0004#, + Intel_16(Unsigned_16(r-1)) & + Intel_16(Unsigned_16(c-1)) & + Cell_attributes(xl) & + To_buf_8_bit_length(str) + ); + when BIFF3 | BIFF4 => + WriteBiff(xl, 16#0204#, + Intel_16(Unsigned_16(r-1)) & + Intel_16(Unsigned_16(c-1)) & + Intel_16(Unsigned_16(xl.xf_in_use)) & + To_buf_16_bit_length(str) + ); + -- when BIFF8 => + -- WriteBiff(xl, 16#0204#, + -- Intel_16(Unsigned_16(r-1)) & + -- Intel_16(Unsigned_16(c-1)) & + -- Intel_16(Unsigned_16(xl.xf_in_use)) & + -- To_buf_16_bit_length(ISO_8859_1_to_UTF_16(str)) + -- ); + end case; + end if; + Jump_to(xl, r, c+1); -- Store and check new position + end Write; + + procedure Write(xl: in out Excel_Out_Stream; r,c : Positive; str : Unbounded_String) + is + begin + Write(xl, r,c, To_String(str)); + end Write; + + -- Excel uses a floating-point type for time - ouch! + -- + function To_Number(date: Time) return Long_Float is + -- 1901 is the lowest year supported by Ada.Calendar. + -- 1900 is not a leap year, but Lotus 1-2-3, then Excel, consider it + -- as a leap year. So, with 1901, we skip that issue anyway... + -- + function Days_since_1901 (y, m, d : Integer) return Integer is + function Is_leap (y: Integer) return Boolean is + begin + if y mod 4 = 0 then + if y mod 100 = 0 then + if y mod 400 = 0 then + return True; + else + return False; + end if; + else + return True; + end if; + else + return False; + end if; + end Is_leap; + days_of_previous_months : Integer; + days_of_previous_years : Integer; + y_diff, y_diff_4, y_diff_100, y_diff_400 : Integer; + begin + case m is + when 02 => days_of_previous_months := 31; + when 03 => days_of_previous_months := 59; + when 04 => days_of_previous_months := 90; + when 05 => days_of_previous_months := 120; + when 06 => days_of_previous_months := 151; + when 07 => days_of_previous_months := 181; + when 08 => days_of_previous_months := 212; + when 09 => days_of_previous_months := 243; + when 10 => days_of_previous_months := 273; + when 11 => days_of_previous_months := 304; + when 12 => days_of_previous_months := 334; + when others => days_of_previous_months := 0; + end case; + if m > 2 and then Is_leap (y) then -- February has 29 days in leap years. + days_of_previous_months := days_of_previous_months + 1; + end if; + -- + y_diff := (y - 1) - 1900; + y_diff_4 := (y - 1) / 4 - 1900 / 4; + y_diff_100 := (y - 1) / 100 - 1900 / 100; + y_diff_400 := (y - 1) / 400 - 1900 / 400; + -- Add extra days of leap years from 1901 (included) to year y (excluded). + days_of_previous_years := 365 * y_diff + y_diff_4 - y_diff_100 + y_diff_400; + -- + return days_of_previous_years + days_of_previous_months + d - 1; + end Days_since_1901; + -- + sec : constant Day_Duration := Seconds (date); + begin + -- With GNAT and perhaps other systems, Duration's range allows the following: + -- return Long_Float(date - Time_Of(1901, 01, 01, 0.0)) / 86_400.0 + 367.0; + -- With ObjectAda and perhaps other systems, we need to count days since 1900 ourselves. + return + Long_Float (sec) / 86_400.0 + + Long_Float (Days_since_1901 (Year (date), Month (date), Day (date))) + + 367.0; -- Days from 1899-12-31 to 1901-01-01. + -- Lotus 1-2-3, then Excel, are based on 1899-12-31 (and believe it is 1900-01-01). + end To_Number; + + procedure Write(xl: in out Excel_Out_Stream; r,c : Positive; date: Time) + is + begin + Write(xl, r,c, To_Number(date)); + end Write; + + -- Ada.Text_IO - like. No need to specify row & column each time + procedure Put(xl: in out Excel_Out_Stream; num : Long_Float) is + begin + Write(xl, xl.curr_row, xl.curr_col, num); + end Put; + + procedure Put(xl : in out Excel_Out_Stream; + num : in Integer; + width : in Ada.Text_IO.Field := 0; -- ignored + base : in Ada.Text_IO.Number_Base := 10 + ) + is + begin + if base = 10 then + Write(xl, xl.curr_row, xl.curr_col, num); + else + declare + use Ada.Strings.Fixed; + s: String(1..50 + 0*width); + -- 0*width is just to skip a warning of width being unused + package IIO is new Ada.Text_IO.Integer_IO(Integer); + begin + IIO.Put(s, num, Base => base); + Put(xl, Trim(s, Ada.Strings.Left));" +function Mantissa (Value : Float_64) return Unsigned_64 is,"pragma Inline (Mantissa); + begin + return + ( Unsigned_64 (Value (8)) + or Shift_Left (Unsigned_64 (Value (7)), 8 ) + or Shift_Left (Unsigned_64 (Value (6)), 2*8) + or Shift_Left (Unsigned_64 (Value (5)), 3*8) + or Shift_Left (Unsigned_64 (Value (4)), 4*8) + or Shift_Left (Unsigned_64 (Value (3)), 5*8) + or Shift_Left (Unsigned_64 (Value (2)) and 16#0F#, 6*8) + or 2 ** Fraction_Bits + ); + end Mantissa; + + procedure Normalize + ( Value : Number; + Mantissa : out Unsigned_64; + Exponent : out Integer + ) is + begin + if Number'Machine_Radix = 2 then + -- + -- The machine radix is binary. We can use the hardware + -- representation attributes in order to get the exponent and + -- the fraction. + -- + Exponent := Number'Exponent (Value) - Mantissa_Bits; + Mantissa := Unsigned_64 (Number'Scaling (Value, -Exponent)); + else + -- + -- OK, this gets more tricky. The number is normalized to be in + -- the range 2**53 > X >= 2**52, by multiplying to the powers + -- of two. Some optimization is made to factor out the powers + -- 2**(2**n)). Though we do not use powers bigger than 30. + -- + declare + Accum : Number := Value; + Shift : Integer; + begin + Exponent := 0; + if Accum < 2.0**Fraction_Bits then + Shift := 24; + while Shift > 0 loop + if Accum < 2.0**(Mantissa_Bits - Shift) then + Accum := Accum * 2.0**Shift; + Exponent := Exponent - Shift; + else + Shift := Shift / 2; + end if; + end loop; + elsif Accum >= 2.0**Mantissa_Bits then + Shift := 8; + while Shift > 0 loop + if Accum >= 2.0**(Fraction_Bits + Shift) then + Accum := Accum / 2.0**Shift; + Exponent := Exponent + Shift; + else + Shift := Shift / 2; + end if; + end loop; + end if; + Mantissa := Unsigned_64 (Accum);" +procedure Select_Table_1 is new Select_Table_N (1);,"procedure Select_Table_10 is new Select_Table_N (10); + + procedure Select_Table_100 is new Select_Table_N (100); + + procedure Select_Table_500 is new Select_Table_N (500); + + procedure Select_Table_1000 is new Select_Table_N (1000); + + Create_SQL : Ada.Strings.Unbounded.Unbounded_String; + + procedure Register (Tests : in out Context_Type) is + Driver : constant String := Tests.Get_Driver_Name; + begin + if Driver /= ""sqlite"" and Driver /= ""postgresql"" then + Tests.Register (Do_Static'Access, ""DO 1""); + end if; + Tests.Register (Select_Static'Access, ""SELECT 1""); + Tests.Register (Connect_Select_Static'Access, ""CONNECT; SELECT 1; CLOSE""); + Tests.Register (Drop_Create'Access, ""DROP table; CREATE table"", 1); + Tests.Register (Insert'Access, ""INSERT INTO table"", 10); + Tests.Register (Select_Table_1'Access, ""SELECT * FROM table LIMIT 1""); + Tests.Register (Select_Table_10'Access, ""SELECT * FROM table LIMIT 10""); + Tests.Register (Select_Table_100'Access, ""SELECT * FROM table LIMIT 100""); + Tests.Register (Select_Table_500'Access, ""SELECT * FROM table LIMIT 500""); + Tests.Register (Select_Table_1000'Access, ""SELECT * FROM table LIMIT 1000""); + Util.Files.Read_File (Tests.Get_Config_Path (""create-table.sql""), Create_SQL); + end Register; + + procedure Do_Static (Context : in out Context_Type) is + Stmt : ADO.Statements.Query_Statement := Context.Session.Create_Statement (""DO 1""); + begin + for I in 1 .. Context.Repeat loop + Stmt.Execute; + end loop; + end Do_Static; + + procedure Select_Static (Context : in out Context_Type) is + Stmt : ADO.Statements.Query_Statement := Context.Session.Create_Statement (""SELECT 1""); + begin + for I in 1 .. Context.Repeat loop + Stmt.Execute; + end loop; + end Select_Static; + + procedure Connect_Select_Static (Context : in out Context_Type) is + begin + for I in 1 .. Context.Repeat loop + declare + DB : constant ADO.Sessions.Session := Context.Factory.Get_Session; + Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (""SELECT 1""); + begin + Stmt.Execute;" +procedure Main is,"WG : World_Grid (16); + B : Boolean; +begin + WG := New_World (16); + B := Get_Spot (WG, 1, 1); + Put_Line (""World Size: "" & Integer'Image(WG.Size)); + Put_Line (""Hello Ada!""); + --Gtk.Main.Init; + --Gtk_New (Life_Value); + --Gtk.Main.Main;" +function on_is_Label_clicked (the_Label : access Gtk_Label_Record'Class;,"Self : in aIDE.Editor.of_enumeration_type.view) return Boolean + is + pragma Unreferenced (the_Label); + begin + Self.Target.add_Literal (""literal""); + Self.freshen; + + return False; + end on_is_Label_clicked; + + + package Label_return_Callbacks is new Gtk.Handlers.User_Return_Callback (Gtk_Label_Record, + Boolean, + aIDE.Editor.of_enumeration_type.view); + + package body Forge + is + function to_Editor (the_Target : in AdaM.a_Type.enumeration_type.view) return View + is + use AdaM, + Glib; + + Self : constant Editor.of_enumeration_type.view := new Editor.of_enumeration_type.item; + + the_Builder : Gtk_Builder; + Error : aliased GError; + Result : Guint; + pragma Unreferenced (Result); + + begin + Self.Target := the_Target; + + Gtk_New (the_Builder); + + Result := the_Builder.Add_From_File (""glade/editor/enumeration_type_editor.glade"", Error'Access); + + if Error /= null then + raise Program_Error with ""Error: adam.Editor.of_enumeration_type ~ "" & Get_Message (Error); + end if; + + Self.top_Box := gtk_Box (the_Builder.get_Object (""top_Box"")); + Self.name_Entry := Gtk_Entry (the_Builder.get_Object (""name_Entry"")); + Self.is_Label := Gtk_Label (the_Builder.get_Object (""is_Label"")); + Self.literals_Box := gtk_Box (the_Builder.get_Object (""literals_Box"")); + Self.rid_Button := gtk_Button (the_Builder.get_Object (""rid_Button"")); + + Self.open_parenthesis_Label := Gtk_Label (the_Builder.get_Object (""open_parenthesis_Label"")); + Self.close_parenthesis_Label := Gtk_Label (the_Builder.get_Object (""close_parenthesis_Label"")); + + + Self.name_Entry.Set_Text (+Self.Target.Name); + + declare + use type Ada.Containers.Count_Type; + Attributes : Pango.Attributes.Pango_Attr_List := Pango.Attributes.Pango_Attr_List_New; + Scale : gDouble := Gdouble (2 * Self.Target.Literals.Length); + begin + Attributes.Change (pango.Attributes.Attr_Scale_New (Scale)); + Self. open_parenthesis_Label.set_Attributes (Attributes); + Self.close_parenthesis_Label.set_Attributes (Attributes); +-- Self.close_parenthesis_Label.Set_Size_Request (Height => 10);" +procedure Context_is (Self : in out Item; Now : in AdaM.Context.view),"is + begin + Self.Context := Now; + Self.freshen; + end Context_is; + + + + overriding function top_Widget (Self : in Item) return gtk.Widget.Gtk_Widget + is + begin + return gtk.Widget.Gtk_Widget (Self.Top); + end top_Widget; + + + + overriding + procedure freshen (Self : in out Item) + is + the_Lines : constant AdaM.context_Line.Vector := Self.Context.Lines; + begin + loop + declare + the_Child : constant gtk_Widget := Self.context_lines_Box.Get_Child (0); + begin + exit when the_Child = null; + the_Child.destroy;" +procedure register_Usage (the_Exception : in AdaM.Declaration.of_exception.view);,"function fetch return AdaM.Declaration.of_exception.vector; + end recent_Exceptions; + + + package body recent_Exceptions + is + type exception_Usage is + record + the_Exception : AdaM.Declaration.of_exception.view; + Count : Natural; + end record; + + function ""<"" (L, R : in exception_Usage) return Boolean + is + use type AdaM.Identifier; + begin + return L.the_Exception.Name < R.the_Exception.Name; + end ""<""; + + overriding function ""="" (L, R : in exception_Usage) return Boolean + is + use type AdaM.Identifier; + begin + return L.the_Exception.Name = R.the_Exception.Name; + end ""=""; + + package exception_Usage_Sets is new ada.Containers.Ordered_Sets (exception_Usage); + the_usage_Stats : exception_Usage_Sets.Set; + + +-- procedure register_Usage (the_Exception : in adam.Text) +-- is +-- use exception_Usage_Sets; +-- +-- the_exception_Usage : exception_Usage := (the_Exception, others => <>); +-- Current : constant exception_Usage_Sets.Cursor := the_usage_Stats.find (the_exception_Usage); +-- begin +-- if Current /= No_Element +-- then +-- the_exception_Usage.Count := Element (Current).Count + 1; +-- the_usage_Stats.replace_Element (Current, the_exception_Usage); +-- else +-- the_exception_Usage.Count := 1; +-- the_usage_Stats.insert (the_exception_Usage); +-- end if; +-- end register_Usage; + + procedure register_Usage (the_Exception : in AdaM.Declaration.of_exception.view) + is + use exception_Usage_Sets; + use type AdaM.Declaration.of_exception.view; + + the_exception_Usage : exception_Usage := (the_Exception, others => <>); + Current : constant exception_Usage_Sets.Cursor := the_usage_Stats.find (the_exception_Usage); + begin + if the_Exception = null + then + raise program_Error with ""NULLLLLLLL exception !!!""; + else + put_Line (""ALL FINEEEEEEEEEEEEEEEEEEEEEE""); + end if; + + if Current /= No_Element + then + the_exception_Usage.Count := Element (Current).Count + 1; + the_usage_Stats.replace_Element (Current, the_exception_Usage); + else + the_exception_Usage.Count := 1; + the_usage_Stats.insert (the_exception_Usage); + end if; + end register_Usage; + + + + function fetch return AdaM.Declaration.of_exception.vector + is + use exception_Usage_Sets, + ada.Containers; + +-- the_Lines : AdaM.text_Lines; + the_Exceptions : AdaM.Declaration.of_exception.vector; + + package type_Usage_Vectors is new ada.Containers.Vectors (Positive, exception_Usage); + use type_Usage_Vectors; + + the_usage_List : type_Usage_Vectors.Vector; + + begin + declare + Cursor : exception_Usage_Sets.Cursor := the_usage_Stats.First; + begin + while has_Element (Cursor) + loop + if Element (Cursor).Count > 0 then + the_usage_List.append (Element (Cursor)); + end if; + + exit when the_Exceptions.Length = 25; -- Limit results to 25 entries. + next (Cursor); + end loop;" +procedure choice_is (Self : in out Item; --Now : in String;,"-- package_Name : in String; + the_Exception : in AdaM.Declaration.of_exception.view) + is + use AdaM, + AdaM.Assist; + +-- full_Name : constant String := package_Name & ""."" & Now; + full_Name : constant String := String (the_Exception.full_Name); + + begin +-- recent_Exceptions.register_Usage (+full_Name); + recent_Exceptions.register_Usage (the_Exception); + Self.build_recent_List; + + Self.Invoked_by.set_Label (String (strip_standard_Prefix (identifier_Suffix (the_Exception.full_Name, 2)))); + Self.Invoked_by.set_Tooltip_Text (full_Name); + + Self.Target.my_Exception_is (Self.Slot, the_Exception); +-- Self.Target.my_add_Exception (the_Exception); + + Self.Top.hide; + end choice_is; + + + + procedure show (Self : in out Item; Invoked_by : in gtk_Button; + Target : in adam.exception_Handler.view; + Slot : in Positive) + is + begin + Self.Invoked_by := Invoked_by; + Self.Target := Target; + Self.Slot := Slot; + + Self.Top.show_All; + end show; + + + + procedure freshen (Self : in out Item) + is + use Adam; + +-- type a_Package; +-- type Package_view is access all a_Package; +-- +-- package package_Vectors is new ada.Containers.Vectors (Positive, Package_view); +-- subtype Package_vector is package_Vectors.Vector; +-- +-- type a_Package is +-- record +-- Name : adam.Text; +-- Parent : Package_view; +-- Children : Package_vector; +-- +-- Exceptions : adam.text_Lines; +-- end record; + +-- the_Exceptions : constant adam.text_Lines := adam.Assist.known_Exceptions; +-- Root : aliased a_Package; + + begin +-- Root.Name := +""Root""; + + + -- Clear out old notebook pages. + -- + while Self.all_Notebook.Get_N_Pages > 0 + loop + Self.all_Notebook.Get_Nth_Page (0).Destroy; + end loop; + + + -- Build the Gui tree. + -- + build_Gui_Tree: + declare + + procedure build_Gui_for (the_Package : in AdaM.a_Package.view; + children_Notebook : in gtk_Notebook) + is + the_Children : AdaM.a_Package.Vector renames the_Package.child_Packages; + the_exceptions_Palette_package : constant Palette.of_exceptions_subpackages.view + := aIDE.Palette.of_exceptions_subpackages.to_exceptions_Palette_package; + begin + -- Build the package pane. + -- + the_exceptions_Palette_package.Parent_is (Self'unchecked_Access); + + the_exceptions_Palette_package.top_Widget.Reparent (children_Notebook); + children_Notebook.set_Tab_Label_Text (the_exceptions_Palette_package.top_Widget, + +the_Package.Name); + + -- Build the exceptions sub-pane. + -- + for Each of the_Package.all_Exceptions + loop + the_exceptions_Palette_package.add_Exception (Each, the_Package); +-- the_exceptions_Palette_package.add_Exception (named => Each.Name, +-- package_Name => the_Package.Name); +-- -- package_Name => full_Name (the_Package)); + end loop; + + -- Configure event handling. + -- +-- declare +-- use gtk.Label; +-- the_tab_Label : constant gtk_Label +-- := gtk_Label (children_Notebook.get_tab_Label (the_exceptions_Palette_package.top_Widget)); +-- begin +-- the_tab_Label.set_Selectable (True); +-- label_return_Callbacks.connect (the_tab_Label, +-- ""button-release-event"", +-- on_tab_Label_clicked'Access, +-- (package_name => the_Package.Name, +-- palette => Self'unchecked_Access)); +-- end; + + -- Build each childs Gui. + -- + for i in 1 .. Integer (the_Children.Length) + loop + build_Gui_for (the_Children.Element (i), + the_exceptions_Palette_package.children_Notebook); -- Recurse. + end loop; + + enable_bold_Tabs_for (the_exceptions_Palette_package.children_Notebook); + end build_Gui_for; + + begin + -- Recursively add sub-gui's for each package, rooted at 'Standard'. + -- +-- for i in 1 .. Integer (the_Environ.standard_Package.Children.Length) +-- loop +-- build_Gui_for (the_Environ.standard_Package.child_Packages.Element (i).all'Access, +-- Self.all_Notebook); +-- end loop; + +-- for i in 1 .. Integer (the_entity_Environ.standard_Package.child_Packages.Length) +-- loop +-- build_Gui_for (the_Environ.standard_Package.child_Packages.Element (i).all'Access, +-- Self.all_Notebook); +-- end loop; + + build_Gui_for (the_entity_Environ.standard_Package, + Self.all_Notebook); + + Self.all_Notebook.Popup_enable; + Self.all_Notebook.Show_All; + end build_Gui_Tree; + + Self.build_recent_List; -- todo: This is useless til usage stats are made persistent. + end freshen; + + + + procedure destroy_Callback (Widget : not null access Gtk.Widget.Gtk_Widget_Record'Class) + is + begin + Widget.destroy; + end destroy_Callback; + + + + procedure build_recent_List (Self : in out Item) + is +-- the_Recent : constant adam.text_Lines := recent_Exceptions.fetch; + the_Recent : constant adam.Declaration.of_exception.vector := recent_Exceptions.fetch; + the_Button : gtk_Button; + + Row, Col : Guint := 0; + begin + Self.recent_Table.Foreach (destroy_Callback'Access); + + for i in 1 .. Integer (the_Recent.Length) + loop + declare + use adam, + ada.Strings.Unbounded; +-- the_Exception : adam.Text renames the_Recent.Element (i); + the_Exception : constant adam.Declaration.of_exception.view := the_Recent.Element (i); + begin + put_Line (""Recent: "" & String (the_Exception.full_Name)); + put_Line (""Named : "" & String (assist. Tail_of (the_Exception.full_Name))); + put_Line (""package_Name: "" & String (assist.strip_Tail_of (the_Exception.full_Name))); + +-- gtk_New (the_Button, +the_Exception); + the_Button := aIDE.Palette.of_exceptions_subpackages.new_Button + (for_Exception => the_Exception, + Named => String (assist. Tail_of (the_Exception.full_Name)), + package_Name => String (assist.strip_Tail_of (the_Exception.full_Name)), + exceptions_Palette => Self'unchecked_Access, + use_simple_Name => False); + + Self.recent_Table.attach (the_Button, + Col, Col + 1, + Row, Row + 1, + Xoptions => 0, + Yoptions => 0); + the_Button.show_All; + + if Row = 6 then + Row := 0; + Col := Col + 1; + else + Row := Row + 1; + end if;" +procedure register_Usage (the_Exception : in AdaM.a_Type.view);,"function fetch return AdaM.a_Type.vector; + end recent_Exceptions; + + + package body recent_Exceptions + is + type exception_Usage is + record + the_Exception : AdaM.a_Type.view; + Count : Natural; + end record; + + function ""<"" (L, R : in exception_Usage) return Boolean + is + use type AdaM.Identifier; + begin + return L.the_Exception.Name < R.the_Exception.Name; + end ""<""; + + overriding function ""="" (L, R : in exception_Usage) return Boolean + is + use type AdaM.Identifier; + begin + return L.the_Exception.Name = R.the_Exception.Name; + end ""=""; + + package exception_Usage_Sets is new ada.Containers.Ordered_Sets (exception_Usage); + the_usage_Stats : exception_Usage_Sets.Set; + + +-- procedure register_Usage (the_Exception : in adam.Text) +-- is +-- use exception_Usage_Sets; +-- +-- the_exception_Usage : exception_Usage := (the_Exception, others => <>); +-- Current : constant exception_Usage_Sets.Cursor := the_usage_Stats.find (the_exception_Usage); +-- begin +-- if Current /= No_Element +-- then +-- the_exception_Usage.Count := Element (Current).Count + 1; +-- the_usage_Stats.replace_Element (Current, the_exception_Usage); +-- else +-- the_exception_Usage.Count := 1; +-- the_usage_Stats.insert (the_exception_Usage); +-- end if; +-- end register_Usage; + + procedure register_Usage (the_Exception : in AdaM.a_Type.view) + is + use exception_Usage_Sets; + use type AdaM.a_Type.view; + + the_exception_Usage : exception_Usage := (the_Exception, others => <>); + Current : constant exception_Usage_Sets.Cursor := the_usage_Stats.find (the_exception_Usage); + begin + if the_Exception = null + then + raise program_Error with ""NULLLLLLLL exception !!!""; + else + put_Line (""ALL FINEEEEEEEEEEEEEEEEEEEEEE""); + end if; + + if Current /= No_Element + then + the_exception_Usage.Count := Element (Current).Count + 1; + the_usage_Stats.replace_Element (Current, the_exception_Usage); + else + the_exception_Usage.Count := 1; + the_usage_Stats.insert (the_exception_Usage); + end if; + end register_Usage; + + + + function fetch return AdaM.a_Type.vector + is + use exception_Usage_Sets, + ada.Containers; + +-- the_Lines : AdaM.text_Lines; + the_Exceptions : AdaM.a_Type.vector; + + package type_Usage_Vectors is new ada.Containers.Vectors (Positive, exception_Usage); + use type_Usage_Vectors; + + the_usage_List : type_Usage_Vectors.Vector; + + begin + declare + Cursor : exception_Usage_Sets.Cursor := the_usage_Stats.First; + begin + while has_Element (Cursor) + loop + if Element (Cursor).Count > 0 then + the_usage_List.append (Element (Cursor)); + end if; + + exit when the_Exceptions.Length = 25; -- Limit results to 25 entries. + next (Cursor); + end loop;" +procedure choice_is (Self : in out Item; --Now : in String;,"-- package_Name : in String; + the_Type : in AdaM.a_Type.view) + is + use AdaM, + AdaM.Assist; + +-- full_Name : constant String := package_Name & ""."" & Now; + full_Name : constant String := String (the_Type.full_Name); + + begin +-- recent_Exceptions.register_Usage (+full_Name); + recent_Exceptions.register_Usage (the_Type); + Self.build_recent_List; + + Self.Invoked_by.set_Label (String (strip_standard_Prefix (identifier_Suffix (the_Type.full_Name, 2)))); + Self.Invoked_by.set_Tooltip_Text (full_Name); + + Self.Target.all := the_Type; +-- Self.Target.my_add_Exception (the_Exception); + + Self.Top.hide; + end choice_is; + + + + procedure show (Self : in out Item; Invoked_by : in Gtk.Button.gtk_Button; + Target : access AdaM.a_Type.view) + is + begin + Self.Invoked_by := Invoked_by; + Self.Target := Target; +-- Self.Slot := Slot; + + Self.Top.show_All; + end show; + + + + procedure freshen (Self : in out Item) + is + use Adam; + +-- type a_Package; +-- type Package_view is access all a_Package; +-- +-- package package_Vectors is new ada.Containers.Vectors (Positive, Package_view); +-- subtype Package_vector is package_Vectors.Vector; +-- +-- type a_Package is +-- record +-- Name : adam.Text; +-- Parent : Package_view; +-- Children : Package_vector; +-- +-- Exceptions : adam.text_Lines; +-- end record; + +-- the_Exceptions : constant adam.text_Lines := adam.Assist.known_Exceptions; +-- Root : aliased a_Package; + + begin +-- Root.Name := +""Root""; + + + -- Clear out old notebook pages. + -- + while Self.all_Notebook.Get_N_Pages > 0 + loop + Self.all_Notebook.Get_Nth_Page (0).Destroy; + end loop; + + + -- Build the Gui tree. + -- + build_Gui_Tree: + declare + + procedure build_Gui_for (the_Package : in AdaM.a_Package.view; + children_Notebook : in gtk_Notebook) + is + the_Children : AdaM.a_Package.Vector renames the_Package.child_Packages; + the_exceptions_Palette_package : constant Palette.of_types_subpackages.view + := aIDE.Palette.of_types_subpackages.to_exceptions_Palette_package; + begin + -- Build the package pane. + -- + the_exceptions_Palette_package.Parent_is (Self'unchecked_Access); + + the_exceptions_Palette_package.top_Widget.Reparent (children_Notebook); + children_Notebook.set_Tab_Label_Text (the_exceptions_Palette_package.top_Widget, + +the_Package.Name); + + -- Build the exceptions sub-pane. + -- + for Each of the_Package.all_Types + loop + the_exceptions_Palette_package.add_Exception (Each, the_Package); +-- the_exceptions_Palette_package.add_Exception (named => Each.Name, +-- package_Name => the_Package.Name); +-- -- package_Name => full_Name (the_Package)); + end loop; + + -- Configure event handling. + -- +-- declare +-- use gtk.Label; +-- the_tab_Label : constant gtk_Label +-- := gtk_Label (children_Notebook.get_tab_Label (the_exceptions_Palette_package.top_Widget)); +-- begin +-- the_tab_Label.set_Selectable (True); +-- label_return_Callbacks.connect (the_tab_Label, +-- ""button-release-event"", +-- on_tab_Label_clicked'Access, +-- (package_name => the_Package.Name, +-- palette => Self'unchecked_Access)); +-- end; + + -- Build each childs Gui. + -- + for i in 1 .. Integer (the_Children.Length) + loop + build_Gui_for (the_Children.Element (i), + the_exceptions_Palette_package.children_Notebook); -- Recurse. + end loop; + + enable_bold_Tabs_for (the_exceptions_Palette_package.children_Notebook); + end build_Gui_for; + + begin + -- Recursively add sub-gui's for each package, rooted at 'Standard'. + -- +-- for i in 1 .. Integer (the_Environ.standard_Package.Children.Length) +-- loop +-- build_Gui_for (the_Environ.standard_Package.child_Packages.Element (i).all'Access, +-- Self.all_Notebook); +-- end loop; + +-- for i in 1 .. Integer (the_entity_Environ.standard_Package.child_Packages.Length) +-- loop +-- build_Gui_for (the_Environ.standard_Package.child_Packages.Element (i).all'Access, +-- Self.all_Notebook); +-- end loop; + + build_Gui_for (the_entity_Environ.standard_Package, + Self.all_Notebook); + + Self.all_Notebook.Popup_enable; + Self.all_Notebook.Show_All; + end build_Gui_Tree; + + Self.build_recent_List; -- todo: This is useless til usage stats are made persistent. + end freshen; + + + + procedure destroy_Callback (Widget : not null access Gtk.Widget.Gtk_Widget_Record'Class) + is + begin + Widget.destroy; + end destroy_Callback; + + + + procedure build_recent_List (Self : in out Item) + is +-- the_Recent : constant adam.text_Lines := recent_Exceptions.fetch; + the_Recent : constant adam.a_Type.vector := recent_Exceptions.fetch; + the_Button : gtk_Button; + + Row, Col : Guint := 0; + begin + Self.recent_Table.Foreach (destroy_Callback'Access); + + for i in 1 .. Integer (the_Recent.Length) + loop + declare + use adam, + ada.Strings.Unbounded; +-- the_Exception : adam.Text renames the_Recent.Element (i); + the_Exception : constant adam.a_Type.view := the_Recent.Element (i); + begin + put_Line (""Recent: "" & String (the_Exception.full_Name)); + put_Line (""Named : "" & String (assist. Tail_of (the_Exception.full_Name))); + put_Line (""package_Name: "" & String (assist.strip_Tail_of (the_Exception.full_Name))); + +-- gtk_New (the_Button, +the_Exception); + the_Button := aIDE.Palette.of_types_subpackages.new_Button + (for_Exception => the_Exception, + Named => String (assist. Tail_of (the_Exception.full_Name)), + package_Name => String (assist.strip_Tail_of (the_Exception.full_Name)), + exceptions_Palette => Self'unchecked_Access, + use_simple_Name => False); + + Self.recent_Table.attach (the_Button, + Col, Col + 1, + Row, Row + 1, + Xoptions => 0, + Yoptions => 0); + the_Button.show_All; + + if Row = 6 then + Row := 0; + Col := Col + 1; + else + Row := Row + 1; + end if;" +-- procedure register_Usage (package_Name : in AdaM.Text;,"-- the_Package : in AdaM.a_Package.view) +-- is +-- use package_Usage_Sets; +-- +-- the_type_Usage : package_Usage := (the_Package, package_Name, others => <>); +-- Current : constant package_Usage_Sets.Cursor := the_usage_Stats.find (the_type_Usage); +-- begin +-- if Current /= No_Element +-- then +-- the_type_Usage.Count := Element (Current).Count + 1; +-- the_usage_Stats.replace_Element (Current, the_type_Usage); +-- else +-- the_type_Usage.Count := 1; +-- the_usage_Stats.insert (the_type_Usage); +-- end if; +-- end register_Usage; + + + + + procedure register_Usage (the_Package : in AdaM.a_Package.view) + is + use package_Usage_Sets; + + the_type_Usage : package_Usage := (the_Package, others => <>); + Current : constant package_Usage_Sets.Cursor := the_usage_Stats.find (the_type_Usage); + begin + if Current /= No_Element + then + the_type_Usage.Count := Element (Current).Count + 1; + the_usage_Stats.replace_Element (Current, the_type_Usage); + else + the_type_Usage.Count := 1; + the_usage_Stats.insert (the_type_Usage); + end if; + end register_Usage; + + + + function fetch return AdaM.a_Package.vector + is + use package_Usage_Sets, + ada.Containers; + +-- the_Lines : AdaM.text_Lines; + the_Packages : AdaM.a_Package.vector; + + package type_Usage_Vectors is new ada.Containers.Vectors (Positive, package_Usage); + use type_Usage_Vectors; + + the_usage_List : type_Usage_Vectors.Vector; + + begin + declare + Cursor : package_Usage_Sets.Cursor := the_usage_Stats.First; + begin + while has_Element (Cursor) + loop + if Element (Cursor).Count > 0 then + the_usage_List.append (Element (Cursor)); + end if; + + exit when the_Packages.Length = 25; -- Limit results to 25 entries. + next (Cursor); + end loop;" +procedure choice_is (Self : in out Item; package_Name : in String;,"the_Package : in AdaM.a_Package.view) + is + use AdaM, + AdaM.Assist; + use type AdaM.context_Line.view, + AdaM.a_Package.view; + + full_Name : constant String := package_Name; + begin +-- recent_Packages.register_Usage (+full_Name, the_Package); + recent_Packages.register_Usage (the_Package); + Self.build_recent_List; + + if Self.Invoked_by /= null + then +-- Self.Invoked_by.set_Label (full_Name); + Self.Invoked_by.set_Label (String (identifier_Suffix (the_Package.full_Name, 2))); + Self.Invoked_by.set_Tooltip_Text (String (the_Package.full_Name)); + end if; + + if Self.Target /= null and Self.Target_2 /= null + then + raise program_Error with ""Self.Target /= null and Self.Target_2 /= null""; + end if; + + if Self.Target /= null + then + Self.Target.Name_is (full_Name); + Self.Target.Package_is (the_Package.all'Access); + + elsif Self.Target_2 /= null + then +-- put_Line (""JJJJJ "" & String (Self.Target_2.Name)); +-- aIDE.Gui.set_selected_Package (to => Self.Target_2); + put_Line (""JJJJJ "" & String (the_Package.Name)); + aIDE.Gui.set_selected_Package (to => the_Package); + + else + raise program_Error with ""No target has been set""; + end if; + + Self.Top.hide; + end choice_is; + + + + procedure show (Self : in out Item; Invoked_by : in Gtk.Button.gtk_Button; + Target : in AdaM.context_Line.view) + is + begin + Self.Invoked_by := Invoked_by; + Self.Target := Target; + Self.Target_2 := null; + + Self.Top.show_All; + end show; + + + procedure show (Self : in out Item; Invoked_by : in Gtk.Button.gtk_Button; + Target : in AdaM.a_Package.view) + is + begin + Self.Invoked_by := Invoked_by; + Self.Target_2 := Target; + Self.Target := null; + + Self.freshen; + Self.Top.show_All; + end show; + + + + procedure freshen (Self : in out Item) + is + use AdaM; + +-- the_Environ : AdaM.Environment.Item renames aIDE.the_Environ; + + begin + -- Clear out old notebook pages. + -- + while Self.all_Notebook.Get_N_Pages > 0 + loop + Self.all_Notebook.Get_Nth_Page (0).Destroy; + end loop; + + + -- Build the Gui tree. + -- + build_Gui_Tree: + declare + procedure build_Gui_for (the_Package : in AdaM.a_Package.view; + children_Notebook : in gtk_Notebook) + is + the_Children : AdaM.a_Package.Vector renames the_Package.child_Packages; + the_packages_Palette_package : constant Palette.of_packages_subpackages.view + := aIDE.Palette.of_packages_subpackages.to_packages_Palette_package; + begin + -- Build the package pane. + -- + the_packages_Palette_package.Parent_is (Self'unchecked_Access); + + the_packages_Palette_package.top_Widget.reparent (children_Notebook); + children_Notebook.set_Tab_Label_Text (the_packages_Palette_package.top_Widget, + +the_Package.Name); + -- Configure event handling. + -- + declare + use gtk.Label; + the_tab_Label : constant gtk_Label + := gtk_Label (children_Notebook.get_tab_Label (the_packages_Palette_package.top_Widget)); + begin + the_tab_Label.set_Selectable (True); + label_return_Callbacks.connect (the_tab_Label, + ""button-release-event"", + on_tab_Label_clicked'Access, + (package_name => +(+the_Package.Name), + palette => Self'unchecked_Access, + the_Package => the_Package));" +procedure build_recent_List (Self : in out Item),"is +-- the_Recent : constant AdaM.text_Lines := recent_Packages.fetch; + the_Recent : constant AdaM.a_Package.vector := recent_Packages.fetch; + the_Button : gtk_Button; + + Row, Col : Guint := 0; + begin + put_Line (""build_recent_List""); + + Self.recent_Table.Foreach (destroy_Callback'Access); + + for i in 1 .. Integer (the_Recent.Length) + loop + declare + use AdaM; + the_Package : AdaM.a_Package.view renames the_Recent.Element (i); + begin + the_Button := aIDE.Palette.of_packages_subpackages.new_Button (for_Package => the_Package, + Named => +the_Package.Name, + packages_Palette => Self'unchecked_Access); + Self.recent_Table.attach (the_Button, + Col, Col + 1, + Row, Row + 1, + Xoptions => 0, + Yoptions => 0); + the_Button.show_All; + + if Row = 6 + then + Row := 0; + Col := Col + 1; + else + Row := Row + 1; + end if;" +procedure register_Usage (the_Type : in Identifier);,"function fetch return text_Lines; + end recent_Types; + + + package body recent_Types + is + type type_Usage is + record + Name : Text; -- The type name. + Count : Natural; -- Number of times the type has been used. + end record; + + use type Adam.Text; + + function ""<"" (L, R : in type_Usage) return Boolean + is + begin + return L.Name < R.Name; + end ""<""; + + overriding function ""="" (L, R : in type_Usage) return Boolean + is + begin + return L.Name = R.Name; + end ""=""; + + package type_Usage_Sets is new ada.Containers.Ordered_Sets (type_Usage); + the_usage_Stats : type_Usage_Sets.Set; + + + procedure register_Usage (the_Type : in Identifier) + is + use type_Usage_Sets; + + the_type_Usage : type_Usage := (+String (the_Type), others => <>); + Current : constant type_Usage_Sets.Cursor := the_usage_Stats.find (the_type_Usage); + begin + if Current /= No_Element + then + the_type_Usage.Count := Element (Current).Count + 1; + the_usage_Stats.replace_Element (Current, the_type_Usage); + else + the_type_Usage.Count := 1; + the_usage_Stats.insert (the_type_Usage); + end if; + end register_Usage; + + + function fetch return text_Lines + is + use type_Usage_Sets, + ada.Containers; + + the_Lines : text_Lines; + + package type_Usage_Vectors is new ada.Containers.Vectors (Positive, type_Usage); + use type_Usage_Vectors; + + the_usage_List : type_Usage_Vectors.Vector; + + begin + declare + Cursor : type_Usage_Sets.Cursor := the_usage_Stats.First; + begin + while has_Element (Cursor) + loop + if Element (Cursor).Count > 0 then + the_usage_List.append (Element (Cursor)); + end if; + + exit when the_Lines.Length = 25; + next (Cursor); + end loop;" +procedure choice_is (Self : in out Item; Now : in String;,"package_Name : in String) + is + full_Name : constant Identifier := Identifier (package_Name & ""."" & Now); + begin + recent_Types.register_Usage (full_Name); + Self.build_recent_List; + + Self.Invoked_by.set_Label (assist.type_button_Name_of (full_Name)); + Self.Invoked_by.set_Tooltip_Text (String (full_Name)); + +-- Self.Target.all := +full_Name; + +-- declare +-- use type Class.view; +-- the_Class : constant Class.view := aIDE.fetch_Class (named => package_Name); +-- begin +-- if the_Class = null then + Self.Target.all := aIDE.the_entity_Environ.find (full_Name); -- .Name_is (full_Name); +-- Self.Target.all.Class_is (null); +-- else +-- -- Self.Target.all.Name_is (""""); +-- Self.Target.all := a_Type.class_type.new_Type.all'Access; -- .Class_is (the_Class); +-- Self.Target.all.Class_is (the_Class); +-- end if; +-- end; + + Self.Top.hide; + end choice_is; + + + + procedure show (Self : in out Item; Invoked_by : in gtk.Button.gtk_Button; + Target : access adam.a_Type.view) + is + begin + Self.Invoked_by := Invoked_by; + Self.Target := Target; + + Self.Top.show_All; + end show; + + + + procedure freshen (Self : in out Item) + is + type a_Package; + type Package_view is access all a_Package; + + package package_Vectors is new ada.Containers.Vectors (Positive, Package_view); + subtype Package_vector is package_Vectors.Vector; + + type a_Package is + record + Name : Text; + Parent : Package_view; + Children : Package_vector; + + Types : adam.text_Lines; + end record; + + the_Types : constant adam.a_Type.Vector := aIDE.the_entity_Environ.all_Types; + Root : aliased a_Package; + + + function full_Name (the_Package : in Package_view) return String + is + use ada.Strings.Unbounded, + text_Vectors; + the_Name : Text; + Parent : Package_view := the_Package.Parent; + begin + the_Name := the_Package.Name; + + while Parent /= null + loop + if Parent.Parent /= null then + insert (the_Name, 1, +Parent.Name & "".""); + end if; + + Parent := Parent.Parent; + end loop; + + return +the_Name; + end full_Name; + + + function find_Child (Parent : in Package_view; + Named : in String) return Package_view + is + use Adam.Assist; + Names : text_Lines := Split (Named); + begin +-- put_Line (""Finding '"" & Named & ""' in '"" & full_Name (Parent) & ""'""); + + for i in 1 .. Integer (Parent.Children.Length) + loop + declare + use ada.Characters.handling; + the_Child : constant Package_view := Parent.Children.Element (i); + begin + if to_Lower (+the_Child.Name) = to_Lower (Named) then + return the_Child; + end if;" +procedure build_recent_List (Self : in out Item),"is + the_Recent : constant text_Lines := recent_Types.fetch; + the_Button : gtk_Button; + + Row, Col : Guint := 0; + begin + Self.recent_Table.Foreach (destroy_Callback'Access); + + for i in 1 .. Integer (the_Recent.Length) + loop + declare + use ada.Strings.Unbounded; + the_Type : Text renames the_Recent.Element (i); + begin + new_Line; + put_Line (+(""Recent: "" & the_Type)); + put_Line ("" Tail: "" & assist. Tail_of (+the_Type)); + put_Line ("" Head: "" & assist.strip_Tail_of (+the_Type)); + +-- gtk_New (the_Button, +the_Type); + the_Button := aIDE.Palette.types_package.new_Button (Named => assist. Tail_of (+the_Type), + package_Name => assist.strip_Tail_of (+the_Type), + types_Palette => Self'unchecked_Access, + use_simple_Name => False); + Self.recent_Table.attach (the_Button, + Col, Col + 1, + Row, Row + 1, + Xoptions => 0, + Yoptions => 0); + the_Button.show_All; + + if Row = 6 then + Row := 0; + Col := Col + 1; + else + Row := Row + 1; + end if;" +procedure Name_is (Self : in out Item; Now : in String),"is + begin + Self.Name := +Now; + end Name_is; + + + + function full_Name (Self : in Item) return Identifier + is + use type Entity.view; + begin + if Self.parent_Entity = null + then + return ""Standard."" & (+Self.Name); + else + return a_Package.view (Self.parent_Entity).full_Name & ""."" & (+Self.Name); + end if; + end full_Name; + + + + -- Streams + -- + + procedure View_write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; + Self : in View) + is + use Ada.Tags; + begin + if Self = null + then + AdaM.Id'write (Stream, null_Id); + return; + end if; + + AdaM.Id'write (Stream, Self.Id); + String 'output (Stream, external_Tag (Self.all'Tag)); + end View_write; + + + + procedure View_read (Stream : not null access Ada.Streams.Root_Stream_Type'Class; + Self : out View) + is + Id : AdaM.Id; + begin + AdaM.Id'read (Stream, Id); + + if Id = null_Id + then + Self := null; + return; + end if; + + declare + use Ada.Tags; + the_String : constant String := String'Input (Stream); -- Read tag as string from stream. + the_Tag : constant Tag := Descendant_Tag (the_String, Item'Tag); -- Convert to a tag. + begin + Self := View (AdaM.Factory.to_View (Id, the_Tag));" +procedure register_Storer (the_Storer : access procedure),"is + begin + all_Storers.append (the_Storer); + end register_Storer; + + + procedure register_Restorer (the_Restorer : access procedure) + is + begin + all_Restorers.append (the_Restorer); + end register_Restorer; + + + + + type to_View_function is access function (Id : in AdaM.Id) return Any_view; + + function Hash is new ada.Unchecked_Conversion (ada.Tags.Tag, ada.Containers.Hash_Type); + use type ada.Tags.Tag; + + package tag_Maps_of_to_View_function is new ada.Containers.Hashed_Maps (Key_Type => ada.Tags.Tag, + Element_Type => to_View_function, + Hash => Hash, + Equivalent_Keys => ""=""); + + tag_Map_of_to_View_function : tag_Maps_of_to_View_function.Map; + + procedure register_to_view_Function (the_Tag : in ada.Tags.Tag; + the_Function : access function (Id : in AdaM.Id) return Any_view) + is + begin + tag_Map_of_to_View_function.insert (the_Tag, the_Function); + end register_to_view_Function; + + + + function to_View (Id : in AdaM.Id; Tag : in ada.Tags.Tag) return Any_view + is + use tag_Maps_of_to_View_function; + the_Function : constant to_View_function := Element (tag_Map_of_to_View_function.Find (Tag)); + begin + return the_Function (Id); + end to_View; + + + + -- Pools + -- + + + package body Pools + is + use Interfaces.C; + + -- Arrays and Pointers for our Pool. + -- + + subtype item_Id is AdaM.Id range 1 .. AdaM.Id'Last; + + type Items is array (item_Id range <>) of aliased Item; + + type Addr is mod 2 ** System.Parameters.ptr_bits; + + function to_Addr is new Ada.Unchecked_Conversion (View, Addr); + function to_Ptrdiff is new Ada.Unchecked_Conversion (Addr, Interfaces.C.ptrdiff_t); + + Elmt_Size : constant ptrdiff_t := (Items'Component_Size + System.Storage_Unit - 1) + / System.Storage_Unit; + + + function ""-"" (Left : in View; + Right : in View) return ptrdiff_t + is + begin + if Left = null + or else Right = null + then + raise constraint_Error; + end if; + + return To_Ptrdiff (To_Addr (Left) - To_Addr (Right)) + / Elmt_Size; + end ""-""; + + + -- The storage pool. + -- + Pool : Items (1 .. item_Id (max_Items)); + pool_Last : AdaM.Id := null_Id; + + stored_record_Version : Positive; + + function storage_record_Version return Positive + is + begin + return stored_record_Version; + end storage_record_Version; + + + package view_Vectors is new ada.Containers.Vectors (Positive, View); + + freed_Views : view_Vectors.Vector; + + + -- 'View' to 'Id' Resolution. + -- + + function to_View (Id : in AdaM.Id) return View + is + begin + return Pool (Id)'Access; + end to_View; + + + function to_View (Id : in AdaM.Id) return Any_view + is + begin + if Id not in item_Id + then + raise Constraint_Error with ""AdaM.Factory ~ Bad pool Id ("" & item_Id'Image (Id) & "") for pool "" & pool_Name; + end if; + + declare + the_View : constant View := Pool (Id)'Access; + begin + return Any_view (the_View);" +procedure standard_package_is (Self : in out Item; Now : in AdaM.a_Package.view),"is + begin + Self.standard_Package := Now; + end standard_package_is; + + + + function standard_Package (Self : in Item) return AdaM.a_Package.view + is + begin + return Self.standard_Package; + end standard_Package; + + + + function all_Types (Self : in Item) return AdaM.a_Type.Vector + is + the_Types : AdaM.a_Type.Vector; + + the_Unit : AdaM.compilation_Unit.view; + pragma Unreferenced (the_Unit); +-- the_Entity : AdaM.Source.Entity_View; + + use type AdaM.a_Type.view; + begin + for i in 1 .. Self.Length + loop + the_Unit := Self.Units.Element (i); + +-- for j in 1 .. the_Unit.Length +-- loop +-- the_Entity := the_Unit.Entity (j); +-- +-- if the_Entity.all in AdaM.a_Type.item'Class +-- then +-- the_Types.append (AdaM.a_Type.view (the_Entity)); +-- end if; +-- end loop; + end loop; + + return the_Types; + end all_Types; + + + + + +-- -- TODO: Move these to AdaM.Assist. +-- +-- function parent_Name (Identifier : in String) return String +-- is +-- use Ada.Strings, +-- Ada.Strings.fixed; +-- I : constant Natural := Index (Identifier, ""."", going => Backward); +-- begin +-- if I = 0 +-- then +-- return ""Standard""; +-- end if; +-- +-- return Identifier (Identifier'First .. I - 1); +-- end parent_Name; +-- +-- +-- +-- function simple_Name (Identifier : in String) return String +-- is +-- use Ada.Strings, +-- Ada.Strings.fixed; +-- I : constant Natural := Index (Identifier, ""."", going => Backward); +-- begin +-- if I = 0 +-- then +-- return Identifier; +-- end if; +-- +-- return Identifier (I + 1 .. Identifier'Last); +-- end simple_Name; +-- +-- +-- +-- function Split (Identifier : in String) return text_Lines +-- is +-- use Ada.Strings, +-- Ada.Strings.fixed; +-- +-- First : Natural := Identifier'First; +-- Last : Natural; +-- +-- I : Natural; +-- Lines : text_Lines; +-- begin +-- loop +-- I := Index (Identifier, ""."", from => First); +-- +-- if I = 0 +-- then +-- Last := Identifier'Last; +-- Lines.append (+Identifier (First .. Last)); +-- exit; +-- end if; +-- +-- Last := I - 1; +-- Lines.append (+Identifier (First .. Last)); +-- First := I + 1; +-- end loop; +-- +-- return Lines; +-- end Split; + + + + function find (Self : in Item; Identifier : in AdaM.Identifier) return AdaM.a_Package.view + is + use AdaM.Assist; + the_Package : AdaM.a_Package.view := Self.standard_Package; + begin + if Identifier /= ""Standard"" + then + declare + use type AdaM.a_Package.view; + Names : constant text_Lines := Split (Identifier); + begin + for Each of Names + loop + the_Package := the_Package.child_Package (+Each); + exit when the_Package = null; + end loop;" +procedure parent_Entity_is (Self : in out Item; Now : in Entity.View),"is + begin + Self.parent_Entity := Now; + end parent_Entity_is; + + + + function Children (Self : access Item) return Entities_view + is + begin + return Self.Children'unchecked_Access; + end Children; + + + function Children (Self : in Item) return Entities'Class + is + begin + return Self.Children; + end Children; + + + procedure Children_are (Self : in out Item; Now : in Entities'Class) + is + begin + Self.Children := Entities (Now); + end Children_are; + + + + function is_Public (Self : in Item) return Boolean + is + begin + return Self.is_Public; + end is_Public; + + + procedure is_Public (Self : in out Item; Now : in Boolean := True) + is + begin + Self.is_Public := Now; + end is_Public; + + + + + ---------- + -- Streams + -- + + procedure View_write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; + Self : in View) + is + use Ada.Tags; + begin + if Self = null + then + AdaM.Id'write (Stream, null_Id); + return; + end if; + + AdaM.Id'write (Stream, Self.Id); + String 'output (Stream, external_Tag (Self.all'Tag)); + end View_write; + + + + procedure View_read (Stream : not null access Ada.Streams.Root_Stream_Type'Class; + Self : out View) + is + Id : AdaM.Id; + begin + AdaM.Id'read (Stream, Id); + + if Id = null_Id + then + Self := null; + return; + end if; + + declare + use Ada.Tags; + the_String : constant String := String'Input (Stream); -- Read tag as string from stream. + the_Tag : constant Tag := Descendant_Tag (the_String, Item'Tag); -- Convert to a tag. + begin + Self := View (AdaM.Factory.to_View (Id, the_Tag));" +-- procedure Name_is (Self : in out Item; Now : in String),"-- is +-- begin +-- Self.Name := +Now; +-- end Name_is; + + + + function Context (Self : in Item) return AdaM.Context.view + is + begin + return Self.Context; + end Context; + + + +-- procedure add (Self : in out Item; the_Declaration : in Source.Entity_View) +-- is +-- begin +-- Self.public_Entities.append (the_Declaration); -- Add the new attribute to current attributes. +-- end add; +-- +-- +-- procedure rid (Self : in out Item; the_Declaration : in Source.Entity_View) +-- is +-- begin +-- Self.public_Entities.delete (Self.public_Entities.find_Index (the_Declaration)); -- Remove the old attribute from current attributes. +-- end rid; +-- +-- +-- +-- +-- function public_Entities (Self : access Item) return access Source.Entities +-- is +-- begin +-- return Self.public_Entities'Access; +-- end public_Entities; +-- +-- +-- procedure public_Entities_are (Self : in out Item; Now : in Source.Entities) +-- is +-- begin +-- Self.public_Entities := Now; +-- end public_Entities_are; +-- + + +-- function all_Exceptions (Self : in Item) return AdaM.Declaration.of_exception.Vector +-- is +-- use type Declaration.of_exception.view; +-- +-- the_Exceptions : AdaM.Declaration.of_exception.Vector; +-- the_Exception : AdaM.Declaration.of_exception.view; +-- begin +-- put_Line (""PACKAGE NAME: "" & (+Self.Name)); +-- +-- for Each of Self.public_Entities +-- loop +-- put_Line (""************* Tag: "" & ada.Tags.External_Tag (Each.all'Tag)); +-- raise program_Error with ""sdfhslkad""; +-- +-- the_Exception := Declaration.of_exception.view (Each); +-- +-- if the_Exception /= null +-- -- if Each in AdaM.an_Exception.item'Class +-- then +-- the_Exceptions.append (the_Exception); +-- end if; +-- end loop; +-- +-- return the_Exceptions; +-- end all_Exceptions; + + + function all_Exceptions (Self : access Item) return AdaM.Declaration.of_exception.Vector + is + use type Declaration.of_exception.view; + + the_Exceptions : AdaM.Declaration.of_exception.Vector; +-- the_Exception : AdaM.Declaration.of_exception.view; + begin +-- put_Line (""all_Exceptions PACKAGE NAME: "" & (+Self.Name)); + + for Each of Self.Children.all + loop +-- put_Line (""************* Tag: "" & ada.Tags.External_Tag (Each.all'Tag)); +-- raise program_Error with ""sdfhslkad""; + +-- the_Exception := Declaration.of_exception.view (Each); + +-- if the_Exception /= null + if Each.all in AdaM.Declaration.of_Exception.item'Class + then + the_Exceptions.append (Declaration.of_exception.view (Each)); + end if; + end loop; + + return the_Exceptions; + end all_Exceptions; + + + + + function all_Types (Self : access Item) return AdaM.a_Type.Vector + is + use type a_Type.view; + + the_Exceptions : AdaM.a_Type.Vector; +-- the_Exception : AdaM.Declaration.of_exception.view; + begin +-- put_Line (""all_Exceptions PACKAGE NAME: "" & (+Self.Name)); + + for Each of Self.Children.all + loop +-- put_Line (""************* Tag: "" & ada.Tags.External_Tag (Each.all'Tag)); +-- raise program_Error with ""sdfhslkad""; + +-- the_Exception := Declaration.of_exception.view (Each); + +-- if the_Exception /= null + if Each.all in AdaM.a_Type.item'Class + then + the_Exceptions.append (a_Type.view (Each)); + end if; + end loop; + + return the_Exceptions; + end all_Types; + + + + + + + + overriding + function to_Source (Self : in Item) return text_Vectors.Vector + is + use ada.Strings.unbounded; + + the_Source : text_Vectors.Vector; + + procedure add (the_Line : in Text) + is + begin + the_Source.append (the_Line); + end add; + + begin + the_Source.append (Self.Context.to_Source); + + add (+""""); + add ( ""package "" & Self.Name); + add (+""is""); + + add (+""""); + +-- the_Source.append (Self.public_Entities.to_spec_Source); + + add (+""""); + add ( ""end "" & Self.Name & "";""); + + return the_Source; + end to_Source; + + + + function to_spec_Source (Self : in Item) return text_Vectors.Vector + is + use ada.Strings.unbounded; + + the_Source : text_Vectors.Vector; + + procedure add (the_Line : in Text) + is + begin + the_Source.append (the_Line); + end add; + + begin + the_Source.append (Self.Context.to_Source); + + add (+""""); + add ( ""package "" & Self.Name); + add (+""is""); + + add (+""""); + +-- the_Source.append (Self.public_Entities.to_spec_Source); + + add (+""""); + add ( ""end "" & Self.Name & "";""); + + return the_Source; + end to_spec_Source; + + + + function to_body_Source (Self : in Item) return text_Vectors.Vector + is + use ada.Strings.unbounded; + + the_Source : text_Vectors.Vector; + + procedure add (the_Line : in Text) + is + begin + the_Source.append (the_Line); + end add; + + begin + the_Source.append (Self.Context.to_Source); + + add (+""""); + add ( ""package body "" & Self.Name); + add (+""is""); + + add (+""""); + +-- the_Source.append (Self.public_Entities.to_body_Source); + + add (+""""); + add ( ""end "" & Self.Name & "";""); + + return the_Source; + end to_body_Source; + + + + function requires_Body (Self : in Item) return Boolean + is + pragma Unreferenced (Self); +-- use AdaM.Source.utility; + begin + return False; -- contains_Subprograms (Self.public_Entities); + end requires_Body; + + + + procedure Parent_is (Self : in out Item; Now : in Declaration.of_package.View) + is + begin + Self.Parent := Now; + end Parent_is; + + + + function Parent (Self : in Item) return Declaration.of_package.view + is + begin + return Self.Parent; + end Parent; + + + + + function child_Packages (Self : in Item'Class) return Declaration.of_package.Vector + is + begin + return Self.child_Packages; + end child_Packages; + + + function child_Package (Self : in Item'Class; Named : in String) return Declaration.of_package.view + is + begin + for Each of Self.child_Packages + loop + if Each.Name = Named + then + return Each; + end if; + end loop; + + return null; + end child_Package; + + + + procedure add_Child (Self : in out Item; Child : in Declaration.of_package.View) + is + begin + Self.child_Packages.append (Child); + end add_Child; + + + + function find (Self : in Item; Named : in Identifier) return AdaM.a_Type.view + is + begin + for Each of Self.Children.all + loop +-- put_Line (""--- find type in package "" & (+Self.Name) & "" --- Tag => "" & ada.Tags.External_Tag (Each.all'Tag)); + + if Each.all in AdaM.a_Type.item'Class + then + if Each.Name = Named + then + return AdaM.a_Type.view (Each); + end if; + end if; + end loop; + + put_Line (String (Named) & "" NOT FOUND in package "" & (+Self.Name)); + return null; + end find; + + + + function find (Self : in Item; Named : in Identifier) return AdaM.Declaration.of_exception.view + is + begin + for Each of Self.Children.all + loop +-- put_Line (""--- find type in package "" & (+Self.Name) & "" --- Tag => "" & ada.Tags.External_Tag (Each.all'Tag)); + + if Each.all in AdaM.Declaration.of_exception.item'Class + then + if Each.Name = Named + then + return AdaM.Declaration.of_exception.view (Each); + end if; + end if; + end loop; + + put_Line (String (Named) & "" NOT FOUND in package "" & (+Self.Name)); + return null; + end find; + + + + + function full_Name (Self : in Item) return Identifier + is + begin + if Self.Parent = null -- Is the Standard package. + then + return ""Standard""; + end if; + + if Self.Parent.Name = ""Standard"" + then + return +Self.Name; + else + return Self.Parent.full_Name & ""."" & (+Self.Name); + end if; + end full_Name; + + + + -- Streams + -- + + procedure Item_write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; + Self : in Item) + is + begin + Text'write (Stream, Self.Name); + + Declaration.of_package.view 'write (Stream, Self.Parent); + Declaration.of_package.Vector'write (Stream, Self.Progenitors); + Declaration.of_package.Vector'write (Stream, Self.child_Packages); + + AdaM.Context.view'write (Stream, Self.Context); +-- Source.Entities 'write (Stream, Self.public_Entities); + + Entity.view 'write (Stream, Self.parent_Entity); + Entity.Entities'write (Stream, Self.Children); + end Item_write; + + + + procedure Item_read (Stream : not null access Ada.Streams.Root_Stream_Type'Class; + Self : out Item) + is + Version : constant Positive := Pool.storage_record_Version; + begin + case Version + is + when 1 => + Text'read (Stream, Self.Name); +-- put_Line (""KKKKKKKKKKKKKK '"" & (+Self.Name) & ""'""); + + Declaration.of_package.view 'read (Stream, Self.Parent); + Declaration.of_package.Vector'read (Stream, Self.Progenitors); + Declaration.of_package.Vector'read (Stream, Self.child_Packages); + + AdaM.Context.view'read (Stream, Self.Context); +-- Source.Entities 'read (Stream, Self.public_Entities); + + declare + Parent : Declaration.of_package.view; + begin + Declaration.of_package.view'read (Stream, Parent); + + if Parent /= null + then +-- program_Unit.item (Self).parent_Entity_is (Parent.all'Access); + Self.parent_Entity_is (Parent.all'Access); + end if;" +-- function Is_Navigation_Disabled (N : LAL.Ada_Node) return Boolean;,"function Node_Filter (N : LAL.Ada_Node) return Boolean + is + ( Enabled_Kinds (N.Kind)); + pragma Unreferenced (Node_Filter); +-- and then not Is_Navigation_Disabled (N)); + + procedure Process_File (Unit : LAL.Analysis_Unit; Filename : String); + +-- procedure Print_Navigation (Part_Name : String; +-- Orig, Dest : access LAL.Ada_Node_Type'Class); + + At_Least_Once : Boolean := False; + + + + Depth : Natural := 0; + + function Indent return String + is + use Ada.Strings.fixed; + begin + return Depth * "" ""; + end Indent; + + procedure log (Message : in String) + is + begin + put_Line (Indent & Message); + end log; + + + ---------- + -- Process + -- + + procedure process (Node : in LAL.Ada_Node); + + + + procedure parse_Range (the_Range : in LAL.Bin_Op; + First : out Text; + Last : out Text) + is + begin + First := +to_String (the_Range.Child (1).Text); + Last := +to_String (the_Range.Child (3).Text); + end parse_Range; + + + + procedure parse_subtype_Indication (Node : in LAL.Subtype_Indication; + new_Indication : out AdaM.subtype_Indication.item'Class) + is + + index_Type : constant String := to_String (Node.F_Name.Text); + Constraint : constant LAL.Range_Constraint := LAL.Range_Constraint (Node.Child (3)); + + begin + Depth := Depth + 1; + + log (""parse_subtype_Indication""); + + -- Parse children. + -- + new_Indication.main_Type_is (Environ.find (Identifier (index_Type))); + + if Constraint /= null + then + if Constraint.Child (1).Kind = LAL.Ada_Bin_Op + then + new_Indication.is_Constrained (True); + + declare + the_Range : constant LAL.Bin_Op := LAL.Bin_Op (Constraint.Child (1)); + First : Text; + Last : Text; + begin + parse_Range (the_Range, First, Last); + + new_Indication.First_is (+First); + new_Indication.Last_is (+Last);" +procedure run_Tests is new AUnit.Run.Test_Runner(GStreamer.tests.Rtsp_Suit.Suit);,"begin + Run_Tests (Reporter);" +"function Convert is new Ada.Unchecked_Conversion (Source => GcharPtr , Target => Interfaces.C.Strings.Chars_Ptr);","function To_Ada ( C : access constant Glib.Gchar) return String is + + begin + return (if C /= null + then + Interfaces.C.Strings.Value (Convert (C.all'Unrestricted_Access)) + else + """");" +procedure Simple_Producer is,"Config : Kafka.Config_Type; + Handle : Kafka.Handle_Type; + Topic : Kafka.Topic_Type; + + package CommandTopic is new GetCommandArgument (""-t:"", ""--topic:"", ""Topic name to use""); +begin + Ada.Text_IO.Put_Line(""Kafka version: "" & Kafka.Version); + + -- Create a new config object + Config := Kafka.Config.Create; + + -- Configure your properties + Kafka.Config.Set(Config, ""client.id"", GNAT.Sockets.Host_name); + Kafka.Config.Set(Config, ""bootstrap.servers"", ""localhost:9092""); + + -- Create handle + Handle := Kafka.Create_Handle(Kafka.RD_KAFKA_PRODUCER, Config); + + -- Create topic handle + Topic := Kafka.Topic.Create_Topic_Handle(Handle, + CommandTopic.Parse_Command_Line(""test_topic"")); -- topic must already exist + + -- Producing a String + Kafka.Produce(Topic, + Kafka.RD_KAFKA_PARTITION_UA, + ""World"", -- payload + ""Hello"", -- key + System.Null_Address); + + -- Producing binary data + declare + type Some_Message is record + A : Interfaces.Unsigned_32; + B : Interfaces.Unsigned_64; + C : Interfaces.Unsigned_8; + end record + with Convention => C; + + for Some_Message use record + A at 0 range 0 .. 31; + B at 4 range 0 .. 63; + C at 12 range 0 .. 7; + end record; + + for Some_Message'Bit_Order use System.High_Order_First; + for Some_Message'Scalar_Storage_Order use System.High_Order_First; + + Message : Some_Message := (A => 55, B => 40002, C => 13); + begin + Kafka.Produce(Topic, + Kafka.RD_KAFKA_PARTITION_UA, + Kafka.RD_KAFKA_MSG_F_COPY, + Message'Address, + 13, + System.Null_Address, -- key is optional + 0, + System.Null_Address);" +procedure Simple_Consumer is,"use type System.Address; + use type Interfaces.C.size_t; + + Config : Kafka.Config_Type; + Handle : Kafka.Handle_Type; + + Handler : Signal.Handler; -- basic Signal handler to stop on CTRL + C + package KafkaTopic is new GetCommandArgument (""-t:"", ""--topic:"", ""Topic name to use""); +begin + -- Create configuration + Config := Kafka.Config.Create; + + -- Configure + -- see librdkafka documentation on how to configure your Kafka consumer + -- Kafka-Ada does not add any configuration entries of its own + Kafka.Config.Set(Config, ""group.id"", GNAT.Sockets.Host_name); + Kafka.Config.Set(Config, ""bootstrap.servers"", ""localhost:9092""); + Kafka.Config.Set(Config, ""auto.offset.reset"", ""earliest""); + + Handle := Kafka.Create_Handle(Kafka.RD_KAFKA_CONSUMER, Config); + + Kafka.Consumer.Poll_Set_Consumer(Handle); + + declare + Partition_List : Kafka.Partition_List_Type; + begin + Partition_List := Kafka.Topic.Partition.Create_List(1); + Kafka.Topic.Partition.List_Add(Partition_List, + KafkaTopic.Parse_Command_Line(""test_topic""), Kafka.RD_KAFKA_PARTITION_UA); + + Kafka.Subscribe(Handle, Partition_List); + Kafka.Topic.Partition.Destroy_List(Partition_List);" +procedure Stemwords is,"use Stemmer.Factory; + + function Get_Language (Name : in String) return Language_Type; + function Is_Space (C : in Character) return Boolean; + + function Is_Space (C : in Character) return Boolean is + begin + return C = ' ' or C = ASCII.HT; + end Is_Space; + + function Get_Language (Name : in String) return Language_Type is + begin + return Language_Type'Value (""L_"" & Name); + + exception + when Constraint_Error => + Ada.Text_IO.Put_Line (""Unsupported language: "" & Ada.Command_Line.Argument (1)); + return L_ENGLISH; + + end Get_Language; + + Count : constant Natural := Ada.Command_Line.Argument_Count; +begin + if Count <= 1 then + Ada.Text_IO.Put_Line (""Usage: stemwords language file""); + return; + end if; + declare + Lang : constant Language_Type := Get_Language (Ada.Command_Line.Argument (1)); + Path : constant String := Ada.Command_Line.Argument (2); + File : Ada.Text_IO.File_Type; + begin + Ada.Text_IO.Open (File, Ada.Text_IO.In_File, Path); + while not Ada.Text_IO.End_Of_File (File) loop + declare + Line : constant String := Ada.Text_IO.Get_Line (File); + Pos : Positive := Line'First; + Last_Pos : Positive; + Start_Pos : Positive; + begin + while Pos <= Line'Last loop + Last_Pos := Pos; + while Pos <= Line'Last and then Is_Space (Line (Pos)) loop + Pos := Pos + 1; + end loop; + if Last_Pos < Pos then + Ada.Text_IO.Put (Line (Last_Pos .. Pos - 1)); + end if; + exit when Pos > Line'Last; + Start_Pos := Pos; + while Pos <= Line'Last and then not Is_Space (Line (Pos)) loop + Pos := Pos + 1; + end loop; + Ada.Text_IO.Put (Stemmer.Factory.Stem (Lang, Line (Start_Pos .. Pos - 1))); + end loop; + Ada.Text_IO.New_Line;" +procedure Stemargs is,"use Stemmer.Factory; + + function Get_Language (Name : in String) return Language_Type; + + function Get_Language (Name : in String) return Language_Type is + begin + return Language_Type'Value (""L_"" & Name); + + exception + when Constraint_Error => + Ada.Text_IO.Put_Line (""Unsupported language: "" & Ada.Command_Line.Argument (1)); + return L_ENGLISH; + + end Get_Language; + + Count : constant Natural := Ada.Command_Line.Argument_Count; +begin + if Count <= 1 then + Ada.Text_IO.Put_Line (""Usage: stemargs language words...""); + return; + end if; + declare + Lang : constant Language_Type := Get_Language (Ada.Command_Line.Argument (1)); + begin + for I in 2 .. Count loop + Ada.Text_IO.Put_Line (Stem (Lang, Ada.Command_Line.Argument (I))); + end loop;" +procedure Car is,"--class +type Car is tagged + record + wheels : Integer; + doors : Integer; + cylinders : Integer; + end record; +-- functions +--prior to Ada 2012, passed arguments could not be written to +--that would defeat the purpose of writing functions for records +procedure addWheels(myCar : in out Car; wheelsIn : Integer) +is +begin + myCar.wheels := myCar.wheels + wheelsIn; +end addWheels; + +procedure addDoors(myCar : in out Car; doorsIn : Integer) +is +begin + myCar.doors := myCar.doors + doorsIn; +end addDoors; + +procedure addCylinders(myCar : in out Car; cylindersIn : Integer) +is +begin + myCar.cylinders := myCar.cylinders + cylindersIn; +end addCylinders; + +procedure deleteWheels(myCar : in out Car; wheelsIn : Integer) +is +begin + myCar.wheels := myCar.wheels - wheelsIn; +end deleteWheels; + +procedure deleteDoors(myCar : in out Car; doorsIn : Integer) +is +begin + myCar.doors := myCar.doors - doorsIn; +end deleteDoors; + +procedure deleteCylinders(myCar : in out Car; cylindersIn : Integer) +is +begin + myCar.cylinders := myCar.cylinders - cylindersIn; +end deleteCylinders; + +--main program block +begin + Put_Line(""Creating car.""); + declare + subaru : Car; + begin + subaru.wheels := 4; + subaru.doors := 4; + subaru.cylinders := 4; + Put(""Wheel check: ""); + Put(Integer'Image(subaru.wheels)); + New_Line; + Put(""Door check: ""); + Put(Integer'Image(subaru.doors)); + New_Line; + Put(""Cylinder check: ""); + Put(Integer'Image(subaru.cylinders)); + New_Line; + New_Line; + Put_Line(""Adding wheel directly to car object.""); + subaru.wheels := subaru.wheels + 1; + Put(""Wheel check: ""); + Put(Integer'Image(subaru.wheels)); + New_Line; + Put(""Door check: ""); + Put(Integer'Image(subaru.doors)); + New_Line; + Put(""Cylinder check: ""); + Put(Integer'Image(subaru.cylinders)); + New_Line; + New_Line; + Put_Line(""Removing wheel using object method.""); + deleteWheels(subaru, 1); + Put(""Wheel check: ""); + Put(Integer'Image(subaru.wheels)); + New_Line; + Put(""Door check: ""); + Put(Integer'Image(subaru.doors)); + New_Line; + Put(""Cylinder check: ""); + Put(Integer'Image(subaru.cylinders)); + New_Line;" +procedure Free_Logger_Msg_Ptr is new Ada.Unchecked_Deallocation,"(Object => Logger_Message_Packet, Name => Logger_Message_Packet_Ptr); + + function Format_Log_Level + (Use_Color : Boolean; + Log_Level : Log_Levels) + return Unbounded_String + is + Color_Prefix : Unbounded_String; + Log_Level_Str : Unbounded_String; + Now : constant Time := Clock; + begin + + -- Add ANSI color codes if we're using color on Linux + if Use_Color + then + case Log_Level is + when EMERGERENCY => + Color_Prefix := To_Unbounded_String (ANSI_Light_Red); + when ALERT => + Color_Prefix := To_Unbounded_String (ANSI_Light_Red); + when CRITICAL => + Color_Prefix := To_Unbounded_String (ANSI_Light_Red); + when ERROR => + Color_Prefix := To_Unbounded_String (ANSI_Red); + when WARNING => + Color_Prefix := To_Unbounded_String (ANSI_Light_Yellow); + when NOTICE => + Color_Prefix := To_Unbounded_String (ANSI_Yellow); + when INFO => + Color_Prefix := To_Unbounded_String (ANSI_Green); + when DEBUG => + Color_Prefix := To_Unbounded_String (ANSI_Light_Blue); + end case; + + Log_Level_Str := + Color_Prefix & To_Unbounded_String (Log_Level'Image) & ANSI_Reset; + else + Log_Level_Str := To_Unbounded_String (Log_Level'Image); + end if; + + return To_Unbounded_String + (Image (Date => Now) & "" ["" & To_String (Log_Level_Str) & ""]""); + end Format_Log_Level; + + function Create_String_From_Components + (Components : Component_Vector.Vector) + return Unbounded_String + is + Components_String : Unbounded_String; + procedure Component_To_String (c : Component_Vector.Cursor) is + Scratch_String : Unbounded_String; + begin + Scratch_String := Components (c); + Components_String := Components_String & ""["" & Scratch_String & ""]""; + end Component_To_String; + begin + -- If there's no component, just leave it blank + if Components.Length = 0 + then + return To_Unbounded_String (""""); + end if; + + Components.Iterate (Component_To_String'Access); + return Components_String; + end Create_String_From_Components; + + protected body Logger_Queue_Type is + -- Handles queue of packets for the logger thread + entry Add_Packet (Queue : Logger_Message_Packet_Ptr) when True is + begin + Queued_Packets.Append (Queue); + end Add_Packet; + + entry Get (Queue : out Logger_Message_Packet_Ptr) + when Queued_Packets.Length > 0 is + begin + Queue := Queued_Packets.First_Element; + Queued_Packets.Delete_First; + end Get; + + entry Count (Count : out Integer) when True is + begin + Count := Integer (Queued_Packets.Length); + end Count; + + entry Empty when True is + begin + declare + procedure Dump_Vector_Data + (c : Logger_Message_Packet_Vector.Cursor) + is + begin + Free_Logger_Msg_Ptr (Queued_Packets (c)); + end Dump_Vector_Data; + begin + Queued_Packets.Iterate (Dump_Vector_Data'access);" +procedure Process_Queue is,"procedure Print_Messages (c : Log_Message_Vector.Cursor) is + Current_Msg : constant Log_Message_Record := + Log_Message_Vector.Element (c); + begin + -- This is so ugly :( + if Log_Levels'Enum_Rep (Logger_Cfg.Log_Level) >= + Log_Levels'Enum_Rep (Current_Msg.Log_Level) + then + Msg_String := + Format_Log_Level + (Logger_Cfg.Use_Color, Current_Msg.Log_Level); + Msg_String := + Msg_String & + Create_String_From_Components (Current_Msg.Component); + Msg_String := Msg_String & "" "" & Current_Msg.Message; + Put_Line (To_String (Msg_String)); + end if; + end Print_Messages; + + begin + Logger_Queue.Count (Queues_To_Process); + while Queues_To_Process > 0 + loop + Logger_Queue.Get (Current_Queue); + + -- Get a local copy and then empty it; we don't care past that + -- point + if Current_Queue /= null + then + Current_Queue.Get_All_And_Empty (Msg_Packets); + Msg_Packets.Iterate (Print_Messages'Access); + Free_Logger_Msg_Ptr (Current_Queue); + end if; + + Logger_Queue.Count (Queues_To_Process); + end loop; + + exception + -- Not sure if there's a better way to do this, but avoids a race + -- condition + when Constraint_Error => + begin + null;" +function To_Domain_Section is new Ada.Unchecked_Conversion,"(Source => Stream_Element_Array, Target => Domain_Section); + begin + Domain_Name := Domain_Name & To_Domain_Section (Raw_Data.all + (Offset .. Stream_Element_Offset (Section_Length))); + + Offset := Offset + Stream_Element_Offset (Section_Length);" +function Get_Byte_Fixed_Header is new Ada.Unchecked_Conversion,"(Source => Stream_Element_Array, Target => Packer_Pointer); + begin + -- Oh, and for more fuckery, the pointer is 16-bit ... + Packet_Ptr := Get_Byte_Fixed_Header (Raw_Data.all + (Offset .. Offset + 1)); -- Make the top bytes vanish + + -- We subtract 12-1 for the packet header + Packet_Ptr.Packet_Offset := + (Packet_Ptr.Packet_Offset and 16#3fff#) - 11; + + -- Sanity check ourselves + if (Section_Length and 2#11#) /= 0 + then + -- Should never happen but you never know ... + raise Unknown_Compression_Method; + end if; + + -- Now we need to decode the whole old string ... ugh + Decompressed_Domain_String := + Parse_DNS_Packet_Name_Records + (Raw_Data, + Stream_Element_Offset (Packet_Ptr.Packet_Offset)); + Offset := Offset + 2; + return Domain_Name & Decompressed_Domain_String;" +function To_RData is new Ada.Unchecked_Conversion,"(Source => Stream_Element_Array, Target => RData); + begin + Parsed_Response.RData := To_Unbounded_String (To_RData (Raw_Data + (Offset .. Stream_Element_Offset (RData_Length)))); + Offset := Offset + Stream_Element_Offset (RData_Length);" +procedure Start_Server is,"-- Input and Output Sockets + Capture_Config : DNSCatcher.Config.Configuration; + + DNS_Transactions : DNSCatcher.DNS.Transaction_Manager + .DNS_Transaction_Manager_Task; + Receiver_Interface : DNSCatcher.Network.UDP.Receiver + .UDP_Receiver_Interface; + Sender_Interface : DNSCatcher.Network.UDP.Sender.UDP_Sender_Interface; + Logger_Task : DNSCatcher.Utils.Logger.Logger; + Transaction_Manager_Ptr : DNS_Transaction_Manager_Task_Ptr; + Socket : Socket_Type; + Logger_Packet : DNSCatcher.Utils.Logger.Logger_Message_Packet_Ptr; + + procedure Free_Transaction_Manager is new Ada.Unchecked_Deallocation + (Object => DNS_Transaction_Manager_Task, + Name => DNS_Transaction_Manager_Task_Ptr); + begin + -- Load the config file from disk + DNSCatcher.Config.Initialize (Capture_Config); + DNSCatcher.Config.Read_Cfg_File + (Capture_Config, ""conf/dnscatcherd.conf""); + + -- Configure the logger + Capture_Config.Logger_Config.Log_Level := DEBUG; + Capture_Config.Logger_Config.Use_Color := True; + + Logger_Task.Initialize (Capture_Config.Logger_Config); + Transaction_Manager_Ptr := new DNS_Transaction_Manager_Task; + + -- Connect the packet queue and start it all up + Logger_Task.Start; + Logger_Packet := new DNSCatcher.Utils.Logger.Logger_Message_Packet; + Logger_Packet.Log_Message (NOTICE, ""DNSCatcher starting up ...""); + DNSCatcher.Utils.Logger.Logger_Queue.Add_Packet (Logger_Packet); + + -- Socket has to be shared between receiver and sender. This likely needs + -- to move to to a higher level class + begin + Create_Socket + (Socket => Socket, + Mode => Socket_Datagram); + Set_Socket_Option + (Socket => Socket, + Level => IP_Protocol_For_IP_Level, + Option => (GNAT.Sockets.Receive_Timeout, Timeout => 1.0)); + Bind_Socket + (Socket => Socket, + Address => + (Family => Family_Inet, Addr => Any_Inet_Addr, + Port => Capture_Config.Local_Listen_Port)); + exception + when Exp_Error : GNAT.Sockets.Socket_Error => + begin + Logger_Packet := + new DNSCatcher.Utils.Logger.Logger_Message_Packet; + Logger_Packet.Log_Message + (ERROR, ""Socket error: "" & Exception_Information (Exp_Error)); + Logger_Packet.Log_Message (ERROR, ""Refusing to start!""); + Logger_Queue.Add_Packet (Logger_Packet); + goto Shutdown_Procedure;" +function Uint8_To_Character is new Ada.Unchecked_Conversion,"(Source => Unsigned_8, Target => Character); + function Uint16_To_String is new Ada.Unchecked_Conversion + (Source => Unsigned_16, Target => QAttributes); + -- Actually does the dirty work of creating a question + function Create_QName_Record + (Domain_Section : String) + return String + is + Label : String (1 .. Domain_Section'Length + 1); + begin + if Domain_Section /= ""."" + then + Label (1) := + Uint8_To_Character (Unsigned_8 (Domain_Section'Length)); + Label + (2 .. Domain_Section'Length + 1) := Domain_Section; + else + -- If this is a ""."" by itself, it's the terminator, and we need to + -- do special handling + declare + Empty_Label : String (1 .. 1); + begin + Empty_Label (1) := Uint8_To_Character (Unsigned_8 (0)); + return Empty_Label;" +function String_To_Packet is new Ada.Unchecked_Conversion,"(Source => String, Target => QData_SEA); + + begin + Outbound_Packet.Raw_Data.Data := + new Stream_Element_Array (1 .. QData'Length); + Outbound_Packet.Raw_Data.Data.all := String_To_Packet (QData); + Outbound_Packet.Raw_Data_Length := + DNS_PACKET_HEADER_SIZE + QData'Length;" +-- Parse_Procedure is an access procedure that is used as a common prototype,"-- for all parsing functionality dispatched from GCP_Management and other + -- vectors. + -- + -- @value Config + -- Configuration struct to update + -- + -- @value Value_Str + -- Pure text version of the configuration argument + -- + type Parse_Procedure is access procedure + (Config : in out Configuration; + Value_Str : String); + + -- GCP_Management is a vector that handles dynamic dispatch to the + -- parsing parameters above; it is used to match key/values from the + -- config file to + package GCP_Management is new Ada.Containers.Indefinite_Ordered_Maps + (String, Parse_Procedure); + + GCP_Map : GCP_Management.Map; + + -- Configuration constructor + procedure Initialize (Config : in out Configuration) is + begin + -- We initialize the ports to 53 by default + Config.Local_Listen_Port := 53; + Config.Upstream_DNS_Server_Port := 53; + + -- No upstream server is set + Config.Upstream_DNS_Server := To_Unbounded_String (""""); + end Initialize; + + -- Loads the load listen value and sets it in the config record + -- + -- @value Config + -- Configuration struct to update + -- + -- @value Value_Str + -- Pure text version of the configuration argument + -- + procedure Parse_Local_Listen_Port + (Config : in out Configuration; + Value_Str : String) + is + begin + Config.Local_Listen_Port := Port_Type'Value (Value_Str); + exception + when Constraint_Error => + raise Malformed_Line with ""Local_Listen_Port not a valid port number""; + end Parse_Local_Listen_Port; + + -- Loads the upstream DNS Server from the config file + -- + -- @value Config + -- Configuration struct to update + -- + -- @value Value_Str + -- Pure text version of the configuration argument + -- + procedure Parse_Upstream_DNS_Server + (Config : in out Configuration; + Value_Str : String) + is + begin + Config.Upstream_DNS_Server := To_Unbounded_String (Value_Str); + exception + when Constraint_Error => + raise Malformed_Line with ""Invalid upstrema DNS Server""; + end Parse_Upstream_DNS_Server; + + -- Loads the upstream DNS Server port from the config file + -- + -- @value Config + -- Configuration struct to update + -- + -- @value Value_Str + -- Pure text version of the configuration argument + -- + procedure Parse_Upstream_DNS_Server_Port + (Config : in out Configuration; + Value_Str : String) + is + begin + Config.Upstream_DNS_Server_Port := Port_Type'Value (Value_Str); + exception + when Constraint_Error => + raise Malformed_Line + with ""Upstream_DNS_Server_Port not a valid port number""; + end Parse_Upstream_DNS_Server_Port; + + procedure Initialize_Config_Parse is + begin + -- Load String to Type Mapping + GCP_Map.Insert (""LOCAL_LISTEN_PORT"", Parse_Local_Listen_Port'Access); + GCP_Map.Insert (""UPSTREAM_DNS_SERVER"", Parse_Upstream_DNS_Server'Access); + GCP_Map.Insert + (""UPSTREAM_DNS_SERVER_PORT"", Parse_Upstream_DNS_Server_Port'Access); + end Initialize_Config_Parse; + + procedure Read_Cfg_File + (Config : in out Configuration; + Config_File_Path : String) + is + Config_File : Ada.Text_IO.File_Type; + Line_Count : Integer := 1; + Exception_Message : Unbounded_String; + use GCP_Management; + begin + Initialize_Config_Parse; + + -- Try to open the configuration file + Open + (File => Config_File, + Mode => Ada.Text_IO.In_File, + Name => Config_File_Path); + + while not End_Of_File (Config_File) + loop + declare + Current_Line : constant String := Get_Line (Config_File); + Key_End_Loc : Integer := 0; + Equals_Loc : Integer := 0; + Value_Loc : Integer := 0; + Is_Whitespace : Boolean := True; + begin + -- Skip lines starting with a comment or blank + if Current_Line = """" + then + goto Config_Parse_Continue; + end if; + + -- Has to be done seperately or it blows an index check + if Current_Line (1) = '#' + then + goto Config_Parse_Continue; + end if; + + -- Skip line if its all whitespace + for I in Current_Line'range + loop + if Current_Line (I) /= ' ' and + Current_Line (I) /= Ada.Characters.Latin_1.HT + then + Is_Whitespace := False; + end if; + + if Current_Line (I) = '=' + then + Equals_Loc := I; + end if; + + -- Determine length of the key + -- + -- This is a little non-obvious at first glance. We subtract 2 + -- here to remove the character we want, and the previous char + -- because a 17 char string will be 1..18 in the array. + + if (Is_Whitespace or Current_Line (I) = '=') and Key_End_Loc = 0 + then + Key_End_Loc := I - 2; + end if; + + exit when Is_Whitespace and Equals_Loc /= 0; + -- We also want to confirm there's a = in there somewhere + end loop; + + -- It's all whitespace, skip it + if Is_Whitespace + then + goto Config_Parse_Continue; + end if; + + if Equals_Loc = 0 + then + Exception_Message := + To_Unbounded_String (""Malformed line (no = found) at""); + Append (Exception_Message, Line_Count'Image); + Append (Exception_Message, "": ""); + Append (Exception_Message, Current_Line); + + raise Malformed_Line with To_String (Exception_Message); + end if; + + -- Read in the essential values + for C in GCP_Map.Iterate + loop + -- Slightly annoying, but need to handle not reading past the + -- end of Current_Line. We also need to check that the next char + -- is a space or = so we don't match substrings by accident. + if Key_End_Loc = Key (C)'Length + then + if Key (C) = To_Upper (Current_Line + (1 .. Key (C)'Length)) + then + -- Determine the starting character of the value + for I in Current_Line + (Equals_Loc + 1 .. Current_Line'Length)'range + loop + if Current_Line (I) /= ' ' and + Current_Line (I) /= Ada.Characters.Latin_1.HT + then + Value_Loc := I; + exit; + end if; + end loop; + + -- If Value_Loc is zero, pass an empty string in + if Value_Loc = 0 + then + Element (C).all (Config, """"); + else + Element (C).all (Config, Current_Line + (Value_Loc .. Current_Line'Length)); + end if; + end if; + end if; + end loop; + + <> + Line_Count := Line_Count + 1;" +procedure DNSC is,"DClient : DNSCatcher.DNS.Client.Client; + Capture_Config : DNSCatcher.Config.Configuration; + Logger_Task : DNSCatcher.Utils.Logger.Logger; + Transaction_Manager_Ptr : DNS_Transaction_Manager_Task_Ptr; + Sender_Interface : DNSCatcher.Network.UDP.Sender.UDP_Sender_Interface; + Receiver_Interface : DNSCatcher.Network.UDP.Receiver.UDP_Receiver_Interface; + Outbound_Packet : Raw_Packet_Record_Ptr; + Logger_Packet : DNSCatcher.Utils.Logger.Logger_Message_Packet_Ptr; + Socket : Socket_Type; + +begin + Capture_Config.Local_Listen_Port := 41231; + Capture_Config.Upstream_DNS_Server := To_Unbounded_String (""4.2.2.2""); + Capture_Config.Upstream_DNS_Server_Port := 53; + + -- Configure the logger + Capture_Config.Logger_Config.Log_Level := DEBUG; + Capture_Config.Logger_Config.Use_Color := True; + + Logger_Task.Initialize (Capture_Config.Logger_Config); + Logger_Task.Start; + Logger_Packet := new Logger_Message_Packet; + + Transaction_Manager_Ptr := new DNS_Transaction_Manager_Task; + + -- Socket has to be shared between receiver and sender. This likely needs to + -- move to to a higher level class + begin + Create_Socket + (Socket => Socket, + Mode => Socket_Datagram); + Set_Socket_Option + (Socket => Socket, + Level => IP_Protocol_For_IP_Level, + Option => (GNAT.Sockets.Receive_Timeout, Timeout => 1.0)); + Bind_Socket + (Socket => Socket, + Address => + (Family => Family_Inet, Addr => Any_Inet_Addr, + Port => Capture_Config.Local_Listen_Port)); + exception + when Exp_Error : GNAT.Sockets.Socket_Error => + begin + Logger_Packet := new DNSCatcher.Utils.Logger.Logger_Message_Packet; + Logger_Packet.Log_Message + (ERROR, ""Socket error: "" & Exception_Information (Exp_Error)); + Logger_Packet.Log_Message (ERROR, ""Refusing to start!""); + Logger_Queue.Add_Packet (Logger_Packet); + goto Shutdown_Procedure;" +procedure DNSCatcherD is,"begin + Install_Handler (Handler => Signal_Handlers.SIGINT_Handler'Access); + DNSCatcher.DNS.Server.Start_Server; +exception + when Error : Ada.IO_Exceptions.Name_Error => + begin + Put (Standard_Error, ""FATAL: Unable to open config file: ""); + Put_Line (Standard_Error, Exception_Message (Error)); + DNSCatcher.DNS.Server.Stop_Server;" +"procedure Dispose is new Ada.Unchecked_Deallocation (Dir_Entries, Pdir_Entries);","procedure Resize (A : in out Pdir_Entries; Size : Integer) is + Hlp : constant Pdir_Entries := new Dir_Entries (1 .. Size); + begin + if A = null then + A := Hlp; + else + Hlp (1 .. Integer'Min (Size, A'Length)) := A (1 .. Integer'Min (Size, A'Length)); + Dispose (A); + A := Hlp; + end if; + end Resize; + + -- Internal - add the catalogue entry corresponding to a + -- compressed file in the Zip archive. + -- The entire catalogue will be written at the end of the zip stream, + -- and the entry as a local header just before the compressed data. + -- The entry's is mostly incomplete in the end (name, size, ...); stream + -- operations on the archive being built are not performed here, + -- see Add_Stream for that. + procedure Add_Catalogue_Entry (Info : in out Zip_Create_Info) is + begin + if Info.Last_Entry = 0 then + Info.Last_Entry := 1; + Resize (Info.Contains, 32); + else + Info.Last_Entry := Info.Last_Entry + 1; + if Info.Last_Entry > Info.Contains'Last then + -- Info.Contains is full, time to resize it! + -- We do nothing less than double the size - better than + -- whatever offer you'd get in your e-mails. + Resize (Info.Contains, Info.Contains'Last * 2); + end if; + end if; + declare + Cfh : Central_File_Header renames Info.Contains (Info.Last_Entry).Head; + begin + -- Administration + Cfh.Made_By_Version := 20; -- Version 2.0 + Cfh.Comment_Length := 0; + Cfh.Disk_Number_Start := 0; + Cfh.Internal_Attributes := 0; -- 0: binary; 1: text + Cfh.External_Attributes := 0; + Cfh.Short_Info.Needed_Extract_Version := 10; -- Value put by Zip/PKZip + Cfh.Short_Info.Bit_Flag := 0;" +"procedure Dispose_Buffer is new Ada.Unchecked_Deallocation (Byte_Buffer, P_Byte_Buffer);","Inbuf : P_Byte_Buffer; -- I/O buffers + Outbuf : P_Byte_Buffer; + + Inbufidx : Positive; -- Points to next char in buffer to be read + Outbufidx : Positive := 1; -- Points to next free space in output buffer + + Maxinbufidx : Natural; -- Count of valid chars in input buffer + Inputeof : Boolean; -- End of file indicator + + procedure Read_Block is + begin + Zip.Blockread (Stream => Input, Buffer => Inbuf.all, Actually_Read => Maxinbufidx); + Inputeof := Maxinbufidx = 0; + Inbufidx := 1; + end Read_Block; + + -- Exception for the case where compression works but produces + -- a bigger file than the file to be compressed (data is too ""random""). + Compression_Inefficient : exception; + + procedure Write_Block is + Amount : constant Integer := Outbufidx - 1; + begin + Output_Size := Output_Size + File_Size_Type (Integer'Max (0, Amount)); + if Output_Size >= Input_Size then + -- The compression so far is obviously inefficient for that file. + -- Useless to go further. + -- Stop immediately before growing the file more than the + -- uncompressed size. + raise Compression_Inefficient; + end if; + Zip.Blockwrite (Output, Outbuf (1 .. Amount)); + Outbufidx := 1; + end Write_Block; + + procedure Put_Byte (B : Byte) is -- Put a byte, at the byte granularity level + pragma Inline (Put_Byte); + begin + Outbuf (Outbufidx) := B; + Outbufidx := Outbufidx + 1; + if Outbufidx > Outbuf'Last then + Write_Block; + end if; + end Put_Byte; + + procedure Flush_Byte_Buffer is + begin + if Outbufidx > 1 then + Write_Block; + end if; + end Flush_Byte_Buffer; + + ------------------------------------------------------ + -- Bit code buffer, for sending data at bit level -- + ------------------------------------------------------ + + -- Output buffer. Bits are inserted starting at the right (least + -- significant bits). The width of bit_buffer must be at least 16 bits + subtype U32 is Unsigned_32; + Bit_Buffer : U32 := 0; + -- Number of valid bits in bit_buffer. All bits above the last valid bit are always zero + Valid_Bits : Integer := 0; + + procedure Flush_Bit_Buffer is + begin + while Valid_Bits > 0 loop + Put_Byte (Byte (Bit_Buffer and 16#FF#)); + Bit_Buffer := Shift_Right (Bit_Buffer, 8); + Valid_Bits := Integer'Max (0, Valid_Bits - 8); + end loop; + Bit_Buffer := 0; + end Flush_Bit_Buffer; + + -- Bit codes are at most 15 bits for Huffman codes, + -- or 13 for explicit codes (distance extra bits). + subtype Code_Size_Type is Integer range 1 .. 15; + + -- Send a value on a given number of bits. + procedure Put_Code (Code : U32; Code_Size : Code_Size_Type) is + pragma Inline (Put_Code); + begin + -- Put bits from code at the left of existing ones. They might be shifted away + -- partially on the left side (or even entirely if valid_bits is already = 32). + Bit_Buffer := Bit_Buffer or Shift_Left (Code, Valid_Bits); + Valid_Bits := Valid_Bits + Code_Size; + if Valid_Bits > 32 then + -- Flush 32 bits to output as 4 bytes + Put_Byte (Byte (Bit_Buffer and 16#FF#)); + Put_Byte (Byte (Shift_Right (Bit_Buffer, 8) and 16#FF#)); + Put_Byte (Byte (Shift_Right (Bit_Buffer, 16) and 16#FF#)); + Put_Byte (Byte (Shift_Right (Bit_Buffer, 24) and 16#FF#)); + Valid_Bits := Valid_Bits - 32; + -- Empty buffer and put on it the rest of the code + Bit_Buffer := Shift_Right (Code, Code_Size - Valid_Bits); + end if; + end Put_Code; + + ------------------------------------------------------ + -- Deflate, post LZ encoding, with Huffman encoding -- + ------------------------------------------------------ + + Invalid : constant := -1; + + subtype Huffman_Code_Range is Integer range Invalid .. Integer'Last; + + type Length_Code_Pair is record + Bit_Length : Natural; -- Huffman code length, in bits + Code : Huffman_Code_Range := Invalid; -- The code itself + end record; + + procedure Invert (Lc : in out Length_Code_Pair) is + pragma Inline (Invert); + A : Natural := Lc.Code; + B : Natural := 0; + begin + for I in 1 .. Lc.Bit_Length loop + B := B * 2 + A mod 2; + A := A / 2; + end loop; + Lc.Code := B; + end Invert; + + -- The Huffman code set (and therefore the Huffman tree) is completely determined by + -- the bit length to be used for reaching leaf nodes, thanks to two special + -- rules (explanation in RFC 1951, section 3.2.2). + -- + -- So basically the process is the following: + -- + -- (A) Gather statistics (just counts) for the alphabet + -- (B) Turn these counts into code lengths, by calling Length_limited_Huffman_code_lengths + -- (C) Build Huffman codes (the bits to be sent) with a call to Prepare_Huffman_codes + -- + -- In short: + -- + -- data -> (A) -> stats -> (B) -> Huffman codes' bit lengths -> (C) -> Huffman codes + + type Huff_Descriptor is array (Natural range <>) of Length_Code_Pair; + + type Bit_Length_Array is array (Natural range <>) of Natural; + subtype Alphabet_Lit_Len is Natural range 0 .. 287; + subtype Bit_Length_Array_Lit_Len is Bit_Length_Array (Alphabet_Lit_Len); + subtype Alphabet_Dis is Natural range 0 .. 31; + subtype Bit_Length_Array_Dis is Bit_Length_Array (Alphabet_Dis); + + type Deflate_Huff_Descriptors is record + -- Tree descriptor for Literal, EOB or Length encoding + Lit_Len : Huff_Descriptor (0 .. 287); + -- Tree descriptor for Distance encoding + Dis : Huff_Descriptor (0 .. 31); + end record; + -- NB: Appnote: ""Literal codes 286-287 and distance codes 30-31 are never used + -- but participate in the Huffman construction."" + -- Setting upper bound to 285 for literals leads to invalid codes, sometimes. + + -- Copy bit length vectors into Deflate Huffman descriptors + + function Build_Descriptors + (Bl_For_Lit_Len : Bit_Length_Array_Lit_Len; + Bl_For_Dis : Bit_Length_Array_Dis) return Deflate_Huff_Descriptors + is + New_D : Deflate_Huff_Descriptors; + begin + for I in New_D.Lit_Len'Range loop + New_D.Lit_Len (I) := (Bit_Length => Bl_For_Lit_Len (I), Code => Invalid); + end loop; + for I in New_D.Dis'Range loop + New_D.Dis (I) := (Bit_Length => Bl_For_Dis (I), Code => Invalid); + end loop; + return New_D; + end Build_Descriptors; + + type Count_Type is range 0 .. File_Size_Type'Last / 2 - 1; + type Stats_Type is array (Natural range <>) of Count_Type; + + -- The following is a translation of Zopfli's OptimizeHuffmanForRle (v. 11-May-2016). + -- Possible gain: shorten the compression header containing the Huffman trees' bit lengths. + -- Possible loss: since the stats do not correspond anymore exactly to the data + -- to be compressed, the Huffman trees might be suboptimal. + -- + -- Zopfli comment: + -- Changes the population counts in a way that the consequent Huffman tree + -- compression, especially its rle-part, will be more likely to compress this data + -- more efficiently. + procedure Tweak_For_Better_Rle (Counts : in out Stats_Type) is + Length : Integer := Counts'Length; + Stride : Integer; + Symbol, Sum, Limit, New_Count : Count_Type; + Good_For_Rle : array (Counts'Range) of Boolean := (others => False); + begin + -- 1) We don't want to touch the trailing zeros. We may break the + -- rules of the format by adding more data in the distance codes. + loop + if Length = 0 then + return; + end if; + exit when Counts (Length - 1) /= 0; + Length := Length - 1; + end loop; + -- Now counts(0..length - 1) does not have trailing zeros. + -- + -- 2) Let's mark all population counts that already can be encoded with an rle code. + -- + -- Let's not spoil any of the existing good rle codes. + -- Mark any seq of 0's that is longer than 5 as a good_for_rle. + -- Mark any seq of non-0's that is longer than 7 as a good_for_rle. + Symbol := Counts (0); + Stride := 0; + for I in 0 .. Length loop + if I = Length or else Counts (I) /= Symbol then + if (Symbol = 0 and then Stride >= 5) or else (Symbol /= 0 and then Stride >= 7) then + for K in 0 .. Stride - 1 loop + Good_For_Rle (I - K - 1) := True; + end loop; + end if; + Stride := 1; + if I /= Length then + Symbol := Counts (I); + end if; + else + Stride := Stride + 1; + end if; + end loop; + -- 3) Let's replace those population counts that lead to more rle codes. + Stride := 0; + Limit := Counts (0); + Sum := 0; + for I in 0 .. Length loop + if I = Length + or else Good_For_Rle (I) + or else (I > 0 and then Good_For_Rle (I - 1)) -- Added from Brotli, item #1 + -- Heuristic for selecting the stride ranges to collapse. + or else abs (Counts (I) - Limit) >= 4 + then + if Stride >= 4 or else (Stride >= 3 and then Sum = 0) then + -- The stride must end, collapse what we have, if we have enough (4). + -- New_Count is the average of counts on the stride's interval, upper-rounded + New_Count := + Count_Type'Max (1, (Sum + Count_Type (Stride) / 2) / Count_Type (Stride)); + if Sum = 0 then + -- Don't make an all zeros stride to be upgraded to ones. + New_Count := 0; + end if; + for K in 0 .. Stride - 1 loop + -- We don't want to change value at counts(i), + -- that is already belonging to the next stride. Thus - 1. + -- Replace histogram value by averaged value + Counts (I - K - 1) := New_Count; + end loop; + end if; + Stride := 0; + Sum := 0; + if I < Length - 3 then + -- All interesting strides have a count of at least 4, at + -- least when non-zeros. Limit is the average of next 4 + -- counts, upper-rounded + Limit := (Counts (I) + Counts (I + 1) + Counts (I + 2) + Counts (I + 3) + 2) / 4; + elsif I < Length then + Limit := Counts (I); + else + Limit := 0; + end if; + end if; + Stride := Stride + 1; + if I /= Length then + Sum := Sum + Counts (I); + end if; + end loop; + end Tweak_For_Better_Rle; + + subtype Stats_Lit_Len_Type is Stats_Type (Alphabet_Lit_Len); + subtype Stats_Dis_Type is Stats_Type (Alphabet_Dis); + + -- Phase (B) : we turn statistics into Huffman bit lengths + function Build_Descriptors + (Stats_Lit_Len : Stats_Lit_Len_Type; + Stats_Dis : Stats_Dis_Type) return Deflate_Huff_Descriptors + is + Bl_For_Lit_Len : Bit_Length_Array_Lit_Len; + Bl_For_Dis : Bit_Length_Array_Dis; + + procedure Llhcl_Lit_Len is new Length_Limited_Huffman_Code_Lengths + (Alphabet_Lit_Len, + Count_Type, + Stats_Lit_Len_Type, + Bit_Length_Array_Lit_Len, + 15); + + procedure Llhcl_Dis is new Length_Limited_Huffman_Code_Lengths + (Alphabet_Dis, + Count_Type, + Stats_Dis_Type, + Bit_Length_Array_Dis, + 15); + + Stats_Dis_Copy : Stats_Dis_Type := Stats_Dis; + Used : Natural := 0; + begin + -- See ""PatchDistanceCodesForBuggyDecoders"" in Zopfli's deflate.c + -- NB: here, we patch the occurrences and not the bit lengths, to avoid invalid codes. + -- The decoding bug concerns Zlib v.<= 1.2.1, UnZip v.<= 6.0, WinZip v.10.0. + for I in Stats_Dis_Copy'Range loop + if Stats_Dis_Copy (I) /= 0 then + Used := Used + 1; + end if; + end loop; + if Used < 2 then + if Used = 0 then -- No distance code used at all (data must be almost random) + Stats_Dis_Copy (0) := 1; + Stats_Dis_Copy (1) := 1; + elsif Stats_Dis_Copy (0) = 0 then + Stats_Dis_Copy (0) := 1; -- now code 0 and some other code have non-zero counts + else + Stats_Dis_Copy (1) := 1; -- now codes 0 and 1 have non-zero counts + end if; + end if; + Llhcl_Lit_Len (Stats_Lit_Len, Bl_For_Lit_Len); -- Call the magic algorithm for setting + Llhcl_Dis (Stats_Dis_Copy, Bl_For_Dis); -- up Huffman lengths of both trees + return Build_Descriptors (Bl_For_Lit_Len, Bl_For_Dis); + end Build_Descriptors; + + -- Here is one original part in the Taillaule algorithm: use of basic + -- topology (L1, L2 distances) to check similarities between Huffman code sets. + + -- Bit length vector. Convention: 16 is unused bit length (close to the bit length for the + -- rarest symbols, 15, and far from the bit length for the most frequent symbols, 1). + -- Deflate uses 0 for unused. + subtype Bl_Code is Integer_M32 range 1 .. 16; + type Bl_Vector is array (1 .. 288 + 32) of Bl_Code; + + function Convert (H : Deflate_Huff_Descriptors) return Bl_Vector is + Bv : Bl_Vector; + J : Positive := 1; + begin + for I in H.Lit_Len'Range loop + if H.Lit_Len (I).Bit_Length = 0 then + Bv (J) := 16; + else + Bv (J) := Integer_M32 (H.Lit_Len (I).Bit_Length); + end if; + J := J + 1; + end loop; + for I in H.Dis'Range loop + if H.Dis (I).Bit_Length = 0 then + Bv (J) := 16; + else + Bv (J) := Integer_M32 (H.Dis (I).Bit_Length); + end if; + J := J + 1; + end loop; + return Bv; + end Convert; + + -- L1 or Manhattan distance + function L1_Distance (B1, B2 : Bl_Vector) return Natural_M32 is + S : Natural_M32 := 0; + begin + for I in B1'Range loop + S := S + abs (B1 (I) - B2 (I)); + end loop; + return S; + end L1_Distance; + + -- L1, tweaked + Tweak : constant array (Bl_Code) of Positive_M32 := + -- For the origin of the tweak function, see ""za_work.xls"", sheet ""Deflate"". + -- function f3 = 0.20 f1 [logarithmic] + 0.80 * identity + -- NB: all values are multiplied by 100 for accuracy. + (100, 255, 379, 490, 594, 694, 791, 885, 978, 1069, 1159, 1249, 1338, 1426, 1513, 1600); + -- Neutral is: + -- (100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600) + + function L1_Tweaked (B1, B2 : Bl_Vector) return Natural_M32 is + S : Natural_M32 := 0; + begin + for I in B1'Range loop + S := S + abs (Tweak (B1 (I)) - Tweak (B2 (I))); + end loop; + return S; + end L1_Tweaked; + + -- L2 or Euclidean distance + function L2_Distance_Square (B1, B2 : Bl_Vector) return Natural_M32 is + S : Natural_M32 := 0; + begin + for I in B1'Range loop + S := S + (B1 (I) - B2 (I))**2; + end loop; + return S; + end L2_Distance_Square; + + -- L2, tweaked + function L2_Tweaked_Square (B1, B2 : Bl_Vector) return Natural_M32 is + S : Natural_M32 := 0; + begin + for I in B1'Range loop + S := S + (Tweak (B1 (I)) - Tweak (B2 (I)))**2; + end loop; + return S; + end L2_Tweaked_Square; + + type Distance_Type is (L1, L1_Tweaked, L2, L2_Tweaked); + + function Similar + (H1, H2 : Deflate_Huff_Descriptors; + Dist_Kind : Distance_Type; + Threshold : Natural) return Boolean + is + Dist : Natural_M32; + Thres : Natural_M32 := Natural_M32 (Threshold); + begin + case Dist_Kind is + when L1 => + Dist := L1_Distance (Convert (H1), Convert (H2)); + when L1_Tweaked => + Thres := Thres * Tweak (1); + Dist := L1_Tweaked (Convert (H1), Convert (H2)); + when L2 => + Thres := Thres * Thres; + Dist := L2_Distance_Square (Convert (H1), Convert (H2)); + when L2_Tweaked => + Thres := (Thres * Thres) * (Tweak (1) * Tweak (1)); + Dist := L2_Tweaked_Square (Convert (H1), Convert (H2)); + end case; + return Dist < Thres; + end Similar; + + -- Another original part in the Taillaule algorithm: the possibility of recycling + -- Huffman codes. It is possible only if previous block was not stored and if + -- the new block's used alphabets are included in the old block's used alphabets. + function Recyclable (H_Old, H_New : Deflate_Huff_Descriptors) return Boolean is + begin + for I in H_Old.Lit_Len'Range loop + if H_Old.Lit_Len (I).Bit_Length = 0 and H_New.Lit_Len (I).Bit_Length > 0 then + return False; -- Code used in new, but not in old + end if; + end loop; + for I in H_Old.Dis'Range loop + if H_Old.Dis (I).Bit_Length = 0 and H_New.Dis (I).Bit_Length > 0 then + return False; -- Code used in new, but not in old + end if; + end loop; + return True; + end Recyclable; + + -- Phase (C): the Prepare_Huffman_codes procedure finds the Huffman code for each + -- value, given the bit length imposed as input. + procedure Prepare_Huffman_Codes (Hd : in out Huff_Descriptor) is + Max_Huffman_Bits : constant := 15; + Bl_Count, Next_Code : array (0 .. Max_Huffman_Bits) of Natural := (others => 0); + Code : Natural := 0; + Bl : Natural; + begin + -- Algorithm from RFC 1951, section 3.2.2. + -- Step 1) + for I in Hd'Range loop + Bl := Hd (I).Bit_Length; + Bl_Count (Bl) := Bl_Count (Bl) + 1; -- One more code to be defined with bit length bl + end loop; + -- Step 2) + for Bits in 1 .. Max_Huffman_Bits loop + Code := (Code + Bl_Count (Bits - 1)) * 2; + Next_Code (Bits) := Code; -- This will be the first code for bit length ""bits"" + end loop; + -- Step 3) + for N in Hd'Range loop + Bl := Hd (N).Bit_Length; + if Bl > 0 then + Hd (N).Code := Next_Code (Bl); + Next_Code (Bl) := Next_Code (Bl) + 1; + else + Hd (N).Code := 0; + end if; + end loop; + -- Invert bit order for output: + for I in Hd'Range loop + Invert (Hd (I)); + end loop; + end Prepare_Huffman_Codes; + + -- This is the phase (C) for the pair of alphabets used in the Deflate format + function Prepare_Huffman_Codes + (Dhd : Deflate_Huff_Descriptors) return Deflate_Huff_Descriptors + is + Dhd_Var : Deflate_Huff_Descriptors := Dhd; + begin + Prepare_Huffman_Codes (Dhd_Var.Lit_Len); + Prepare_Huffman_Codes (Dhd_Var.Dis); + return Dhd_Var; + end Prepare_Huffman_Codes; + + -- Emit a variable length Huffman code + procedure Put_Huffman_Code (Lc : Length_Code_Pair) is + pragma Inline (Put_Huffman_Code); + begin + -- Huffman code of length 0 should never occur: when constructing + -- the code lengths (LLHCL) any single occurrence in the statistics + -- will trigger the build of a code length of 1 or more. + Put_Code + (Code => U32 (Lc.Code), + Code_Size => Code_Size_Type (Lc.Bit_Length) -- Range check for length 0 (if enabled). + ); + end Put_Huffman_Code; + + -- This is where the ""dynamic"" Huffman trees are sent before the block's data are sent. + -- + -- The decoder needs to know in advance the pair of trees (first tree for literals-eob-LZ + -- lengths, second tree for LZ distances) for decoding the compressed data. + -- But this information takes some room. Fortunately Deflate allows for compressing it + -- with a combination of Huffman and Run-Length Encoding (RLE) to make this header smaller. + -- Concretely, the trees are described by the bit length of each symbol, so the header's + -- content is a vector of length max 320, whose contents are in the 0 .. 18 range and typically + -- look like: ... 8, 8, 9, 7, 8, 10, 6, 8, 8, 8, 8, 8, 11, 8, 9, 8, ... + -- Clearly this vector has redundancies and can be sent in a compressed form. In this example, + -- the RLE will compress the string of 8's with a single code 8, then a code 17 + -- (repeat x times). Anyway, the very frequent 8's will be encoded with a small number of + -- bits (less than the 5 plain bits, or maximum 7 Huffman-encoded bits + -- needed for encoding integers in the 0 .. 18 range). + procedure Put_Compression_Structure + (Dhd : Deflate_Huff_Descriptors; + Cost_Analysis : Boolean; -- If True: just simulate the whole, and count needed bits + Bits : in out Count_Type) -- This is incremented when cost_analysis = True + is + subtype Alphabet is Integer range 0 .. 18; + type Alpha_Array is new Bit_Length_Array (Alphabet); + Truc_Freq, Truc_Bl : Alpha_Array; + Truc : Huff_Descriptor (Alphabet); + -- Compression structure: cs_bl is the ""big"" array with all bit lengths + -- for compressing data. cs_bl will be sent compressed, too. + Cs_Bl : array (1 .. Dhd.Lit_Len'Length + Dhd.Dis'Length) of Natural; + Last_Cs_Bl : Natural; + Max_Used_Lln_Code : Alphabet_Lit_Len := 0; + Max_Used_Dis_Code : Alphabet_Dis := 0; + + procedure Concatenate_All_Bit_Lengths is + Idx : Natural := 0; + begin + for A in reverse Alphabet_Lit_Len loop + if Dhd.Lit_Len (A).Bit_Length > 0 then + Max_Used_Lln_Code := A; + exit; + end if; + end loop; + for A in reverse Alphabet_Dis loop + if Dhd.Dis (A).Bit_Length > 0 then + Max_Used_Dis_Code := A; + exit; + end if; + end loop; + -- Copy bit lengths for both trees into one array, cs_bl. + for A in 0 .. Max_Used_Lln_Code loop + Idx := Idx + 1; + Cs_Bl (Idx) := Dhd.Lit_Len (A).Bit_Length; + end loop; + for A in 0 .. Max_Used_Dis_Code loop + Idx := Idx + 1; + Cs_Bl (Idx) := Dhd.Dis (A).Bit_Length; + end loop; + Last_Cs_Bl := Idx; + end Concatenate_All_Bit_Lengths; + + Extra_Bits_Needed : constant array (Alphabet) of Natural := + (16 => 2, 17 => 3, 18 => 7, others => 0); + + type Emission_Mode is (Simulate, Effective); + + procedure Emit_Data_Compression_Structures (Mode : Emission_Mode) is + procedure Emit_Data_Compression_Atom (X : Alphabet; Extra_Code : U32 := 0) is + -- x is a bit length (value in 0..15), or a RLE instruction + begin + case Mode is + when Simulate => + Truc_Freq (X) := Truc_Freq (X) + 1; -- +1 for x's histogram bar + when Effective => + Put_Huffman_Code (Truc (X)); + declare + Extra_Bits : constant Natural := Extra_Bits_Needed (X); + begin + if Extra_Bits > 0 then + Put_Code (Extra_Code, Extra_Bits); + end if;" +procedure Llhcl is new Length_Limited_Huffman_Code_Lengths,"(Alphabet, + Natural, + Alpha_Array, + Alpha_Array, + 7); + A_Non_Zero : Alphabet; + begin + Concatenate_All_Bit_Lengths; + Truc_Freq := (others => 0); + Emit_Data_Compression_Structures (Simulate); + -- We have now statistics of all bit lengths occurrences of both Huffman + -- trees used for compressing the data. + -- We turn these counts into bit lengths for the local tree + -- that helps us to store the compression structure in a more compact form. + Llhcl (Truc_Freq, Truc_Bl); -- Call the magic algorithm for setting up Huffman lengths + -- At least lengths for codes 16, 17, 18, 0 will always be sent, + -- even if all other bit lengths are 0 because codes 1 to 15 are unused. + A_Non_Zero := 3; + for A in Alphabet loop + if A > A_Non_Zero and then Truc_Bl (Alphabet_Permutation (A)) > 0 then + A_Non_Zero := A; + end if; + end loop; + if Cost_Analysis then + -- In this mode, no data output: we sum up the exact + -- number of bits needed by the compression header. + Bits := Bits + 14 + Count_Type (1 + A_Non_Zero) * 3; + for A in Alphabet loop + Bits := Bits + Count_Type (Truc_Freq (A) * (Truc_Bl (A) + Extra_Bits_Needed (A))); + end loop; + else + -- We output the compression header to the output stream. + for A in Alphabet loop + Truc (A).Bit_Length := Truc_Bl (A); + end loop; + Prepare_Huffman_Codes (Truc); + -- Output of the compression structure + Put_Code + (U32 (Max_Used_Lln_Code - 256), + 5); -- max_used_lln_code is always >= 256 = EOB code + Put_Code (U32 (Max_Used_Dis_Code), 5); + Put_Code (U32 (A_Non_Zero - 3), 4); + -- Save the local alphabet's Huffman lengths. It's the compression structure + -- for compressing the data compression structure. Easy, isn't it ? + for A in 0 .. A_Non_Zero loop + Put_Code (U32 (Truc (Alphabet_Permutation (A)).Bit_Length), 3); + end loop; + -- Emit the Huffman lengths for encoding the data, in the local Huffman-encoded fashion. + Emit_Data_Compression_Structures (Effective); + end if; + end Put_Compression_Structure; + + End_Of_Block : constant := 256; + + -- Default Huffman trees, for ""fixed"" blocks, as defined in appnote.txt or RFC 1951 + Default_Lit_Len_Bl : constant Bit_Length_Array_Lit_Len := + (0 .. 143 => 8, -- For literals (""plain text"" bytes) + 144 .. 255 => 9, -- For more literals (""plain text"" bytes) + End_Of_Block => 7, -- For EOB (256) + 257 .. 279 => 7, -- For length codes + 280 .. 287 => 8); -- For more length codes + Default_Dis_Bl : constant Bit_Length_Array_Dis := (others => 5); + + Deflate_Fixed_Descriptors : constant Deflate_Huff_Descriptors := + Prepare_Huffman_Codes (Build_Descriptors (Default_Lit_Len_Bl, Default_Dis_Bl)); + + -- Current tree descriptors + Curr_Descr : Deflate_Huff_Descriptors := Deflate_Fixed_Descriptors; + + -- Write a normal, ""clear-text"" (post LZ, pre Huffman), 8-bit character (literal) + procedure Put_Literal_Byte (B : Byte) is + begin + Put_Huffman_Code (Curr_Descr.Lit_Len (Integer (B))); + end Put_Literal_Byte; + + -- Possible ranges for distance and length encoding in the Zip-Deflate format: + subtype Length_Range is Integer range 3 .. 258; + subtype Distance_Range is Integer range 1 .. 32768; + + -- This is where LZ distance-length tokens are written to the output stream. + -- The Deflate format defines a sort of logarithmic compression, with codes + -- for various distance and length ranges, plus extra bits for specifying the + -- exact values. The codes are sent as Huffman codes with variable bit lengths + -- (nothing to do with the lengths of LZ distance-length tokens). + + -- Length Codes + -- ------------ + -- Extra Extra Extra Extra + -- Code Bits Length Code Bits Lengths Code Bits Lengths Code Bits Length(s) + -- ---- ---- ------ ---- ---- ------- ---- ---- ------- ---- ---- --------- + -- 257 0 3 265 1 11,12 273 3 35-42 281 5 131-162 + -- 258 0 4 266 1 13,14 274 3 43-50 282 5 163-194 + -- 259 0 5 267 1 15,16 275 3 51-58 283 5 195-226 + -- 260 0 6 268 1 17,18 276 3 59-66 284 5 227-257 + -- 261 0 7 269 2 19-22 277 4 67-82 285 0 258 + -- 262 0 8 270 2 23-26 278 4 83-98 + -- 263 0 9 271 2 27-30 279 4 99-114 + -- 264 0 10 272 2 31-34 280 4 115-130 + -- + -- Example: the code # 266 means the LZ length (# of message bytes to be copied) + -- shall be 13 or 14, depending on the extra bit value. + + Deflate_Code_For_Lz_Length : constant array (Length_Range) of Natural := + (3 => 257, -- Codes 257..264, with no extra bit + 4 => 258, + 5 => 259, + 6 => 260, + 7 => 261, + 8 => 262, + 9 => 263, + 10 => 264, + 11 .. 12 => 265, -- Codes 265..268, with 1 extra bit + 13 .. 14 => 266, + 15 .. 16 => 267, + 17 .. 18 => 268, + 19 .. 22 => 269, -- Codes 269..272, with 2 extra bits + 23 .. 26 => 270, + 27 .. 30 => 271, + 31 .. 34 => 272, + 35 .. 42 => 273, -- Codes 273..276, with 3 extra bits + 43 .. 50 => 274, + 51 .. 58 => 275, + 59 .. 66 => 276, + 67 .. 82 => 277, -- Codes 277..280, with 4 extra bits + 83 .. 98 => 278, + 99 .. 114 => 279, + 115 .. 130 => 280, + 131 .. 162 => 281, -- Codes 281..284, with 5 extra bits + 163 .. 194 => 282, + 195 .. 226 => 283, + 227 .. 257 => 284, + 258 => 285); -- Code 285, with no extra bit + + Extra_Bits_For_Lz_Length_Offset : constant array (Length_Range) of Integer := + (3 .. 10 | 258 => Invalid, -- just placeholder, there is no extra bit there! + 11 .. 18 => 11, + 19 .. 34 => 19, + 35 .. 66 => 35, + 67 .. 130 => 67, + 131 .. 257 => 131); + + Extra_Bits_For_Lz_Length : constant array (Length_Range) of Natural := + (3 .. 10 | 258 => 0, + 11 .. 18 => 1, + 19 .. 34 => 2, + 35 .. 66 => 3, + 67 .. 130 => 4, + 131 .. 257 => 5); + + procedure Put_Dl_Code (Distance : Distance_Range; Length : Length_Range) is + Extra_Bits : Natural; + begin + Put_Huffman_Code (Curr_Descr.Lit_Len (Deflate_Code_For_Lz_Length (Length))); + -- Extra bits are needed to differentiate lengths sharing the same code. + Extra_Bits := Extra_Bits_For_Lz_Length (Length); + if Extra_Bits > 0 then + -- We keep only the last extra_bits bits of the length (minus given offset). + -- Example: if extra_bits = 1, only the parity is sent (0 or 1); + -- the rest has been already sent with Put_Huffman_code above. + -- Equivalent: x:= x mod (2 ** extra_bits); + Put_Code + (U32 (Length - Extra_Bits_For_Lz_Length_Offset (Length)) and + (Shift_Left (U32'(1), Extra_Bits) - 1), + Extra_Bits); + end if; + -- Distance Codes + -- -------------- + -- Extra Extra Extra Extra + -- Code Bits Dist Code Bits Dist Code Bits Distance Code Bits Distance + -- ---- ---- ---- ---- ---- ------ ---- ---- -------- ---- ---- -------- + -- 0 0 1 8 3 17-24 16 7 257-384 24 11 4097-6144 + -- 1 0 2 9 3 25-32 17 7 385-512 25 11 6145-8192 + -- 2 0 3 10 4 33-48 18 8 513-768 26 12 8193-12288 + -- 3 0 4 11 4 49-64 19 8 769-1024 27 12 12289-16384 + -- 4 1 5,6 12 5 65-96 20 9 1025-1536 28 13 16385-24576 + -- 5 1 7,8 13 5 97-128 21 9 1537-2048 29 13 24577-32768 + -- 6 2 9-12 14 6 129-192 22 10 2049-3072 + -- 7 2 13-16 15 6 193-256 23 10 3073-4096 + -- + -- + -- Example: the code # 10 means the LZ distance (# positions back in the circular + -- message buffer for starting the copy) shall be 33, plus the value given + -- by the 4 extra bits (between 0 and 15). + case Distance is + when 1 .. 4 => -- Codes 0..3, with no extra bit + Put_Huffman_Code (Curr_Descr.Dis (Distance - 1)); + when 5 .. 8 => -- Codes 4..5, with 1 extra bit + Put_Huffman_Code (Curr_Descr.Dis (4 + (Distance - 5) / 2)); + Put_Code (U32 ((Distance - 5) mod 2), 1); + when 9 .. 16 => -- Codes 6..7, with 2 extra bits + Put_Huffman_Code (Curr_Descr.Dis (6 + (Distance - 9) / 4)); + Put_Code (U32 ((Distance - 9) mod 4), 2); + when 17 .. 32 => -- Codes 8..9, with 3 extra bits + Put_Huffman_Code (Curr_Descr.Dis (8 + (Distance - 17) / 8)); + Put_Code (U32 ((Distance - 17) mod 8), 3); + when 33 .. 64 => -- Codes 10..11, with 4 extra bits + Put_Huffman_Code (Curr_Descr.Dis (10 + (Distance - 33) / 16)); + Put_Code (U32 ((Distance - 33) mod 16), 4); + when 65 .. 128 => -- Codes 12..13, with 5 extra bits + Put_Huffman_Code (Curr_Descr.Dis (12 + (Distance - 65) / 32)); + Put_Code (U32 ((Distance - 65) mod 32), 5); + when 129 .. 256 => -- Codes 14..15, with 6 extra bits + Put_Huffman_Code (Curr_Descr.Dis (14 + (Distance - 129) / 64)); + Put_Code (U32 ((Distance - 129) mod 64), 6); + when 257 .. 512 => -- Codes 16..17, with 7 extra bits + Put_Huffman_Code (Curr_Descr.Dis (16 + (Distance - 257) / 128)); + Put_Code (U32 ((Distance - 257) mod 128), 7); + when 513 .. 1024 => -- Codes 18..19, with 8 extra bits + Put_Huffman_Code (Curr_Descr.Dis (18 + (Distance - 513) / 256)); + Put_Code (U32 ((Distance - 513) mod 256), 8); + when 1025 .. 2048 => -- Codes 20..21, with 9 extra bits + Put_Huffman_Code (Curr_Descr.Dis (20 + (Distance - 1025) / 512)); + Put_Code (U32 ((Distance - 1025) mod 512), 9); + when 2049 .. 4096 => -- Codes 22..23, with 10 extra bits + Put_Huffman_Code (Curr_Descr.Dis (22 + (Distance - 2049) / 1024)); + Put_Code (U32 ((Distance - 2049) mod 1024), 10); + when 4097 .. 8192 => -- Codes 24..25, with 11 extra bits + Put_Huffman_Code (Curr_Descr.Dis (24 + (Distance - 4097) / 2048)); + Put_Code (U32 ((Distance - 4097) mod 2048), 11); + when 8193 .. 16384 => -- Codes 26..27, with 12 extra bits + Put_Huffman_Code (Curr_Descr.Dis (26 + (Distance - 8193) / 4096)); + Put_Code (U32 ((Distance - 8193) mod 4096), 12); + when 16385 .. 32768 => -- Codes 28..29, with 13 extra bits + Put_Huffman_Code (Curr_Descr.Dis (28 + (Distance - 16385) / 8192)); + Put_Code (U32 ((Distance - 16385) mod 8192), 13); + end case; + end Put_Dl_Code; + + function Deflate_Code_For_Lz_Distance (Distance : Distance_Range) return Natural is + begin + case Distance is + when 1 .. 4 => -- Codes 0..3, with no extra bit + return Distance - 1; + when 5 .. 8 => -- Codes 4..5, with 1 extra bit + return 4 + (Distance - 5) / 2; + when 9 .. 16 => -- Codes 6..7, with 2 extra bits + return 6 + (Distance - 9) / 4; + when 17 .. 32 => -- Codes 8..9, with 3 extra bits + return 8 + (Distance - 17) / 8; + when 33 .. 64 => -- Codes 10..11, with 4 extra bits + return 10 + (Distance - 33) / 16; + when 65 .. 128 => -- Codes 12..13, with 5 extra bits + return 12 + (Distance - 65) / 32; + when 129 .. 256 => -- Codes 14..15, with 6 extra bits + return 14 + (Distance - 129) / 64; + when 257 .. 512 => -- Codes 16..17, with 7 extra bits + return 16 + (Distance - 257) / 128; + when 513 .. 1024 => -- Codes 18..19, with 8 extra bits + return 18 + (Distance - 513) / 256; + when 1025 .. 2048 => -- Codes 20..21, with 9 extra bits + return 20 + (Distance - 1025) / 512; + when 2049 .. 4096 => -- Codes 22..23, with 10 extra bits + return 22 + (Distance - 2049) / 1024; + when 4097 .. 8192 => -- Codes 24..25, with 11 extra bits + return 24 + (Distance - 4097) / 2048; + when 8193 .. 16384 => -- Codes 26..27, with 12 extra bits + return 26 + (Distance - 8193) / 4096; + when 16385 .. 32768 => -- Codes 28..29, with 13 extra bits + return 28 + (Distance - 16385) / 8192; + end case; + end Deflate_Code_For_Lz_Distance; + + ----------------- + -- LZ Buffer -- + ----------------- + + -- We buffer the LZ codes (plain, or distance/length) in order to + -- analyse them and try to do smart things. + + Max_Expand : constant := 14; + -- *Tuned* Sometimes it is better to store data and expand short strings + + Code_For_Max_Expand : constant := 266; + subtype Expanded_Data is Byte_Buffer (1 .. Max_Expand); + + type Lz_Atom_Kind is (Plain_Byte, Distance_Length); + type Lz_Atom is record + Kind : Lz_Atom_Kind; + Plain : Byte; + Lz_Distance : Natural; + Lz_Length : Natural; + Lz_Expanded : Expanded_Data; + end record; + + -- *Tuned*. Min: 2**14, = 16384 (min half buffer 8192) + -- Optimal so far: 2**17 + Lz_Buffer_Size : constant := 2**17; + type Lz_Buffer_Index_Type is mod Lz_Buffer_Size; + type Lz_Buffer_Type is array (Lz_Buffer_Index_Type range <>) of Lz_Atom; + + Empty_Lit_Len_Stat : constant Stats_Lit_Len_Type := (End_Of_Block => 1, others => 0); + -- End_Of_Block will have to happen once, but never appears in the LZ statistics... + Empty_Dis_Stat : constant Stats_Dis_Type := (others => 0); + + -- Compute statistics for both Literal-length, and Distance alphabets, + -- from a LZ buffer + procedure Get_Statistics + (Lzb : in Lz_Buffer_Type; + Stats_Lit_Len : out Stats_Lit_Len_Type; + Stats_Dis : out Stats_Dis_Type) + is + Lit_Len : Alphabet_Lit_Len; + Dis : Alphabet_Dis; + begin + Stats_Lit_Len := Empty_Lit_Len_Stat; + Stats_Dis := Empty_Dis_Stat; + for I in Lzb'Range loop + case Lzb (I).Kind is + when Plain_Byte => + Lit_Len := Alphabet_Lit_Len (Lzb (I).Plain); + Stats_Lit_Len (Lit_Len) := + Stats_Lit_Len (Lit_Len) + 1; -- +1 for this literal + when Distance_Length => + Lit_Len := Deflate_Code_For_Lz_Length (Lzb (I).Lz_Length); + Stats_Lit_Len (Lit_Len) := + Stats_Lit_Len (Lit_Len) + 1; -- +1 for this length code + Dis := Deflate_Code_For_Lz_Distance (Lzb (I).Lz_Distance); + Stats_Dis (Dis) := + Stats_Dis (Dis) + 1; -- +1 for this distance code + end case; + end loop; + end Get_Statistics; + + -- Send a LZ buffer using currently defined Huffman codes + procedure Put_Lz_Buffer (Lzb : Lz_Buffer_Type) is + begin + for I in Lzb'Range loop + case Lzb (I).Kind is + when Plain_Byte => + Put_Literal_Byte (Lzb (I).Plain); + when Distance_Length => + Put_Dl_Code (Lzb (I).Lz_Distance, Lzb (I).Lz_Length); + end case; + end loop; + end Put_Lz_Buffer; + + Block_To_Finish : Boolean := False; + Last_Block_Marked : Boolean := False; + type Block_Type is (Stored, Fixed, Dynamic, Reserved); -- Appnote, 5.5.2 + -- If last_block_type = dynamic, we may recycle previous block's Huffman codes + Last_Block_Type : Block_Type := Reserved; + + procedure Mark_New_Block (Last_Block_For_Stream : Boolean) is + begin + if Block_To_Finish and Last_Block_Type in Fixed .. Dynamic then + Put_Huffman_Code (Curr_Descr.Lit_Len (End_Of_Block)); -- Finish previous block + end if; + Block_To_Finish := True; + Put_Code (Code => Boolean'Pos (Last_Block_For_Stream), Code_Size => 1); + Last_Block_Marked := Last_Block_For_Stream; + end Mark_New_Block; + + -- Send a LZ buffer completely decoded as literals (LZ compression is discarded) + procedure Expand_Lz_Buffer (Lzb : Lz_Buffer_Type; Last_Block : Boolean) is + B1, B2 : Byte; + To_Be_Sent : Natural_M32 := 0; + -- To_Be_Sent is not always equal to lzb'Length: sometimes you have a DL code + Mid : Lz_Buffer_Index_Type; + begin + for I in Lzb'Range loop + case Lzb (I).Kind is + when Plain_Byte => + To_Be_Sent := To_Be_Sent + 1; + when Distance_Length => + To_Be_Sent := To_Be_Sent + Natural_M32 (Lzb (I).Lz_Length); + end case; + end loop; + if To_Be_Sent > 16#FFFF# then -- Ow, cannot send all that in one chunk. + -- Instead of a tedious block splitting, just divide and conquer: + Mid := Lz_Buffer_Index_Type ((Natural_M32 (Lzb'First) + Natural_M32 (Lzb'Last)) / 2); + Expand_Lz_Buffer (Lzb (Lzb'First .. Mid), Last_Block => False); + Expand_Lz_Buffer (Lzb (Mid + 1 .. Lzb'Last), Last_Block => Last_Block); + return; + end if; + B1 := Byte (To_Be_Sent mod 256); + B2 := Byte (To_Be_Sent / 256); + Mark_New_Block (Last_Block_For_Stream => Last_Block); + Last_Block_Type := Stored; + Put_Code (Code => 0, Code_Size => 2); -- Signals a ""stored"" block + Flush_Bit_Buffer; -- Go to byte boundary + Put_Byte (B1); + Put_Byte (B2); + Put_Byte (not B1); + Put_Byte (not B2); + for I in Lzb'Range loop + case Lzb (I).Kind is + when Plain_Byte => + Put_Byte (Lzb (I).Plain); + when Distance_Length => + for J in 1 .. Lzb (I).Lz_Length loop + Put_Byte (Lzb (I).Lz_Expanded (J)); + end loop; + end case; + end loop; + end Expand_Lz_Buffer; + + -- Extra bits that need to be sent after various Deflate codes + + Extra_Bits_For_Lz_Length_Code : constant array (257 .. 285) of Natural := + (257 .. 264 => 0, + 265 .. 268 => 1, + 269 .. 272 => 2, + 273 .. 276 => 3, + 277 .. 280 => 4, + 281 .. 284 => 5, + 285 => 0); + + Extra_Bits_For_Lz_Distance_Code : constant array (0 .. 29) of Natural := + (0 .. 3 => 0, + 4 .. 5 => 1, + 6 .. 7 => 2, + 8 .. 9 => 3, + 10 .. 11 => 4, + 12 .. 13 => 5, + 14 .. 15 => 6, + 16 .. 17 => 7, + 18 .. 19 => 8, + 20 .. 21 => 9, + 22 .. 23 => 10, + 24 .. 25 => 11, + 26 .. 27 => 12, + 28 .. 29 => 13); + + subtype Long_Length_Codes is + Alphabet_Lit_Len range Code_For_Max_Expand + 1 .. Alphabet_Lit_Len'Last; + Zero_Bl_Long_Lengths : constant Stats_Type (Long_Length_Codes) := (others => 0); + + -- Send_as_block. + -- + -- lzb (can be a slice of the principal buffer) will be sent as: + -- * a new ""dynamic"" block, preceded by a compression structure header + -- or * the continuation of previous ""dynamic"" block + -- or * a new ""fixed"" block, if lz data's Huffman descriptor is close enough to ""fixed"" + -- or * a new ""stored"" block, if lz data are too random + procedure Send_As_Block (Lzb : Lz_Buffer_Type; Last_Block : Boolean) is + New_Descr, New_Descr_2 : Deflate_Huff_Descriptors; + + procedure Send_Fixed_Block is + begin + if Last_Block_Type = Fixed then + -- Cool, we don't need to mark a block boundary: the Huffman codes are already + -- the expected ones. We can just continue sending the LZ atoms. + null; + else + Mark_New_Block (Last_Block_For_Stream => Last_Block); + Curr_Descr := Deflate_Fixed_Descriptors; + Put_Code (Code => 1, Code_Size => 2); -- Signals a ""fixed"" block + Last_Block_Type := Fixed; + end if; + Put_Lz_Buffer (Lzb); + end Send_Fixed_Block; + + Stats_Lit_Len, Stats_Lit_Len_2 : Stats_Lit_Len_Type; + Stats_Dis, Stats_Dis_2 : Stats_Dis_Type; + + procedure Send_Dynamic_Block (Dyn : Deflate_Huff_Descriptors) is + Dummy : Count_Type := 0; + begin + Mark_New_Block (Last_Block_For_Stream => Last_Block); + Curr_Descr := Prepare_Huffman_Codes (Dyn); + Put_Code (Code => 2, Code_Size => 2); -- Signals a ""dynamic"" block + Put_Compression_Structure (Curr_Descr, Cost_Analysis => False, Bits => Dummy); + Put_Lz_Buffer (Lzb); + Last_Block_Type := Dynamic; + end Send_Dynamic_Block; + + -- The following variables will contain the *exact* number of bits taken + -- by the block to be sent, using different Huffman encodings, or stored. + Stored_Format_Bits, -- Block is stored (no compression) + Fixed_Format_Bits, -- Fixed (preset) Huffman codes + Dynamic_Format_Bits, -- Dynamic Huffman codes using block's statistics + Dynamic_Format_Bits_2, -- Dynamic Huffman codes after Tweak_for_better_RLE + Recycled_Format_Bits : Count_Type := + 0; -- Continue previous block, use current Huffman codes + Stored_Format_Possible : Boolean; -- Can we store (needs expansion of DL codes) ? + Recycling_Possible : Boolean; -- Can we recycle current Huffman codes ? + + procedure Compute_Sizes_Of_Variants is + C : Count_Type; + Extra : Natural; + begin + -- We count bits taken by literals, for each block format variant + for I in 0 .. 255 loop + C := Stats_Lit_Len (I); -- This literal appears c times in the LZ buffer + Stored_Format_Bits := Stored_Format_Bits + 8 * C; + Fixed_Format_Bits := Fixed_Format_Bits + Count_Type (Default_Lit_Len_Bl (I)) * C; + Dynamic_Format_Bits := + Dynamic_Format_Bits + Count_Type (New_Descr.Lit_Len (I).Bit_Length) * C; + Dynamic_Format_Bits_2 := + Dynamic_Format_Bits_2 + Count_Type (New_Descr_2.Lit_Len (I).Bit_Length) * C; + Recycled_Format_Bits := + Recycled_Format_Bits + Count_Type (Curr_Descr.Lit_Len (I).Bit_Length) * C; + end loop; + + -- We count bits taken by DL codes + if Stored_Format_Possible then + for I in Lzb'Range loop + case Lzb (I).Kind is + when Plain_Byte => + null; -- Already counted + when Distance_Length => + -- In the stored format, DL codes are expanded + Stored_Format_Bits := Stored_Format_Bits + 8 * Count_Type (Lzb (I).Lz_Length); + end case; + end loop; + end if; + + -- For compressed formats, count Huffman bits and extra bits + for I in 257 .. 285 loop + C := Stats_Lit_Len (I); -- This length code appears c times in the LZ buffer + Extra := Extra_Bits_For_Lz_Length_Code (I); + Fixed_Format_Bits := + Fixed_Format_Bits + Count_Type (Default_Lit_Len_Bl (I) + Extra) * C; + Dynamic_Format_Bits := + Dynamic_Format_Bits + Count_Type (New_Descr.Lit_Len (I).Bit_Length + Extra) * C; + Dynamic_Format_Bits_2 := + Dynamic_Format_Bits_2 + Count_Type (New_Descr_2.Lit_Len (I).Bit_Length + Extra) * C; + Recycled_Format_Bits := + Recycled_Format_Bits + Count_Type (Curr_Descr.Lit_Len (I).Bit_Length + Extra) * C; + end loop; + + for I in 0 .. 29 loop + C := Stats_Dis (I); -- This distance code appears c times in the LZ buffer + Extra := Extra_Bits_For_Lz_Distance_Code (I); + Fixed_Format_Bits := Fixed_Format_Bits + Count_Type (Default_Dis_Bl (I) + Extra) * C; + Dynamic_Format_Bits := + Dynamic_Format_Bits + Count_Type (New_Descr.Dis (I).Bit_Length + Extra) * C; + Dynamic_Format_Bits_2 := + Dynamic_Format_Bits_2 + Count_Type (New_Descr_2.Dis (I).Bit_Length + Extra) * C; + Recycled_Format_Bits := + Recycled_Format_Bits + Count_Type (Curr_Descr.Dis (I).Bit_Length + Extra) * C; + end loop; + + -- Supplemental bits to be counted + Stored_Format_Bits := + Stored_Format_Bits + + (1 + (Stored_Format_Bits / 8) / 65_535) -- Number of stored blocks needed + * 5 -- 5 bytes per header + * 8; -- ... converted into bits + + C := 1; -- Is-last-block flag + if Block_To_Finish and Last_Block_Type in Fixed .. Dynamic then + C := C + Count_Type (Curr_Descr.Lit_Len (End_Of_Block).Bit_Length); + end if; + + Stored_Format_Bits := Stored_Format_Bits + C; + Fixed_Format_Bits := Fixed_Format_Bits + C + 2; + Dynamic_Format_Bits := Dynamic_Format_Bits + C + 2; + Dynamic_Format_Bits_2 := Dynamic_Format_Bits_2 + C + 2; + + -- For both dynamic formats, we also counts the bits taken by + -- the compression header! + Put_Compression_Structure (New_Descr, Cost_Analysis => True, Bits => Dynamic_Format_Bits); + Put_Compression_Structure + (New_Descr_2, + Cost_Analysis => True, + Bits => Dynamic_Format_Bits_2); + end Compute_Sizes_Of_Variants; + + Optimal_Format_Bits : Count_Type; + begin + Get_Statistics (Lzb, Stats_Lit_Len, Stats_Dis); + New_Descr := Build_Descriptors (Stats_Lit_Len, Stats_Dis); + Stats_Lit_Len_2 := Stats_Lit_Len; + Stats_Dis_2 := Stats_Dis; + Tweak_For_Better_Rle (Stats_Lit_Len_2); + Tweak_For_Better_Rle (Stats_Dis_2); + New_Descr_2 := Build_Descriptors (Stats_Lit_Len_2, Stats_Dis_2); + -- For ""stored"" block format, prevent expansion of DL codes with length > max_expand + -- We check stats are all 0 for long length codes: + Stored_Format_Possible := Stats_Lit_Len (Long_Length_Codes) = Zero_Bl_Long_Lengths; + Recycling_Possible := + Last_Block_Type = Fixed -- The ""fixed"" alphabets use all symbols, then always recyclable + or else (Last_Block_Type = Dynamic and then Recyclable (Curr_Descr, New_Descr)); + Compute_Sizes_Of_Variants; + if not Stored_Format_Possible then + Stored_Format_Bits := Count_Type'Last; + end if; + if not Recycling_Possible then + Recycled_Format_Bits := Count_Type'Last; + end if; + Optimal_Format_Bits := + Count_Type'Min + (Count_Type'Min (Stored_Format_Bits, Fixed_Format_Bits), + Count_Type'Min + (Count_Type'Min (Dynamic_Format_Bits, Dynamic_Format_Bits_2), + Recycled_Format_Bits)); + + -- Selection of the block format with smallest size + if Fixed_Format_Bits = Optimal_Format_Bits then + Send_Fixed_Block; + elsif Dynamic_Format_Bits = Optimal_Format_Bits then + Send_Dynamic_Block (New_Descr); + elsif Dynamic_Format_Bits_2 = Optimal_Format_Bits then + Send_Dynamic_Block (New_Descr_2); + elsif Recycled_Format_Bits = Optimal_Format_Bits then + Put_Lz_Buffer (Lzb); + else -- We have stored_format_bits = optimal_format_bits + Expand_Lz_Buffer (Lzb, Last_Block); + end if; + end Send_As_Block; + + subtype Full_Range_Lz_Buffer_Type is Lz_Buffer_Type (Lz_Buffer_Index_Type); + type P_Full_Range_Lz_Buffer_Type is access Full_Range_Lz_Buffer_Type; + procedure Dispose is new Ada.Unchecked_Deallocation + (Full_Range_Lz_Buffer_Type, + P_Full_Range_Lz_Buffer_Type); + + -- This is the main, big, fat, circular buffer containing LZ codes, + -- each LZ code being a literal or a DL code. + -- Heap allocation is needed because default stack is too small on some targets. + Lz_Buffer : P_Full_Range_Lz_Buffer_Type; + Lz_Buffer_Index : Lz_Buffer_Index_Type := 0; + Past_Lz_Data : Boolean := False; + -- When True: some LZ_buffer_size data before lz_buffer_index (modulo!) are real, past data + + --------------------------------------------------------------------------------- + -- Scanning and sampling: the really sexy part of the Taillaule algorithm... -- + --------------------------------------------------------------------------------- + + -- We examine similarities in the LZ data flow at different step sizes. + -- If the optimal Huffman encoding for this portion is very different, we choose to + -- cut current block and start a new one. The shorter the step, the higher the threshold + -- for starting a dynamic block, since the compression header is taking some room each time. + + -- *Tuned* (a bit...) + Min_Step : constant := 750; + + type Step_Threshold_Metric is record + Slider_Step : Lz_Buffer_Index_Type; -- Should be a multiple of Min_Step + Cutting_Threshold : Positive; + Metric : Distance_Type; + end record; + + -- *Tuned* thresholds + -- NB: the enwik8, then silesia, then others tests are tough for lowering any! + Step_Choice : constant array (Positive range <>) of Step_Threshold_Metric := + ((8 * Min_Step, 420, L1_Tweaked), -- Deflate_1, Deflate_2, Deflate_3 (enwik8) + (4 * Min_Step, 430, L1_Tweaked), -- Deflate_2, Deflate_3 (silesia) + (Min_Step, 2050, L1_Tweaked)); -- Deflate_3 (DB test) + + Max_Choice : constant array (Taillaule_Deflation_Method) of Positive := + (Deflate_1 => 1, + Deflate_2 => 2, + Deflate_3 => Step_Choice'Last); + + Slider_Size : constant := 4096; + Half_Slider_Size : constant := Slider_Size / 2; + Slider_Max : constant := Slider_Size - 1; + + -- Phases (A) and (B) are done in a single function: we get Huffman + -- descriptors that should be good for encoding a given sequence of LZ atoms. + function Build_Descriptors (Lzb : Lz_Buffer_Type) return Deflate_Huff_Descriptors is + Stats_Lit_Len : Stats_Lit_Len_Type; + Stats_Dis : Stats_Dis_Type; + begin + Get_Statistics (Lzb, Stats_Lit_Len, Stats_Dis); + return Build_Descriptors (Stats_Lit_Len, Stats_Dis); + end Build_Descriptors; + + procedure Scan_And_Send_From_Main_Buffer + (From, To : Lz_Buffer_Index_Type; + Last_Flush : Boolean) + is + -- The following descriptors are *not* used for compressing, but for detecting similarities. + Initial_Hd, Sliding_Hd : Deflate_Huff_Descriptors; + Start, Slide_Mid, Send_From : Lz_Buffer_Index_Type; + Sliding_Hd_Computed : Boolean; + begin + if To - From < Slider_Max then + Send_As_Block (Lz_Buffer (From .. To), Last_Flush); + return; + end if; + -- For further comments: n := LZ_buffer_size + if Past_Lz_Data then -- We have n / 2 previous data before 'from'. + Start := From - Lz_Buffer_Index_Type (Half_Slider_Size); + else + Start := From; -- Cannot have past data + end if; + + -- Looped over, (mod n). Slider data are in two chunks in main buffer + if Start > From then + -- put_line(from'img & to'img & start'img); + declare + Copy_From : Lz_Buffer_Index_Type := Start; + Copy : Lz_Buffer_Type (0 .. Slider_Max); + begin + for I in Copy'Range loop + Copy (I) := Lz_Buffer (Copy_From); + Copy_From := Copy_From + 1; -- Loops over (mod n) + end loop; + Initial_Hd := Build_Descriptors (Copy);" +procedure Encode is,"X_Percent : Natural; + Bytes_In : Natural; -- Count of input file bytes processed + User_Aborting : Boolean; + Pctdone : Natural; + + function Read_Byte return Byte is + B : Byte; + begin + B := Inbuf (Inbufidx); + Inbufidx := Inbufidx + 1; + Zip.CRC.Update (CRC, (1 => B)); + Bytes_In := Bytes_In + 1; + if Feedback /= null then + if Bytes_In = 1 then + Feedback (0, User_Aborting); + end if; + if X_Percent > 0 + and then ((Bytes_In - 1) mod X_Percent = 0 or Bytes_In = Integer (Input_Size)) + then + Pctdone := Integer ((100.0 * Float (Bytes_In)) / Float (Input_Size)); + Feedback (Pctdone, User_Aborting); + if User_Aborting then + raise User_Abort; + end if; + end if; + end if; + return B; + end Read_Byte; + + function More_Bytes return Boolean is + begin + if Inbufidx > Maxinbufidx then + Read_Block; + end if; + return not Inputeof; + end More_Bytes; + + -- LZ77 parameters + Look_Ahead : constant Integer := 258; + String_Buffer_Size : constant := 2**15; -- Required: 2**15 for Deflate, 2**16 for Deflate_e + type Text_Buffer_Index is mod String_Buffer_Size; + type Text_Buffer is array (Text_Buffer_Index) of Byte; + Text_Buf : Text_Buffer; + R : Text_Buffer_Index; + + -- If the DLE coding doesn't fit the format constraints, we need + -- to decode it as a simple sequence of literals. The buffer used is + -- called ""Text"" buffer by reference to ""clear-text"", but actually it + -- is any binary data. + + procedure Lz77_Emits_Dl_Code (Distance, Length : Integer) is + -- NB: no worry, all arithmetics in Text_buffer_index are modulo String_buffer_size + B : Byte; + Copy_Start : Text_Buffer_Index; + Expand : Expanded_Data; + Ie : Positive := 1; + begin + if Distance = + String_Buffer_Size + then -- Happens with 7-Zip, cannot happen with Info-Zip + Copy_Start := R; + else + Copy_Start := R - Text_Buffer_Index (Distance); + end if; + -- Expand into the circular text buffer to have it up to date + for K in 0 .. Text_Buffer_Index (Length - 1) loop + B := Text_Buf (Copy_Start + K); + Text_Buf (R) := B; + R := R + 1; + if Ie <= Max_Expand then -- Also memorize short sequences for LZ buffer + Expand (Ie) := B; -- for the case a block needs to be stored in clear + Ie := Ie + 1; + end if; + end loop; + if Distance in Distance_Range and Length in Length_Range then + Put_Or_Delay_Dl_Code (Distance, Length, Expand); + else + for K in 0 .. Text_Buffer_Index (Length - 1) loop + Put_Or_Delay_Literal_Byte (Text_Buf (Copy_Start + K)); + end loop; + end if; + end Lz77_Emits_Dl_Code; + + procedure Lz77_Emits_Literal_Byte (B : Byte) is + begin + Text_Buf (R) := B; + R := R + 1; + Put_Or_Delay_Literal_Byte (B); + end Lz77_Emits_Literal_Byte; + + Lz77_Choice : constant array (Deflation_Method) of Lz77.Method_Type := + (Deflate_Fixed => Lz77.Iz_4, + Deflate_1 => Lz77.Iz_6, -- Level 6 is the default in Info-Zip's zip.exe + Deflate_2 => Lz77.Iz_8, + Deflate_3 => Lz77.Iz_10); + + procedure My_Lz77 is new Lz77.Encode + (String_Buffer_Size => String_Buffer_Size, + Look_Ahead => Look_Ahead, + Threshold => 2, -- From a string match length > 2, a DL code is sent + Method => Lz77_Choice (Method), + Read_Byte => Read_Byte, + More_Bytes => More_Bytes, + Write_Literal => Lz77_Emits_Literal_Byte, + Write_Dl_Code => Lz77_Emits_Dl_Code); + begin + Read_Block; + R := Text_Buffer_Index (String_Buffer_Size - Look_Ahead); + Bytes_In := 0; + X_Percent := Integer (Input_Size / 40); + case Method is + when Deflate_Fixed => -- ""Fixed"" (predefined) compression structure + -- We have only one compressed data block, then it is already the last one. + Put_Code (Code => 1, Code_Size => 1); -- Signals last block + Put_Code (Code => 1, Code_Size => 2); -- Signals a ""fixed"" block + when Taillaule_Deflation_Method => + null; -- No start data sent, all is delayed + end case; + + -- The whole compression is happening in the following line: + My_Lz77; + + -- Done. Send the code signaling the end of compressed data block: + case Method is + when Deflate_Fixed => + Put_Huffman_Code (Curr_Descr.Lit_Len (End_Of_Block)); + when Taillaule_Deflation_Method => + if Lz_Buffer_Index * 2 = 0 then -- Already flushed at latest Push, or empty data + if Block_To_Finish and then Last_Block_Type in Fixed .. Dynamic then + Put_Huffman_Code (Curr_Descr.Lit_Len (End_Of_Block)); + end if; + else + Flush_Half_Buffer (Last_Flush => True); + if Last_Block_Type in Fixed .. Dynamic then + Put_Huffman_Code (Curr_Descr.Lit_Len (End_Of_Block)); + end if; + end if; + if not Last_Block_Marked then + -- Add a fake fixed block, just to have a final block... + Put_Code (Code => 1, Code_Size => 1); -- Signals last block + Put_Code (Code => 1, Code_Size => 2); -- Signals a ""fixed"" block + Curr_Descr := Deflate_Fixed_Descriptors; + Put_Huffman_Code (Curr_Descr.Lit_Len (End_Of_Block)); + end if; + end case; + end Encode; + +begin + -- Allocate input and output buffers + Inbuf := new Byte_Buffer + (1 .. Integer'Min (Integer'Max (8, Integer (Input_Size)), Default_Buffer_Size)); + Outbuf := new Byte_Buffer (1 .. Default_Buffer_Size); + Output_Size := 0; + Lz_Buffer := new Full_Range_Lz_Buffer_Type; + + begin + Encode; + Compression_Ok := True; + Flush_Bit_Buffer; + Flush_Byte_Buffer; + exception + when Compression_Inefficient => + -- Escaped from Encode + Compression_Ok := False;" +function Intel_Nb is new Intel_X86_Number (Unsigned_16);,"function Intel_Nb is new Intel_X86_Number (Unsigned_32); + + -- Put numbers with correct endianess as bytes + + generic + type Number is mod <>; -- range <> in Ada83 version (fake Interfaces) + Size : Stream_Element_Count; + function Intel_X86_Buffer (N : Number) return Stream_Element_Array; + + function Intel_X86_Buffer (N : Number) return Stream_Element_Array is + B : Stream_Element_Array (1 .. Size); + M : Number := N; + begin + for I in B'Range loop + B (I) := Stream_Element (M and 255); + M := M / 256; + end loop; + return B; + end Intel_X86_Buffer; + + function Intel_Bf is new Intel_X86_Buffer (Unsigned_16, 2); + function Intel_Bf is new Intel_X86_Buffer (Unsigned_32, 4); + + --------------------- + -- PK signatures -- + --------------------- + + function Pk_Signature (Buf : Stream_Element_Array; Code : Stream_Element) return Boolean is + begin + return Buf (Buf'First .. Buf'First + 3) = (16#50#, 16#4B#, Code, Code + 1); + -- PK12, PK34, ... + end Pk_Signature; + + procedure Pk_Signature (Buf : in out Stream_Element_Array; Code : Stream_Element) is + begin + Buf (1 .. 4) := (16#50#, 16#4B#, Code, Code + 1); -- PK12, PK34, ... + end Pk_Signature; + + --------------------------------------------------------- + -- PKZIP file header, as in central directory - PK12 -- + --------------------------------------------------------- + procedure Read_And_Check + (Stream : in out Root_Zipstream_Type'Class; + Header : out Central_File_Header) + is + Chb : Stream_Element_Array (1 .. 46); + begin + Blockread (Stream, Chb); + + if not Pk_Signature (Chb, 1) then + raise Bad_Central_Header; + end if; + + Header.Made_By_Version := Intel_Nb (Chb (5 .. 6)); + Header.Short_Info.Needed_Extract_Version := Intel_Nb (Chb (7 .. 8)); + Header.Short_Info.Bit_Flag := Intel_Nb (Chb (9 .. 10)); + Header.Short_Info.Zip_Type := Intel_Nb (Chb (11 .. 12)); + Header.Short_Info.File_Timedate := + DCF.Streams.Convert (Unsigned_32'(Intel_Nb (Chb (13 .. 16)))); + Header.Short_Info.Dd.Crc_32 := Intel_Nb (Chb (17 .. 20)); + Header.Short_Info.Dd.Compressed_Size := Intel_Nb (Chb (21 .. 24)); + Header.Short_Info.Dd.Uncompressed_Size := Intel_Nb (Chb (25 .. 28)); + Header.Short_Info.Filename_Length := Intel_Nb (Chb (29 .. 30)); + Header.Short_Info.Extra_Field_Length := Intel_Nb (Chb (31 .. 32)); + Header.Comment_Length := Intel_Nb (Chb (33 .. 34)); + Header.Disk_Number_Start := Intel_Nb (Chb (35 .. 36)); + Header.Internal_Attributes := Intel_Nb (Chb (37 .. 38)); + Header.External_Attributes := Intel_Nb (Chb (39 .. 42)); + Header.Local_Header_Offset := Intel_Nb (Chb (43 .. 46)); + + if not Valid_Version (Header.Short_Info) then + raise Bad_Central_Header with ""Archive needs invalid version to extract""; + end if; + + if Header.Disk_Number_Start /= 0 then + raise Bad_Central_Header with ""Archive may not span multiple volumes""; + end if; + + if not Valid_Bitflag (Header.Short_Info) then + raise Bad_Central_Header with ""Archive uses prohibited features""; + end if; + end Read_And_Check; + + procedure Write (Stream : in out Root_Zipstream_Type'Class; Header : in Central_File_Header) is + Chb : Stream_Element_Array (1 .. 46); + begin + Pk_Signature (Chb, 1); + + Chb (5 .. 6) := Intel_Bf (Header.Made_By_Version); + Chb (7 .. 8) := Intel_Bf (Header.Short_Info.Needed_Extract_Version); + Chb (9 .. 10) := Intel_Bf (Header.Short_Info.Bit_Flag); + Chb (11 .. 12) := Intel_Bf (Header.Short_Info.Zip_Type); + Chb (13 .. 16) := Intel_Bf (DCF.Streams.Convert (Header.Short_Info.File_Timedate)); + Chb (17 .. 20) := Intel_Bf (Header.Short_Info.Dd.Crc_32); + Chb (21 .. 24) := Intel_Bf (Header.Short_Info.Dd.Compressed_Size); + Chb (25 .. 28) := Intel_Bf (Header.Short_Info.Dd.Uncompressed_Size); + Chb (29 .. 30) := Intel_Bf (Header.Short_Info.Filename_Length); + Chb (31 .. 32) := Intel_Bf (Header.Short_Info.Extra_Field_Length); + Chb (33 .. 34) := Intel_Bf (Header.Comment_Length); + Chb (35 .. 36) := Intel_Bf (Header.Disk_Number_Start); + Chb (37 .. 38) := Intel_Bf (Header.Internal_Attributes); + Chb (39 .. 42) := Intel_Bf (Header.External_Attributes); + Chb (43 .. 46) := Intel_Bf (Header.Local_Header_Offset); + + Stream.Write (Chb); + end Write; + + ------------------------------------------------------------------------- + -- PKZIP local file header, in front of every file in archive - PK34 -- + ------------------------------------------------------------------------- + procedure Read_And_Check + (Stream : in out Root_Zipstream_Type'Class; + Header : out Local_File_Header) + is + Lhb : Stream_Element_Array (1 .. 30); + begin + Blockread (Stream, Lhb); + + if not Pk_Signature (Lhb, 3) then + raise Bad_Local_Header; + end if; + + Header.Needed_Extract_Version := Intel_Nb (Lhb (5 .. 6)); + Header.Bit_Flag := Intel_Nb (Lhb (7 .. 8)); + Header.Zip_Type := Intel_Nb (Lhb (9 .. 10)); + Header.File_Timedate := + DCF.Streams.Convert (Unsigned_32'(Intel_Nb (Lhb (11 .. 14)))); + Header.Dd.Crc_32 := Intel_Nb (Lhb (15 .. 18)); + Header.Dd.Compressed_Size := Intel_Nb (Lhb (19 .. 22)); + Header.Dd.Uncompressed_Size := Intel_Nb (Lhb (23 .. 26)); + Header.Filename_Length := Intel_Nb (Lhb (27 .. 28)); + Header.Extra_Field_Length := Intel_Nb (Lhb (29 .. 30)); + + if not Valid_Version (Header) then + raise Bad_Local_Header with ""Archived file needs invalid version to extract""; + end if; + + if not Valid_Bitflag (Header) then + raise Bad_Local_Header with ""Archived file uses prohibited features""; + end if; + end Read_And_Check; + + procedure Write (Stream : in out Root_Zipstream_Type'Class; Header : in Local_File_Header) is + Lhb : Stream_Element_Array (1 .. 30); + begin + Pk_Signature (Lhb, 3); + + Lhb (5 .. 6) := Intel_Bf (Header.Needed_Extract_Version); + Lhb (7 .. 8) := Intel_Bf (Header.Bit_Flag); + Lhb (9 .. 10) := Intel_Bf (Header.Zip_Type); + Lhb (11 .. 14) := Intel_Bf (DCF.Streams.Convert (Header.File_Timedate)); + Lhb (15 .. 18) := Intel_Bf (Header.Dd.Crc_32); + Lhb (19 .. 22) := Intel_Bf (Header.Dd.Compressed_Size); + Lhb (23 .. 26) := Intel_Bf (Header.Dd.Uncompressed_Size); + Lhb (27 .. 28) := Intel_Bf (Header.Filename_Length); + Lhb (29 .. 30) := Intel_Bf (Header.Extra_Field_Length); + + Stream.Write (Lhb); + end Write; + + --------------------------------------------- + -- PKZIP end-of-central-directory - PK56 -- + --------------------------------------------- + procedure Copy_And_Check (Buffer : in Stream_Element_Array; The_End : out End_Of_Central_Dir) is + O : constant Stream_Element_Offset := Buffer'First - 1; + begin + if not Pk_Signature (Buffer, 5) then + raise Bad_End; + end if; + + The_End.Disknum := Intel_Nb (Buffer (O + 5 .. O + 6)); + The_End.Disknum_With_Start := Intel_Nb (Buffer (O + 7 .. O + 8)); + The_End.Disk_Total_Entries := Intel_Nb (Buffer (O + 9 .. O + 10)); + The_End.Total_Entries := Intel_Nb (Buffer (O + 11 .. O + 12)); + The_End.Central_Dir_Size := Intel_Nb (Buffer (O + 13 .. O + 16)); + The_End.Central_Dir_Offset := Intel_Nb (Buffer (O + 17 .. O + 20)); + The_End.Main_Comment_Length := Intel_Nb (Buffer (O + 21 .. O + 22)); + end Copy_And_Check; + + procedure Read_And_Check + (Stream : in out Root_Zipstream_Type'Class; + The_End : out End_Of_Central_Dir) + is + Buffer : Stream_Element_Array (1 .. 22); + begin + Blockread (Stream, Buffer); + Copy_And_Check (Buffer, The_End); + end Read_And_Check; + + procedure Load (Stream : in out Root_Zipstream_Type'Class; The_End : out End_Of_Central_Dir) is + Min_End_Start : Zs_Index_Type; -- min_end_start >= 1 + Max_Comment : constant := 65_535; + -- In appnote.txt : + -- .ZIP file comment length 2 bytes + begin + if Size (Stream) < 22 then + raise Bad_End; + end if; + -- 20-Jun-2001: abandon search below min_end_start. + if Size (Stream) <= Max_Comment then + Min_End_Start := 1; + else + Min_End_Start := Size (Stream) - Max_Comment; + end if; + Set_Index (Stream, Min_End_Start); + declare + -- We copy a large chunk of the zip stream's tail into a buffer. + Large_Buffer : Stream_Element_Array + (0 .. Stream_Element_Count (Size (Stream) - Min_End_Start)); + Ilb : Stream_Element_Offset; + X : Zs_Size_Type; + begin + Blockread (Stream, Large_Buffer); + for I in reverse Min_End_Start .. Size (Stream) - 21 loop + -- Yes, we must _search_ for the header... + -- because PKWARE put a variable-size comment _after_ it 8-( + Ilb := Stream_Element_Offset (I - Min_End_Start); + if Pk_Signature (Large_Buffer (Ilb .. Ilb + 3), 5) then + Copy_And_Check (Large_Buffer (Ilb .. Ilb + 21), The_End); + -- At this point, the buffer was successfully read, the_end is + -- is set with its standard contents. + -- + -- This is the *real* position of the end-of-central-directory block to begin with: + X := I; + -- We subtract the *theoretical* (stored) position of the end-of-central-directory. + -- The theoretical position is equal to central_dir_offset + central_dir_size. + -- The theoretical position should be smaller or equal than the real position - + -- unless the archive is corrupted. + -- We do it step by step, because ZS_Size_Type was modular until rev. 644. + -- Now it's a signed 64 bits, but we don't want to change anything again... + X := X - 1; + -- i >= 1, so no dragons here. The ""- 1"" is for adapting + -- from the 1-based Ada index. + + -- Fuzzy value, will trigger bad_end + exit when Zs_Size_Type (The_End.Central_Dir_Offset) > X; + + -- Fuzzy value, will trigger bad_end + X := X - Zs_Size_Type (The_End.Central_Dir_Offset); + exit when Zs_Size_Type (The_End.Central_Dir_Size) > X; + + X := X - Zs_Size_Type (The_End.Central_Dir_Size); + -- Now, x is the difference : real - theoretical. + -- x > 0 if the archive was appended to another file (typically an executable + -- for self-extraction purposes). + -- x = 0 if this is a ""pure"" Zip archive. + The_End.Offset_Shifting := X; + Set_Index (Stream, I + 22); + return; -- The_End found and filled -> exit + end if; + end loop; + raise Bad_End; -- Definitely no ""end-of-central-directory"" in this stream" +"procedure Dispose is new Ada.Unchecked_Deallocation (Huft_Table, P_Huft_Table);","procedure Dispose is new Ada.Unchecked_Deallocation (Table_List, P_Table_List); + + Current : P_Table_List; + begin + while Tl /= null loop + Dispose (Tl.Table); -- Destroy the Huffman table + Current := Tl; + Tl := Tl.Next; + Dispose (Current); -- Destroy the current node + end loop; + end Huft_Free; + + -- Build huffman table from code lengths given by array b + + procedure Huft_Build + (B : Length_Array; + S : Integer; + D, E : Length_Array; + Tl : out P_Table_List; + M : in out Integer; + Huft_Incomplete : out Boolean) + is + B_Max : constant := 16; + B_Maxp1 : constant := B_Max + 1; + + -- Bit length count table + Count : array (0 .. B_Maxp1) of Integer := (others => 0); + + F : Integer; -- I repeats in table every f entries + G : Integer; -- Maximum code length + I : Integer; -- Counter, current code + J : Integer; -- Counter + Kcc : Integer; -- Number of bits in current code + + C_Idx, V_Idx : Natural; -- Array indices + + Current_Table_Ptr : P_Huft_Table := null; + Current_Node_Ptr : P_Table_List := null; -- Current node for the current table + New_Node_Ptr : P_Table_List; -- New node for the new table + + New_Entry : Huft; -- Table entry for structure assignment + + U : array (0 .. B_Max) of P_Huft_Table; -- Table stack + + N_Max : constant := 288; + -- Values in order of bit length + V : array (0 .. N_Max) of Integer := (others => 0); + El_V, El_V_M_S : Integer; + + W : Natural := 0; -- Bits before this table + + Offset, Code_Stack : array (0 .. B_Maxp1) of Integer; + + Table_Level : Integer := -1; + Bits : array (Integer'(-1) .. B_Maxp1) of Integer; + -- ^ bits(table_level) = # bits in table of level table_level + + Y : Integer; -- Number of dummy codes added + Z : Natural := 0; -- Number of entries in current table + El : Integer; -- Length of eob code=code 256 + + No_Copy_Length_Array : constant Boolean := D'Length = 0 or E'Length = 0; + + begin + Tl := null; + + if B'Length > 256 then -- Set length of EOB code, if any + El := B (256); + else + El := B_Max; + end if; + + -- Generate counts for each bit length + + for K in B'Range loop + if B (K) > B_Max then + -- m := 0; -- GNAT 2005 doesn't like it (warning). + raise Huft_Error; + end if; + Count (B (K)) := Count (B (K)) + 1; + end loop; + + if Count (0) = B'Length then + M := 0; + Huft_Incomplete := False; -- Spotted by Tucker Taft, 19-Aug-2004 + return; -- Complete + end if; + + -- Find minimum and maximum length, bound m by those + + J := 1; + while J <= B_Max and then Count (J) = 0 loop + J := J + 1; + end loop; + Kcc := J; + if M < J then + M := J; + end if; + I := B_Max; + while I > 0 and then Count (I) = 0 loop + I := I - 1; + end loop; + G := I; + if M > I then + M := I; + end if; + + -- Adjust last length count to fill out codes, if needed + + Y := Integer (Shift_Left (Unsigned_32'(1), J)); -- y:= 2 ** j; + while J < I loop + Y := Y - Count (J); + if Y < 0 then + raise Huft_Error; + end if; + Y := Y * 2; + J := J + 1; + end loop; + + Y := Y - Count (I); + if Y < 0 then + raise Huft_Error; + end if; + Count (I) := Count (I) + Y; + + -- Generate starting offsets into the value table for each length + + Offset (1) := 0; + J := 0; + for Idx in 2 .. I loop + J := J + Count (Idx - 1); + Offset (Idx) := J; + end loop; + + -- Make table of values in order of bit length + + for Idx in B'Range loop + J := B (Idx); + if J /= 0 then + V (Offset (J)) := Idx - B'First; + Offset (J) := Offset (J) + 1; + end if; + end loop; + + -- Generate huffman codes and for each, make the table entries + + Code_Stack (0) := 0; + I := 0; + V_Idx := V'First; + Bits (-1) := 0; + + -- Go through the bit lengths (kcc already is bits in shortest code) + for K in Kcc .. G loop + for Am1 in reverse 0 .. Count (K) - 1 loop -- A counts codes of length k + -- Here i is the huffman code of length k bits for value v(v_idx) + while K > W + Bits (Table_Level) loop + W := W + Bits (Table_Level); -- Length of tables to this position + Table_Level := Table_Level + 1; + Z := G - W; -- Compute min size table <= m bits + if Z > M then + Z := M; + end if; + J := K - W; + F := Integer (Shift_Left (Unsigned_32'(1), J)); -- f:= 2 ** j; + if F > Am1 + 2 then + -- Try a k-w bit table + F := F - (Am1 + 2); + C_Idx := K; + + -- Try smaller tables up to z bits + loop + J := J + 1; + exit when J >= Z; + F := F * 2; + C_Idx := C_Idx + 1; + exit when F - Count (C_Idx) <= 0; + F := F - Count (C_Idx); + end loop; + end if; + + if W + J > El and then W < El then + J := El - W; -- Make EOB code end at table + end if; + if W = 0 then + J := M; -- Fix: main table always m bits! + end if; + Z := Integer (Shift_Left (Unsigned_32'(1), J)); -- z:= 2 ** j; + Bits (Table_Level) := J; + + -- Allocate and link new table + + begin + Current_Table_Ptr := new Huft_Table (0 .. Z); + New_Node_Ptr := new Table_List'(Current_Table_Ptr, null); + exception + when Storage_Error => + raise Huft_Out_Of_Memory;" +"procedure Dispose is new Ada.Unchecked_Deallocation (Dir_Node, P_Dir_Node);","procedure Dispose is new Ada.Unchecked_Deallocation (String, P_String); + + package Binary_Tree_Rebalancing is + procedure Rebalance (Root : in out P_Dir_Node); + end Binary_Tree_Rebalancing; + + package body Binary_Tree_Rebalancing is + + ------------------------------------------------------------------- + -- Tree Rebalancing in Optimal Time and Space -- + -- QUENTIN F. STOUT and BETTE L. WARREN -- + -- Communications of the ACM September 1986 Volume 29 Number 9 -- + ------------------------------------------------------------------- + -- http://www.eecs.umich.edu/~qstout/pap/CACM86.pdf + -- + -- Translated by (New) P2Ada v. 15-Nov-2006 + + procedure Tree_To_Vine (Root : P_Dir_Node; Size : out Integer) is + -- Transform the tree with pseudo-root ""root^"" into a vine with + -- pseudo-root node ""root^"", and store the number of nodes in ""size"" + Vine_Tail, Remainder, Temp : P_Dir_Node; + begin + Vine_Tail := Root; + Remainder := Vine_Tail.Right; + Size := 0; + while Remainder /= null loop + if Remainder.Left = null then + -- Move vine-tail down one: + Vine_Tail := Remainder; + Remainder := Remainder.Right; + Size := Size + 1; + else + -- Rotate: + Temp := Remainder.Left; + Remainder.Left := Temp.Right; + Temp.Right := Remainder; + Remainder := Temp; + Vine_Tail.Right := Temp; + end if; + end loop; + end Tree_To_Vine; + + procedure Vine_To_Tree (Root : P_Dir_Node; Size_Given : Integer) is + -- Convert the vine with ""size"" nodes and pseudo-root + -- node ""root^"" into a balanced tree + Leaf_Count : Integer; + Size : Integer := Size_Given; + + procedure Compression (Root_Compress : P_Dir_Node; Count : Integer) is + -- Compress ""count"" spine nodes in the tree with pseudo-root ""root_compress^"" + Scanner, Child : P_Dir_Node; + begin + Scanner := Root_Compress; + for Counter in reverse 1 .. Count loop + Child := Scanner.Right; + Scanner.Right := Child.Right; + Scanner := Scanner.Right; + Child.Right := Scanner.Left; + Scanner.Left := Child; + end loop; + end Compression; + + -- Returns n - 2 ** Integer( Float'Floor( log( Float(n) ) / log(2.0) ) ) + -- without Float-Point calculation and rounding errors with too short floats + function Remove_Leading_Binary_1 (N : Integer) return Integer is + X : Integer := 2**16; -- supposed maximum + begin + if N < 1 then + return N; + end if; + while N mod X = N loop + X := X / 2; + end loop; + return N mod X; + end Remove_Leading_Binary_1; + + begin -- Vine_to_tree + Leaf_Count := Remove_Leading_Binary_1 (Size + 1); + Compression (Root, Leaf_Count); -- create deepest leaves + -- Use Perfect_leaves instead for a perfectly balanced tree + Size := Size - Leaf_Count; + while Size > 1 loop + Compression (Root, Size / 2); + Size := Size / 2; + end loop; + end Vine_To_Tree; + + procedure Rebalance (Root : in out P_Dir_Node) is + -- Rebalance the binary search tree with root ""root.all"", + -- with the result also rooted at ""root.all"". + -- Uses the Tree_to_vine and Vine_to_tree procedures + Pseudo_Root : P_Dir_Node; + Size : Integer; + begin + Pseudo_Root := new Dir_Node (Name_Len => 0); + Pseudo_Root.Right := Root; + Tree_To_Vine (Pseudo_Root, Size); + Vine_To_Tree (Pseudo_Root, Size); + Root := Pseudo_Root.Right; + Dispose (Pseudo_Root); + end Rebalance; + + end Binary_Tree_Rebalancing; + + -- 19-Jun-2001: Enhanced file name identification + -- a) when case insensitive -> all UPPER (current) + -- b) '\' and '/' identified -> all '/' (new) + + function Normalize (S : String; Case_Sensitive : Boolean) return String is + Sn : String := (if Case_Sensitive then S else Ada.Characters.Handling.To_Upper (S)); + begin + for I in Sn'Range loop + if Sn (I) = '\' then + Sn (I) := '/'; + end if; + end loop; + return Sn; + end Normalize; + + function Get_Node (Info : in Zip_Info; Name : in String) return P_Dir_Node is + Aux : P_Dir_Node := Info.Dir_Binary_Tree; + Up_Name : constant String := Normalize (Name, Info.Case_Sensitive); + begin + while Aux /= null loop + if Up_Name > Aux.Dico_Name then + Aux := Aux.Right; + elsif Up_Name < Aux.Dico_Name then + Aux := Aux.Left; + else -- entry found ! + return Aux; + end if; + end loop; + return null; + end Get_Node; + + Boolean_To_Encoding : constant array (Boolean) of Zip_Name_Encoding := + (False => IBM_437, True => UTF_8); + + ------------------------------------------------------------- + -- Load Zip_info from a stream containing the .zip archive -- + ------------------------------------------------------------- + + procedure Load + (Info : out Zip_Info; + From : in out DCF.Streams.Root_Zipstream_Type'Class; + Case_Sensitive : in Boolean := False) + is + procedure Insert + (Dico_Name : String; -- UPPER if case-insensitive search + File_Name : String; + File_Index : DCF.Streams.Zs_Index_Type; + Comp_Size, Uncomp_Size : File_Size_Type; + Crc_32 : Unsigned_32; + Date_Time : Time; + Method : Pkzip_Method; + Name_Encoding : Zip_Name_Encoding; + Read_Only : Boolean; + Encrypted_2_X : Boolean; + Root_Node : in out P_Dir_Node) + is + procedure Insert_Into_Tree (Node : in out P_Dir_Node) is + begin + if Node = null then + Node := + new Dir_Node' + ((Name_Len => File_Name'Length, + Left => null, + Right => null, + Dico_Name => Dico_Name, + File_Name => File_Name, + File_Index => File_Index, + Comp_Size => Comp_Size, + Uncomp_Size => Uncomp_Size, + Crc_32 => Crc_32, + Date_Time => Date_Time, + Method => Method, + Name_Encoding => Name_Encoding, + Read_Only => Read_Only, + Encrypted_2_X => Encrypted_2_X)); + elsif Dico_Name > Node.Dico_Name then + Insert_Into_Tree (Node.Right); + elsif Dico_Name < Node.Dico_Name then + Insert_Into_Tree (Node.Left); + else + -- Here we have a case where the entry name already exists + -- in the dictionary + raise Duplicate_Name with + ""Entry name '"" & Dico_Name & ""' appears twice in archive""; + end if; + end Insert_Into_Tree; + begin + Insert_Into_Tree (Root_Node); + end Insert; + + The_End : Zip.Headers.End_Of_Central_Dir; + Header : Zip.Headers.Central_File_Header; + P : P_Dir_Node := null; + Main_Comment : P_String; + begin + if Info.Loaded then + raise Program_Error; + end if; + + Zip.Headers.Load (From, The_End); + + -- We take the opportunity to read the main comment, which is right + -- after the end-of-central-directory block + Main_Comment := new String (1 .. Integer (The_End.Main_Comment_Length)); + String'Read (From'Access, Main_Comment.all); + + -- Process central directory + From.Set_Index + (DCF.Streams.Zs_Index_Type (1 + The_End.Central_Dir_Offset) + The_End.Offset_Shifting); + + for I in 1 .. The_End.Total_Entries loop + Zip.Headers.Read_And_Check (From, Header); + declare + This_Name : String (1 .. Natural (Header.Short_Info.Filename_Length)); + begin + String'Read (From'Access, This_Name); + -- Skip extra field and entry comment + From.Set_Index + (From.Index + + DCF.Streams.Zs_Size_Type + (Header.Short_Info.Extra_Field_Length + Header.Comment_Length)); + -- Now the whole i_th central directory entry is behind + Insert + (Dico_Name => Normalize (This_Name, Case_Sensitive), + File_Name => Normalize (This_Name, True), + File_Index => + DCF.Streams.Zs_Index_Type (1 + Header.Local_Header_Offset) + + The_End.Offset_Shifting, + Comp_Size => Header.Short_Info.Dd.Compressed_Size, + Uncomp_Size => Header.Short_Info.Dd.Uncompressed_Size, + Crc_32 => Header.Short_Info.Dd.Crc_32, + Date_Time => Header.Short_Info.File_Timedate, + Method => Method_From_Code (Header.Short_Info.Zip_Type), + Name_Encoding => + Boolean_To_Encoding + ((Header.Short_Info.Bit_Flag and Zip.Headers.Language_Encoding_Flag_Bit) /= 0), + Read_Only => + Header.Made_By_Version / 256 = 0 and -- DOS-like + (Header.External_Attributes and 1) = 1, + Encrypted_2_X => + (Header.Short_Info.Bit_Flag and Zip.Headers.Encryption_Flag_Bit) /= 0, + Root_Node => P); + -- Since the files are usually well ordered, the tree as inserted + -- is very unbalanced; we need to rebalance it from time to time + -- during loading, otherwise the insertion slows down dramatically + -- for zip files with plenty of files - converges to + -- O(total_entries ** 2)... + if I mod 256 = 0 then + Binary_Tree_Rebalancing.Rebalance (P); + end if;" +procedure Init_Buffers;,"function Read_Byte_Decrypted return Unsigned_8; -- NB: reading goes on a while even if + pragma Inline (Read_Byte_Decrypted); -- Zip_EOF is set: just gives garbage + + package Bit_Buffer is + procedure Init; + -- Read at least n bits into the bit buffer, returns the n first bits + function Read (N : Natural) return Integer; + pragma Inline (Read); + function Read_U32 (N : Natural) return Unsigned_32; + pragma Inline (Read_U32); + -- Dump n bits no longer needed from the bit buffer + procedure Dump (N : Natural); + pragma Inline (Dump); + procedure Dump_To_Byte_Boundary; + function Read_And_Dump (N : Natural) return Integer; + pragma Inline (Read_And_Dump); + function Read_And_Dump_U32 (N : Natural) return Unsigned_32; + pragma Inline (Read_And_Dump_U32); + end Bit_Buffer; + + procedure Flush (X : Natural); -- directly from slide to output stream + + procedure Flush_If_Full (W : in out Integer); + pragma Inline (Flush_If_Full); + + procedure Copy (Distance, Length : Natural; Index : in out Natural); + pragma Inline (Copy); + end Unz_Io; + + package Unz_Meth is + procedure Copy_Stored (Size : Ada.Streams.Stream_Element_Offset); + procedure Inflate; + end Unz_Meth; + + ------------------------------ + -- Bodies of UnZ_* packages -- + ------------------------------ + package body Unz_Io is + + procedure Init_Buffers is + begin + Unz_Glob.Inpos := 0; -- Input buffer position + Unz_Glob.Readpos := -1; -- Nothing read + Unz_Glob.Slide_Index := 0; + Unz_Glob.Reachedsize := 0; + Zip_Eof := False; + Zip.CRC.Init (CRC_Value); + Bit_Buffer.Init; + end Init_Buffers; + + procedure Process_Compressed_End_Reached is + begin + if Zip_Eof then -- We came already here once + raise Zip.Archive_Corrupted with + ""Decoding went past compressed data size plus one buffer length""; + -- Avoid infinite loop on data with exactly buffer's length and no end marker + else + Unz_Glob.Readpos := Unz_Glob.Inbuf'Length; + -- Simulates reading -> no blocking. + -- The buffer is full of ""random"" data and we hope for a wrong code or a CRC error + Zip_Eof := True; + end if; + end Process_Compressed_End_Reached; + + procedure Read_Buffer is + begin + if Unz_Glob.Reachedsize > Compressed_Size + 2 then + -- +2: last code is smaller than requested! + Process_Compressed_End_Reached; + else + begin + Zip.Blockread + (Stream => Zip_File, + Buffer => Unz_Glob.Inbuf, + Actually_Read => Unz_Glob.Readpos); + exception + when others => -- I/O error + Process_Compressed_End_Reached;" +procedure Init is,"begin + B := 0; + K := 0; + end Init; + + procedure Need (N : Natural) is + pragma Inline (Need); + begin + while K < N loop + B := B or Shift_Left (Unsigned_32 (Read_Byte_Decrypted), K); + K := K + 8; + end loop; + end Need; + + procedure Dump (N : Natural) is + begin + B := Shift_Right (B, N); + K := K - N; + end Dump; + + procedure Dump_To_Byte_Boundary is + begin + Dump (K mod 8); + end Dump_To_Byte_Boundary; + + function Read_U32 (N : Natural) return Unsigned_32 is + begin + Need (N); + return B and (Shift_Left (1, N) - 1); + end Read_U32; + + function Read (N : Natural) return Integer is + begin + return Integer (Read_U32 (N)); + end Read; + + function Read_And_Dump (N : Natural) return Integer is + Res : Integer; + begin + Res := Read (N); + Dump (N); + return Res; + end Read_And_Dump; + + function Read_And_Dump_U32 (N : Natural) return Unsigned_32 is + Res : Unsigned_32; + begin + Res := Read_U32 (N); + Dump (N); + return Res; + end Read_And_Dump_U32; + + end Bit_Buffer; + + procedure Flush (X : Natural) is + use Zip; + use Ada.Streams; + begin + begin + Blockwrite (Output_Stream_Access.all, Unz_Glob.Slide (0 .. X - 1)); + exception + when others => + raise Unzip.Write_Error;" +"procedure Inflate_Stored_Block is -- Actually, nothing to inflate","N : Integer; + begin + Unz_Io.Bit_Buffer.Dump_To_Byte_Boundary; + -- Get the block length and its complement + N := Unz_Io.Bit_Buffer.Read_And_Dump (16); + if N /= Integer ((not Unz_Io.Bit_Buffer.Read_And_Dump_U32 (16)) and 16#ffff#) then + raise Zip.Archive_Corrupted; + end if; + while N > 0 and then not Zip_Eof loop + -- Read and output the non-compressed data + N := N - 1; + Unz_Glob.Slide (Unz_Glob.Slide_Index) := + Zip.Byte (Unz_Io.Bit_Buffer.Read_And_Dump (8)); + Unz_Glob.Slide_Index := Unz_Glob.Slide_Index + 1; + Unz_Io.Flush_If_Full (Unz_Glob.Slide_Index); + end loop; + end Inflate_Stored_Block; + + -- Copy lengths for literal codes 257..285 + + Copy_Lengths_Literal : constant Length_Array (0 .. 30) := + (3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 13, + 15, + 17, + 19, + 23, + 27, + 31, + 35, + 43, + 51, + 59, + 67, + 83, + 99, + 115, + 131, + 163, + 195, + 227, + 258, + 0, + 0); + + -- Extra bits for literal codes 257..285 + + Extra_Bits_Literal : constant Length_Array (0 .. 30) := + (0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 5, + 0, + Invalid, + Invalid); + + -- Copy offsets for distance codes 0..29 (30..31: deflate_e) + + Copy_Offset_Distance : constant Length_Array (0 .. 31) := + (1, + 2, + 3, + 4, + 5, + 7, + 9, + 13, + 17, + 25, + 33, + 49, + 65, + 97, + 129, + 193, + 257, + 385, + 513, + 769, + 1025, + 1537, + 2049, + 3073, + 4097, + 6145, + 8193, + 12289, + 16385, + 24577, + 32769, + 49153); + + -- Extra bits for distance codes + + Extra_Bits_Distance : constant Length_Array (0 .. 31) := + (0, + 0, + 0, + 0, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 7, + 8, + 8, + 9, + 9, + 10, + 10, + 11, + 11, + 12, + 12, + 13, + 13, + 14, + 14); + + Max_Dist : constant Integer := 29; -- changed to 31 for deflate_e + + Length_List_For_Fixed_Block_Literals : constant Length_Array (0 .. 287) := + (0 .. 143 => 8, 144 .. 255 => 9, 256 .. 279 => 7, 280 .. 287 => 8); + + procedure Inflate_Fixed_Block is + Tl, -- literal/length code table + Td : P_Table_List; -- distance code table + Bl, Bd : Integer; -- lookup bits for tl/bd + Huft_Incomplete : Boolean; + begin + -- Make a complete, but wrong [why ?] code set (see Appnote: 5.5.2, RFC 1951: 3.2.6) + Bl := 7; + Huft_Build + (Length_List_For_Fixed_Block_Literals, + 257, + Copy_Lengths_Literal, + Extra_Bits_Literal, + Tl, + Bl, + Huft_Incomplete); + -- Make an incomplete code set (see Appnote: 5.5.2, RFC 1951: 3.2.6) + Bd := 5; + begin + Huft_Build + ((0 .. Max_Dist => 5), + 0, + Copy_Offset_Distance, + Extra_Bits_Distance, + Td, + Bd, + Huft_Incomplete); + exception + when Huft_Out_Of_Memory | Huft_Error => + Huft_Free (Tl); + raise Zip.Archive_Corrupted;" +procedure Inflate_Dynamic_Block is,"Lbits : constant := 9; + Dbits : constant := 6; + + Current_Length : Natural; + Defined, Number_Of_Lengths : Natural; + + Tl : P_Table_List; -- literal/length code tables + Td : P_Table_List; -- distance code tables + + Ct : P_Huft_Table; -- current table + Ct_Idx : Natural; -- current table's index + + Bl, Bd : Integer; -- lookup bits for tl/bd + Nb : Natural; -- number of bit length codes + Nl : Natural; -- number of literal length codes + Nd : Natural; -- number of distance codes + + -- literal/length and distance code lengths + Ll : Length_Array (0 .. 288 + 32 - 1) := (others => 0); + + Huft_Incomplete : Boolean; + + procedure Repeat_Length_Code (Amount : Natural) is + begin + if Defined + Amount > Number_Of_Lengths then + raise Zip.Archive_Corrupted; + end if; + for C in reverse 1 .. Amount loop + Ll (Defined) := Current_Length; + Defined := Defined + 1; + end loop; + end Repeat_Length_Code; + + begin + -- Read in table lengths + Nl := 257 + Unz_Io.Bit_Buffer.Read_And_Dump (5); + Nd := 1 + Unz_Io.Bit_Buffer.Read_And_Dump (5); + Nb := 4 + Unz_Io.Bit_Buffer.Read_And_Dump (4); + + if Nl > 288 or else Nd > 32 then + raise Zip.Archive_Corrupted; + end if; + + -- Read in bit-length-code lengths for decoding the compression structure. + -- The rest, Ll( Bit_Order( Nb .. 18 ) ), is already = 0 + for J in 0 .. Nb - 1 loop + Ll (Bit_Order_For_Dynamic_Block (J)) := Unz_Io.Bit_Buffer.Read_And_Dump (3); + end loop; + + -- Build decoding table for trees--single level, 7 bit lookup + Bl := 7; + begin + Huft_Build (Ll (0 .. 18), 19, Empty, Empty, Tl, Bl, Huft_Incomplete); + if Huft_Incomplete then + Huft_Free (Tl); + raise Zip.Archive_Corrupted with + ""Incomplete code set for compression structure""; + end if; + exception + when Zip.Archive_Corrupted => + raise; + when others => + raise Zip.Archive_Corrupted with + ""Error when building tables for compression structure"";" +procedure Inflate is,"Is_Last_Block : Boolean; + Blocks, Blocks_Fix, Blocks_Dyn : Long_Integer := 0; + begin + loop + Blocks := Blocks + 1; + Inflate_Block (Is_Last_Block, Blocks_Fix, Blocks_Dyn); + exit when Is_Last_Block; + end loop; + Unz_Io.Flush (Unz_Glob.Slide_Index); + Unz_Glob.Slide_Index := 0; + end Inflate; + end Unz_Meth; + + procedure Process_Descriptor_Store (Descriptor : out Zip.Headers.Data_Descriptor) is + Buffer : Ada.Streams.Stream_Element_Array (1 .. 16); + begin + Zip.Blockread (Zip_File, Buffer); + Zip.Headers.Copy_And_Check (Buffer, Descriptor); + end Process_Descriptor_Store; + + procedure Process_Descriptor_Deflate (Descriptor : out Zip.Headers.Data_Descriptor) is + Buffer : Ada.Streams.Stream_Element_Array (1 .. 16); + begin + Unz_Io.Bit_Buffer.Dump_To_Byte_Boundary; + for I in Buffer'Range loop + Buffer (I) := Ada.Streams.Stream_Element (Unz_Io.Read_Byte_Decrypted); + end loop; + Zip.Headers.Copy_And_Check (Buffer, Descriptor); + end Process_Descriptor_Deflate; + + use Zip; + begin + Unz_Io.Init_Buffers; + + -- Unzip correct type + case Format is + when Store => + Unz_Meth.Copy_Stored (Ada.Streams.Stream_Element_Offset (Compressed_Size)); + when Deflate => + Unz_Meth.Inflate; + end case; + + if Verify_Integrity then + CRC_Value := Zip.CRC.Final (CRC_Value); + end if; + + if Data_Descriptor_After_Data then -- Sizes and CRC at the end + declare + Memo_Uncomp_Size : constant Unsigned_32 := Hint.Dd.Uncompressed_Size; + begin + case Format is + when Store => + Process_Descriptor_Store (Hint.Dd); + when Deflate => + Process_Descriptor_Deflate (Hint.Dd); + end case; + + -- CRC is for checking; sizes are for informing user + if Memo_Uncomp_Size < Unsigned_32'Last + and then Memo_Uncomp_Size /= Hint.Dd.Uncompressed_Size + then + raise Uncompressed_Size_Error; + end if; + exception + when Zip.Headers.Bad_Data_Descriptor => + raise Zip.Archive_Corrupted;" +procedure UnzipDCF is,"package Dirs renames Ada.Directories; + package SU renames Ada.Strings.Unbounded; + + List_Files : Boolean := False; + Test_Data : Boolean := False; + Comment : Boolean := False; + + Quiet : Boolean := False; + + No_Directories : Boolean := False; + Lower_Case : Boolean := False; + + Last_Option : Natural := 0; + + Extraction_Directory : SU.Unbounded_String + := SU.To_Unbounded_String (Dirs.Current_Directory); + + Name_Conflict_Decision : DCF.Unzip.Name_Conflict_Intervention := DCF.Unzip.Yes; + + procedure Help is + begin + Put_Line (""UnZipDCF "" & DCF.Zip.Version & "" - unzip document container files""); + New_Line; + Put_Line (""Usage: unzipdcf [-options[modifiers]] [-d exdir] file [list]""); + New_Line; + Put_Line ("" -l list files""); + Put_Line ("" -t test integrity of files, no write""); + Put_Line ("" -z display archive comment only""); + Put_Line ("" -d extract to """"exdir""""""); + Put_Line (""modifiers:""); + Put_Line ("" -n never overwrite existing files -q quiet mode""); + Put_Line ("" -o always overwrite existing files""); + Put_Line ("" -j junk archived directory structure -L make names lower case""); + end Help; + + procedure Resolve_Conflict + (Name : in String; + Action : out DCF.Unzip.Name_Conflict_Intervention; + New_Name : out String; + New_Name_Length : out Natural) + is + C : Character; + + use all type DCF.Unzip.Name_Conflict_Intervention; + begin + loop + Put (""replace "" & Name & ""? [y]es, [n]o, [A]ll, [N]one, [r]ename: ""); + declare + Input : constant String := Get_Line; + begin + C := Input (Input'First); + exit when C = 'y' or C = 'n' or C = 'A' or C = 'N' or C = 'r'; + Put_Line (""error: invalid response ["" & Input & ""]"");" +procedure List_File_From_Stream (File : DCF.Zip.Archived_File) is,"Date_Time : constant Ada.Calendar.Time + := DCF.Streams.Calendar.Convert (File.Date_Time); + Date : constant String := Ada.Calendar.Formatting.Image + (Date_Time, Time_Zone => Ada.Calendar.Time_Zones.UTC_Time_Offset (Date_Time)); + begin + Total_Uncompressed_Size := Total_Uncompressed_Size + File.Uncompressed_Size; + Total_Compressed_Size := Total_Compressed_Size + File.Compressed_Size; + + -- Print date and time without seconds + Mod_IO.Put (File.Uncompressed_Size, 10); + Int_IO.Put (Percentage (File.Compressed_Size, File.Uncompressed_Size), 4); + Put_Line (""% "" & Date (Date'First .. Date'Last - 3) & "" "" & File.Name); + end List_File_From_Stream; + + procedure List_All_Files is new DCF.Zip.Traverse (List_File_From_Stream); + begin + Put_Line ("" Length Cmpr Date Time Name""); + Put_Line (""---------- ---- ---------- ----- ----""); + + List_All_Files (Info); + + Put_Line (""---------- ---- -------""); + Mod_IO.Put (Total_Uncompressed_Size, 10); + Int_IO.Put (Percentage (Total_Compressed_Size, Total_Uncompressed_Size), 4); + Put (""% "" & Info.Entries'Image); + Put_Line (if Info.Entries > 1 then "" files"" else "" file"");" +procedure Extract_All_Files is new DCF.Zip.Traverse (Extract_From_Stream);,"procedure Extract_One_File is new DCF.Zip.Traverse_One_File (Extract_From_Stream); + begin + if not Test_Data and then not Dirs.Exists (Extraction_Folder) then + Dirs.Create_Path (Extraction_Folder); + end if; + + if Extract_All then + Extract_All_Files (Info); + else + for I in Last_Option + 2 .. Argument_Count loop + Extract_One_File (Info, Argument (I)); + end loop; + end if;" +procedure ZipDCF is,"package Dirs renames Ada.Directories; + package SU renames Ada.Strings.Unbounded; + + Quiet : Boolean := False; + + Add_Directories : Boolean := True; + Recursive : Boolean := False; + Junk_Directories : Boolean := False; + + Comment : SU.Unbounded_String; + Compression_Method : DCF.Zip.Compress.Compression_Method := DCF.Zip.Compress.Deflate_2; + + Last_Option : Natural := 0; + + procedure Help is + begin + Put_Line (""ZipDCF "" & DCF.Zip.Version & "" - create document container files""); + New_Line; + Put_Line (""Usage: zipdcf [-options] [-z comment] file list""); + New_Line; + Put_Line ("" -D no directory entries -q quiet mode""); + Put_Line ("" -r recurse into directories -j junk directory structure""); + Put_Line ("" -0 store files uncompressed""); + Put_Line ("" -1 use faster compression -z add archive file comment""); + Put_Line ("" -9 use better compression""); + end Help; + + function Maybe_Trash_Dir (Name : String) return String is + Index : constant Natural := Ada.Strings.Fixed.Index (Name, ""/"", Ada.Strings.Backward); + begin + return (if Junk_Directories then Name (Index + 1 .. Name'Last) else Name); + end Maybe_Trash_Dir; +begin + if Argument_Count = 0 then + Help; + return; + end if; + + for I in 1 .. Argument_Count loop + if Argument (I) (1) = '-' then + if Last_Option = I then + null; -- Argument for a previous option + else + Last_Option := I; + + if Argument (I)'Length = 1 then + Help; + return; + end if; + + for J in 2 .. Argument (I)'Last loop + case Argument (I) (J) is + when 'D' => + Add_Directories := False; + when 'r' => + Recursive := True; + when '0' => + Compression_Method := DCF.Zip.Compress.Store; + when '1' => + Compression_Method := DCF.Zip.Compress.Deflate_1; + when '9' => + Compression_Method := DCF.Zip.Compress.Deflate_3; + when 'q' => + Quiet := True; + when 'j' => + Junk_Directories := True; + when 'z' => + if I = Argument_Count then + Help; + return; + end if; + + Comment := SU.To_Unbounded_String (Argument (I + 1)); + Last_Option := I + 1; + when others => + Help; + return; + end case; + end loop; + end if; + end if; + end loop; + + if Argument_Count = Last_Option then + Help; + return; + end if; + + declare + Archive : constant String := Argument (Last_Option + 1); + begin + if Dirs.Exists (Archive) then + Put_Line (""Archive file '"" & Archive & ""' already exists""); + return; + end if; + + if not Quiet then + Put_Line (""Archive: "" & Archive); + end if; + + declare + Archive_Stream : aliased DCF.Streams.File_Zipstream + := DCF.Streams.Create (Archive); + Info : DCF.Zip.Create.Zip_Create_Info; + + procedure Add_File (Path : String) is + Name : constant String := Maybe_Trash_Dir (Path); + begin + if not Dirs.Exists (Path) then + Put_Line (""warning: "" & Name & "" does not exist""); + return; + end if; + + declare + use all type Dirs.File_Kind; + + File_Is_Directory : constant Boolean := Dirs.Kind (Path) = Directory; + begin + if not File_Is_Directory then + if not Quiet then + Put_Line ("" adding: "" & Name); + end if; + + declare + File_Stream : aliased DCF.Streams.File_Zipstream + := DCF.Streams.Open (Path); + begin + DCF.Streams.Set_Name (File_Stream, Name); + DCF.Streams.Set_Time (File_Stream, + DCF.Streams.Calendar.Convert (Dirs.Modification_Time (Path))); + DCF.Zip.Create.Add_Stream (Info, File_Stream);" +function Convert is new Ada.Unchecked_Conversion,"(System.Address, + Float_Star); + + function Convert is new Ada.Unchecked_Conversion + (System.Address, + paTestData_Ptr); + + -------------------- + -- paTestCallback -- + -------------------- + + function paTestCallback + (inputBuffer : System.Address; + outputBuffer : System.Address; + framesPerBuffer : Interfaces.C.unsigned_long; + timeInfo : access PA_Stream_Callback_Time_Info; + statusFlags : PA_Stream_Callback_Flags; + userData : System.Address) + return PA_Stream_Callback_Result + is + pragma Unreferenced (inputBuffer); + pragma Unreferenced (timeInfo); + pragma Unreferenced (statusFlags); + + oBuff : Float_Star := Convert (outputBuffer); + lData : constant paTestData_Ptr := Convert (userData); + begin + for i in 1 .. Integer (framesPerBuffer) loop + declare + output : Float := 0.0; + phaseInc : Long_Float := 0.02; + phase : Long_Float; + begin + for j in 1 .. lData.all.numSines loop + + -- Advance phase of next oscillator. + + phase := lData.all.phases (j); + phase := phase + phaseInc; + + if phase > Two_Pi then + phase := phase - Two_Pi; + end if; + + phaseInc := phaseInc * 1.02; + + if phaseInc > 0.5 then + phaseInc := phaseInc * 0.5; + end if; + + -- This is not a very efficient way to calc sines. + + output := output + Sin (Float (phase)); + lData.all.phases (j) := phase; + + end loop; + + oBuff.all := output / Float (lData.all.numSines); + Float_Ptrs.Increment (oBuff);" +procedure exercise8 is,"Count_Failed : exception; -- Exception to be raised when counting fails + Gen : Generator; -- Random number generator + + protected type Transaction_Manager (N : Positive) is + entry Finished; + entry Wait_Until_Aborted; + procedure Signal_Abort; + private + Finished_Gate_Open : Boolean := False; + Aborted : Boolean := False; + end Transaction_Manager; + protected body Transaction_Manager is + -- PART 1 -- + entry Finished when Finished_Gate_Open or Finished'Count = N is + begin + if Finished'Count = N - 1 then + Finished_Gate_Open := True; + end if; + + if Finished'Count = 0 then + Finished_Gate_Open := False; + end if; + end Finished; + + -- PART 2 -- + entry Wait_Until_Aborted when Aborted is + begin + if Wait_Until_Aborted'Count = 0 then + Aborted := False; + end if; + end Wait_Until_Aborted; + + + procedure Signal_Abort is + begin + Aborted := True; + end Signal_Abort; + + end Transaction_Manager; + + + + + function Unreliable_Slow_Add (x : Integer) return Integer is + Error_Rate : Constant := 0.125; -- (between 0 and 1) + Random_Num : Float := 0.0; + begin + Random_Num := Random(Gen); + delay Duration(Random_Num * 4.0); + if Random_Num > Error_Rate then + return x + 10; + else + raise Count_Failed; + end if; + end Unreliable_Slow_Add; + + + + + task type Transaction_Worker (Initial : Integer; Manager : access Transaction_Manager); + task body Transaction_Worker is + Num : Integer := Initial; + Prev : Integer := Num; + Round_Num : Integer := 0; + begin + Put_Line (""Worker"" & Integer'Image(Initial) & "" started""); + + loop + Put_Line (""Worker"" & Integer'Image(Initial) & "" started round"" & Integer'Image(Round_Num)); + Round_Num := Round_Num + 1; + -- PART 1 -- + select + Manager.Wait_Until_Aborted; + Num := Prev + 5; + Put_Line( ""Forward error recovery: Worker"" + & Integer'Image( Initial ) & "" commiting"" & Integer'Image( Num ) ); + then abort + begin + Num := Unreliable_Slow_Add( Num ); + Manager.Finished; + Put_Line ("" Worker"" & Integer'Image(Initial) & "" comitting"" & Integer'Image(Num)); + exception + when Count_Failed => + begin + Put_Line( "" Worker"" & Integer'Image( Initial ) & "" aborting"" ); + Manager.Signal_Abort; + Manager.Finished;" +procedure exercise7 is,"Count_Failed : exception; -- Exception to be raised when counting fails + Gen : Generator; -- Random number generator + + protected type Transaction_Manager (N : Positive) is + entry Finished; + function Commit return Boolean; + procedure Signal_Abort; + private + Finished_Gate_Open : Boolean := False; + Aborted : Boolean := False; + Should_Commit : Boolean := True; + end Transaction_Manager; + protected body Transaction_Manager is + entry Finished when Finished_Gate_Open or Finished'Count = N is + begin + ------------------------------------------ + -- PART 3: Complete the exit protocol here + ------------------------------------------ + if Finished'Count = N - 1 then + Finished_Gate_Open := True; + Should_Commit := True; + end if; + if Aborted then + Should_Commit := False; + end if; + if Finished'Count = 0 then + Finished_Gate_Open := False; + Aborted := False; + end if; + end Finished; + + procedure Signal_Abort is + begin + Aborted := True; + end Signal_Abort; + + function Commit return Boolean is + begin + return Should_Commit; + end Commit; + + end Transaction_Manager; + + + + + function Unreliable_Slow_Add (x : Integer) return Integer is + Error_Rate : Constant := 0.15; -- (between 0 and 1) + begin + ------------------------------------------- + -- PART 1: Create the transaction work here + ------------------------------------------- + Random_Num := Random(Gen); + delay Duration(Random_Num * 4.0); + if Random_Num > Error_Rate then + return x + 10; + else + raise Count_Failed; + end if; + end Unreliable_Slow_Add; + + + + + task type Transaction_Worker (Initial : Integer; Manager : access Transaction_Manager); + task body Transaction_Worker is + Num : Integer := Initial; + Prev : Integer := Num; + Round_Num : Integer := 0; + begin + Put_Line (""Worker"" & Integer'Image(Initial) & "" started""); + + loop + Put_Line (""Worker"" & Integer'Image(Initial) & "" started round"" & Integer'Image(Round_Num)); + Round_Num := Round_Num + 1; + + --------------------------------------- + -- PART 2: Do the transaction work here + --------------------------------------- + begin + Num := Unreliable_Slow_Add( Num ); + Manager.Finished; + exception + when Count_Failed => + begin + Put_Line( "" Worker"" & Integer'Image( Initial ) & "" aborting"" ); + Manager.Signal_Abort; + Manager.Finished;" +procedure Convert_Card_Identification_Data_Register,"(W0, W1, W2, W3 : UInt32; + Res : out Card_Identification_Data_Register); + -- Convert the R2 reply to CID + + procedure Convert_Card_Specific_Data_Register + (W0, W1, W2, W3 : UInt32; + Card_Type : Supported_SD_Memory_Cards; + CSD : out Card_Specific_Data_Register); + -- Convert the R2 reply to CSD + + procedure Convert_SDCard_Configuration_Register + (W0, W1 : UInt32; + SCR : out SDCard_Configuration_Register); + -- Convert W0 (MSB) / W1 (LSB) to SCR. + + function Compute_Card_Capacity + (CSD : Card_Specific_Data_Register; + Card_Type : Supported_SD_Memory_Cards) return UInt64; + -- Compute the card capacity (in bytes) from the CSD + + function Compute_Card_Block_Size + (CSD : Card_Specific_Data_Register; + Card_Type : Supported_SD_Memory_Cards) return UInt32; + -- Compute the card block size (in bytes) from the CSD. + + function Get_Transfer_Rate + (CSD : Card_Specific_Data_Register) return Natural; + -- Compute transfer rate from CSD + + function Swap32 (Val : UInt32) return UInt32 with Inline_Always; + + function BE32_To_Host (Val : UInt32) return UInt32 with Inline_Always; + + -- Swap bytes in a word + ------------ + -- Swap32 -- + ------------ + + function Swap32 (Val : UInt32) return UInt32 is + begin + return Shift_Left (Val and 16#00_00_00_ff#, 24) + or Shift_Left (Val and 16#00_00_ff_00#, 8) + or Shift_Right (Val and 16#00_ff_00_00#, 8) + or Shift_Right (Val and 16#ff_00_00_00#, 24); + end Swap32; + + ------------------ + -- BE32_To_Host -- + ------------------ + + function BE32_To_Host (Val : UInt32) return UInt32 is + use System; + begin + if Default_Bit_Order = Low_Order_First then + return Swap32 (Val); + else + return Val; + end if; + end BE32_To_Host; + + --------------------------------- + -- Card_Identification_Process -- + --------------------------------- + + procedure Card_Identification_Process + (This : in out SDMMC_Driver'Class; + Info : out Card_Information; + Status : out SD_Error) + is + Rsp : UInt32; + W0, W1, W2, W3 : UInt32; + Rca : UInt32; + + begin + -- Reset controller + This.Reset (Status); + + if Status /= OK then + return; + end if; + + -- CMD0: Sets the SDCard state to Idle + Send_Cmd (This, Go_Idle_State, 0, Status); + + if Status /= OK then + return; + end if; + + -- CMD8: IF_Cond, voltage supplied: 0x1 (2.7V - 3.6V) + -- It is mandatory for the host compliant to Physical Spec v2.00 + -- to send CMD8 before ACMD41 + Send_Cmd (This, Send_If_Cond, 16#1a5#, Status); + + if Status = OK then + -- at least SD Card 2.0 + Info.Card_Type := STD_Capacity_SD_Card_v2_0; + + Read_Rsp48 (This, Rsp); + + if (Rsp and 16#fff#) /= 16#1a5# then + -- Bad voltage or bad pattern. + Status := Error; + return; + end if; + else + -- If SD Card, then it's v1.1 + Info.Card_Type := STD_Capacity_SD_Card_V1_1; + end if; + + for I in 1 .. 5 loop + This.Delay_Milliseconds (200); + + -- CMD55: APP_CMD + -- This is done manually to handle error (this command is not + -- supported by mmc). + Send_Cmd (This, Cmd_Desc (App_Cmd), 0, Status); + + if Status /= OK then + if Status = Command_Timeout_Error + and then I = 1 + and then Info.Card_Type = STD_Capacity_SD_Card_V1_1 + then + -- Not an SDCard. Suppose MMC. + Info.Card_Type := Multimedia_Card; + exit; + end if; + return; + end if; + + -- ACMD41: SD_SEND_OP_COND (no crc check) + -- Arg: HCS=1, XPC=0, S18R=0 + Send_Cmd + (This, Acmd_Desc (SD_App_Send_Op_Cond), 16#40ff_0000#, Status); + if Status /= OK then + return; + end if; + + Read_Rsp48 (This, Rsp); + + if (Rsp and SD_OCR_High_Capacity) = SD_OCR_High_Capacity then + Info.Card_Type := High_Capacity_SD_Card; + end if; + + if (Rsp and SD_OCR_Power_Up) = 0 then + Status := Error; + + else + Status := OK; + exit; + end if; + end loop; + + if Status = Command_Timeout_Error + and then Info.Card_Type = Multimedia_Card + then + for I in 1 .. 5 loop + This.Delay_Milliseconds (200); + + -- CMD1: SEND_OP_COND query voltage + Send_Cmd (This, Cmd_Desc (Send_Op_Cond), 16#00ff_8000#, Status); + if Status /= OK then + return; + end if; + + Read_Rsp48 (This, Rsp); + + if (Rsp and SD_OCR_Power_Up) = 0 then + Status := Error; + else + if (Rsp and 16#00ff_8000#) /= 16#00ff_8000# then + Status := Error; + return; + end if; + Status := OK; + exit; + end if; + end loop; + end if; + + if Status /= OK then + return; + end if; + + -- TODO: Switch voltage + + -- CMD2: ALL_SEND_CID (136 bits) + Send_Cmd (This, All_Send_CID, 0, Status); + if Status /= OK then + return; + end if; + + Read_Rsp136 (This, W0, W1, W2, W3); + Convert_Card_Identification_Data_Register (W0, W1, W2, W3, Info.SD_CID); + + -- CMD3: SEND_RELATIVE_ADDR + case Info.Card_Type is + when Multimedia_Card => + Rca := 16#01_0000#; + when others => + Rca := 0; + end case; + + Send_Cmd (This, Send_Relative_Addr, Rca, Status); + if Status /= OK then + return; + end if; + case Info.Card_Type is + when Multimedia_Card => + null; + when others => + Read_Rsp48 (This, Rsp); + Rca := Rsp and 16#ffff_0000#; + if (Rsp and 16#e100#) /= 16#0100# then + return; + end if; + end case; + Info.RCA := UInt16 (Shift_Right (Rca, 16)); + + -- Switch to 25Mhz + case Info.Card_Type is + when Multimedia_Card => + Set_Clock (This, Get_Transfer_Rate (Info.SD_CSD)); + when STD_Capacity_SD_Card_V1_1 + | STD_Capacity_SD_Card_v2_0 + | High_Capacity_SD_Card => + Set_Clock (This, 25_000_000); + when others => + -- Not yet handled + raise Program_Error; + end case; + + -- CMD10: SEND_CID (136 bits) + Send_Cmd (This, Send_CID, Rca, Status); + if Status /= OK then + return; + end if; + + -- CMD9: SEND_CSD + Send_Cmd (This, Send_CSD, Rca, Status); + if Status /= OK then + return; + end if; + Read_Rsp136 (This, W0, W1, W2, W3); + Convert_Card_Specific_Data_Register + (W0, W1, W2, W3, Info.Card_Type, Info.SD_CSD); + Info.Card_Capacity := + Compute_Card_Capacity (Info.SD_CSD, Info.Card_Type); + Info.Card_Block_Size := + Compute_Card_Block_Size (Info.SD_CSD, Info.Card_Type); + + -- CMD7: SELECT + Send_Cmd (This, Select_Card, Rca, Status); + if Status /= OK then + return; + end if; + + -- CMD13: STATUS + Send_Cmd (This, Send_Status, Rca, Status); + if Status /= OK then + return; + end if; + + -- Bus size + case Info.Card_Type is + when STD_Capacity_SD_Card_V1_1 + | STD_Capacity_SD_Card_v2_0 + | High_Capacity_SD_Card => + Send_ACmd (This, SD_App_Set_Bus_Width, Info.RCA, 2, Status); + if Status /= OK then + return; + else + Set_Bus_Size (This, Wide_Bus_4B); + end if; + when others => + null; + end case; + + if (Info.SD_CSD.Card_Command_Class and 2**10) /= 0 then + -- Class 10 supported. + declare + subtype Switch_Status_Type is UInt32_Array (1 .. 16); + + Switch_Status : Switch_Status_Type; + begin + -- CMD6 + Read_Cmd (This, Cmd_Desc (Switch_Func), 16#00_fffff0#, + Switch_Status, Status); + if Status /= OK then + return; + end if; + + -- Handle endianness + for I in Switch_Status'Range loop + Switch_Status (I) := BE32_To_Host (Switch_Status (I)); + end loop; + + -- Switch tp 50Mhz if possible. + if (Switch_Status (4) and 2**(16 + 1)) /= 0 then + Read_Cmd (This, Cmd_Desc (Switch_Func), 16#80_fffff1#, + Switch_Status, Status); + if Status /= OK then + return; + end if; + + -- Switch to 50Mhz + Set_Clock (This, 50_000_000); + end if;" +"function Convert is new Ada.Unchecked_Conversion (HALFS.Status_Code, Status_Code);","function Convert is new Ada.Unchecked_Conversion (File_Mode, HALFS.File_Mode); + function Convert is new Ada.Unchecked_Conversion (File_Size, HALFS.File_Size); + function Convert is new Ada.Unchecked_Conversion (HALFS.File_Size, File_Size); + function Convert is new Ada.Unchecked_Conversion (Seek_Mode, HALFS.Seek_Mode); + + type Mount_Record is record + Is_Free : Boolean := True; + Name : String (1 .. Max_Mount_Name_Length); + Name_Len : Positive; + FS : Any_Filesystem_Driver; + end record; + + subtype Mount_Index is Integer range 0 .. Max_Mount_Points; + subtype Valid_Mount_Index is Mount_Index range 1 .. Max_Mount_Points; + type Mount_Array is array (Valid_Mount_Index) of Mount_Record; + + type VFS_Directory_Handle is new Directory_Handle with record + Is_Free : Boolean := True; + Mount_Id : Mount_Index; + end record; + + overriding function Get_FS + (Dir : VFS_Directory_Handle) return Any_Filesystem_Driver; + -- Return the filesystem the handle belongs to. + + overriding function Read + (Dir : in out VFS_Directory_Handle; + Handle : out Any_Node_Handle) return HALFS.Status_Code; + -- Reads the next directory entry. If no such entry is there, an error + -- code is returned in Status. + + overriding procedure Reset (Dir : in out VFS_Directory_Handle); + -- Resets the handle to the first node + + overriding procedure Close (Dir : in out VFS_Directory_Handle); + -- Closes the handle, and free the associated resources. + + function Open + (Path : String; + Handle : out Any_Directory_Handle) + return Status_Code; + + function Open + (Path : String; + Mode : File_Mode; + Handle : out Any_File_Handle) + return Status_Code; + + Mount_Points : Mount_Array; + + Handles : array (1 .. 2) of aliased VFS_Directory_Handle; + + function Name (Point : Mount_Record) return Mount_Path; + procedure Set_Name (Point : in out Mount_Record; + Path : Mount_Path); + procedure Split + (Path : String; + FS : out Any_Filesystem_Driver; + Start_Index : out Natural); + + ---------- + -- Open -- + ---------- + + function Open + (File : in out File_Descriptor; + Name : String; + Mode : File_Mode) + return Status_Code + is + Ret : Status_Code; + begin + if Is_Open (File) then + return Invalid_Parameter; + end if; + Ret := Open (Name, Mode, File.Handle); + + if Ret /= OK then + File.Handle := null; + end if; + + return Ret; + end Open; + + ----------- + -- Close -- + ----------- + + procedure Close (File : in out File_Descriptor) is + begin + if File.Handle /= null then + File.Handle.Close; + File.Handle := null; + end if; + end Close; + + ------------- + -- Is_Open -- + ------------- + + function Is_Open + (File : File_Descriptor) + return Boolean + is (File.Handle /= null); + + ----------- + -- Flush -- + ----------- + + function Flush + (File : File_Descriptor) + return Status_Code + is + begin + if File.Handle /= null then + return Convert (File.Handle.Flush); + else + return Invalid_Parameter; + end if; + end Flush; + + ---------- + -- Size -- + ---------- + + function Size + (File : File_Descriptor) + return File_Size + is + begin + if File.Handle = null then + return 0; + else + return Convert (File.Handle.Size); + end if; + end Size; + + ---------- + -- Read -- + ---------- + + function Read + (File : File_Descriptor; + Addr : System.Address; + Length : File_Size) + return File_Size + is + Ret : HALFS.File_Size; + Status : Status_Code; + begin + if File.Handle = null then + return 0; + end if; + + Ret := Convert (Length); + Status := Convert (File.Handle.Read (Addr, Ret)); + + if Status /= OK then + return 0; + else + return Convert (Ret); + end if; + end Read; + + ----------- + -- Write -- + ----------- + + function Write + (File : File_Descriptor; + Addr : System.Address; + Length : File_Size) + return File_Size + is + Ret : HALFS.File_Size; + Status : Status_Code; + begin + if File.Handle = null then + return 0; + end if; + + Ret := Convert (Length); + Status := Convert (File.Handle.Write (Addr, Ret)); + + if Status /= OK then + return 0; + else + return Convert (Ret); + end if; + end Write; + + ------------ + -- Offset -- + ------------ + + function Offset + (File : File_Descriptor) + return File_Size + is + begin + if File.Handle /= null then + return Convert (File.Handle.Offset); + else + return 0; + end if; + end Offset; + + ---------- + -- Seek -- + ---------- + + function Seek + (File : in out File_Descriptor; + Origin : Seek_Mode; + Amount : in out File_Size) + return Status_Code + is + Ret : Status_Code; + HALFS_Amount : HALFS.File_Size; + begin + if File.Handle /= null then + HALFS_Amount := Convert (Amount); + Ret := Convert (File.Handle.Seek (Convert (Origin), HALFS_Amount)); + Amount := Convert (HALFS_Amount); + return Ret; + else + return Invalid_Parameter; + end if; + end Seek; + + ------------------- + -- Generic_Write -- + ------------------- + + function Generic_Write + (File : File_Descriptor; + Value : T) + return Status_Code + is + begin + if File.Handle /= null then + return Convert (File.Handle.Write (Value'Address, T'Size / 8)); + else + return Invalid_Parameter; + end if; + end Generic_Write; + + ------------------ + -- Generic_Read -- + ------------------ + + function Generic_Read + (File : File_Descriptor; + Value : out T) + return Status_Code + is + L : HALFS.File_Size := T'Size / 8; + begin + if File.Handle /= null then + return Convert (File.Handle.Read (Value'Address, L)); + else + return Invalid_Parameter; + end if; + end Generic_Read; + + ---------- + -- Open -- + ---------- + + function Open + (Dir : in out Directory_Descriptor; + Name : String) + return Status_Code + is + Ret : Status_Code; + begin + if Dir.Handle /= null then + return Invalid_Parameter; + end if; + Ret := Open (Name, Dir.Handle); + + if Ret /= OK then + Dir.Handle := null; + end if; + + return Ret; + end Open; + + ----------- + -- Close -- + ----------- + + procedure Close (Dir : in out Directory_Descriptor) is + begin + if Dir.Handle /= null then + Dir.Handle.Close; + end if; + end Close; + + ---------- + -- Read -- + ---------- + + function Read (Dir : in out Directory_Descriptor) + return Directory_Entry + is + Node : Any_Node_Handle; + Status : Status_Code; + begin + if Dir.Handle = null then + return Invalid_Dir_Entry; + end if; + + Status := Convert (Dir.Handle.Read (Node)); + if Status /= OK then + return Invalid_Dir_Entry; + end if; + + declare + Name : constant String := Node.Basename; + Ret : Directory_Entry (Name_Length => Name'Length); + begin + Ret.Name := Name; + Ret.Subdirectory := Node.Is_Subdirectory; + Ret.Read_Only := Node.Is_Read_Only; + Ret.Hidden := Node.Is_Hidden; + Ret.Symlink := Node.Is_Symlink; + Ret.Size := Convert (Node.Size); + Node.Close; + return Ret;" +function To_Data is new Ada.Unchecked_Conversion,"(FAT_Directory_Entry, Entry_Data); + function To_Data is new Ada.Unchecked_Conversion + (VFAT_Directory_Entry, Entry_Data); + + function Find_Empty_Entry_Sequence + (Parent : access FAT_Directory_Handle; + Num_Entries : Natural) return Entry_Index; + -- Finds a sequence of deleted entries that can fit Num_Entries. + -- Returns the first entry of this sequence + + -------------- + -- Set_Size -- + -------------- + + procedure Set_Size + (E : in out FAT_Node; + Size : FAT_File_Size) + is + begin + if E.Size /= Size then + E.Size := Size; + E.Is_Dirty := True; + end if; + end Set_Size; + + ---------- + -- Find -- + ---------- + + function Find + (Parent : FAT_Node; + Filename : FAT_Name; + DEntry : out FAT_Node) return Status_Code + is + -- We use a copy of the handle, so as not to touch the state of initial + -- handle + Status : Status_Code; + Cluster : Cluster_Type := Parent.Start_Cluster; + Block : Block_Offset := Parent.FS.Cluster_To_Block (Cluster); + Index : Entry_Index := 0; + + begin + loop + Status := Next_Entry + (FS => Parent.FS, + Current_Cluster => Cluster, + Current_Block => Block, + Current_Index => Index, + DEntry => DEntry); + + if Status /= OK then + return No_Such_File; + end if; + + if Long_Name (DEntry) = Filename or else + (DEntry.L_Name.Len = 0 and then Short_Name (DEntry) = Filename) + then + return OK; + end if; + end loop; + end Find; + + ---------- + -- Find -- + ---------- + + function Find + (FS : in out FAT_Filesystem; + Path : String; + DEntry : out FAT_Node) return Status_Code + is + Status : Status_Code; + Idx : Natural; -- Idx is used to walk through the Path + Token : FAT_Name; + + begin + DEntry := Root_Entry (FS); + + -- Looping through the Path. We start at 2 as we ignore the initial '/' + Idx := Path'First + 1; + + while Idx <= Path'Last loop + Token.Len := 0; + + for J in Idx .. Path'Last loop + if Path (J) = '/' then + exit; + end if; + + Token.Len := Token.Len + 1; + Token.Name (Token.Len) := Path (J); + end loop; + + Idx := Idx + Token.Len + 1; + + Status := Find (DEntry, Token, DEntry); + + if Status /= OK then + return No_Such_File; + end if; + + if Idx < Path'Last then + -- Intermediate entry: needs to be a directory + if not Is_Subdirectory (DEntry) then + return No_Such_Path; + end if; + end if; + end loop; + + return OK; + end Find; + + ------------------ + -- Update_Entry -- + ------------------ + + function Update_Entry + (Parent : FAT_Node; + Value : in out FAT_Node) return Status_Code + is + subtype Entry_Block is Block (1 .. 32); + function To_Block is new + Ada.Unchecked_Conversion (FAT_Directory_Entry, Entry_Block); + function To_Entry is new + Ada.Unchecked_Conversion (Entry_Block, FAT_Directory_Entry); + + Ent : FAT_Directory_Entry; + Cluster : Cluster_Type := Parent.Start_Cluster; + Offset : FAT_File_Size := FAT_File_Size (Value.Index) * 32; + Block_Off : Natural; + Block : Block_Offset; + Ret : Status_Code; + + begin + if not Value.Is_Dirty then + return OK; + end if; + + while Offset > Parent.FS.Cluster_Size loop + Cluster := Parent.FS.Get_FAT (Cluster); + Offset := Offset - Parent.FS.Cluster_Size; + end loop; + + Block := Block_Offset (Offset / Parent.FS.Block_Size); + Block_Off := Natural (Offset mod Parent.FS.Block_Size); + + Ret := Parent.FS.Ensure_Block + (Parent.FS.Cluster_To_Block (Cluster) + Block); + if Ret /= OK then + return Ret; + end if; + + Ent := To_Entry (Parent.FS.Window (Block_Off .. Block_Off + 31)); + + -- For now only the size can be modified, so just apply this + -- modification + Ent.Size := Value.Size; + Value.Is_Dirty := False; + + Parent.FS.Window (Block_Off .. Block_Off + 31) := To_Block (Ent); + Ret := Parent.FS.Write_Window; + + return Ret; + end Update_Entry; + + ---------------- + -- Root_Entry -- + ---------------- + + function Root_Entry (FS : in out FAT_Filesystem) return FAT_Node + is + Ret : FAT_Node; + begin + Ret.FS := FS'Unchecked_Access; + Ret.Attributes := (Subdirectory => True, + others => False); + Ret.Is_Root := True; + Ret.L_Name := (Name => (others => ' '), + Len => 0); + if FS.Version = FAT16 then + Ret.Start_Cluster := 0; + else + Ret.Start_Cluster := FS.Root_Dir_Cluster; + end if; + Ret.Index := 0; + + return Ret; + end Root_Entry; + + ---------------- + -- Next_Entry -- + ---------------- + + function Next_Entry + (FS : access FAT_Filesystem; + Current_Cluster : in out Cluster_Type; + Current_Block : in out Block_Offset; + Current_Index : in out Entry_Index; + DEntry : out FAT_Directory_Entry) return Status_Code + is + subtype Entry_Data is Block (1 .. 32); + function To_Entry is new Ada.Unchecked_Conversion + (Entry_Data, FAT_Directory_Entry); + + Ret : Status_Code; + Block_Off : Natural; + + begin + if Current_Index = 16#FFFF# then + return No_More_Entries; + end if; + + if Current_Cluster = 0 and then FS.Version = FAT16 then + if Current_Index > + Entry_Index (FS.FAT16_Root_Dir_Num_Entries) + then + return No_More_Entries; + else + Block_Off := + Natural (FAT_File_Size (Current_Index * 32) mod + FS.Block_Size); + Current_Block := + FS.Root_Dir_Area + + Block_Offset + (FAT_File_Size (Current_Index * 32) / FS.Block_Size); + end if; + + else + Block_Off := Natural + (FAT_File_Size (Current_Index * 32) mod FS.Block_Size); + + -- Check if we're on a block boundare + if Unsigned_32 (Block_Off) = 0 and then Current_Index /= 0 then + Current_Block := Current_Block + 1; + end if; + + -- Check if we're on the boundary of a new cluster + if Current_Block - FS.Cluster_To_Block (Current_Cluster) + = FS.Blocks_Per_Cluster + then + -- The block we need to read is outside of the current cluster. + -- Let's move on to the next + + -- Read the FAT table to determine the next cluster + Current_Cluster := FS.Get_FAT (Current_Cluster); + + if Current_Cluster = 1 + or else FS.Is_Last_Cluster (Current_Cluster) + then + return Internal_Error; + end if; + + Current_Block := FS.Cluster_To_Block (Current_Cluster); + end if; + end if; + + Ret := FS.Ensure_Block (Current_Block); + + if Ret /= OK then + return Ret; + end if; + + if FS.Window (Block_Off) = 0 then + -- End of entries: we stick the index here to make sure that further + -- calls to Next_Entry always end-up here + return No_More_Entries; + end if; + + DEntry := To_Entry (FS.Window (Block_Off .. Block_Off + 31)); + Current_Index := Current_Index + 1; + + return OK; + end Next_Entry; + + ---------------- + -- Next_Entry -- + ---------------- + + function Next_Entry + (FS : access FAT_Filesystem; + Current_Cluster : in out Cluster_Type; + Current_Block : in out Block_Offset; + Current_Index : in out Entry_Index; + DEntry : out FAT_Node) return Status_Code + is + procedure Prepend + (Name : Wide_String; + Full : in out String; + Idx : in out Natural); + -- Prepends Name to Full + + ------------- + -- Prepend -- + ------------- + + procedure Prepend + (Name : Wide_String; + Full : in out String; + Idx : in out Natural) + is + Val : Unsigned_16; + begin + for J in reverse Name'Range loop + Val := Wide_Character'Pos (Name (J)); + if Val /= 16#FFFF# + and then Val /= 0 + then + Idx := Idx - 1; + + exit when Idx not in Full'Range; + + if Val < 255 then + Full (Idx) := Character'Val (Val); + elsif Val = 16#F029# then + -- Path ends with a '.' + Full (Idx) := '.'; + elsif Val = 16#F028# then + -- Path ends with a ' ' + Full (Idx) := ' '; + else + Full (Idx) := '?'; + end if; + end if; + end loop; + end Prepend; + + Ret : Status_Code; + D_Entry : FAT_Directory_Entry; + V_Entry : VFAT_Directory_Entry; + function To_VFAT_Entry is new Ada.Unchecked_Conversion + (FAT_Directory_Entry, VFAT_Directory_Entry); + + C : Unsigned_8; + Last_Seq : VFAT_Sequence_Number := 0; + CRC : Unsigned_8 := 0; + Matches : Boolean; + Current_CRC : Unsigned_8; + L_Name : String (1 .. MAX_FILENAME_LENGTH); + L_Name_First : Natural; + + begin + L_Name_First := L_Name'Last + 1; + + loop + Ret := Next_Entry + (FS, + Current_Cluster => Current_Cluster, + Current_Block => Current_Block, + Current_Index => Current_Index, + DEntry => D_Entry); + + if Ret /= OK then + return Ret; + end if; + + -- Check if we have a VFAT entry here by checking that the + -- attributes are 16#0F# (e.g. all attributes set except + -- subdirectory and archive) + if D_Entry.Attributes = VFAT_Directory_Entry_Attribute then + V_Entry := To_VFAT_Entry (D_Entry); + + if V_Entry.VFAT_Attr.Stop_Bit then + L_Name_First := L_Name'Last + 1; + + else + if Last_Seq = 0 + or else Last_Seq - 1 /= V_Entry.VFAT_Attr.Sequence + then + L_Name_First := L_Name'Last + 1; + end if; + end if; + + Last_Seq := V_Entry.VFAT_Attr.Sequence; + + Prepend (V_Entry.Name_3, L_Name, L_Name_First); + Prepend (V_Entry.Name_2, L_Name, L_Name_First); + Prepend (V_Entry.Name_1, L_Name, L_Name_First); + + if V_Entry.VFAT_Attr.Sequence = 1 then + CRC := V_Entry.Checksum; + end if; + + -- Ignore Volumes and deleted files + elsif not D_Entry.Attributes.Volume_Label + and then Character'Pos (D_Entry.Filename (1)) /= 16#E5# + then + if L_Name_First not in L_Name'Range then + Matches := False; + else + Current_CRC := 0; + Last_Seq := 0; + + for Ch of String'(D_Entry.Filename & D_Entry.Extension) loop + C := Character'Enum_Rep (Ch); + Current_CRC := Shift_Right (Current_CRC and 16#FE#, 1) + or Shift_Left (Current_CRC and 16#01#, 7); + -- Modulo addition + Current_CRC := Current_CRC + C; + end loop; + + Matches := Current_CRC = CRC; + end if; + + DEntry := + (FS => FAT_Filesystem_Access (FS), + L_Name => <>, + S_Name => D_Entry.Filename, + S_Name_Ext => D_Entry.Extension, + Attributes => D_Entry.Attributes, + Start_Cluster => (if FS.Version = FAT16 + then Cluster_Type (D_Entry.Cluster_L) + else Cluster_Type (D_Entry.Cluster_L) or + Shift_Left + (Cluster_Type (D_Entry.Cluster_H), 16)), + Size => D_Entry.Size, + Index => Current_Index - 1, + Is_Root => False, + Is_Dirty => False); + + if Matches then + DEntry.L_Name := -L_Name (L_Name_First .. L_Name'Last); + else + DEntry.L_Name.Len := 0; + end if; + + return OK; + end if; + end loop; + end Next_Entry; + + ---------- + -- Read -- + ---------- + + function Read + (Dir : in out FAT_Directory_Handle; + DEntry : out FAT_Node) return Status_Code + is + begin + return Next_Entry + (Dir.FS, + Current_Cluster => Dir.Current_Cluster, + Current_Block => Dir.Current_Block, + Current_Index => Dir.Current_Index, + DEntry => DEntry); + end Read; + + ------------------- + -- Create_Subdir -- + ------------------- + + function Create_Subdir + (Dir : FAT_Node; + Name : FAT_Name; + New_Dir : out FAT_Node) return Status_Code + is + Handle : FAT_Directory_Handle_Access; + Ret : Status_Code; + Block : Block_Offset; + Dot : FAT_Directory_Entry; + Dot_Dot : FAT_Directory_Entry; + + begin + Ret := Dir.FAT_Open (Handle); + + if Ret /= OK then + return Ret; + end if; + + Ret := Allocate_Entry + (Parent => Handle, + Name => Name, + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => True, + Archive => False), + E => New_Dir); + + if Ret /= OK then + return Ret; + end if; + + Block := Dir.FS.Cluster_To_Block (New_Dir.Start_Cluster); + Ret := Handle.FS.Ensure_Block (Block); + if Ret /= OK then + return Ret; + end if; + + -- Allocate '.', '..' and the directory entry terminator + Dot := + (Filename => (1 => '.', others => ' '), + Extension => (others => ' '), + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => True, + Archive => False), + Reserved => (others => ASCII.NUL), + Cluster_H => + Unsigned_16 + (Shift_Right + (Unsigned_32 + (New_Dir.Start_Cluster) and 16#FFFF_0000#, 16)), + Time => 0, + Date => 0, + Cluster_L => Unsigned_16 (New_Dir.Start_Cluster and 16#FFFF#), + Size => 0); + Dot_Dot := + (Filename => (1 .. 2 => '.', others => ' '), + Extension => (others => ' '), + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => True, + Archive => False), + Reserved => (others => ASCII.NUL), + Cluster_H => + Unsigned_16 + (Shift_Right + (Unsigned_32 (Handle.Start_Cluster) and 16#FFFF_0000#, 16)), + Time => 0, + Date => 0, + Cluster_L => Unsigned_16 (Handle.Start_Cluster and 16#FFFF#), + Size => 0); + + Handle.FS.Window (0 .. 31) := To_Data (Dot); + Handle.FS.Window (32 .. 63) := To_Data (Dot_Dot); + Handle.FS.Window (64 .. 95) := (others => 0); + Ret := Handle.FS.Write_Window; + + Close (Handle.all); + + return Ret; + end Create_Subdir; + + ---------------------- + -- Create_File_Node -- + ---------------------- + + function Create_File_Node + (Dir : FAT_Node; + Name : FAT_Name; + New_File : out FAT_Node) return Status_Code + is + Handle : FAT_Directory_Handle_Access; + Ret : Status_Code; + + begin + Ret := Dir.FAT_Open (Handle); + + if Ret /= OK then + return Ret; + end if; + + Ret := Allocate_Entry + (Parent => Handle, + Name => Name, + Attributes => (Read_Only => False, + Hidden => False, + System_File => False, + Volume_Label => False, + Subdirectory => False, + Archive => True), + E => New_File); + + Close (Handle.all); + + if Ret /= OK then + return Ret; + end if; + + return Ret; + end Create_File_Node; + + ------------------- + -- Delete_Subdir -- + ------------------- + + function Delete_Subdir + (Dir : FAT_Node; + Recursive : Boolean) return Status_Code + is + Parent : FAT_Node; + Handle : FAT_Directory_Handle_Access; + Ent : FAT_Node; + Ret : Status_Code; + + begin + Ret := Dir.FAT_Open (Handle); + + if Ret /= OK then + return Ret; + end if; + + while Read (Handle.all, Ent) = OK loop + if -Long_Name (Ent) = ""."" then + null; + elsif -Long_Name (Ent) = "".."" then + Parent := Ent; + elsif not Recursive then + return Non_Empty_Directory; + else + if Ent.Attributes.Subdirectory then + Ret := Delete_Subdir (Ent, True); + else + Ret := Delete_Entry (Dir, Ent); + end if; + + if Ret /= OK then + Close (Handle.all); + + return Ret; + end if; + end if; + end loop; + + Close (Handle.all); + + -- Free the clusters associated to the subdirectory + Ret := Delete_Entry (Parent, Dir); + + if Ret /= OK then + return Ret; + end if; + + return Ret; + end Delete_Subdir; + + ------------------ + -- Delete_Entry -- + ------------------ + + function Delete_Entry + (Dir : FAT_Node; + Ent : FAT_Node) return Status_Code + is + Current : Cluster_Type := Ent.Start_Cluster; + Handle : FAT_Directory_Handle_Access; + Next : Cluster_Type; + Child_Ent : FAT_Node; + Ret : Status_Code; + Block_Off : Natural; + + begin + -- Mark the entry's cluster chain as available + loop + Next := Ent.FS.Get_FAT (Current); + Ret := Ent.FS.Set_FAT (Current, FREE_CLUSTER_VALUE); + + exit when Ret /= OK; + exit when Ent.FS.Is_Last_Cluster (Next); + Current := Next; + end loop; + + -- Mark the parent's entry as deleted + Ret := Dir.FAT_Open (Handle); + if Ret /= OK then + return Ret; + end if; + + while Read (Handle.all, Child_Ent) = OK loop + if Long_Name (Child_Ent) = Long_Name (Ent) then + Block_Off := Natural + ((FAT_File_Size (Handle.Current_Index - 1) * 32) + mod Dir.FS.Block_Size); + -- Mark the entry as deleted: first basename character set to + -- 16#E5# + Handle.FS.Window (Block_Off) := 16#E5#; + Ret := Handle.FS.Write_Window; + + exit; + end if; + end loop; + + Close (Handle.all); + + return Ret; + end Delete_Entry; + + --------------------- + -- Adjust_Clusters -- + --------------------- + + function Adjust_Clusters (Ent : FAT_Node) return Status_Code + is + B_Per_Cluster : constant FAT_File_Size := + FAT_File_Size (Ent.FS.Blocks_Per_Cluster) * + Ent.FS.Block_Size; + Size : FAT_File_Size := Ent.Size; + Current : Cluster_Type := Ent.Start_Cluster; + Next : Cluster_Type; + Ret : Status_Code := OK; + + begin + if Ent.Attributes.Subdirectory then + -- ??? Do nothing for now + return OK; + end if; + + loop + Next := Ent.FS.Get_FAT (Current); + + if Size > B_Per_Cluster then + -- Current cluster is fully used + Size := Size - B_Per_Cluster; + elsif Size > 0 or else Current = Ent.Start_Cluster then + -- Partially used cluster, but the last one + Size := 0; + if Next /= LAST_CLUSTER_VALUE then + Ret := Ent.FS.Set_FAT (Current, LAST_CLUSTER_VALUE); + end if; + else + -- We don't need more clusters + Ret := Ent.FS.Set_FAT (Current, FREE_CLUSTER_VALUE); + end if; + + exit when Ret /= OK; + exit when Ent.FS.Is_Last_Cluster (Next); + Current := Next; + Size := Size - B_Per_Cluster; + end loop; + + return Ret; + end Adjust_Clusters; + + ------------------------------- + -- Find_Empty_Entry_Sequence -- + ------------------------------- + + function Find_Empty_Entry_Sequence + (Parent : access FAT_Directory_Handle; + Num_Entries : Natural) return Entry_Index + is + Status : Status_Code; + D_Entry : FAT_Directory_Entry; + Sequence : Natural := 0; + Ret : Entry_Index; + Cluster : Cluster_Type := Parent.Start_Cluster; + Block : Block_Offset := Cluster_To_Block (Parent.FS.all, Cluster); + begin + Parent.Current_Index := 0; + loop + Status := Next_Entry + (Parent.FS, + Current_Cluster => Cluster, + Current_Block => Block, + Current_Index => Parent.Current_Index, + DEntry => D_Entry); + + if Status /= OK then + return Null_Index; + end if; + + if D_Entry.Attributes = VFAT_Directory_Entry_Attribute then + if Sequence = 0 then + -- Parent.Current_Index points to the next unread value. + -- So the just read entry is at Parent.Current_Index - 1 + Ret := Parent.Current_Index - 1; + end if; + + Sequence := Sequence + 1; + + elsif Character'Pos (D_Entry.Filename (1)) = 16#E5# then + -- A deleted entry has been found + if Sequence >= Num_Entries then + return Ret; + else + Sequence := 0; + end if; + + else + Sequence := 0; + end if; + end loop; + end Find_Empty_Entry_Sequence; + + -------------------- + -- Allocate_Entry -- + -------------------- + + function Allocate_Entry + (Parent : access FAT_Directory_Handle; + Name : FAT_Name; + Attributes : FAT_Directory_Entry_Attribute; + E : out FAT_Node) return Status_Code + is + subtype Short_Name is String (1 .. 8); + subtype Extension is String (1 .. 3); + + function Is_Legal_Character (C : Character) return Boolean + is (C in 'A' .. 'Z' + or else C in '0' .. '9' + or else C = '!' + or else C = '#' + or else C = '$' + or else C = '%' + or else C = '&' + or else C = ''' + or else C = '(' + or else C = ')' + or else C = '-' + or else C = '@' + or else C = '^' + or else C = '_' + or else C = '`' + or else C = '{' + or else C = '}' + or else C = '~'); + + Block_Off : Natural; + Status : Status_Code; + DEntry : FAT_Node; + SName : Short_Name := (others => ' '); + SExt : Extension := (others => ' '); + Index : Entry_Index; + + -- Retrieve the number of VFAT entries that are needed, plus one for + -- the regular FAT entry. + N_Entries : Natural := Get_Num_VFAT_Entries (Name) + 1; + Bytes : Entry_Data; + + procedure To_Short_Name + (Name : FAT_Name; + SName : out Short_Name; + Ext : out Extension); + -- Translates a long name into short 8.3 name + -- If the long name is mixed or lower case. then 8.3 will be uppercased + -- If the long name contains characters not allowed in an 8.3 name, then + -- the name is stripped of invalid characters such as space and extra + -- periods. Other unknown characters are changed to underscores. + -- The stripped name is then truncated, followed by a ~1. Inc_SName + -- below will increase the digit number in case there's overloaded 8.3 + -- names. + -- If the long name is longer than 8.3, then ~1 suffix will also be + -- used. + + function To_Upper (C : Character) return Character is + (if C in 'a' .. 'z' + then Character'Val + (Character'Pos (C) + Character'Pos ('A') - Character'Pos ('a')) + else C); + + function Value (S : String) return Natural; + -- For a positive int represented in S, returns its value + + procedure Inc_SName (SName : in out String); + -- Increment the suffix of the short FAT name + -- e.g.: + -- ABCDEFGH => ABCDEF~1 + -- ABC => ABC~1 + -- ABC~9 => ABC~10 + -- ABCDEF~9 => ABCDE~10 + + procedure To_WString + (S : FAT_Name; + Idx : in out Natural; + WS : in out Wide_String); + -- Dumps S (Idx .. Idx + WS'Length - 1) into WS and increments Idx + + ----------- + -- Value -- + ----------- + + function Value (S : String) return Natural + is + Val : constant String := Trim (S); + Digit : Natural; + Ret : Natural := 0; + begin + for J in Val'Range loop + Digit := Character'Pos (Val (J)) - Character'Pos ('0'); + Ret := Ret * 10 + Digit; + end loop; + + return Ret; + end Value; + + ------------------- + -- To_Short_Name -- + ------------------- + + procedure To_Short_Name + (Name : FAT_Name; + SName : out Short_Name; + Ext : out Extension) + is + S_Idx : Natural := 0; + Add_Tilde : Boolean := False; + Last : Natural := Name.Len; + + begin + -- Copy the file extension + + Ext := (others => ' '); + + for J in reverse 1 .. Name.Len loop + if Name.Name (J) = '.' then + if J = Name.Len then + -- Take care of names ending with a '.' (e.g. no extension, + -- the final '.' is part of the basename) + Last := J; + Ext := (others => ' '); + else + Last := J - 1; + S_Idx := Ext'First; + + for K in J + 1 .. Name.Len loop + Ext (S_Idx) := To_Upper (Name.Name (K)); + S_Idx := S_Idx + 1; + -- In case the extension is more than 3 characters, we + -- keep the first 3 ones. + exit when S_Idx > Ext'Last; + end loop; + end if; + + exit; + end if; + end loop; + + S_Idx := 0; + SName := (others => ' '); + + for J in 1 .. Last loop + exit when Add_Tilde and then S_Idx >= 6; + exit when not Add_Tilde and then S_Idx = 8; + + if Name.Name (J) in 'a' .. 'z' then + S_Idx := S_Idx + 1; + SName (S_Idx) := To_Upper (Name.Name (J)); + + elsif Is_Legal_Character (Name.Name (J)) then + S_Idx := S_Idx + 1; + SName (S_Idx) := Name.Name (J); + + elsif Name.Name (J) = '.' + or else Name.Name (J) = ' ' + then + -- dots that are not used as extension delimiters are invalid + -- in FAT short names and ignored in long names to short names + -- translation + Add_Tilde := True; + + else + -- Any other character is translated as '_' + Add_Tilde := True; + S_Idx := S_Idx + 1; + SName (S_Idx) := '_'; + end if; + end loop; + + if Add_Tilde then + if S_Idx >= 6 then + SName (7 .. 8) := ""~1""; + else + SName (S_Idx + 1 .. S_Idx + 2) := ""~1""; + end if; + end if; + end To_Short_Name; + + --------------- + -- Inc_SName -- + --------------- + + procedure Inc_SName (SName : in out String) + is + Idx : Natural := 0; + Num : Natural := 0; + + begin + for J in reverse SName'Range loop + if Idx = 0 then + if SName (J) = ' ' then + null; + elsif SName (J) in '0' .. '9' then + Idx := J; + else + SName (SName'Last - 1 .. SName'Last) := ""~1""; + + return; + end if; + + elsif SName (J) in '0' .. '9' then + Idx := J; + + elsif SName (J) = '~' then + Num := Value (SName (Idx .. SName'Last)) + 1; + -- make Idx point to '~' + Idx := J; + + declare + N_Suffix : String := Natural'Image (Num); + begin + N_Suffix (N_Suffix'First) := '~'; + + if Idx + N_Suffix'Length - 1 > SName'Last then + SName (SName'Last - N_Suffix'Length + 1 .. SName'Last) := + N_Suffix; + else + SName (Idx .. Idx + N_Suffix'Length - 1) := N_Suffix; + end if; + + return;" +function To_Disk_Parameter is new Ada.Unchecked_Conversion,"(Disk_Parameter_Block, FAT_Disk_Parameter); + + subtype FSInfo_Block is Block (0 .. 11); + function To_FSInfo is new Ada.Unchecked_Conversion + (FSInfo_Block, FAT_FS_Info); + + begin + FS.Window_Block := 16#FFFF_FFFF#; + Status := FS.Ensure_Block (0); + + if Status /= OK then + return; + end if; + + if FS.Window (510 .. 511) /= (16#55#, 16#AA#) then + Status := No_Filesystem; + return; + end if; + + FS.Disk_Parameters := + To_Disk_Parameter (FS.Window (0 .. 91)); + + if FS.Version = FAT32 then + Status := + FS.Ensure_Block (Block_Offset (FS.FSInfo_Block_Number)); + + if Status /= OK then + return; + end if; + + -- Check the generic FAT block signature + if FS.Window (510 .. 511) /= (16#55#, 16#AA#) then + Status := No_Filesystem; + return; + end if; + + FS.FSInfo := + To_FSInfo (FS.Window (16#1E4# .. 16#1EF#)); + FS.FSInfo_Changed := False; + end if; + + declare + FAT_Size_In_Block : constant Unsigned_32 := + FS.FAT_Table_Size_In_Blocks * + Unsigned_32 (FS.Number_Of_FATs); + Root_Dir_Size : Block_Offset; + begin + FS.FAT_Addr := Block_Offset (FS.Reserved_Blocks); + FS.Data_Area := FS.FAT_Addr + Block_Offset (FAT_Size_In_Block); + + if FS.Version = FAT16 then + -- Add space for the root directory + FS.Root_Dir_Area := FS.Data_Area; + Root_Dir_Size := + (Block_Offset (FS.FAT16_Root_Dir_Num_Entries) * 32 + + Block_Offset (FS.Block_Size) - 1) / + Block_Offset (FS.Block_Size); + -- Align on clusters + Root_Dir_Size := + ((Root_Dir_Size + FS.Blocks_Per_Cluster - 1) / + FS.Blocks_Per_Cluster) * + FS.Blocks_Per_Cluster; + + FS.Data_Area := FS.Data_Area + Root_Dir_Size; + end if; + + FS.Num_Clusters := + Cluster_Type + ((FS.Total_Number_Of_Blocks - Unsigned_32 (FS.Data_Area)) / + Unsigned_32 (FS.Blocks_Per_Cluster));" +procedure List (Path : String);,"---------- + -- List -- + ---------- + + procedure List (Path : String) is + DD : Directory_Descriptor; + Status : Status_Code; + First : Boolean := True; + begin + Status := Open (DD, Path); + if Status /= OK then + Put (""Cannot open directory '"" & Path & ""': "" & Status'Img); + return; + end if; + + if Recursive then + Put_Line (Path & "":""); + end if; + + loop + declare + Ent : constant Directory_Entry := Read (DD); + begin + exit when Ent = Invalid_Dir_Entry; + + if not Ent.Hidden or else Show_All then + if First then + Put (Ent.Name); + First := False; + else + Put ("" "" & Ent.Name); + end if; + end if;" +procedure Display_File (Path : String);,"------------------ + -- Display_File -- + ------------------ + + procedure Display_File (Path : String) is + FD : File_Descriptor; + Status : Status_Code; + Data : String (1 .. 512); + Amount : File_Size; + begin + Status := Open (FD, Path, Read_Only); + if Status /= OK then + Put_Line (""Cannot open file '"" & Path & ""': "" & Status'Img); + return; + end if; + + loop + Amount := Read (FD, Data'Address, Data'Length); + exit when Amount = 0; + Put (Data (Data'First .. Data'First + Natural (Amount) - 1)); + end loop; + Close (FD); + end Display_File; + + begin + loop + declare + Arg : constant String := Args.Next; + begin + if Arg'Length = 0 then + return; + end if; + Display_File (Arg);" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2ENR.USART1EN := True; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1ENR.USART2EN := True; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1ENR.USART3EN := True; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1ENR.UART4EN := True; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1ENR.UART5EN := True; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2ENR.USART6EN := True; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1ENR.UART7ENR := True; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1ENR.UART8ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2RSTR.USART1RST := True; + RCC_Periph.APB2RSTR.USART1RST := False; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1RSTR.UART2RST := True; + RCC_Periph.APB1RSTR.UART2RST := False; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1RSTR.UART3RST := True; + RCC_Periph.APB1RSTR.UART3RST := False; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1RSTR.UART4RST := True; + RCC_Periph.APB1RSTR.UART4RST := False; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1RSTR.UART5RST := True; + RCC_Periph.APB1RSTR.UART5RST := False; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2RSTR.USART6RST := True; + RCC_Periph.APB2RSTR.USART6RST := False; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1RSTR.UART7RST := True; + RCC_Periph.APB1RSTR.UART7RST := False; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1RSTR.UART8RST := True; + RCC_Periph.APB1RSTR.UART8RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out SPI_Port'Class) is + begin + if This'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SAI_Port) + is + begin + pragma Assert (This'Address = SAI_Base); + RCC_Periph.APB2ENR.SAI1EN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SAI_Port) + is + begin + pragma Assert (This'Address = SAI_Base); + RCC_Periph.APB2RSTR.SAI1RST := True; + RCC_Periph.APB2RSTR.SAI1RST := False; + end Reset; + + --------------------- + -- Get_Input_Clock -- + --------------------- + + function Get_Input_Clock (Periph : SAI_Port) return UInt32 + is + Input_Selector : UInt2; + VCO_Input : UInt32; + SAI_First_Level : UInt32; + begin + if Periph'Address /= SAI_Base then + raise Unknown_Device; + end if; + + Input_Selector := RCC_Periph.DCKCFGR.SAI1ASRC; + + -- This driver doesn't support external source clock + if Input_Selector > 1 then + raise Constraint_Error + with ""External PLL SAI source clock unsupported""; + end if; + + if not RCC_Periph.PLLCFGR.PLLSRC then + -- PLLSAI SRC is HSI + VCO_Input := HSI_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + else + -- PLLSAI SRC is HSE + VCO_Input := HSE_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + end if; + + if Input_Selector = 0 then + -- PLLSAI is the clock source + + -- VCO out = VCO in & PLLSAIN + -- SAI firstlevel = VCO out / PLLSAIQ + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIN) / + UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIQ); + + -- SAI frequency is SAI First level / PLLSAIDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DCKCFGR.PLLSAIDIVQ); + + else + -- PLLI2S as clock source + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SN) / + UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SQ); + -- SAI frequency is SAI First level / PLLI2SDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DCKCFGR.PLLIS2DIVQ + 1); + end if; + end Get_Input_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDIO_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2ENR.SDIOEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDIO_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2RSTR.SDIORST := True; + RCC_Periph.APB2RSTR.SDIORST := False; + end Reset; + + ---------------------- + -- Set_Clock_Source -- + ---------------------- + + procedure Set_Clock_Source + (This : in out SDMMC_Controller; + Src : SDIO_Clock_Source) + is + Src_Val : constant Boolean := Src = Src_Sysclk; + begin + if This.Periph.all'Address /= SDIO_Base then + raise Unknown_Device; + end if; + + RCC_Periph.DCKCFGR.SDMMCSEL := Src_Val; + + case Src is + when Src_Sysclk => + STM32.SDMMC.Set_Clk_Src_Speed + (This, System_Clock_Frequencies.SYSCLK); + when Src_48Mhz => + STM32.SDMMC.Set_Clk_Src_Speed + (This, 48_000_000); + end case; + end Set_Clock_Source; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + +-- procedure Enable_Clock (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2ENR.USART1EN := True; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1ENR.USART2EN := True; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1ENR.USART3EN := True; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1ENR.UART4EN := True; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1ENR.UART5EN := True; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2ENR.USART6EN := True; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1ENR.UART7ENR := True; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1ENR.UART8ENR := True; +-- else +-- raise Unknown_Device; +-- end if; +-- end Enable_Clock; + + ----------- + -- Reset -- + ----------- + +-- procedure Reset (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2RSTR.USART1RST := True; +-- RCC_Periph.APB2RSTR.USART1RST := False; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1RSTR.UART2RST := True; +-- RCC_Periph.APB1RSTR.UART2RST := False; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1RSTR.UART3RST := True; +-- RCC_Periph.APB1RSTR.UART3RST := False; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1RSTR.UART4RST := True; +-- RCC_Periph.APB1RSTR.UART4RST := False; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1RSTR.UART5RST := True; +-- RCC_Periph.APB1RSTR.UART5RST := False; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2RSTR.USART6RST := True; +-- RCC_Periph.APB2RSTR.USART6RST := False; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1RSTR.UART7RST := True; +-- RCC_Periph.APB1RSTR.UART7RST := False; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1RSTR.UART8RST := True; +-- RCC_Periph.APB1RSTR.UART8RST := False; +-- else +-- raise Unknown_Device; +-- end if; +-- end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + elsif Port.Periph.all'Address = I2C4_Base then + return I2C_Id_4; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + when I2C_Id_4 => + RCC_Periph.APB1ENR.I2C4EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + when I2C_Id_4 => + RCC_Periph.APB1RSTR.I2C4RST := True; + RCC_Periph.APB1RSTR.I2C4RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2ENR.SAI1EN := True; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2ENR.SAI2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2RSTR.SAI1RST := True; + RCC_Periph.APB2RSTR.SAI1RST := False; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2RSTR.SAI2RST := True; + RCC_Periph.APB2RSTR.SAI2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + --------------------- + -- Get_Input_Clock -- + --------------------- + + function Get_Input_Clock (Periph : SAI_Port) return UInt32 + is + Input_Selector : UInt2; + VCO_Input : UInt32; + SAI_First_Level : UInt32; + begin + if Periph'Address = SAI1_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI1SEL; + elsif Periph'Address = SAI2_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI2SEL; + else + raise Unknown_Device; + end if; + + + -- This driver doesn't support external source clock + if Input_Selector > 1 then + raise Constraint_Error + with ""External PLL SAI source clock unsupported""; + end if; + + if not RCC_Periph.PLLCFGR.PLLSRC then + -- PLLSAI SRC is HSI + VCO_Input := HSI_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + else + -- PLLSAI SRC is HSE + VCO_Input := HSE_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + end if; + + if Input_Selector = 0 then + -- PLLSAI is the clock source + + -- VCO out = VCO in & PLLSAIN + -- SAI firstlevel = VCO out / PLLSAIQ + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIN) / + UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIQ); + + -- SAI frequency is SAI First level / PLLSAIDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLSAIDIVQ); + + else + -- PLLI2S as clock source + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SN) / + UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SQ); + -- SAI frequency is SAI First level / PLLI2SDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLI2SDIV + 1); + end if; + end Get_Input_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address = SDMMC1_Base then + RCC_Periph.APB2ENR.SDMMC1EN := True; + elsif This.Periph.all'Address = SDMMC2_Base then + RCC_Periph.APB2ENR.SDMMC2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address = SDMMC1_Base then + RCC_Periph.APB2RSTR.SDMMC1RST := True; + RCC_Periph.APB2RSTR.SDMMC1RST := False; + elsif This.Periph.all'Address = SDMMC2_Base then + RCC_Periph.APB2RSTR.SDMMC2RST := True; + RCC_Periph.APB2RSTR.SDMMC2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------------- + -- Set_Clock_Source -- + ---------------------- + + procedure Set_Clock_Source + (This : in out SDMMC_Controller; + Src : SDMMC_Clock_Source) + is + Sel_Value : constant Boolean := Src = Src_Sysclk; + begin + if This.Periph.all'Address = SDMMC1_Base then + RCC_Periph.DKCFGR2.SDMMC1SEL := Sel_Value; + elsif This.Periph.all'Address = SDMMC2_Base then + RCC_Periph.DKCFGR2.SDMMC2SEL := Sel_Value; + else + raise Unknown_Device; + end if; + + case Src is + when Src_Sysclk => + STM32.SDMMC.Set_Clk_Src_Speed + (This, System_Clock_Frequencies.SYSCLK); + when Src_48Mhz => + STM32.SDMMC.Set_Clk_Src_Speed + (This, 48_000_000); + end case; + end Set_Clock_Source; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2ENR.USART1EN := True; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1ENR.USART2EN := True; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1ENR.USART3EN := True; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2ENR.USART6EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2RSTR.USART1RST := True; + RCC_Periph.APB2RSTR.USART1RST := False; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1RSTR.UART2RST := True; + RCC_Periph.APB1RSTR.UART2RST := False; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1RSTR.UART3RST := True; + RCC_Periph.APB1RSTR.UART3RST := False; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2RSTR.USART6RST := True; + RCC_Periph.APB2RSTR.USART6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1ENR.SPI3EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant + UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant + UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2ENR.USART1EN := True; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1ENR.USART2EN := True; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1ENR.USART3EN := True; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1ENR.UART4EN := True; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1ENR.UART5EN := True; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2ENR.USART6EN := True; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1ENR.UART7ENR := True; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1ENR.UART8ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out USART) is + begin + if This.Periph.all'Address = USART1_Base then + RCC_Periph.APB2RSTR.USART1RST := True; + RCC_Periph.APB2RSTR.USART1RST := False; + elsif This.Periph.all'Address = USART2_Base then + RCC_Periph.APB1RSTR.UART2RST := True; + RCC_Periph.APB1RSTR.UART2RST := False; + elsif This.Periph.all'Address = USART3_Base then + RCC_Periph.APB1RSTR.UART3RST := True; + RCC_Periph.APB1RSTR.UART3RST := False; + elsif This.Periph.all'Address = UART4_Base then + RCC_Periph.APB1RSTR.UART4RST := True; + RCC_Periph.APB1RSTR.UART4RST := False; + elsif This.Periph.all'Address = UART5_Base then + RCC_Periph.APB1RSTR.UART5RST := True; + RCC_Periph.APB1RSTR.UART5RST := False; + elsif This.Periph.all'Address = USART6_Base then + RCC_Periph.APB2RSTR.USART6RST := True; + RCC_Periph.APB2RSTR.USART6RST := False; + elsif This.Periph.all'Address = UART7_Base then + RCC_Periph.APB1RSTR.UART7RST := True; + RCC_Periph.APB1RSTR.UART7RST := False; + elsif This.Periph.all'Address = UART8_Base then + RCC_Periph.APB1RSTR.UART8RST := True; + RCC_Periph.APB1RSTR.UART8RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base + or else + This.Periph.all'Address = I2S2ext_Base + then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base + or else + This.Periph.all'Address = I2S3ext_Base + then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Reset_All_ADC_Units is,"begin + RCC_Periph.APB2RSTR.ADCRST := True; + RCC_Periph.APB2RSTR.ADCRST := False; + end Reset_All_ADC_Units; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out Digital_To_Analog_Converter) + is + pragma Unreferenced (This); + begin + RCC_Periph.APB1ENR.DACEN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out Digital_To_Analog_Converter) is + pragma Unreferenced (This); + begin + RCC_Periph.APB1RSTR.DACRST := True; + RCC_Periph.APB1RSTR.DACRST := False; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + +-- procedure Enable_Clock (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2ENR.USART1EN := True; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1ENR.USART2EN := True; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1ENR.USART3EN := True; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1ENR.UART4EN := True; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1ENR.UART5EN := True; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2ENR.USART6EN := True; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1ENR.UART7ENR := True; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1ENR.UART8ENR := True; +-- else +-- raise Unknown_Device; +-- end if; +-- end Enable_Clock; + + ----------- + -- Reset -- + ----------- + +-- procedure Reset (This : aliased in out USART) is +-- begin +-- if This'Address = USART1_Base then +-- RCC_Periph.APB2RSTR.USART1RST := True; +-- RCC_Periph.APB2RSTR.USART1RST := False; +-- elsif This'Address = USART2_Base then +-- RCC_Periph.APB1RSTR.UART2RST := True; +-- RCC_Periph.APB1RSTR.UART2RST := False; +-- elsif This'Address = USART3_Base then +-- RCC_Periph.APB1RSTR.UART3RST := True; +-- RCC_Periph.APB1RSTR.UART3RST := False; +-- elsif This'Address = UART4_Base then +-- RCC_Periph.APB1RSTR.UART4RST := True; +-- RCC_Periph.APB1RSTR.UART4RST := False; +-- elsif This'Address = UART5_Base then +-- RCC_Periph.APB1RSTR.UART5RST := True; +-- RCC_Periph.APB1RSTR.UART5RST := False; +-- elsif This'Address = USART6_Base then +-- RCC_Periph.APB2RSTR.USART6RST := True; +-- RCC_Periph.APB2RSTR.USART6RST := False; +-- elsif This'Address = UART7_Base then +-- RCC_Periph.APB1RSTR.UART7RST := True; +-- RCC_Periph.APB1RSTR.UART7RST := False; +-- elsif This'Address = UART8_Base then +-- RCC_Periph.APB1RSTR.UART8RST := True; +-- RCC_Periph.APB1RSTR.UART8RST := False; +-- else +-- raise Unknown_Device; +-- end if; +-- end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1ENR.DMA1EN := True; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1ENR.DMA2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : aliased in out DMA_Controller) is + begin + if This'Address = STM32_SVD.DMA1_Base then + RCC_Periph.AHB1RSTR.DMA1RST := True; + RCC_Periph.AHB1RSTR.DMA1RST := False; + elsif This'Address = STM32_SVD.DMA2_Base then + RCC_Periph.AHB1RSTR.DMA2RST := True; + RCC_Periph.AHB1RSTR.DMA2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ---------------- + -- As_Port_Id -- + ---------------- + + function As_Port_Id (Port : I2C_Port'Class) return I2C_Port_Id is + begin + if Port.Periph.all'Address = I2C1_Base then + return I2C_Id_1; + elsif Port.Periph.all'Address = I2C2_Base then + return I2C_Id_2; + elsif Port.Periph.all'Address = I2C3_Base then + return I2C_Id_3; + elsif Port.Periph.all'Address = I2C4_Base then + return I2C_Id_4; + else + raise Unknown_Device; + end if; + end As_Port_Id; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : aliased I2C_Port'Class) is + begin + Enable_Clock (As_Port_Id (This)); + end Enable_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1ENR.I2C1EN := True; + when I2C_Id_2 => + RCC_Periph.APB1ENR.I2C2EN := True; + when I2C_Id_3 => + RCC_Periph.APB1ENR.I2C3EN := True; + when I2C_Id_4 => + RCC_Periph.APB1ENR.I2C4EN := True; + end case; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port'Class) is + begin + Reset (As_Port_Id (This)); + end Reset; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : I2C_Port_Id) is + begin + case This is + when I2C_Id_1 => + RCC_Periph.APB1RSTR.I2C1RST := True; + RCC_Periph.APB1RSTR.I2C1RST := False; + when I2C_Id_2 => + RCC_Periph.APB1RSTR.I2C2RST := True; + RCC_Periph.APB1RSTR.I2C2RST := False; + when I2C_Id_3 => + RCC_Periph.APB1RSTR.I2C3RST := True; + RCC_Periph.APB1RSTR.I2C3RST := False; + when I2C_Id_4 => + RCC_Periph.APB1RSTR.I2C4RST := True; + RCC_Periph.APB1RSTR.I2C4RST := False; + end case; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI4ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : SPI_Port'Class) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2ENR.SPI1EN := True; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1ENR.SPI2EN := True; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1ENR.SPI3EN := True; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2ENR.SPI5ENR := True; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2ENR.SPI6ENR := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out I2S_Port) is + begin + if This.Periph.all'Address = SPI1_Base then + RCC_Periph.APB2RSTR.SPI1RST := True; + RCC_Periph.APB2RSTR.SPI1RST := False; + elsif This.Periph.all'Address = SPI2_Base then + RCC_Periph.APB1RSTR.SPI2RST := True; + RCC_Periph.APB1RSTR.SPI2RST := False; + elsif This.Periph.all'Address = SPI3_Base then + RCC_Periph.APB1RSTR.SPI3RST := True; + RCC_Periph.APB1RSTR.SPI3RST := False; + elsif This.Periph.all'Address = SPI4_Base then + RCC_Periph.APB2RSTR.SPI4RST := True; + RCC_Periph.APB2RSTR.SPI4RST := False; + elsif This.Periph.all'Address = SPI5_Base then + RCC_Periph.APB2RSTR.SPI5RST := True; + RCC_Periph.APB2RSTR.SPI5RST := False; + elsif This.Periph.all'Address = SPI6_Base then + RCC_Periph.APB2RSTR.SPI6RST := True; + RCC_Periph.APB2RSTR.SPI6RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2ENR.TIM1EN := True; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1ENR.TIM2EN := True; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1ENR.TIM3EN := True; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1ENR.TIM4EN := True; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1ENR.TIM5EN := True; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1ENR.TIM6EN := True; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1ENR.TIM7EN := True; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2ENR.TIM8EN := True; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2ENR.TIM9EN := True; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2ENR.TIM10EN := True; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2ENR.TIM11EN := True; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1ENR.TIM12EN := True; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1ENR.TIM13EN := True; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1ENR.TIM14EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out Timer) is + begin + if This'Address = TIM1_Base then + RCC_Periph.APB2RSTR.TIM1RST := True; + RCC_Periph.APB2RSTR.TIM1RST := False; + elsif This'Address = TIM2_Base then + RCC_Periph.APB1RSTR.TIM2RST := True; + RCC_Periph.APB1RSTR.TIM2RST := False; + elsif This'Address = TIM3_Base then + RCC_Periph.APB1RSTR.TIM3RST := True; + RCC_Periph.APB1RSTR.TIM3RST := False; + elsif This'Address = TIM4_Base then + RCC_Periph.APB1RSTR.TIM4RST := True; + RCC_Periph.APB1RSTR.TIM4RST := False; + elsif This'Address = TIM5_Base then + RCC_Periph.APB1RSTR.TIM5RST := True; + RCC_Periph.APB1RSTR.TIM5RST := False; + elsif This'Address = TIM6_Base then + RCC_Periph.APB1RSTR.TIM6RST := True; + RCC_Periph.APB1RSTR.TIM6RST := False; + elsif This'Address = TIM7_Base then + RCC_Periph.APB1RSTR.TIM7RST := True; + RCC_Periph.APB1RSTR.TIM7RST := False; + elsif This'Address = TIM8_Base then + RCC_Periph.APB2RSTR.TIM8RST := True; + RCC_Periph.APB2RSTR.TIM8RST := False; + elsif This'Address = TIM9_Base then + RCC_Periph.APB2RSTR.TIM9RST := True; + RCC_Periph.APB2RSTR.TIM9RST := False; + elsif This'Address = TIM10_Base then + RCC_Periph.APB2RSTR.TIM10RST := True; + RCC_Periph.APB2RSTR.TIM10RST := False; + elsif This'Address = TIM11_Base then + RCC_Periph.APB2RSTR.TIM11RST := True; + RCC_Periph.APB2RSTR.TIM11RST := False; + elsif This'Address = TIM12_Base then + RCC_Periph.APB1RSTR.TIM12RST := True; + RCC_Periph.APB1RSTR.TIM12RST := False; + elsif This'Address = TIM13_Base then + RCC_Periph.APB1RSTR.TIM13RST := True; + RCC_Periph.APB1RSTR.TIM13RST := False; + elsif This'Address = TIM14_Base then + RCC_Periph.APB1RSTR.TIM14RST := True; + RCC_Periph.APB1RSTR.TIM14RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2ENR.SAI1EN := True; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2ENR.SAI2EN := True; + else + raise Unknown_Device; + end if; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SAI_Port) + is + begin + if This'Address = SAI1_Base then + RCC_Periph.APB2RSTR.SAI1RST := True; + RCC_Periph.APB2RSTR.SAI1RST := False; + elsif This'Address = SAI2_Base then + RCC_Periph.APB2RSTR.SAI2RST := True; + RCC_Periph.APB2RSTR.SAI2RST := False; + else + raise Unknown_Device; + end if; + end Reset; + + --------------------- + -- Get_Input_Clock -- + --------------------- + + function Get_Input_Clock (Periph : SAI_Port) return UInt32 + is + Input_Selector : UInt2; + VCO_Input : UInt32; + SAI_First_Level : UInt32; + begin + if Periph'Address = SAI1_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI1SEL; + elsif Periph'Address = SAI2_Base then + Input_Selector := RCC_Periph.DKCFGR1.SAI2SEL; + else + raise Unknown_Device; + end if; + + + -- This driver doesn't support external source clock + if Input_Selector > 1 then + raise Constraint_Error + with ""External PLL SAI source clock unsupported""; + end if; + + if not RCC_Periph.PLLCFGR.PLLSRC then + -- PLLSAI SRC is HSI + VCO_Input := HSI_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + else + -- PLLSAI SRC is HSE + VCO_Input := HSE_VALUE / UInt32 (RCC_Periph.PLLCFGR.PLLM); + end if; + + if Input_Selector = 0 then + -- PLLSAI is the clock source + + -- VCO out = VCO in & PLLSAIN + -- SAI firstlevel = VCO out / PLLSAIQ + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIN) / + UInt32 (RCC_Periph.PLLSAICFGR.PLLSAIQ); + + -- SAI frequency is SAI First level / PLLSAIDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLSAIDIVQ); + + else + -- PLLI2S as clock source + SAI_First_Level := + VCO_Input * UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SN) / + UInt32 (RCC_Periph.PLLI2SCFGR.PLLI2SQ); + -- SAI frequency is SAI First level / PLLI2SDIVQ + return SAI_First_Level / UInt32 (RCC_Periph.DKCFGR1.PLLI2SDIV + 1); + end if; + end Get_Input_Clock; + + ------------------ + -- Enable_Clock -- + ------------------ + + procedure Enable_Clock (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDMMC_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2ENR.SDMMC1EN := True; + end Enable_Clock; + + ----------- + -- Reset -- + ----------- + + procedure Reset (This : in out SDMMC_Controller) + is + begin + if This.Periph.all'Address /= SDMMC_Base then + raise Unknown_Device; + end if; + + RCC_Periph.APB2RSTR.SDMMC1RST := True; + RCC_Periph.APB2RSTR.SDMMC1RST := False; + end Reset; + + ---------------------- + -- Set_Clock_Source -- + ---------------------- + + procedure Set_Clock_Source + (This : in out SDMMC_Controller; + Src : SDMMC_Clock_Source) + is + begin + if This.Periph.all'Address /= SDMMC_Base then + raise Unknown_Device; + end if; + + RCC_Periph.DKCFGR2.SDMMCSEL := Src = Src_Sysclk; + + case Src is + when Src_Sysclk => + STM32.SDMMC.Set_Clk_Src_Speed + (This, System_Clock_Frequencies.SYSCLK); + when Src_48Mhz => + STM32.SDMMC.Set_Clk_Src_Speed + (This, 48_000_000); + end case; + end Set_Clock_Source; + + ------------------------------ + -- System_Clock_Frequencies -- + ------------------------------ + + function System_Clock_Frequencies return RCC_System_Clocks + is + Source : constant UInt2 := RCC_Periph.CFGR.SWS; + Result : RCC_System_Clocks; + begin + Result.I2SCLK := 0; + + case Source is + when 0 => + -- HSI as source + Result.SYSCLK := HSI_VALUE; + when 1 => + -- HSE as source + Result.SYSCLK := HSE_VALUE; + when 2 => + -- PLL as source + declare + HSE_Source : constant Boolean := RCC_Periph.PLLCFGR.PLLSRC; + Pllm : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLM); + Plln : constant UInt32 := + UInt32 (RCC_Periph.PLLCFGR.PLLN); + Pllp : constant UInt32 := + (UInt32 (RCC_Periph.PLLCFGR.PLLP) + 1) * 2; + Pllvco : UInt32; + begin + if not HSE_Source then + Pllvco := HSI_VALUE; + else + Pllvco := HSE_VALUE; + end if; + + Pllvco := Pllvco / Pllm; + + Result.I2SCLK := Pllvco; + + Pllvco := Pllvco * Plln; + + Result.SYSCLK := Pllvco / Pllp;" +procedure Disable,"(This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.EN1 := False; + when Channel_2 => + This.CR.EN2 := False; + end case; + end Disable; + + ------------- + -- Enabled -- + ------------- + + function Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean is + begin + case Channel is + when Channel_1 => + return This.CR.EN1; + when Channel_2 => + return This.CR.EN2; + end case; + end Enabled; + + ---------------- + -- Set_Output -- + ---------------- + + procedure Set_Output + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel; + Value : UInt32; + Resolution : DAC_Resolution; + Alignment : Data_Alignment) + is + begin + case Channel is + + when Channel_1 => + case Resolution is + when DAC_Resolution_12_Bits => + case Alignment is + when Left_Aligned => + This.DHR12L1.DACC1DHR := + UInt12 (Value and Max_12bit_Resolution); + when Right_Aligned => + This.DHR12R1.DACC1DHR := + UInt12 (Value and Max_12bit_Resolution); + end case; + when DAC_Resolution_8_Bits => + This.DHR8R1.DACC1DHR := UInt8 (Value and Max_8bit_Resolution); + end case; + + when Channel_2 => + case Resolution is + when DAC_Resolution_12_Bits => + case Alignment is + when Left_Aligned => + This.DHR12L2.DACC2DHR := + UInt12 (Value and Max_12bit_Resolution); + when Right_Aligned => + This.DHR12R2.DACC2DHR := + UInt12 (Value and Max_12bit_Resolution); + end case; + when DAC_Resolution_8_Bits => + This.DHR8R2.DACC2DHR := UInt8 (Value and Max_8bit_Resolution); + end case; + + end case; + end Set_Output; + + ------------------------------------ + -- Trigger_Conversion_By_Software -- + ------------------------------------ + + procedure Trigger_Conversion_By_Software + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.SWTRIGR.SWTRIG.Arr (1) := True; -- cleared by hardware + when Channel_2 => + This.SWTRIGR.SWTRIG.Arr (2) := True; -- cleared by hardware + end case; + end Trigger_Conversion_By_Software; + + ---------------------------- + -- Converted_Output_Value -- + ---------------------------- + + function Converted_Output_Value + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return UInt32 + is + begin + case Channel is + when Channel_1 => + return UInt32 (This.DOR1.DACC1DOR); + when Channel_2 => + return UInt32 (This.DOR2.DACC2DOR); + end case; + end Converted_Output_Value; + + ------------------------------ + -- Set_Dual_Output_Voltages -- + ------------------------------ + + procedure Set_Dual_Output_Voltages + (This : in out Digital_To_Analog_Converter; + Channel_1_Value : UInt32; + Channel_2_Value : UInt32; + Resolution : DAC_Resolution; + Alignment : Data_Alignment) + is + begin + case Resolution is + when DAC_Resolution_12_Bits => + case Alignment is + when Left_Aligned => + This.DHR12LD.DACC1DHR := + UInt12 (Channel_1_Value and Max_12bit_Resolution); + This.DHR12LD.DACC2DHR := + UInt12 (Channel_2_Value and Max_12bit_Resolution); + when Right_Aligned => + This.DHR12RD.DACC1DHR := + UInt12 (Channel_1_Value and Max_12bit_Resolution); + This.DHR12RD.DACC2DHR := + UInt12 (Channel_2_Value and Max_12bit_Resolution); + end case; + when DAC_Resolution_8_Bits => + This.DHR8RD.DACC1DHR := + UInt8 (Channel_1_Value and Max_8bit_Resolution); + This.DHR8RD.DACC2DHR := + UInt8 (Channel_2_Value and Max_8bit_Resolution); + end case; + end Set_Dual_Output_Voltages; + + --------------------------------- + -- Converted_Dual_Output_Value -- + --------------------------------- + + function Converted_Dual_Output_Value (This : Digital_To_Analog_Converter) + return Dual_Channel_Output + is + Result : Dual_Channel_Output; + begin + Result.Channel_1_Data := UInt16 (This.DOR1.DACC1DOR); + Result.Channel_2_Data := UInt16 (This.DOR2.DACC2DOR); + return Result; + end Converted_Dual_Output_Value; + + -------------------------- + -- Enable_Output_Buffer -- + -------------------------- + + procedure Enable_Output_Buffer + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.BOFF1 := True; + when Channel_2 => + This.CR.BOFF2 := True; + end case; + end Enable_Output_Buffer; + + --------------------------- + -- Disable_Output_Buffer -- + --------------------------- + + procedure Disable_Output_Buffer + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.BOFF1 := False; + when Channel_2 => + This.CR.BOFF2 := False; + end case; + end Disable_Output_Buffer; + + --------------------------- + -- Output_Buffer_Enabled -- + --------------------------- + + function Output_Buffer_Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean + is + begin + case Channel is + when Channel_1 => + return This.CR.BOFF1; + when Channel_2 => + return This.CR.BOFF2; + end case; + end Output_Buffer_Enabled; + + -------------------- + -- Select_Trigger -- + -------------------- + + procedure Select_Trigger + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel; + Trigger : External_Event_Trigger_Selection) + is + begin + case Channel is + when Channel_1 => + This.CR.TSEL1 := + External_Event_Trigger_Selection'Enum_Rep (Trigger); + when Channel_2 => + This.CR.TSEL2 := + External_Event_Trigger_Selection'Enum_Rep (Trigger); + end case; + end Select_Trigger; + + ----------------------- + -- Trigger_Selection -- + ----------------------- + + function Trigger_Selection + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return External_Event_Trigger_Selection + is + begin + case Channel is + when Channel_1 => + return External_Event_Trigger_Selection'Val (This.CR.TSEL1); + when Channel_2 => + return External_Event_Trigger_Selection'Val (This.CR.TSEL2); + end case; + end Trigger_Selection; + + -------------------- + -- Enable_Trigger -- + -------------------- + + procedure Enable_Trigger + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.TEN1 := True; + when Channel_2 => + This.CR.TEN2 := True; + end case; + end Enable_Trigger; + + --------------------- + -- Disable_Trigger -- + --------------------- + + procedure Disable_Trigger + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.TEN1 := False; + when Channel_2 => + This.CR.TEN2 := False; + end case; + end Disable_Trigger; + + --------------------- + -- Trigger_Enabled -- + --------------------- + + function Trigger_Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean + is + begin + case Channel is + when Channel_1 => + return This.CR.TEN1; + when Channel_2 => + return This.CR.TEN2; + end case; + end Trigger_Enabled; + + ---------------- + -- Enable_DMA -- + ---------------- + + procedure Enable_DMA + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.DMAEN1 := True; + when Channel_2 => + This.CR.DMAEN2 := True; + end case; + end Enable_DMA; + + ----------------- + -- Disable_DMA -- + ----------------- + + procedure Disable_DMA + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.CR.DMAEN1 := False; + when Channel_2 => + This.CR.DMAEN2 := False; + end case; + end Disable_DMA; + + ----------------- + -- DMA_Enabled -- + ----------------- + + function DMA_Enabled + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Boolean + is + begin + case Channel is + when Channel_1 => + return This.CR.DMAEN1; + when Channel_2 => + return This.CR.DMAEN2; + end case; + end DMA_Enabled; + + ------------ + -- Status -- + ------------ + + function Status + (This : Digital_To_Analog_Converter; + Flag : DAC_Status_Flag) + return Boolean + is + begin + case Flag is + when DMA_Underrun_Channel_1 => + return This.SR.DMAUDR1; + when DMA_Underrun_Channel_2 => + return This.SR.DMAUDR2; + end case; + end Status; + + ------------------ + -- Clear_Status -- + ------------------ + + procedure Clear_Status + (This : in out Digital_To_Analog_Converter; + Flag : DAC_Status_Flag) + is + begin + case Flag is + when DMA_Underrun_Channel_1 => + This.SR.DMAUDR1 := True; -- set to 1 to clear + when DMA_Underrun_Channel_2 => + This.SR.DMAUDR2 := True; -- set to 1 to clear + end case; + end Clear_Status; + + ----------------------- + -- Enable_Interrupts -- + ----------------------- + + procedure Enable_Interrupts + (This : in out Digital_To_Analog_Converter; + Source : DAC_Interrupts) + is + begin + case Source is + when DMA_Underrun_Channel_1 => + This.CR.DMAUDRIE1 := True; + when DMA_Underrun_Channel_2 => + This.CR.DMAUDRIE2 := True; + end case; + end Enable_Interrupts; + + ------------------------ + -- Disable_Interrupts -- + ------------------------ + + procedure Disable_Interrupts + (This : in out Digital_To_Analog_Converter; + Source : DAC_Interrupts) + is + begin + case Source is + when DMA_Underrun_Channel_1 => + This.CR.DMAUDRIE1 := False; + when DMA_Underrun_Channel_2 => + This.CR.DMAUDRIE2 := False; + end case; + end Disable_Interrupts; + + ----------------------- + -- Interrupt_Enabled -- + ----------------------- + + function Interrupt_Enabled + (This : Digital_To_Analog_Converter; + Source : DAC_Interrupts) + return Boolean + is + begin + case Source is + when DMA_Underrun_Channel_1 => + return This.CR.DMAUDRIE1; + when DMA_Underrun_Channel_2 => + return This.CR.DMAUDRIE2; + end case; + end Interrupt_Enabled; + + ---------------------- + -- Interrupt_Source -- + ---------------------- + + function Interrupt_Source + (This : Digital_To_Analog_Converter) + return DAC_Interrupts + is + begin + if This.CR.DMAUDRIE1 then + return DMA_Underrun_Channel_1; + else + return DMA_Underrun_Channel_2; + end if; + end Interrupt_Source; + + ----------------------------- + -- Clear_Interrupt_Pending -- + ----------------------------- + + procedure Clear_Interrupt_Pending + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel) + is + begin + case Channel is + when Channel_1 => + This.SR.DMAUDR1 := False; + when Channel_2 => + This.SR.DMAUDR2 := False; + end case; + end Clear_Interrupt_Pending; + + ---------------------------- + -- Select_Wave_Generation -- + ---------------------------- + + procedure Select_Wave_Generation + (This : in out Digital_To_Analog_Converter; + Channel : DAC_Channel; + Selection : Wave_Generation) + is + + function As_UInt4 is new Ada.Unchecked_Conversion + (Source => Noise_Wave_Mask_Selection, Target => UInt4); + + function As_UInt4 is new Ada.Unchecked_Conversion + (Source => Triangle_Wave_Amplitude_Selection, Target => UInt4); + + begin + case Channel is + when Channel_1 => + This.CR.WAVE1 := + Wave_Generation_Selection'Enum_Rep (Selection.Kind); + when Channel_2 => + This.CR.WAVE2 := + Wave_Generation_Selection'Enum_Rep (Selection.Kind); + end case; + + case Selection.Kind is + + when No_Wave_Generation => + null; + + when Noise_Wave => + case Channel is + when Channel_1 => + This.CR.MAMP1 := As_UInt4 (Selection.Mask); + when Channel_2 => + This.CR.MAMP2 := As_UInt4 (Selection.Mask); + end case; + + when Triangle_Wave => + case Channel is + when Channel_1 => + This.CR.MAMP1 := As_UInt4 (Selection.Amplitude); + when Channel_2 => + This.CR.MAMP2 := As_UInt4 (Selection.Amplitude); + end case; + + end case; + end Select_Wave_Generation; + + ------------------------------ + -- Selected_Wave_Generation -- + ------------------------------ + + function Selected_Wave_Generation + (This : Digital_To_Analog_Converter; + Channel : DAC_Channel) + return Wave_Generation + is + Kind : Wave_Generation_Selection; + + function As_Mask is new Ada.Unchecked_Conversion + (Target => Noise_Wave_Mask_Selection, Source => UInt4); + + function As_Amplitude is new Ada.Unchecked_Conversion + (Target => Triangle_Wave_Amplitude_Selection, Source => UInt4); + + begin + case Channel is + when Channel_1 => + Kind := Wave_Generation_Selection'Val (This.CR.WAVE1); + when Channel_2 => + Kind := Wave_Generation_Selection'Val (This.CR.WAVE2); + end case; + declare + Result : Wave_Generation (Kind); + begin + case Kind is + when No_Wave_Generation => + null; + + when Noise_Wave => + case Channel is + when Channel_1 => + Result.Mask := As_Mask (This.CR.MAMP1); + when Channel_2 => + Result.Mask := As_Mask (This.CR.MAMP2); + end case; + + when Triangle_Wave => + case Channel is + when Channel_1 => + Result.Amplitude := As_Amplitude (This.CR.MAMP1); + when Channel_2 => + Result.Amplitude := As_Amplitude (This.CR.MAMP2); + end case; + end case; + + return Result;" +procedure Disable (This : in out Analog_To_Digital_Converter) is,"begin + This.CR2.ADON := False; + end Disable; + + ------------- + -- Enabled -- + ------------- + + function Enabled (This : Analog_To_Digital_Converter) return Boolean is + (This.CR2.ADON); + + ---------------------- + -- Conversion_Value -- + ---------------------- + + function Conversion_Value + (This : Analog_To_Digital_Converter) + return UInt16 + is + begin + return This.DR.DATA; + end Conversion_Value; + + --------------------------- + -- Data_Register_Address -- + --------------------------- + + function Data_Register_Address + (This : Analog_To_Digital_Converter) + return System.Address + is + (This.DR'Address); + + ------------------------------- + -- Injected_Conversion_Value -- + ------------------------------- + + function Injected_Conversion_Value + (This : Analog_To_Digital_Converter; + Rank : Injected_Channel_Rank) + return UInt16 + is + begin + case Rank is + when 1 => + return This.JDR1.JDATA; + when 2 => + return This.JDR2.JDATA; + when 3 => + return This.JDR3.JDATA; + when 4 => + return This.JDR4.JDATA; + end case; + end Injected_Conversion_Value; + + -------------------------------- + -- Multimode_Conversion_Value -- + -------------------------------- + + function Multimode_Conversion_Value return UInt32 is + (C_ADC_Periph.CDR.Val); + + -------------------- + -- Configure_Unit -- + -------------------- + + procedure Configure_Unit + (This : in out Analog_To_Digital_Converter; + Resolution : ADC_Resolution; + Alignment : Data_Alignment) + is + begin + This.CR1.RES := ADC_Resolution'Enum_Rep (Resolution); + This.CR2.ALIGN := Alignment = Left_Aligned; + end Configure_Unit; + + ------------------------ + -- Current_Resolution -- + ------------------------ + + function Current_Resolution + (This : Analog_To_Digital_Converter) + return ADC_Resolution + is (ADC_Resolution'Val (This.CR1.RES)); + + ----------------------- + -- Current_Alignment -- + ----------------------- + + function Current_Alignment + (This : Analog_To_Digital_Converter) + return Data_Alignment + is ((if This.CR2.ALIGN then Left_Aligned else Right_Aligned)); + + --------------------------------- + -- Configure_Common_Properties -- + --------------------------------- + + procedure Configure_Common_Properties + (Mode : Multi_ADC_Mode_Selections; + Prescalar : ADC_Prescalars; + DMA_Mode : Multi_ADC_DMA_Modes; + Sampling_Delay : Sampling_Delay_Selections) + is + begin + C_ADC_Periph.CCR.MULT := Multi_ADC_Mode_Selections'Enum_Rep (Mode); + C_ADC_Periph.CCR.DELAY_k := + Sampling_Delay_Selections'Enum_Rep (Sampling_Delay); + C_ADC_Periph.CCR.DMA := Multi_ADC_DMA_Modes'Enum_Rep (DMA_Mode); + C_ADC_Periph.CCR.ADCPRE := ADC_Prescalars'Enum_Rep (Prescalar); + end Configure_Common_Properties; + + ----------------------------------- + -- Configure_Regular_Conversions -- + ----------------------------------- + + procedure Configure_Regular_Conversions + (This : in out Analog_To_Digital_Converter; + Continuous : Boolean; + Trigger : Regular_Channel_Conversion_Trigger; + Enable_EOC : Boolean; + Conversions : Regular_Channel_Conversions) + is + begin + This.CR2.EOCS := Enable_EOC; + This.CR2.CONT := Continuous; + + This.CR1.SCAN := Conversions'Length > 1; + + if Trigger.Enabler /= Trigger_Disabled then + This.CR2.EXTSEL := External_Events_Regular_Group'Enum_Rep (Trigger.Event); + This.CR2.EXTEN := External_Trigger'Enum_Rep (Trigger.Enabler); + else + This.CR2.EXTSEL := 0; + This.CR2.EXTEN := 0; + end if; + + for Rank in Conversions'Range loop + declare + Conversion : Regular_Channel_Conversion renames Conversions (Rank); + begin + Configure_Regular_Channel + (This, Conversion.Channel, Rank, Conversion.Sample_Time); + + -- We check the VBat first because that channel is also used for + -- the temperature sensor channel on some MCUs, in which case the + -- VBat conversion is the only one done. This order reflects that + -- hardware behavior. + if VBat_Conversion (This, Conversion.Channel) then + Enable_VBat_Connection; + elsif VRef_TemperatureSensor_Conversion (This, Conversion.Channel) + then + Enable_VRef_TemperatureSensor_Connection; + end if;" +procedure Disable_Interrupt,"(This : in out SDMMC_Controller; + Interrupt : SDMMC_Interrupts) + is + begin + case Interrupt is + when Data_End_Interrupt => + This.Periph.MASK.DATAENDIE := False; + when Data_CRC_Fail_Interrupt => + This.Periph.MASK.DCRCFAILIE := False; + when Data_Timeout_Interrupt => + This.Periph.MASK.DTIMEOUTIE := False; + when TX_FIFO_Empty_Interrupt => + This.Periph.MASK.TXFIFOEIE := False; + when RX_FIFO_Full_Interrupt => + This.Periph.MASK.RXFIFOFIE := False; + when TX_Underrun_Interrupt => + This.Periph.MASK.TXUNDERRIE := False; + when RX_Overrun_Interrupt => + This.Periph.MASK.RXOVERRIE := False; + end case; + end Disable_Interrupt; + + ------------------------ + -- Delay_Milliseconds -- + ------------------------ + + overriding procedure Delay_Milliseconds + (This : SDMMC_Controller; + Amount : Natural) + is + pragma Unreferenced (This); + begin + delay until Clock + Milliseconds (Amount); + end Delay_Milliseconds; + + ----------- + -- Reset -- + ----------- + + overriding procedure Reset + (This : in out SDMMC_Controller; + Status : out SD_Error) + is + begin + -- Make sure the POWER register is writable by waiting a bit after + -- the Power_Off command + DCTRL_Write_Delay; + + This.Periph.POWER.PWRCTRL := Power_Off; + + -- Use the Default SDMMC peripheral configuration for SD card init + This.Periph.CLKCR := (others => <>); + This.Set_Clock (400_000); + This.Periph.DTIMER := SD_DATATIMEOUT; + + This.Periph.CLKCR.CLKEN := False; + DCTRL_Write_Delay; + This.Periph.POWER.PWRCTRL := Power_On; + + -- Wait for the clock to stabilize. + DCTRL_Write_Delay; + + This.Periph.CLKCR.CLKEN := True; + + delay until Clock + Milliseconds (20); + + Status := OK; + end Reset; + + --------------- + -- Set_Clock -- + --------------- + + overriding procedure Set_Clock + (This : in out SDMMC_Controller; + Freq : Natural) + is + Div : UInt32; + CLKCR : CLKCR_Register; + begin + Div := (This.CLK_In + UInt32 (Freq) - 1) / UInt32 (Freq); + + -- Make sure the POWER register is writable by waiting a bit after + -- the Power_Off command + DCTRL_Write_Delay; + + if Div <= 1 then + This.Periph.CLKCR.BYPASS := True; + else + Div := Div - 2; + CLKCR := This.Periph.CLKCR; + CLKCR.BYPASS := False; + + if Div > UInt32 (CLKCR_CLKDIV_Field'Last) then + CLKCR.CLKDIV := CLKCR_CLKDIV_Field'Last; + else + CLKCR.CLKDIV := CLKCR_CLKDIV_Field (Div); + end if; + + This.Periph.CLKCR := CLKCR; + end if; + end Set_Clock; + + ------------------ + -- Set_Bus_Size -- + ------------------ + + overriding procedure Set_Bus_Size + (This : in out SDMMC_Controller; + Mode : Wide_Bus_Mode) + is + function To_WIDBUS_Field is new Ada.Unchecked_Conversion + (Wide_Bus_Mode, CLKCR_WIDBUS_Field); + begin + This.Periph.CLKCR.WIDBUS := To_WIDBUS_Field (Mode); + end Set_Bus_Size; + + ------------------ + -- Send_Command -- + ------------------ + + overriding procedure Send_Cmd + (This : in out SDMMC_Controller; + Cmd : Cmd_Desc_Type; + Arg : UInt32; + Status : out SD_Error) + is + CMD_Reg : CMD_Register := This.Periph.CMD; + begin + if Cmd.Rsp = Rsp_Invalid or else Cmd.Tfr = Tfr_Invalid then + raise Program_Error with ""Not implemented""; + end if; + + This.Periph.ARG := Arg; + CMD_Reg.CMDINDEX := CMD_CMDINDEX_Field (Cmd.Cmd); + CMD_Reg.WAITRESP := (case Cmd.Rsp is + when Rsp_No => No_Response, + when Rsp_R2 => Long_Response, + when others => Short_Response); + CMD_Reg.WAITINT := False; + CMD_Reg.CPSMEN := True; + This.Periph.CMD := CMD_Reg; + + case Cmd.Rsp is + when Rsp_No => + Status := This.Command_Error; + + when Rsp_R1 | Rsp_R1B => + Status := This.Response_R1_Error (Cmd.Cmd); + + when Rsp_R2 => + Status := This.Response_R2_Error; + + when Rsp_R3 => + Status := This.Response_R3_Error; + + when Rsp_R6 => + declare + RCA : UInt32; + begin + Status := This.Response_R6_Error (Cmd.Cmd, RCA); + This.RCA := UInt16 (Shift_Right (RCA, 16));" +procedure Disable_Data,"(This : in out SDMMC_Controller) + is + begin + This.Periph.DCTRL := (others => <>); + end Disable_Data; + + -------------------------- + -- Enable_DMA_Transfers -- + -------------------------- + + procedure Enable_DMA_Transfers + (This : in out SDMMC_Controller; + RX_Int : not null STM32.DMA.Interrupts.DMA_Interrupt_Controller_Access; + TX_Int : not null STM32.DMA.Interrupts.DMA_Interrupt_Controller_Access; + SD_Int : not null STM32.SDMMC_Interrupt.SDMMC_Interrupt_Handler_Access) + is + begin + This.TX_DMA_Int := TX_Int; + This.RX_DMA_Int := RX_Int; + This.SD_Int := SD_Int; + end Enable_DMA_Transfers; + + -------------------------- + -- Has_Card_Information -- + -------------------------- + + function Has_Card_Information + (This : SDMMC_Controller) + return Boolean + is (This.Has_Info); + + ---------------------- + -- Card_Information -- + ---------------------- + + function Card_Information + (This : SDMMC_Controller) + return HAL.SDMMC.Card_Information + is + begin + return This.Info; + end Card_Information; + + ---------------------------- + -- Clear_Card_Information -- + ---------------------------- + + procedure Clear_Card_Information + (This : in out SDMMC_Controller) + is + begin + This.Has_Info := False; + end Clear_Card_Information; + + --------------- + -- Read_FIFO -- + --------------- + + function Read_FIFO + (Controller : in out SDMMC_Controller) return UInt32 + is + begin + return Controller.Periph.FIFO; + end Read_FIFO; + + ------------------- + -- Command_Error -- + ------------------- + + function Command_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + Start : constant Time := Clock; + begin + while not Controller.Periph.STA.CMDSENT loop + if Clock - Start > Milliseconds (1000) then + return Timeout_Error; + end if; + end loop; + + Clear_Static_Flags (Controller); + + return OK; + end Command_Error; + + ----------------------- + -- Response_R1_Error -- + ----------------------- + + function Response_R1_Error + (Controller : in out SDMMC_Controller; + Command_Index : SD_Command) return SD_Error + is + Start : constant Time := Clock; + Timeout : Boolean := False; + R1 : UInt32; + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + if Clock - Start > Milliseconds (1000) then + Timeout := True; + + exit; + end if; + end loop; + + if Timeout or else Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + end if; + + if SD_Command (Controller.Periph.RESPCMD.RESPCMD) /= + Command_Index + then + return Illegal_Cmd; + end if; + + Clear_Static_Flags (Controller); + + R1 := Controller.Periph.RESP1; + + if (R1 and SD_OCR_ERRORMASK) = 0 then + return OK; + end if; + + if (R1 and SD_OCR_ADDR_OUT_OF_RANGE) /= 0 then + return Address_Out_Of_Range; + elsif (R1 and SD_OCR_ADDR_MISALIGNED) /= 0 then + return Address_Missaligned; + elsif (R1 and SD_OCR_BLOCK_LEN_ERR) /= 0 then + return Block_Length_Error; + elsif (R1 and SD_OCR_ERASE_SEQ_ERR) /= 0 then + return Erase_Seq_Error; + elsif (R1 and SD_OCR_BAD_ERASE_PARAM) /= 0 then + return Bad_Erase_Parameter; + elsif (R1 and SD_OCR_WRITE_PROT_VIOLATION) /= 0 then + return Write_Protection_Violation; + elsif (R1 and SD_OCR_LOCK_UNLOCK_FAILED) /= 0 then + return Lock_Unlock_Failed; + elsif (R1 and SD_OCR_COM_CRC_FAILED) /= 0 then + return CRC_Check_Fail; + elsif (R1 and SD_OCR_ILLEGAL_CMD) /= 0 then + return Illegal_Cmd; + elsif (R1 and SD_OCR_CARD_ECC_FAILED) /= 0 then + return Card_ECC_Failed; + elsif (R1 and SD_OCR_CC_ERROR) /= 0 then + return CC_Error; + elsif (R1 and SD_OCR_GENERAL_UNKNOWN_ERROR) /= 0 then + return General_Unknown_Error; + elsif (R1 and SD_OCR_STREAM_READ_UNDERRUN) /= 0 then + return Stream_Read_Underrun; + elsif (R1 and SD_OCR_STREAM_WRITE_UNDERRUN) /= 0 then + return Stream_Write_Underrun; + elsif (R1 and SD_OCR_CID_CSD_OVERWRITE) /= 0 then + return CID_CSD_Overwrite; + elsif (R1 and SD_OCR_WP_ERASE_SKIP) /= 0 then + return WP_Erase_Skip; + elsif (R1 and SD_OCR_CARD_ECC_DISABLED) /= 0 then + return Card_ECC_Disabled; + elsif (R1 and SD_OCR_ERASE_RESET) /= 0 then + return Erase_Reset; + elsif (R1 and SD_OCR_AKE_SEQ_ERROR) /= 0 then + return AKE_SEQ_Error; + else + return General_Unknown_Error; + end if; + end Response_R1_Error; + + ----------------------- + -- Response_R2_Error -- + ----------------------- + + function Response_R2_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + null; + end loop; + + if Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + end if; + + Clear_Static_Flags (Controller); + + return OK; + end Response_R2_Error; + + ----------------------- + -- Response_R3_Error -- + ----------------------- + + function Response_R3_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + null; + end loop; + + if Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + end if; + + Clear_Static_Flags (Controller); + + return OK; + end Response_R3_Error; + + ----------------------- + -- Response_R6_Error -- + ----------------------- + + function Response_R6_Error + (Controller : in out SDMMC_Controller; + Command_Index : SD_Command; + RCA : out UInt32) return SD_Error + is + Response : UInt32; + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + null; + end loop; + + if Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + end if; + + if SD_Command (Controller.Periph.RESPCMD.RESPCMD) /= + Command_Index + then + return Illegal_Cmd; + end if; + + Clear_Static_Flags (Controller); + + Response := Controller.Periph.RESP1; + + if (Response and SD_R6_Illegal_Cmd) = SD_R6_Illegal_Cmd then + return Illegal_Cmd; + + elsif (Response and SD_R6_General_Unknown_Error) = + SD_R6_General_Unknown_Error + then + return General_Unknown_Error; + + elsif (Response and SD_R6_Com_CRC_Failed) = SD_R6_Com_CRC_Failed then + return CRC_Check_Fail; + end if; + + RCA := Response and 16#FFFF_0000#; + + return OK; + end Response_R6_Error; + + ----------------------- + -- Response_R7_Error -- + ----------------------- + + function Response_R7_Error + (Controller : in out SDMMC_Controller) return SD_Error + is + Start : constant Time := Clock; + Timeout : Boolean := False; + begin + while not Controller.Periph.STA.CCRCFAIL + and then not Controller.Periph.STA.CMDREND + and then not Controller.Periph.STA.CTIMEOUT + loop + if Clock - Start > Milliseconds (1000) then + Timeout := True; + + exit; + end if; + end loop; + + if Timeout or else Controller.Periph.STA.CTIMEOUT then + -- Card is not v2.0 compliant or card does not support the set + -- voltage range + Controller.Periph.ICR.CTIMEOUTC := True; + + return Timeout_Error; + + elsif Controller.Periph.STA.CCRCFAIL then + Controller.Periph.ICR.CCRCFAILC := True; + + return CRC_Check_Fail; + + elsif Controller.Periph.STA.CMDREND then + Controller.Periph.ICR.CMDRENDC := True; + + return OK; + + else + return Error; + end if; + end Response_R7_Error; + + ------------------- + -- Stop_Transfer -- + ------------------- + + function Stop_Transfer + (This : in out SDMMC_Controller) return SD_Error + is + Ret : SD_Error; + begin + Send_Cmd (This, Cmd_Desc (Stop_Transmission), 0, Ret); + + return Ret; + end Stop_Transfer; + + ----------------------- + -- Set_Clk_Src_Speed -- + ----------------------- + + procedure Set_Clk_Src_Speed + (This : in out SDMMC_Controller; + CLK : UInt32) + is + begin + This.CLK_In := CLK; + end Set_Clk_Src_Speed; + + ---------------- + -- Initialize -- + ---------------- + + function Initialize + (This : in out SDMMC_Controller) return SD_Error + is + Ret : SD_Error; + begin + SDMMC_Init.Card_Identification_Process (This, This.Info, Ret); + This.Card_Type := This.Info.Card_Type; + This.RCA := This.Info.RCA; + + return Ret; + end Initialize; + + ---------- + -- Read -- + ---------- + + overriding + function Read + (This : in out SDMMC_Controller; + Block_Number : UInt64; + Data : out HAL.Block_Drivers.Block) return Boolean + is + Ret : Boolean; + SD_Err : SD_Error; + DMA_Err : DMA_Error_Code; + begin + + Ensure_Card_Informations (This); + + if This.RX_DMA_Int = null or else This.SD_Int = null then + SD_Err := Read_Blocks + (This, + Block_Number * 512, + Data); + return SD_Err = OK; + end if; + + This.SD_Int.Set_Transfer_State (This); + + SD_Err := Read_Blocks_DMA + (This, + Block_Number * 512, + Data); + + if SD_Err /= OK then + This.RX_DMA_Int.Clear_Transfer_State; + This.SD_Int.Clear_Transfer_State; + This.RX_DMA_Int.Abort_Transfer (DMA_Err); + + return False; + end if; + + This.SD_Int.Wait_Transfer (SD_Err); + + if SD_Err /= OK then + This.RX_DMA_Int.Clear_Transfer_State; + else + This.RX_DMA_Int.Wait_For_Completion (DMA_Err); + + loop + exit when not Get_Flag (This, RX_Active); + end loop; + end if; + + Ret := SD_Err = OK and then DMA_Err = DMA_No_Error; + + if Last_Operation (This) = + Read_Multiple_Blocks_Operation + then + SD_Err := Stop_Transfer (This); + Ret := Ret and then SD_Err = OK; + end if; + + Clear_All_Status (This.RX_DMA_Int.Controller.all, This.RX_DMA_Int.Stream); + Disable (This.RX_DMA_Int.Controller.all, This.RX_DMA_Int.Stream); + Disable_Data (This); + Clear_Static_Flags (This); + + Cortex_M.Cache.Invalidate_DCache + (Start => Data'Address, + Len => Data'Length); + + return Ret; + end Read; + + ----------- + -- Write -- + ----------- + + overriding + function Write + (This : in out SDMMC_Controller; + Block_Number : UInt64; + Data : HAL.Block_Drivers.Block) return Boolean + is + Ret : SD_Error; + DMA_Err : DMA_Error_Code; + begin + if This.TX_DMA_Int = null then + raise Program_Error with ""No TX DMA controller""; + end if; + + if This.SD_Int = null then + raise Program_Error with ""No SD interrupt controller""; + end if; + + Ensure_Card_Informations (This); + + -- Flush the data cache + Cortex_M.Cache.Clean_DCache + (Start => Data (Data'First)'Address, + Len => Data'Length); + + This.SD_Int.Set_Transfer_State (This); + + Ret := Write_Blocks_DMA + (This, + Block_Number * 512, + Data); + -- this always leaves the last 12 byte standing. Why? + -- also...NDTR is not what it should be. + + if Ret /= OK then + This.TX_DMA_Int.Clear_Transfer_State; + This.SD_Int.Clear_Transfer_State; + This.TX_DMA_Int.Abort_Transfer (DMA_Err); + + return False; + end if; + + This.TX_DMA_Int.Wait_For_Completion (DMA_Err); -- this unblocks + This.SD_Int.Wait_Transfer (Ret); -- TX underrun! + + -- this seems slow. Do we have to wait? + loop + -- FIXME: some people claim, that this goes wrong with multiblock, see + -- http://blog.frankvh.com/2011/09/04/stm32f2xx-sdio-sd-card-interface/ + exit when not Get_Flag (This, TX_Active); + end loop; + + if Last_Operation (This) = + Write_Multiple_Blocks_Operation + then + Ret := Stop_Transfer (This); + end if; + + Clear_All_Status (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream); + Disable (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream); + + declare + Data_Incomplete : constant Boolean := + This.TX_DMA_Int.Buffer_Error and then + Items_Transferred (This.TX_DMA_Int.Controller.all, This.TX_DMA_Int.Stream) + /= Data'Length / 4; + begin + return Ret = OK + and then DMA_Err = DMA_No_Error + and then not Data_Incomplete;" +"function To_Word is new Ada.Unchecked_Conversion (System.Address, UInt32);","function Offset (Buffer : DMA2D_Buffer; + X, Y : Integer) return UInt32 with Inline_Always; + + DMA2D_Init_Transfer_Int : DMA2D_Sync_Procedure := null; + DMA2D_Wait_Transfer_Int : DMA2D_Sync_Procedure := null; + + ------------------ + -- DMA2D_DeInit -- + ------------------ + + procedure DMA2D_DeInit is + begin + RCC_Periph.AHB1ENR.DMA2DEN := False; + DMA2D_Init_Transfer_Int := null; + DMA2D_Wait_Transfer_Int := null; + end DMA2D_DeInit; + + ---------------- + -- DMA2D_Init -- + ---------------- + + procedure DMA2D_Init + (Init : DMA2D_Sync_Procedure; + Wait : DMA2D_Sync_Procedure) + is + begin + if DMA2D_Init_Transfer_Int = Init then + return; + end if; + + DMA2D_DeInit; + + DMA2D_Init_Transfer_Int := Init; + DMA2D_Wait_Transfer_Int := Wait; + + RCC_Periph.AHB1ENR.DMA2DEN := True; + RCC_Periph.AHB1RSTR.DMA2DRST := True; + RCC_Periph.AHB1RSTR.DMA2DRST := False; + end DMA2D_Init; + + ------------ + -- Offset -- + ------------ + + function Offset (Buffer : DMA2D_Buffer; + X, Y : Integer) return UInt32 + is + Off : constant UInt32 := UInt32 (X + Buffer.Width * Y); + begin + case Buffer.Color_Mode is + when ARGB8888 => + return 4 * Off; + when RGB888 => + return 3 * Off; + when ARGB1555 | ARGB4444 | RGB565 | AL88 => + return 2 * Off; + when L8 | AL44 | A8 => + return Off; + when L4 | A4 => + return Off / 2; + end case; + end Offset; + + ---------------- + -- DMA2D_Fill -- + ---------------- + + procedure DMA2D_Fill + (Buffer : DMA2D_Buffer; + Color : UInt32; + Synchronous : Boolean := False) + is + function Conv is new Ada.Unchecked_Conversion (UInt32, OCOLR_Register); + begin + DMA2D_Wait_Transfer_Int.all; + + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (R2M); + DMA2D_Periph.OPFCCR.CM := As_UInt3 (Buffer.Color_Mode); + DMA2D_Periph.OCOLR := Conv (Color); + DMA2D_Periph.OMAR := To_Word (Buffer.Addr); + DMA2D_Periph.OOR := (LO => 0, others => <>); + DMA2D_Periph.NLR := (NL => UInt16 (Buffer.Height), + PL => UInt14 (Buffer.Width), + others => <>); + + DMA2D_Init_Transfer_Int.all; + + if Synchronous then + DMA2D_Wait_Transfer_Int.all; + end if; + end DMA2D_Fill; + + --------------------- + -- DMA2D_Fill_Rect -- + --------------------- + + procedure DMA2D_Fill_Rect + (Buffer : DMA2D_Buffer; + Color : UInt32; + X : Integer; + Y : Integer; + Width : Integer; + Height : Integer; + Synchronous : Boolean := False) + is + function Conv is new Ada.Unchecked_Conversion (UInt32, OCOLR_Register); + Off : constant UInt32 := Offset (Buffer, X, Y); + + begin + DMA2D_Wait_Transfer_Int.all; + + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (R2M); + DMA2D_Periph.OPFCCR := + (CM => DMA2D_Color_Mode'Enum_Rep (Buffer.Color_Mode), + others => <>); + DMA2D_Periph.OCOLR := Conv (Color); + DMA2D_Periph.OMAR := To_Word (Buffer.Addr) + Off; + DMA2D_Periph.OOR.LO := UInt14 (Buffer.Width - Width); + DMA2D_Periph.NLR := + (NL => UInt16 (Height), PL => UInt14 (Width), others => <>); + + DMA2D_Init_Transfer_Int.all; + if Synchronous then + DMA2D_Wait_Transfer_Int.all; + end if; + end DMA2D_Fill_Rect; + + --------------------- + -- DMA2D_Draw_Rect -- + --------------------- + + procedure DMA2D_Draw_Rect + (Buffer : DMA2D_Buffer; + Color : UInt32; + X : Integer; + Y : Integer; + Width : Integer; + Height : Integer) + is + begin + DMA2D_Draw_Horizontal_Line (Buffer, Color, X, Y, Width); + DMA2D_Draw_Horizontal_Line (Buffer, Color, X, Y + Height - 1, Width); + DMA2D_Draw_Vertical_Line (Buffer, Color, X, Y, Height); + DMA2D_Draw_Vertical_Line (Buffer, Color, X + Width - 1, Y, Height, True); + end DMA2D_Draw_Rect; + + --------------------- + -- DMA2D_Copy_Rect -- + --------------------- + + procedure DMA2D_Copy_Rect + (Src_Buffer : DMA2D_Buffer; + X_Src : Natural; + Y_Src : Natural; + Dst_Buffer : DMA2D_Buffer; + X_Dst : Natural; + Y_Dst : Natural; + Bg_Buffer : DMA2D_Buffer; + X_Bg : Natural; + Y_Bg : Natural; + Width : Natural; + Height : Natural; + Synchronous : Boolean := False) + is + Src_Off : constant UInt32 := Offset (Src_Buffer, X_Src, Y_Src); + Dst_Off : constant UInt32 := Offset (Dst_Buffer, X_Dst, Y_Dst); + begin + DMA2D_Wait_Transfer_Int.all; + + if Bg_Buffer /= Null_Buffer then + -- PFC and blending + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (M2M_BLEND); + + elsif Src_Buffer.Color_Mode = Dst_Buffer.Color_Mode then + -- Direct memory transfer + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (M2M); + else + DMA2D_Periph.CR.MODE := DMA2D_MODE'Enum_Rep (M2M_PFC); + end if; + + -- SOURCE CONFIGURATION + DMA2D_Periph.FGPFCCR := + (CM => DMA2D_Color_Mode'Enum_Rep (Src_Buffer.Color_Mode), + AM => DMA2D_AM'Enum_Rep (NO_MODIF), + ALPHA => 255, + others => <>); + + if Src_Buffer.Color_Mode = L8 or else Src_Buffer.Color_Mode = L4 then + + if Src_Buffer.CLUT_Addr = System.Null_Address then + raise Program_Error with ""Source CLUT address required""; + end if; + + DMA2D_Periph.FGCMAR := To_Word (Src_Buffer.CLUT_Addr); + + DMA2D_Periph.FGCMAR := To_Word (Src_Buffer.CLUT_Addr); + DMA2D_Periph.FGPFCCR.CS := (case Src_Buffer.Color_Mode is + when L8 => 2**8 - 1, + when L4 => 2**4 - 1, + when others => 0); + -- Set CLUT mode to RGB888 + DMA2D_Periph.FGPFCCR.CCM := Src_Buffer.CLUT_Color_Mode = RGB888; + + -- Start loading the CLUT + DMA2D_Periph.FGPFCCR.START := True; + + while DMA2D_Periph.FGPFCCR.START loop + -- Wait for CLUT loading... + null; + end loop; + end if; + + DMA2D_Periph.FGOR := (LO => UInt14 (Src_Buffer.Width - Width), + others => <>); + DMA2D_Periph.FGMAR := To_Word (Src_Buffer.Addr) + Src_Off; + + if Bg_Buffer /= Null_Buffer then + declare + Bg_Off : constant UInt32 := Offset (Bg_Buffer, X_Bg, Y_Bg); + begin + DMA2D_Periph.BGPFCCR.CM := + DMA2D_Color_Mode'Enum_Rep (Bg_Buffer.Color_Mode); + DMA2D_Periph.BGMAR := To_Word (Bg_Buffer.Addr) + Bg_Off; + DMA2D_Periph.BGPFCCR.CS := 0; + DMA2D_Periph.BGPFCCR.START := False; + DMA2D_Periph.BGOR := + (LO => UInt14 (Bg_Buffer.Width - Width), others => <>); + + if Bg_Buffer.Color_Mode = L8 or else Bg_Buffer.Color_Mode = L4 then + + if Bg_Buffer.CLUT_Addr = System.Null_Address then + raise Program_Error with ""Background CLUT address required""; + end if; + + DMA2D_Periph.BGCMAR := To_Word (Bg_Buffer.CLUT_Addr); + DMA2D_Periph.BGPFCCR.CS := (case Bg_Buffer.Color_Mode is + when L8 => 2**8 - 1, + when L4 => 2**4 - 1, + when others => 0); + -- Set CLUT mode to RGB888 + DMA2D_Periph.BGPFCCR.CCM := Bg_Buffer.CLUT_Color_Mode = RGB888; + + -- Start loading the CLUT + DMA2D_Periph.BGPFCCR.START := True; + + while DMA2D_Periph.BGPFCCR.START loop + -- Wait for CLUT loading... + null; + end loop; + end if;" +procedure Demo_Timer_PWM is -- low-level demo of the PWM capabilities,"Period : constant := 1000; + + Output_Channel : constant Timer_Channel := Channel_2; + -- The LED driven by this example is determined by the channel selected. + -- That is so because each channel of Timer_4 is connected to a specific + -- LED in the alternate function configuration on this board. We will + -- initialize all of the LEDs to be in the AF mode for Timer_4. The + -- particular channel selected is completely arbitrary, as long as the + -- selected GPIO port/pin for the LED matches the selected channel. + -- + -- Channel_1 is connected to the green LED. + -- Channel_2 is connected to the orange LED. + -- Channel_3 is connected to the red LED. + -- Channel_4 is connected to the blue LED. + + -------------------- + -- Configure_LEDs -- + -------------------- + + procedure Configure_LEDs; + + procedure Configure_LEDs is + begin + Enable_Clock (GPIO_D); + + Configure_IO + (All_LEDs, + (Mode_AF, + AF => GPIO_AF_TIM4_2, + AF_Speed => Speed_50MHz, + AF_Output_Type => Push_Pull, + Resistors => Floating)); + end Configure_LEDs; + + -- The SFP run-time library for these boards is intended for certified + -- environments and so does not contain the full set of facilities defined + -- by the Ada language. The elementary functions are not included, for + -- example. In contrast, the Ravenscar ""full"" run-times do have these + -- functions. + + function Sine (Input : Long_Float) return Long_Float; + + -- Therefore there are four choices: 1) use the ""ravescar-full-stm32f4"" + -- runtime library, 2) pull the sources for the language-defined elementary + -- function package into the board's run-time library and rebuild the + -- run-time, 3) pull the sources for those packages into the source + -- directory of your application and rebuild your application, or 4) roll + -- your own approximation to the functions required by your application. + + -- In this demonstration we roll our own approximation to the sine function + -- so that it doesn't matter which runtime library is used. + + function Sine (Input : Long_Float) return Long_Float is + Pi : constant Long_Float := 3.14159_26535_89793_23846; + X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0); + B : constant Long_Float := 4.0 / Pi; + C : constant Long_Float := (-4.0) / (Pi * Pi); + Y : constant Long_Float := B * X + C * X * abs (X); + P : constant Long_Float := 0.225; + begin + return P * (Y * abs (Y) - Y) + Y; + end Sine; + + -- We use the sine function to drive the power applied to the LED, thereby + -- making the LED increase and decrease in brightness. We attach the timer + -- to the LED and then control how much power is supplied by changing the + -- value of the timer's output compare register. The sine function drives + -- that value, thus the waxing/waning effect. + +begin + Configure_LEDs; + + Enable_Clock (Timer_4); + + Reset (Timer_4); + + Configure + (Timer_4, + Prescaler => 1, + Period => Period, + Clock_Divisor => Div1, + Counter_Mode => Up); + + Configure_Channel_Output + (Timer_4, + Channel => Output_Channel, + Mode => PWM1, + State => Enable, + Pulse => 0, + Polarity => High); + + Set_Autoreload_Preload (Timer_4, True); + + Enable_Channel (Timer_4, Output_Channel); + + Enable (Timer_4); + + declare + Arg : Long_Float := 0.0; + Pulse : UInt16; + Increment : constant Long_Float := 0.00003; + -- The Increment value controls the rate at which the brightness + -- increases and decreases. The value is more or less arbitrary, but + -- note that the effect of optimization is observable. + begin + loop + Pulse := UInt16 (Long_Float (Period / 2) * (1.0 + Sine (Arg))); + Set_Compare_Value (Timer_4, Output_Channel, Pulse); + Arg := Arg + Increment; + end loop;" +procedure Demo_PWM_ADT is -- demo the higher-level PWM abstract data type,"Selected_Timer : STM32.Timers.Timer renames Timer_4; + -- NOT arbitrary! We drive the on-board LEDs that are tied to the channels + -- of Timer_4 on some boards. Not all boards have this association. If you + -- use a different board, select a GPIO point connected to your selected + -- timer and drive that instead. + + Timer_AF : constant STM32.GPIO_Alternate_Function := GPIO_AF_TIM4_2; + -- Note that this value MUST match the corresponding timer selected! + + Output_Channel : constant Timer_Channel := Channel_2; -- arbitrary + -- The LED driven by this example is determined by the channel selected. + -- That is so because each channel of Timer_4 is connected to a specific + -- LED in the alternate function configuration on this board. We will + -- initialize all of the LEDs to be in the AF mode. The + -- particular channel selected is completely arbitrary, as long as the + -- selected GPIO port/pin for the LED matches the selected channel. + -- + -- Channel_1 is connected to the green LED. + -- Channel_2 is connected to the orange LED. + -- Channel_3 is connected to the red LED. + -- Channel_4 is connected to the blue LED. + LED_For : constant array (Timer_Channel) of User_LED := + (Channel_1 => Green_LED, + Channel_2 => Orange_LED, + Channel_3 => Red_LED, + Channel_4 => Blue_LED); + + Requested_Frequency : constant Hertz := 30_000; -- arbitrary + + Power_Control : PWM_Modulator; + + -- The SFP run-time library for these boards is intended for certified + -- environments and so does not contain the full set of facilities defined + -- by the Ada language. The elementary functions are not included, for + -- example. In contrast, the Ravenscar ""full"" run-times do have these + -- functions. + function Sine (Input : Long_Float) return Long_Float; + + -- Therefore there are four choices: 1) use the ""ravescar-full-stm32f4"" + -- runtime library, 2) pull the sources for the language-defined elementary + -- function package into the board's run-time library and rebuild the + -- run-time, 3) pull the sources for those packages into the source + -- directory of your application and rebuild your application, or 4) roll + -- your own approximation to the functions required by your application. + + -- In this demonstration we roll our own approximation to the sine function + -- so that it doesn't matter which runtime library is used. + + function Sine (Input : Long_Float) return Long_Float is + Pi : constant Long_Float := 3.14159_26535_89793_23846; + X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0); + B : constant Long_Float := 4.0 / Pi; + C : constant Long_Float := (-4.0) / (Pi * Pi); + Y : constant Long_Float := B * X + C * X * abs (X); + P : constant Long_Float := 0.225; + begin + return P * (Y * abs (Y) - Y) + Y; + end Sine; + + -- We use the sine function to drive the power applied to the LED, thereby + -- making the LED increase and decrease in brightness. We attach the timer + -- to the LED and then control how much power is supplied by changing the + -- value of the timer's output compare register. The sine function drives + -- that value, thus the waxing/waning effect. + +begin + Configure_PWM_Timer (Selected_Timer'Access, Requested_Frequency); + + Power_Control.Attach_PWM_Channel + (Selected_Timer'Access, + Output_Channel, + LED_For (Output_Channel), + Timer_AF); + + Power_Control.Enable_Output; + + declare + Arg : Long_Float := 0.0; + Value : Percentage; + Increment : constant Long_Float := 0.00003; + -- The Increment value controls the rate at which the brightness + -- increases and decreases. The value is more or less arbitrary, but + -- note that the effect of compiler optimization is observable. + begin + loop + Value := Percentage (50.0 * (1.0 + Sine (Arg))); + Power_Control.Set_Duty_Cycle (Value); + Arg := Arg + Increment; + end loop;" +procedure Demo_DAC_Basic is,"Output_Channel : constant DAC_Channel := Channel_1; -- arbitrary + + procedure Configure_DAC_GPIO (Output_Channel : DAC_Channel); + -- Once the channel is enabled, the corresponding GPIO pin is automatically + -- connected to the analog converter output. However, in order to avoid + -- parasitic consumption, the PA4 pin (Channel_1) or PA5 pin (Channel_2) + -- should first be configured to analog mode. See the note in the RM, page + -- 431. + + procedure Print (Value : UInt32); + -- Prints the image of the arg at a fixed location + + procedure Await_Button; + -- Wait for the user to press and then release the blue user button + + ----------- + -- Print -- + ----------- + + procedure Print (Value : UInt32) is + Value_Image : constant String := Value'Img; + begin + LCD_Std_Out.Put (170, 52, Value_Image (2 .. Value_Image'Last) & "" ""); + end Print; + + ------------------ + -- Await_Button -- + ------------------ + + procedure Await_Button is + begin + Await_Pressed : loop + exit Await_Pressed when Set (User_Button_Point); + end loop Await_Pressed; + + Await_Released : loop + exit Await_Released when not Set (User_Button_Point); + end loop Await_Released; + end Await_Button; + + ------------------------ + -- Configure_DAC_GPIO -- + ------------------------ + + procedure Configure_DAC_GPIO (Output_Channel : DAC_Channel) is + Output : constant GPIO_Point := (if Output_Channel = Channel_1 + then DAC_Channel_1_IO + else DAC_Channel_2_IO); + begin + Enable_Clock (Output); + Configure_IO (Output, (Mode => Mode_Analog, Resistors => Floating)); + end Configure_DAC_GPIO; + +begin + Initialize_LEDs; + All_LEDs_Off; + + LCD_Std_Out.Clear_Screen; + + Configure_User_Button_GPIO; + + Configure_DAC_GPIO (Output_Channel); + + Enable_Clock (DAC_1); + + Reset (DAC_1); + + Select_Trigger (DAC_1, Output_Channel, Software_Trigger); + + Enable_Trigger (DAC_1, Output_Channel); + + Enable (DAC_1, Output_Channel); + + declare + Value : UInt32 := 0; + Percent : UInt32; + + Resolution : constant DAC_Resolution := DAC_Resolution_12_Bits; + -- Arbitrary, change as desired. Counts will automatically adjust. + + Max_Counts : constant UInt32 := (if Resolution = DAC_Resolution_12_Bits + then Max_12bit_Resolution + else Max_8bit_Resolution); + begin + Put (0, 0, ""VRef+ is 2.95V""); -- measured + Put (0, 25, ""Button advances""); + Put (0, 52, ""Current %:""); + loop + for K in UInt32 range 0 .. 10 loop + Percent := K * 10; + Print (Percent); + + Value := (Percent * Max_Counts) / 100; + + Set_Output + (DAC_1, + Output_Channel, + Value, + Resolution, + Right_Aligned); + + Trigger_Conversion_By_Software (DAC_1, Output_Channel); + + Await_Button; + end loop; + end loop;" +procedure Demo_CRC is,"Checksum_CPU : UInt32 := 0; + -- the checksum obtained by calling a routine that uses the CPU to transfer + -- the memory block to the CRC processor + + Checksum_DMA : UInt32 := 0; + -- the checksum obtained by calling a routine that uses DMA to transfer the + -- memory block to the CRC processor + + -- see the STM32Cube_FW_F4_V1.6.0\Projects\ CRC example for data and + -- expected CRC checksum value + + Section1 : constant Block_32 := + (16#00001021#, 16#20423063#, 16#408450A5#, 16#60C670E7#, 16#9129A14A#, 16#B16BC18C#, + 16#D1ADE1CE#, 16#F1EF1231#, 16#32732252#, 16#52B54294#, 16#72F762D6#, 16#93398318#, + 16#A35AD3BD#, 16#C39CF3FF#, 16#E3DE2462#, 16#34430420#, 16#64E674C7#, 16#44A45485#, + 16#A56AB54B#, 16#85289509#, 16#F5CFC5AC#, 16#D58D3653#, 16#26721611#, 16#063076D7#, + 16#569546B4#, 16#B75BA77A#, 16#97198738#, 16#F7DFE7FE#, 16#C7BC48C4#, 16#58E56886#, + 16#78A70840#, 16#18612802#, 16#C9CCD9ED#, 16#E98EF9AF#, 16#89489969#, 16#A90AB92B#, + 16#4AD47AB7#, 16#6A961A71#, 16#0A503A33#, 16#2A12DBFD#, 16#FBBFEB9E#, 16#9B798B58#, + 16#BB3BAB1A#, 16#6CA67C87#, 16#5CC52C22#, 16#3C030C60#, 16#1C41EDAE#, 16#FD8FCDEC#, + 16#AD2ABD0B#, 16#8D689D49#, 16#7E976EB6#, 16#5ED54EF4#, 16#2E321E51#, 16#0E70FF9F#); + + Section2 : constant Block_32 := + (16#EFBEDFDD#, 16#CFFCBF1B#, 16#9F598F78#, 16#918881A9#, 16#B1CAA1EB#, 16#D10CC12D#, + 16#E16F1080#, 16#00A130C2#, 16#20E35004#, 16#40257046#, 16#83B99398#, 16#A3FBB3DA#, + 16#C33DD31C#, 16#E37FF35E#, 16#129022F3#, 16#32D24235#, 16#52146277#, 16#7256B5EA#, + 16#95A88589#, 16#F56EE54F#, 16#D52CC50D#, 16#34E224C3#, 16#04817466#, 16#64475424#, + 16#4405A7DB#, 16#B7FA8799#, 16#E75FF77E#, 16#C71DD73C#, 16#26D336F2#, 16#069116B0#, + 16#76764615#, 16#5634D94C#, 16#C96DF90E#, 16#E92F99C8#, 16#B98AA9AB#, 16#58444865#, + 16#78066827#, 16#18C008E1#, 16#28A3CB7D#, 16#DB5CEB3F#, 16#FB1E8BF9#, 16#9BD8ABBB#, + 16#4A755A54#, 16#6A377A16#, 16#0AF11AD0#, 16#2AB33A92#, 16#ED0FDD6C#, 16#CD4DBDAA#, + 16#AD8B9DE8#, 16#8DC97C26#, 16#5C644C45#, 16#3CA22C83#, 16#1CE00CC1#, 16#EF1FFF3E#, + 16#DF7CAF9B#, 16#BFBA8FD9#, 16#9FF86E17#, 16#7E364E55#, 16#2E933EB2#, 16#0ED11EF0#); + + -- expected CRC value for the data above is 379E9F06 hex, or 933142278 dec + Expected_Checksum : constant UInt32 := 933142278; + + Next_DMA_Interrupt : DMA_Interrupt; + + procedure Panic with No_Return; + -- flash the on-board LEDs, indefinitely, to indicate a failure + + procedure Panic is + begin + loop + Toggle_LEDs (All_LEDs); + delay until Clock + Milliseconds (100); + end loop; + end Panic; + +begin + Clear_Screen; + Initialize_LEDs; + + Enable_Clock (CRC_Unit); + + -- get the checksum using the CPU to transfer memory to the CRC processor; + -- verify it is the expected value + + Update_CRC (CRC_Unit, Input => Section1, Output => Checksum_CPU); + Update_CRC (CRC_Unit, Input => Section2, Output => Checksum_CPU); + + Put_Line (""CRC:"" & Checksum_CPU'Img); + + if Checksum_CPU /= Expected_Checksum then + Panic; + end if; + + -- get the checksum using DMA to transfer memory to the CRC processor + + Enable_Clock (Controller); + + Reset (Controller); + + Reset_Calculator (CRC_Unit); + + Update_CRC (CRC_Unit, Controller'Access, Stream, Input => Section1); + + DMA_IRQ_Handler.Await_Event (Next_DMA_Interrupt); + + if Next_DMA_Interrupt /= Transfer_Complete_Interrupt then + Panic; + end if; + + -- In this code fragment we use the approach suited for the case in which + -- we are calculating the CRC for a section of system memory rather than a + -- block of application data. We pretend that Section2 is a memory section. + -- All we need is a known starting address and a known length. Given that, + -- we can create a view of it as if it is an object of type Block_32 (or + -- whichever block type is appropriate). + declare + subtype Memory_Section is Block_32 (1 .. Section2'Length); + type Section_Pointer is access all Memory_Section with Storage_Size => 0; + function As_Memory_Section_Reference is new Ada.Unchecked_Conversion + (Source => System.Address, Target => Section_Pointer); + begin + Update_CRC + (CRC_Unit, + Controller'Access, + Stream, + Input => As_Memory_Section_Reference (Section2'Address).all);" +procedure DSB is,"begin + Asm (""dsb"", Volatile => True); + end DSB; + + --------- + -- ISB -- + --------- + + procedure ISB is + begin + Asm (""isb"", Volatile => True); + end ISB; + + ----------------------- + -- Cache_Maintenance -- + ----------------------- + + procedure Cache_Maintenance + (Start : System.Address; + Len : Natural) + is + begin + if not D_Cache_Enabled then + return; + end if; + + declare + function To_U32 is new Ada.Unchecked_Conversion + (System.Address, UInt32); + + Op_Size : Integer_32 := Integer_32 (Len); + Op_Addr : UInt32 := To_U32 (Start); + Reg : UInt32 with Volatile, Address => Reg_Address; + + begin + DSB; + + while Op_Size > 0 loop + Reg := Op_Addr; + Op_Addr := Op_Addr + Data_Cache_Line_Size; + Op_Size := Op_Size - Integer_32 (Data_Cache_Line_Size); + end loop; + + DSB; + ISB;" +"function To_Char is new Ada.Unchecked_Conversion (Source => UInt8,","Target => Character); + function To_UInt8 is new Ada.Unchecked_Conversion (Source => Character, + Target => UInt8); + + procedure Write (This : in out TP_Device; Cmd : String); + procedure Read (This : in out TP_Device; Str : out String); + + ----------- + -- Write -- + ----------- + + procedure Write (This : in out TP_Device; Cmd : String) is + Status : UART_Status; + Data : UART_Data_8b (Cmd'Range); + begin + + for Index in Cmd'Range loop + Data (Index) := To_UInt8 (Cmd (Index)); + end loop; + + This.Port.Transmit (Data, Status); + + if Status /= Ok then + -- No error handling... + raise Program_Error; + end if; + -- This.Time.Delay_Microseconds ((11 * 1000000 / 19_2000) + Cmd'Length); + end Write; + + ---------- + -- Read -- + ---------- + + procedure Read (This : in out TP_Device; Str : out String) is + Status : UART_Status; + Data : UART_Data_8b (Str'Range); + begin + This.Port.Receive (Data, Status); + if Status /= Ok then + -- No error handling... + raise Program_Error; + end if; + + for Index in Str'Range loop + Str (Index) := To_Char (Data (Index)); + end loop; + end Read; + + ---------------------- + -- Set_Line_Spacing -- + ---------------------- + + procedure Set_Line_Spacing (This : in out TP_Device; Spacing : UInt8) is + begin + Write (This, ASCII.ESC & '3' & To_Char (Spacing)); + end Set_Line_Spacing; + + --------------- + -- Set_Align -- + --------------- + + procedure Set_Align (This : in out TP_Device; Align : Text_Align) is + Mode : Character; + begin + case Align is + when Left => Mode := '0'; + when Center => Mode := '1'; + when Right => Mode := '2'; + end case; + Write (This, ASCII.ESC & 'a' & Mode); + end Set_Align; + + ---------------------- + -- Set_Font_Enlarge -- + ---------------------- + + procedure Set_Font_Enlarge (This : in out TP_Device; Height, Width : Boolean) is + Data : UInt8 := 0; + begin + if Height then + Data := Data or 16#01#; + end if; + if Width then + Data := Data or 16#10#; + end if; + Write (This, ASCII.GS & '!' & To_Char (Data)); + end Set_Font_Enlarge; + + -------------- + -- Set_Bold -- + -------------- + + procedure Set_Bold (This : in out TP_Device; Bold : Boolean) is + begin + Write (This, ASCII.ESC & 'E' & To_Char (if Bold then 1 else 0)); + end Set_Bold; + + ---------------------- + -- Set_Double_Width -- + ---------------------- + + procedure Set_Double_Width (This : in out TP_Device; Double : Boolean) is + begin + if Double then + Write (This, ASCII.ESC & ASCII.SO); + else + Write (This, ASCII.ESC & ASCII.DC4); + end if; + end Set_Double_Width; + + ---------------- + -- Set_UpDown -- + ---------------- + + procedure Set_UpDown (This : in out TP_Device; UpDown : Boolean) is + begin + Write (This, ASCII.ESC & '{' & To_Char (if UpDown then 1 else 0)); + end Set_UpDown; + + ------------------ + -- Set_Reversed -- + ------------------ + + procedure Set_Reversed (This : in out TP_Device; Reversed : Boolean) is + begin + Write (This, ASCII.GS & 'B' & To_Char (if Reversed then 1 else 0)); + end Set_Reversed; + + -------------------------- + -- Set_Underline_Height -- + -------------------------- + + procedure Set_Underline_Height (This : in out TP_Device; Height : Underline_Height) is + begin + Write (This, ASCII.ESC & '-' & To_Char (Height)); + end Set_Underline_Height; + + ----------------------- + -- Set_Character_Set -- + ----------------------- + + procedure Set_Character_Set (This : in out TP_Device; Set : Character_Set) is + begin + Write (This, ASCII.ESC & 't' & To_Char (Character_Set'Pos (Set))); + end Set_Character_Set; + + ---------- + -- Feed -- + ---------- + + procedure Feed (This : in out TP_Device; Rows : UInt8) is + begin + Write (This, ASCII.ESC & 'd' & To_Char (Rows)); + end Feed; + + ------------------ + -- Print_Bitmap -- + ------------------ + + procedure Print_Bitmap (This : in out TP_Device; + BM : Thermal_Printer_Bitmap) + is + Nbr_Of_Rows : constant Natural := BM'Length (2); + Nbr_Of_Columns : constant Natural := BM'Length (1); + Str : String (1 .. Nbr_Of_Columns / 8); + begin + + Write (This, ASCII.DC2 & 'v' & + To_Char (UInt8 (Nbr_Of_Rows rem 256)) & + To_Char (UInt8 (Nbr_Of_Rows / 256))); + + for Row in 0 .. Nbr_Of_Rows - 1 loop + for Colum in 0 .. (Nbr_Of_Columns / 8) - 1 loop + declare + BM_Index : constant Natural := BM'First (1) + Colum * 8; + Str_Index : constant Natural := Str'First + Colum; + B : UInt8 := 0; + begin + for X in 0 .. 7 loop + B := B or (if BM (BM_Index + X, + BM'First (2) + Row) + then 2**X else 0); + end loop; + Str (Str_Index) := To_Char (B);" +function As_UInt8 is new Ada.Unchecked_Conversion,"(Source => High_Pass_Filter_Mode, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => High_Pass_Cutoff_Frequency, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Power_Mode_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Output_Data_Rate_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Axes_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Bandwidth_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Block_Data_Update_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Endian_Data_Selection, Target => UInt8); + + function As_UInt8 is new Ada.Unchecked_Conversion + (Source => Full_Scale_Selection, Target => UInt8); + + type Angle_Rate_Pointer is access all Angle_Rate with Storage_Size => 0; + + function As_Angle_Rate_Pointer is new Ada.Unchecked_Conversion + (Source => System.Address, Target => Angle_Rate_Pointer); + -- So that we can treat the address of a UInt8 as a pointer to a two-UInt8 + -- sequence representing a signed integer quantity. + + procedure Swap2 (Location : System.Address) with Inline; + -- Swaps the two UInt8s at Location and Location+1 + + procedure SPI_Mode (This : Three_Axis_Gyroscope; Enabled : Boolean); + -- Enable or disable SPI mode communication with the device. This is named + -- ""chip select"" in other demos/examples. + + ---------------- + -- Initialize -- + ---------------- + + procedure Initialize + (This : in out Three_Axis_Gyroscope; + Port : Any_SPI_Port; + Chip_Select : Any_GPIO_Point) + is + begin + This.Port := Port; + This.CS := Chip_Select; + + SPI_Mode (This, Enabled => False); + end Initialize; + + ----------------- + -- SPI_Mode -- + ----------------- + + procedure SPI_Mode (This : Three_Axis_Gyroscope; Enabled : Boolean) is + -- When the pin is low (cleared), the device is in SPI mode. + -- When the pin is high (set), the device is in I2C mode. + -- We want SPI mode communication, so Enabled, when True, + -- means we must drive the pin low. + begin + if Enabled then + This.CS.Clear; + else + This.CS.Set; + end if; + end SPI_Mode; + + ----------- + -- Write -- + ----------- + + procedure Write (This : Three_Axis_Gyroscope; Addr : Register; Data : UInt8) + is + Status : SPI_Status; + begin + SPI_Mode (This, Enabled => True); + + This.Port.Transmit (SPI_Data_8b'(1 => UInt8 (Addr)), Status); + if Status /= Ok then + raise Program_Error; + end if; + + This.Port.Transmit (SPI_Data_8b'(1 => Data), Status); + if Status /= Ok then + raise Program_Error; + end if; + + SPI_Mode (This, Enabled => False); + end Write; + + ---------- + -- Read -- + ---------- + + procedure Read + (This : Three_Axis_Gyroscope; + Addr : Register; + Data : out UInt8) + is + Status : SPI_Status; + Tmp_Data : SPI_Data_8b (1 .. 1); + begin + SPI_Mode (This, Enabled => True); + + This.Port.Transmit (SPI_Data_8b'(1 => UInt8 (Addr) or ReadWrite_CMD), + Status); + if Status /= Ok then + raise Program_Error; + end if; + + This.Port.Receive (Tmp_Data, Status); + if Status /= Ok then + raise Program_Error; + end if; + Data := Tmp_Data (Tmp_Data'First); + + SPI_Mode (This, Enabled => False); + end Read; + + ---------------- + -- Read_UInt8s -- + ---------------- + + procedure Read_UInt8s + (This : Three_Axis_Gyroscope; + Addr : Register; + Buffer : out SPI_Data_8b; + Count : Natural) + is + Index : Natural := Buffer'First; + Status : SPI_Status; + Tmp_Data : SPI_Data_8b (1 .. 1); + begin + SPI_Mode (This, Enabled => True); + + This.Port.Transmit + (SPI_Data_8b'(1 => UInt8 (Addr) or ReadWrite_CMD or MultiUInt8_CMD), + Status); + + if Status /= Ok then + raise Program_Error; + end if; + + for K in 1 .. Count loop + This.Port.Receive (Tmp_Data, Status); + if Status /= Ok then + raise Program_Error; + end if; + Buffer (Index) := Tmp_Data (Tmp_Data'First); + Index := Index + 1; + end loop; + + SPI_Mode (This, Enabled => False); + end Read_UInt8s; + + --------------- + -- Configure -- + --------------- + + procedure Configure + (This : in out Three_Axis_Gyroscope; + Power_Mode : Power_Mode_Selection; + Output_Data_Rate : Output_Data_Rate_Selection; + Axes_Enable : Axes_Selection; + Bandwidth : Bandwidth_Selection; + BlockData_Update : Block_Data_Update_Selection; + Endianness : Endian_Data_Selection; + Full_Scale : Full_Scale_Selection) + is + Ctrl1 : UInt8; + Ctrl4 : UInt8; + begin + Ctrl1 := As_UInt8 (Power_Mode) or + As_UInt8 (Output_Data_Rate) or + As_UInt8 (Axes_Enable) or + As_UInt8 (Bandwidth); + + Ctrl4 := As_UInt8 (BlockData_Update) or + As_UInt8 (Endianness) or + As_UInt8 (Full_Scale); + + Write (This, CTRL_REG1, Ctrl1); + Write (This, CTRL_REG4, Ctrl4); + end Configure; + + ----------- + -- Sleep -- + ----------- + + procedure Sleep (This : in out Three_Axis_Gyroscope) is + Ctrl1 : UInt8; + Sleep_Mode : constant := 2#1000#; -- per the Datasheet, Table 22, pg 32 + begin + Read (This, CTRL_REG1, Ctrl1); + Ctrl1 := Ctrl1 or Sleep_Mode; + Write (This, CTRL_REG1, Ctrl1); + end Sleep; + + -------------------------------- + -- Configure_High_Pass_Filter -- + -------------------------------- + + procedure Configure_High_Pass_Filter + (This : in out Three_Axis_Gyroscope; + Mode_Selection : High_Pass_Filter_Mode; + Cutoff_Frequency : High_Pass_Cutoff_Frequency) + is + Ctrl2 : UInt8; + begin + -- note that the two high-order bits must remain zero, per the datasheet + Ctrl2 := As_UInt8 (Mode_Selection) or As_UInt8 (Cutoff_Frequency); + Write (This, CTRL_REG2, Ctrl2); + end Configure_High_Pass_Filter; + + ----------------------------- + -- Enable_High_Pass_Filter -- + ----------------------------- + + procedure Enable_High_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- set HPen bit + Ctrl5 := Ctrl5 or HighPass_Filter_Enable; + Write (This, CTRL_REG5, Ctrl5); + end Enable_High_Pass_Filter; + + ------------------------------ + -- Disable_High_Pass_Filter -- + ------------------------------ + + procedure Disable_High_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- clear HPen bit + Ctrl5 := Ctrl5 and (not HighPass_Filter_Enable); + Write (This, CTRL_REG5, Ctrl5); + end Disable_High_Pass_Filter; + + ---------------------------- + -- Enable_Low_Pass_Filter -- + ---------------------------- + + procedure Enable_Low_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + Ctrl5 := Ctrl5 or LowPass_Filter_Enable; + Write (This, CTRL_REG5, Ctrl5); + end Enable_Low_Pass_Filter; + + ----------------------------- + -- Disable_Low_Pass_Filter -- + ----------------------------- + + procedure Disable_Low_Pass_Filter (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- clear HPen bit + Ctrl5 := Ctrl5 and (not LowPass_Filter_Enable); + Write (This, CTRL_REG5, Ctrl5); + end Disable_Low_Pass_Filter; + + --------------------- + -- Reference_Value -- + --------------------- + + function Reference_Value (This : Three_Axis_Gyroscope) return UInt8 is + Result : UInt8; + begin + Read (This, Reference, Result); + return Result; + end Reference_Value; + + ------------------- + -- Set_Reference -- + ------------------- + + procedure Set_Reference (This : in out Three_Axis_Gyroscope; Value : UInt8) is + begin + Write (This, Reference, Value); + end Set_Reference; + + ----------------- + -- Data_Status -- + ----------------- + + function Data_Status (This : Three_Axis_Gyroscope) return Gyro_Data_Status is + Result : UInt8; + function As_Gyro_Data_Status is + new Ada.Unchecked_Conversion (Source => UInt8, + Target => Gyro_Data_Status); + begin + Read (This, Status, Result); + return As_Gyro_Data_Status (Result); + end Data_Status; + + --------------- + -- Device_Id -- + --------------- + + function Device_Id (This : Three_Axis_Gyroscope) return UInt8 is + Result : UInt8; + begin + Read (This, Who_Am_I, Result); + return Result; + end Device_Id; + + ----------------- + -- Temperature -- + ----------------- + + function Temperature (This : Three_Axis_Gyroscope) return UInt8 is + Result : UInt8; + begin + Read (This, OUT_Temp, Result); + return Result; + end Temperature; + + ------------ + -- Reboot -- + ------------ + + procedure Reboot (This : Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + -- set the boot bit + Ctrl5 := Ctrl5 or Boot_Bit; + Write (This, CTRL_REG5, Ctrl5); + end Reboot; + + ---------------------------- + -- Full_Scale_Sensitivity -- + ---------------------------- + + function Full_Scale_Sensitivity (This : Three_Axis_Gyroscope) return Float is + Ctrl4 : UInt8; + Result : Float; + Fullscale_Selection : UInt8; + begin + Read (This, CTRL_REG4, Ctrl4); + + Fullscale_Selection := Ctrl4 and Fullscale_Selection_Bits; + + if Fullscale_Selection = L3GD20_Fullscale_250'Enum_Rep then + Result := Sensitivity_250dps; + elsif Fullscale_Selection = L3GD20_Fullscale_500'Enum_Rep then + Result := Sensitivity_500dps; + else + Result := Sensitivity_2000dps; + end if; + + return Result; + end Full_Scale_Sensitivity; + + ------------------------- + -- Get_Raw_Angle_Rates -- + ------------------------- + + procedure Get_Raw_Angle_Rates + (This : Three_Axis_Gyroscope; + Rates : out Angle_Rates) + is + + Ctrl4 : UInt8; + + UInt8s_To_Read : constant Integer := 6; -- ie, three 2-UInt8 integers + -- the number of UInt8s in an Angle_Rates record object + + Received : SPI_Data_8b (1 .. UInt8s_To_Read); + + begin + Read (This, CTRL_REG4, Ctrl4); + + Read_UInt8s (This, OUT_X_L, Received, UInt8s_To_Read); + -- The above has the effect of separate reads, as follows: + -- Read (This, OUT_X_L, Received (1)); + -- Read (This, OUT_X_H, Received (2)); + -- Read (This, OUT_Y_L, Received (3)); + -- Read (This, OUT_Y_H, Received (4)); + -- Read (This, OUT_Z_L, Received (5)); + -- Read (This, OUT_Z_H, Received (6)); + + if (Ctrl4 and Endian_Selection_Mask) = L3GD20_Big_Endian'Enum_Rep then + Swap2 (Received (1)'Address); + Swap2 (Received (3)'Address); + Swap2 (Received (5)'Address); + end if; + + Rates.X := As_Angle_Rate_Pointer (Received (1)'Address).all; + Rates.Y := As_Angle_Rate_Pointer (Received (3)'Address).all; + Rates.Z := As_Angle_Rate_Pointer (Received (5)'Address).all; + end Get_Raw_Angle_Rates; + + -------------------------- + -- Configure_Interrupt1 -- + -------------------------- + + procedure Configure_Interrupt1 + (This : in out Three_Axis_Gyroscope; + Triggers : Threshold_Event_List; + Latched : Boolean := False; + Active_Edge : Interrupt1_Active_Edge := L3GD20_Interrupt1_High_Edge; + Combine_Events : Boolean := False; + Sample_Count : Sample_Counter := 0) + is + Config : UInt8; + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 and 16#DF#; + Ctrl3 := Ctrl3 or Active_Edge'Enum_Rep; + Ctrl3 := Ctrl3 or INT1_Interrupt_Enable; + Write (This, CTRL_REG3, Ctrl3); + + if Sample_Count > 0 then + Set_Duration_Counter (This, Sample_Count); + end if; + + Config := 0; + + if Latched then + Config := Config or Int1_Latch_Enable_Bit; + end if; + + if Combine_Events then + Config := Config or Logically_And_Or_Events_Bit; + end if; + + for Event of Triggers loop + Config := Config or Axes_Interrupt_Enablers (Event.Axis); + end loop; + + Write (This, INT1_CFG, Config); + + for Event of Triggers loop + Set_Threshold (This, Event.Axis, Event.Threshold); + end loop; + end Configure_Interrupt1; + + ---------------------------- + -- Set_Interrupt_Pin_Mode -- + ---------------------------- + + procedure Set_Interrupt_Pin_Mode + (This : in out Three_Axis_Gyroscope; + Mode : Pin_Modes) + is + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 and (not Interrupt_Pin_Mode_Bit); + Ctrl3 := Ctrl3 or Mode'Enum_Rep; + Write (This, CTRL_REG3, Ctrl3); + end Set_Interrupt_Pin_Mode; + + ----------------------- + -- Enable_Interrupt1 -- + ----------------------- + + procedure Enable_Interrupt1 (This : in out Three_Axis_Gyroscope) is + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 or INT1_Interrupt_Enable; + Write (This, CTRL_REG3, Ctrl3); + end Enable_Interrupt1; + + ------------------------ + -- Disable_Interrupt1 -- + ------------------------ + + procedure Disable_Interrupt1 (This : in out Three_Axis_Gyroscope) is + Ctrl3 : UInt8; + begin + Read (This, CTRL_REG3, Ctrl3); + Ctrl3 := Ctrl3 and (not INT1_Interrupt_Enable); + Write (This, CTRL_REG3, Ctrl3); + end Disable_Interrupt1; + + ----------------------- + -- Interrupt1_Status -- + ----------------------- + + function Interrupt1_Source (This : Three_Axis_Gyroscope) return Interrupt1_Sources is + Result : UInt8; + function As_Interrupt_Source is new Ada.Unchecked_Conversion + (Source => UInt8, Target => Interrupt1_Sources); + begin + Read (This, INT1_SRC, Result); + return As_Interrupt_Source (Result); + end Interrupt1_Source; + + -------------------------- + -- Set_Duration_Counter -- + -------------------------- + + procedure Set_Duration_Counter + (This : in out Three_Axis_Gyroscope; + Value : Sample_Counter) + is + Wait_Bit : constant := 2#1000_0000#; + begin + Write (This, INT1_Duration, UInt8 (Value) or Wait_Bit); + end Set_Duration_Counter; + + ------------------ + -- Enable_Event -- + ------------------ + + procedure Enable_Event + (This : in out Three_Axis_Gyroscope; + Event : Axes_Interrupts) + is + Config : UInt8; + begin + Read (This, INT1_CFG, Config); + Config := Config or Axes_Interrupt_Enablers (Event); + Write (This, INT1_CFG, Config); + end Enable_Event; + + ------------------- + -- Disable_Event -- + ------------------- + + procedure Disable_Event + (This : in out Three_Axis_Gyroscope; + Event : Axes_Interrupts) + is + Config : UInt8; + begin + Read (This, INT1_CFG, Config); + Config := Config and (not Axes_Interrupt_Enablers (Event)); + Write (This, INT1_CFG, Config); + end Disable_Event; + + ------------------- + -- Set_Threshold -- + ------------------- + + procedure Set_Threshold + (This : in out Three_Axis_Gyroscope; + Event : Axes_Interrupts; + Value : Axis_Sample_Threshold) + is + begin + case Event is + when Z_High_Interrupt | Z_Low_Interrupt => + Write (This, INT1_TSH_ZL, UInt8 (Value)); + Write (This, INT1_TSH_ZH, UInt8 (Shift_Right (Value, 8))); + + when Y_High_Interrupt | Y_Low_Interrupt => + Write (This, INT1_TSH_YL, UInt8 (Value)); + Write (This, INT1_TSH_YH, UInt8 (Shift_Right (Value, 8))); + + when X_High_Interrupt | X_Low_Interrupt => + Write (This, INT1_TSH_XL, UInt8 (Value)); + Write (This, INT1_TSH_XH, UInt8 (Shift_Right (Value, 8))); + end case; + end Set_Threshold; + + ------------------- + -- Set_FIFO_Mode -- + ------------------- + + procedure Set_FIFO_Mode + (This : in out Three_Axis_Gyroscope; + Mode : FIFO_Modes) + is + FIFO : UInt8; + begin + Read (This, FIFO_CTRL, FIFO); + FIFO := FIFO and (not FIFO_Mode_Bits); -- clear the current bits + FIFO := FIFO or Mode'Enum_Rep; + Write (This, FIFO_CTRL, FIFO); + end Set_FIFO_Mode; + + ----------------- + -- Enable_FIFO -- + ----------------- + + procedure Enable_FIFO (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + Ctrl5 := Ctrl5 or FIFO_Enable_Bit; + Write (This, CTRL_REG5, Ctrl5); + end Enable_FIFO; + + ------------------ + -- Disable_FIFO -- + ------------------ + + procedure Disable_FIFO (This : in out Three_Axis_Gyroscope) is + Ctrl5 : UInt8; + begin + Read (This, CTRL_REG5, Ctrl5); + Ctrl5 := Ctrl5 and (not FIFO_Enable_Bit); + Write (This, CTRL_REG5, Ctrl5); + end Disable_FIFO; + + ------------------------ + -- Set_FIFO_Watermark -- + ------------------------ + + procedure Set_FIFO_Watermark + (This : in out Three_Axis_Gyroscope; + Level : FIFO_Level) + is + Value : UInt8; + begin + Read (This, FIFO_CTRL, Value); + Value := Value and (not Watermark_Threshold_Bits); -- clear the bits + Value := Value or UInt8 (Level); + Write (This, FIFO_CTRL, Value); + end Set_FIFO_Watermark; + + ------------------------------ + -- Get_Raw_Angle_Rates_FIFO -- + ------------------------------ + + procedure Get_Raw_Angle_Rates_FIFO + (This : in out Three_Axis_Gyroscope; + Buffer : out Angle_Rates_FIFO_Buffer) + is + Ctrl4 : UInt8; + + Angle_Rate_Size : constant Integer := 6; -- UInt8s + UInt8s_To_Read : constant Integer := Buffer'Length * Angle_Rate_Size; + Received : SPI_Data_8b (0 .. UInt8s_To_Read - 1) + with Alignment => 2; + begin + Read (This, CTRL_REG4, Ctrl4); + + Read_UInt8s (This, OUT_X_L, Received, UInt8s_To_Read); + + if (Ctrl4 and Endian_Selection_Mask) = L3GD20_Big_Endian'Enum_Rep then + declare + J : Integer := 0; + begin + for K in Received'First .. Received'Last / 2 loop + Swap2 (Received (J)'Address); + J := J + 2; + end loop;" +function Read_Revision (This : VL53L0X_Ranging_Sensor) return HAL.UInt8,"is + Ret : UInt8; + Status : Boolean; + begin + Read (This, REG_IDENTIFICATION_REVISION_ID, Ret, Status); + + if not Status then + return 0; + else + return Ret; + end if; + end Read_Revision; + + ------------------------ + -- Set_Device_Address -- + ------------------------ + + procedure Set_Device_Address + (This : in out VL53L0X_Ranging_Sensor; + Addr : HAL.I2C.I2C_Address; + Status : out Boolean) + is + begin + Write (This, REG_I2C_SLAVE_DEVICE_ADDRESS, UInt8 (Addr / 2), Status); + if Status then + This.I2C_Address := Addr; + end if; + end Set_Device_Address; + + --------------- + -- Data_Init -- + --------------- + + procedure Data_Init + (This : in out VL53L0X_Ranging_Sensor; + Status : out Boolean) + is + Regval : UInt8; + begin + -- Set I2C Standard mode + Write (This, 16#88#, UInt8'(16#00#), Status); + + if not Status then + return; + end if; + +-- This.Device_Specific_Params.Read_Data_From_Device_Done := False; +-- +-- -- Set default static parameters: +-- -- set first temporary value 9.44MHz * 65536 = 618_660 +-- This.Device_Specific_Params.Osc_Frequency := 618_660; +-- +-- -- Set default cross talk compenstation rate to 0 +-- This.Device_Params.X_Talk_Compensation_Rate_Mcps := 0.0; +-- +-- This.Device_Params.Device_Mode := Single_Ranging; +-- This.Device_Params.Histogram_Mode := Disabled; + + -- TODO: Sigma estimator variable + if Status then + Write (This, 16#80#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#00#), Status); + end if; + if Status then + Read (This, 16#91#, This.Stop_Variable, Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + -- disable SIGNAL_RATE_MSRC (bit 1) and SIGNAL_RATE_PRE_RANGE (bit 4) + -- limit checks + if Status then + Read (This, REG_MSRC_CONFIG_CONTROL, Regval, Status); + end if; + + if Status then + Write (This, REG_MSRC_CONFIG_CONTROL, Regval or 16#12#, Status); + end if; + + if Status then + -- Set final range signal rate limit to 0.25 MCPS + Status := Set_Signal_Rate_Limit (This, 0.25); + end if; + + if Status then + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#FF#), Status); + end if; + end Data_Init; + + ----------------- + -- Static_Init -- + ----------------- + + procedure Static_Init + (This : in out VL53L0X_Ranging_Sensor; + GPIO_Function : VL53L0X_GPIO_Functionality; + Status : out Boolean) + is + type SPAD_Map is array (UInt8 range 1 .. 48) of Boolean + with Pack, Size => 48; + subtype SPAD_Map_Bytes is UInt8_Array (1 .. 6); + function To_Map is new Ada.Unchecked_Conversion + (SPAD_Map_Bytes, SPAD_Map); + function To_Bytes is new Ada.Unchecked_Conversion + (SPAD_Map, SPAD_Map_Bytes); + + SPAD_Count : UInt8; + SPAD_Is_Aperture : Boolean; + Ref_SPAD_Map_Bytes : SPAD_Map_Bytes; + Ref_SPAD_Map : SPAD_Map; + First_SPAD : UInt8; + SPADS_Enabled : UInt8; + Timing_Budget : UInt32; + + begin + Status := SPAD_Info (This, SPAD_Count, SPAD_Is_Aperture); + + if not Status then + return; + end if; + + Read + (This, REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_0, + Ref_SPAD_Map_Bytes, Status); + Ref_SPAD_Map := To_Map (Ref_SPAD_Map_Bytes); + + -- Set reference spads + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, REG_DYNAMIC_SPAD_REF_EN_START_OFFSET, + UInt8'(16#00#), Status); + end if; + if Status then + Write (This, REG_DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, + UInt8'(16#2C#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, REG_GLOBAL_CONFIG_REF_EN_START_SELECT, + UInt8'(16#B4#), Status); + end if; + + if Status then + if SPAD_Is_Aperture then + First_SPAD := 13; + else + First_SPAD := 1; + end if; + + SPADS_Enabled := 0; + + for J in UInt8 range 1 .. 48 loop + + if J < First_SPAD or else SPADS_Enabled = SPAD_Count then + -- This bit is lower than the first one that should be enabled, + -- or SPAD_Count bits have already been enabled, so zero this + -- bit + Ref_SPAD_Map (J) := False; + + elsif Ref_SPAD_Map (J) then + SPADS_Enabled := SPADS_Enabled + 1; + end if; + end loop; + end if; + + if Status then + Ref_SPAD_Map_Bytes := To_Bytes (Ref_SPAD_Map); + Write (This, REG_GLOBAL_CONFIG_SPAD_ENABLES_REF_0, + Ref_SPAD_Map_Bytes, Status); + end if; + + -- Load tuning Settings + -- default tuning settings from vl53l0x_tuning.h + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#00#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#09#, UInt8'(16#00#), Status); + Write (This, 16#10#, UInt8'(16#00#), Status); + Write (This, 16#11#, UInt8'(16#00#), Status); + + Write (This, 16#24#, UInt8'(16#01#), Status); + Write (This, 16#25#, UInt8'(16#FF#), Status); + Write (This, 16#75#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#4E#, UInt8'(16#2C#), Status); + Write (This, 16#48#, UInt8'(16#00#), Status); + Write (This, 16#30#, UInt8'(16#20#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#30#, UInt8'(16#09#), Status); + Write (This, 16#54#, UInt8'(16#00#), Status); + Write (This, 16#31#, UInt8'(16#04#), Status); + Write (This, 16#32#, UInt8'(16#03#), Status); + Write (This, 16#40#, UInt8'(16#83#), Status); + Write (This, 16#46#, UInt8'(16#25#), Status); + Write (This, 16#60#, UInt8'(16#00#), Status); + Write (This, 16#27#, UInt8'(16#00#), Status); + Write (This, 16#50#, UInt8'(16#06#), Status); + Write (This, 16#51#, UInt8'(16#00#), Status); + Write (This, 16#52#, UInt8'(16#96#), Status); + Write (This, 16#56#, UInt8'(16#08#), Status); + Write (This, 16#57#, UInt8'(16#30#), Status); + Write (This, 16#61#, UInt8'(16#00#), Status); + Write (This, 16#62#, UInt8'(16#00#), Status); + Write (This, 16#64#, UInt8'(16#00#), Status); + Write (This, 16#65#, UInt8'(16#00#), Status); + Write (This, 16#66#, UInt8'(16#A0#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#22#, UInt8'(16#32#), Status); + Write (This, 16#47#, UInt8'(16#14#), Status); + Write (This, 16#49#, UInt8'(16#FF#), Status); + Write (This, 16#4A#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#7A#, UInt8'(16#0A#), Status); + Write (This, 16#7B#, UInt8'(16#00#), Status); + Write (This, 16#78#, UInt8'(16#21#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#23#, UInt8'(16#34#), Status); + Write (This, 16#42#, UInt8'(16#00#), Status); + Write (This, 16#44#, UInt8'(16#FF#), Status); + Write (This, 16#45#, UInt8'(16#26#), Status); + Write (This, 16#46#, UInt8'(16#05#), Status); + Write (This, 16#40#, UInt8'(16#40#), Status); + Write (This, 16#0E#, UInt8'(16#06#), Status); + Write (This, 16#20#, UInt8'(16#1A#), Status); + Write (This, 16#43#, UInt8'(16#40#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#34#, UInt8'(16#03#), Status); + Write (This, 16#35#, UInt8'(16#44#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#31#, UInt8'(16#04#), Status); + Write (This, 16#4B#, UInt8'(16#09#), Status); + Write (This, 16#4C#, UInt8'(16#05#), Status); + Write (This, 16#4D#, UInt8'(16#04#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#44#, UInt8'(16#00#), Status); + Write (This, 16#45#, UInt8'(16#20#), Status); + Write (This, 16#47#, UInt8'(16#08#), Status); + Write (This, 16#48#, UInt8'(16#28#), Status); + Write (This, 16#67#, UInt8'(16#00#), Status); + Write (This, 16#70#, UInt8'(16#04#), Status); + Write (This, 16#71#, UInt8'(16#01#), Status); + Write (This, 16#72#, UInt8'(16#FE#), Status); + Write (This, 16#76#, UInt8'(16#00#), Status); + Write (This, 16#77#, UInt8'(16#00#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#0D#, UInt8'(16#01#), Status); + + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#80#, UInt8'(16#01#), Status); + Write (This, 16#01#, UInt8'(16#F8#), Status); + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, 16#8E#, UInt8'(16#01#), Status); + Write (This, 16#00#, UInt8'(16#01#), Status); + Write (This, 16#FF#, UInt8'(16#00#), Status); + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + Set_GPIO_Config (This, GPIO_Function, Polarity_High, Status); + + if Status then + Timing_Budget := Measurement_Timing_Budget (This); + + -- Disable MSRC and TCC by default + -- MSRC = Minimum Signal Rate Check + -- TCC = Target CenterCheck + + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#E8#), Status); + end if; + + -- Recalculate the timing Budget + if Status then + Set_Measurement_Timing_Budget (This, Timing_Budget, Status); + end if; + end Static_Init; + + ------------------------------------ + -- Perform_Single_Ref_Calibration -- + ------------------------------------ + + procedure Perform_Single_Ref_Calibration + (This : VL53L0X_Ranging_Sensor; + VHV_Init : UInt8; + Status : out Boolean) + is + Val : UInt8; + + begin + Write (This, REG_SYSRANGE_START, VHV_Init or 16#01#, Status); + + if not Status then + return; + end if; + + loop + Read (This, REG_RESULT_INTERRUPT_STATUS, Val, Status); + exit when not Status; + exit when (Val and 16#07#) /= 0; + end loop; + + if not Status then + return; + end if; + + Write (This, REG_SYSTEM_INTERRUPT_CLEAR, UInt8'(16#01#), Status); + if not Status then + return; + end if; + + Write (This, REG_SYSRANGE_START, UInt8'(16#00#), Status); + end Perform_Single_Ref_Calibration; + + ----------------------------- + -- Perform_Ref_Calibration -- + ----------------------------- + + procedure Perform_Ref_Calibration + (This : in out VL53L0X_Ranging_Sensor; + Status : out Boolean) + is + begin + -- VHV calibration + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#01#), Status); + + if Status then + Perform_Single_Ref_Calibration (This, 16#40#, Status); + end if; + + -- Phase calibration + if Status then + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#02#), Status); + end if; + + if Status then + Perform_Single_Ref_Calibration (This, 16#00#, Status); + end if; + + -- Restore the sequence config + if Status then + Write (This, REG_SYSTEM_SEQUENCE_CONFIG, UInt8'(16#E8#), Status); + end if; + end Perform_Ref_Calibration; + + ---------------------- + -- Start_Continuous -- + ---------------------- + + procedure Start_Continuous (This : VL53L0X.VL53L0X_Ranging_Sensor; + Period_Ms : HAL.UInt32; + Status : out Boolean) is + -- From vl53l0xStartContinuous() in + -- crazyflie-firmware/src/drivers/src/vl53l0x.c + begin + Write (This, 16#80#, UInt8'(16#01#), Status); + if Status then + Write (This, 16#ff#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#91#, UInt8'(This.Stop_Variable), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#ff#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + if not Status then + return; + end if; + if Period_Ms /= 0 then + -- continuous timed mode + declare + procedure Set_Inter_Measurement_Period_Milliseconds; + -- The Crazyflie code indicates that this is a missing + -- function that they've inlined. + procedure Set_Inter_Measurement_Period_Milliseconds is + Osc_Calibrate_Val : UInt16; + Period : UInt32 := Period_Ms; + begin + Read (This, REG_OSC_CALIBRATE_VAL, Osc_Calibrate_Val, Status); + if Status and then Osc_Calibrate_Val /= 0 then + Period := Period * UInt32 (Osc_Calibrate_Val); + end if; + if Status then + Write + (This, REG_SYSTEM_INTERMEASUREMENT_PERIOD, Period, Status); + end if; + end Set_Inter_Measurement_Period_Milliseconds; + begin + Set_Inter_Measurement_Period_Milliseconds; + if Status then + Write (This, + REG_SYSRANGE_START, + UInt8'(REG_SYSRANGE_MODE_TIMED), + Status); + end if;" +function To_U32 is new Ada.Unchecked_Conversion,"(Fix_Point_16_16, UInt32); + Val : UInt16; + Status : Boolean; + begin + -- Expecting Fixed Point 9.7 + Val := UInt16 (Shift_Right (To_U32 (Limit_Mcps), 9) and 16#FF_FF#); + Write (This, + REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, + Val, + Status); + return Status; + end Set_Signal_Rate_Limit; + + --------------- + -- SPAD_Info -- + --------------- + + function SPAD_Info + (This : VL53L0X_Ranging_Sensor; + SPAD_Count : out HAL.UInt8; + Is_Aperture : out Boolean) return Boolean + is + Status : Boolean; + Tmp : UInt8; + begin + Write (This, 16#80#, UInt8'(16#01#), Status); + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#00#), Status); + end if; + + if Status then + Write (This, 16#FF#, UInt8'(16#06#), Status); + end if; + if Status then + Read (This, 16#83#, Tmp, Status); + end if; + if Status then + Write (This, 16#83#, Tmp or 16#04#, Status); + end if; + + if Status then + Write (This, 16#FF#, UInt8'(16#07#), Status); + end if; + if Status then + Write (This, 16#81#, UInt8'(16#01#), Status); + end if; + + if Status then + Write (This, 16#80#, UInt8'(16#01#), Status); + end if; + + if Status then + Write (This, 16#94#, UInt8'(16#6B#), Status); + end if; + if Status then + Write (This, 16#83#, UInt8'(16#00#), Status); + end if; + + loop + exit when not Status; + Read (This, 16#83#, Tmp, Status); + exit when Tmp /= 0; + end loop; + + if Status then + Write (This, 16#83#, UInt8'(16#01#), Status); + end if; + if Status then + Read (This, 16#92#, Tmp, Status); + end if; + + if Status then + SPAD_Count := Tmp and 16#7F#; + Is_Aperture := (Tmp and 16#80#) /= 0; + + Write (This, 16#81#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#06#), Status); + end if; + if Status then + Read (This, 16#83#, Tmp, Status); + end if; + if Status then + Write (This, 16#83#, Tmp and not 16#04#, Status); + end if; + if Status then + Write (This, 16#FF#, UInt8'(16#01#), Status); + end if; + if Status then + Write (This, 16#00#, UInt8'(16#01#), Status); + end if; + + if Status then + Write (This, 16#FF#, UInt8'(16#00#), Status); + end if; + if Status then + Write (This, 16#80#, UInt8'(16#00#), Status); + end if; + + return Status; + end SPAD_Info; + + --------------------------- + -- Set_Signal_Rate_Limit -- + --------------------------- + + procedure Set_Signal_Rate_Limit + (This : VL53L0X_Ranging_Sensor; + Rate_Limit : Fix_Point_16_16) + is + function To_U32 is new Ada.Unchecked_Conversion + (Fix_Point_16_16, UInt32); + Reg : UInt16; + Status : Boolean with Unreferenced; + begin + -- Encoded as Fixed Point 9.7. Let's translate. + Reg := UInt16 (Shift_Right (To_U32 (Rate_Limit), 9) and 16#FFFF#); + Write (This, REG_FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, + Reg, Status); + end Set_Signal_Rate_Limit; + + -------------------------------------- + -- Set_Vcsel_Pulse_Period_Pre_Range -- + -------------------------------------- + + procedure Set_VCSEL_Pulse_Period_Pre_Range + (This : VL53L0X_Ranging_Sensor; + Period : UInt8; + Status : out Boolean) + is + begin + Set_VCSel_Pulse_Period (This, Period, Pre_Range, Status); + end Set_VCSEL_Pulse_Period_Pre_Range; + + ---------------------------------------- + -- Set_Vcsel_Pulse_Period_Final_Range -- + ---------------------------------------- + + procedure Set_VCSEL_Pulse_Period_Final_Range + (This : VL53L0X_Ranging_Sensor; + Period : UInt8; + Status : out Boolean) + is + begin + Set_VCSel_Pulse_Period (This, Period, Final_Range, Status); + end Set_VCSEL_Pulse_Period_Final_Range; + + ---------------------------- + -- Set_VCSel_Pulse_Period -- + ---------------------------- + + procedure Set_VCSel_Pulse_Period + (This : VL53L0X_Ranging_Sensor; + Period : UInt8; + Sequence : VL53L0x_Sequence_Step; + Status : out Boolean) + is + Encoded : constant UInt8 := Shift_Right (Period, 1) - 1; + Phase_High : UInt8; + Pre_Timeout : UInt32; + Final_Timeout : UInt32; + Msrc_Timeout : UInt32; + Timeout_Mclks : UInt32; + Steps_Enabled : constant VL53L0x_Sequence_Step_Enabled := + Sequence_Step_Enabled (This); + Budget : UInt32; + Sequence_Cfg : UInt8; + + begin + -- Save the measurement timing budget + Budget := Measurement_Timing_Budget (This); + + case Sequence is + when Pre_Range => + Pre_Timeout := Sequence_Step_Timeout (This, Pre_Range); + Msrc_Timeout := Sequence_Step_Timeout (This, MSRC); + + case Period is + when 12 => + Phase_High := 16#18#; + when 14 => + Phase_High := 16#30#; + when 16 => + Phase_High := 16#40#; + when 18 => + Phase_High := 16#50#; + when others => + Status := False; + + return; + end case; + + Write (This, REG_PRE_RANGE_CONFIG_VALID_PHASE_HIGH, + Phase_High, Status); + if not Status then + return; + end if; + + Write (This, REG_PRE_RANGE_CONFIG_VALID_PHASE_LOW, + UInt8'(16#08#), Status); + if not Status then + return; + end if; + + Write (This, REG_PRE_RANGE_CONFIG_VCSEL_PERIOD, + Encoded, Status); + if not Status then + return; + end if; + + -- Update the timeouts + Timeout_Mclks := To_Timeout_Mclks (Pre_Timeout, Period); + Write (This, REG_PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI, + UInt16 (Timeout_Mclks), Status); + + Timeout_Mclks := To_Timeout_Mclks (Msrc_Timeout, Period); + if Timeout_Mclks > 256 then + Timeout_Mclks := 255; + else + Timeout_Mclks := Timeout_Mclks - 1; + end if; + + Write (This, REG_MSRC_CONFIG_TIMEOUT_MACROP, + UInt8 (Timeout_Mclks), Status); + + when Final_Range => + Pre_Timeout := Sequence_Step_Timeout + (This, Pre_Range, As_Mclks => True); + Final_Timeout := Sequence_Step_Timeout (This, Final_Range); + + declare + Phase_High : UInt8; + Width : UInt8; + Cal_Timeout : UInt8; + Cal_Lim : UInt8; + begin + case Period is + when 8 => + Phase_High := 16#10#; + Width := 16#02#; + Cal_Timeout := 16#0C#; + Cal_Lim := 16#30#; + when 10 => + Phase_High := 16#28#; + Width := 16#03#; + Cal_Timeout := 16#09#; + Cal_Lim := 16#20#; + when 12 => + Phase_High := 16#38#; + Width := 16#03#; + Cal_Timeout := 16#08#; + Cal_Lim := 16#20#; + when 14 => + Phase_High := 16#48#; + Width := 16#03#; + Cal_Timeout := 16#07#; + Cal_Lim := 16#20#; + when others => + return; + end case; + + Write (This, REG_FINAL_RANGE_CONFIG_VALID_PHASE_HIGH, + Phase_High, Status); + if not Status then + return; + end if; + + Write (This, REG_FINAL_RANGE_CONFIG_VALID_PHASE_LOW, + UInt8'(16#08#), Status); + if not Status then + return; + end if; + + Write (This, REG_GLOBAL_CONFIG_VCSEL_WIDTH, + Width, Status); + if not Status then + return; + end if; + + Write (This, REG_ALGO_PHASECAL_CONFIG_TIMEOUT, + Cal_Timeout, Status); + if not Status then + return; + end if; + + Write (This, 16#FF#, UInt8'(16#01#), Status); + Write (This, REG_ALGO_PHASECAL_LIM, + Cal_Lim, Status); + Write (This, 16#FF#, UInt8'(16#00#), Status); + if not Status then + return; + end if;" +function To_UInt16 is,"new Ada.Unchecked_Conversion (UInt16_HL_Type, UInt16); + + Ret : TP_Touch_State; + Regs : FT6206_Pressure_Registers; + Tmp : UInt16_HL_Type; + Status : Boolean; + begin + if Touch_Id not in FT6206_Px_Regs'Range then + return (0, 0, 0); + end if; + + if Touch_Id > This.Active_Touch_Points then + return (0, 0, 0); + end if; + + -- X/Y are swaped from the screen coordinates + + Regs := FT6206_Px_Regs (Touch_Id); + + Tmp.Low := This.I2C_Read (Regs.XL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.XH_Reg, Status) and + FT6206_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.Y := Natural (To_UInt16 (Tmp)); + + Tmp.Low := This.I2C_Read (Regs.YL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.YH_Reg, Status) and + FT6206_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.X := Natural (To_UInt16 (Tmp)); + + Ret.Weight := Natural (This.I2C_Read (Regs.Weight_Reg, Status)); + + if not Status then + Ret.Weight := 0; + end if; + + if Ret.Weight = 0 then + Ret.Weight := 50; + end if; + + Ret.X := Natural'Max (0, Ret.X); + Ret.Y := Natural'Max (0, Ret.Y); + Ret.X := Natural'Min (This.LCD_Natural_Width - 1, Ret.X); + Ret.Y := Natural'Min (This.LCD_Natural_Height - 1, Ret.Y); + + if (This.Swap and Invert_X) /= 0 then + Ret.X := This.LCD_Natural_Width - Ret.X - 1; + end if; + if (This.Swap and Invert_Y) /= 0 then + Ret.Y := This.LCD_Natural_Height - Ret.Y - 1; + end if; + if (This.Swap and Swap_XY) /= 0 then + declare + Tmp_X : constant Integer := Ret.X; + begin + Ret.X := Ret.Y; + Ret.Y := Tmp_X;" +function Read_Register (This : STMPE811_Device;,"Reg_Addr : UInt8) return UInt8 + is + Data : TSC_Data (1 .. 1); + Status : I2C_Status; + + begin + This.Port.Mem_Read (This.I2C_Addr, + UInt16 (Reg_Addr), + Memory_Size_8b, + Data, + Status); + + if Status /= Ok then + raise Program_Error with ""Timeout while reading TC data""; + end if; + + return Data (1); + end Read_Register; + + -------------------- + -- Write_Register -- + -------------------- + + procedure Write_Register (This : in out STMPE811_Device; + Reg_Addr : UInt8; + Data : UInt8) is + Status : I2C_Status; + + begin + This.Port.Mem_Write (This.I2C_Addr, + UInt16 (Reg_Addr), + Memory_Size_8b, + (1 => Data), + Status); + + if Status /= Ok then + raise Program_Error with ""Timeout while reading TC data""; + end if; + end Write_Register; + + --------------- + -- IOE_Reset -- + --------------- + + procedure IOE_Reset (This : in out STMPE811_Device) is + begin + This.Write_Register (IOE_REG_SYS_CTRL1, 16#02#); + + -- Give some time for the reset + This.Time.Delay_Milliseconds (2); + + This.Write_Register (IOE_REG_SYS_CTRL1, 16#00#); + end IOE_Reset; + + -------------------------- + -- IOE_Function_Command -- + -------------------------- + + procedure IOE_Function_Command (This : in out STMPE811_Device; + Func : UInt8; + Enabled : Boolean) + is + Reg : UInt8 := This.Read_Register (IOE_REG_SYS_CTRL2); + begin + -- CTRL2 functions are disabled when corresponding bit is set + + if Enabled then + Reg := Reg and (not Func); + else + Reg := Reg or Func; + end if; + + This.Write_Register (IOE_REG_SYS_CTRL2, Reg); + end IOE_Function_Command; + + ------------------- + -- IOE_AF_Config -- + ------------------- + + procedure IOE_AF_Config (This : in out STMPE811_Device; + Pin : UInt8; + Enabled : Boolean) is + Reg : UInt8 := This.Read_Register (IOE_REG_GPIO_AF); + begin + if Enabled then + Reg := Reg or Pin; + else + Reg := Reg and (not Pin); + end if; + + This.Write_Register (IOE_REG_GPIO_AF, Reg); + end IOE_AF_Config; + + ---------------- + -- Get_IOE_ID -- + ---------------- + + function Get_IOE_ID (This : in out STMPE811_Device) return UInt16 is + begin + return (UInt16 (This.Read_Register (0)) * (2**8)) + or UInt16 (This.Read_Register (1)); + end Get_IOE_ID; + + ---------------- + -- Initialize -- + ---------------- + + function Initialize (This : in out STMPE811_Device) return Boolean + is + begin + + This.Time.Delay_Milliseconds (100); + + if This.Get_IOE_ID /= 16#0811# then + return False; + end if; + + This.IOE_Reset; + + This.IOE_Function_Command (IOE_ADC_FCT, True); + This.IOE_Function_Command (IOE_TSC_FCT, True); + + This.Write_Register (IOE_REG_ADC_CTRL1, 16#49#); + + This.Time.Delay_Milliseconds (2); + + This.Write_Register (IOE_REG_ADC_CTRL2, 16#01#); + + This.IOE_AF_Config (TOUCH_IO_ALL, False); + + This.Write_Register (IOE_REG_TSC_CFG, 16#9A#); + + This.Write_Register (IOE_REG_FIFO_TH, 16#01#); + + This.Write_Register (IOE_REG_FIFO_STA, 16#01#); + + This.Write_Register (IOE_REG_FIFO_TH, 16#00#); + + This.Write_Register (IOE_REG_TSC_FRACT_Z, 16#00#); + + This.Write_Register (IOE_REG_TSC_I_DRIVE, 16#01#); + + This.Write_Register (IOE_REG_TSC_CTRL, 16#01#); + + This.Write_Register (IOE_REG_INT_STA, 16#FF#); + + return True; + end Initialize; + + ---------------- + -- Set_Bounds -- + ---------------- + + overriding + procedure Set_Bounds (This : in out STMPE811_Device; + Width : Natural; + Height : Natural; + Swap : HAL.Touch_Panel.Swap_State) + is + begin + This.LCD_Natural_Width := Width; + This.LCD_Natural_Height := Height; + This.Swap := Swap; + end Set_Bounds; + + ------------------------- + -- Active_Touch_Points -- + ------------------------- + + overriding + function Active_Touch_Points (This : in out STMPE811_Device) + return Touch_Identifier + is + Val : constant UInt8 := This.Read_Register (IOE_REG_TSC_CTRL) and 16#80#; + begin + if Val = 0 then + This.Write_Register (IOE_REG_FIFO_STA, 16#01#); + This.Write_Register (IOE_REG_FIFO_STA, 16#00#); + + return 0; + else + return 1; + end if; + end Active_Touch_Points; + + --------------------- + -- Get_Touch_Point -- + --------------------- + + overriding + function Get_Touch_Point (This : in out STMPE811_Device; + Touch_Id : Touch_Identifier) + return TP_Touch_State + is + State : TP_Touch_State; + Raw_X : UInt32; + Raw_Y : UInt32; + Raw_Z : UInt32; + X : Integer; + Y : Integer; + Tmp : Integer; + + begin + + -- Check Touch detected bit in CTRL register + if Touch_Id /= 1 or else This.Active_Touch_Points = 0 then + return (0, 0, 0); + end if; + + declare + Data_X : constant TSC_Data := This.Read_Data (IOE_REG_TSC_DATA_X, 2); + Data_Y : constant TSC_Data := This.Read_Data (IOE_REG_TSC_DATA_Y, 2); + Data_Z : constant TSC_Data := This.Read_Data (IOE_REG_TSC_DATA_Z, 1); + Z_Frac : constant TSC_Data := This.Read_Data (IOE_REG_TSC_FRACT_Z, 1); + + begin + Raw_X := 2 ** 12 - + (Shift_Left (UInt32 (Data_X (1)) and 16#0F#, 8) or UInt32 (Data_X (2))); + Raw_Y := + Shift_Left (UInt32 (Data_Y (1)) and 16#0F#, 8) or UInt32 (Data_Y (2)); + Raw_Z := + Shift_Right (UInt32 (Data_Z (1)), Natural (Z_Frac (1) and 2#111#));" +function To_UInt16 is,"new Ada.Unchecked_Conversion (UInt16_HL_Type, UInt16); + + Ret : TP_Touch_State; + Regs : FT5336_Pressure_Registers; + Tmp : UInt16_HL_Type; + Status : Boolean; + + begin + -- X/Y are swaped from the screen coordinates + + if Touch_Id not in FT5336_Px_Regs'Range + or else Touch_Id > This.Active_Touch_Points + then + return (0, 0, 0); + end if; + + Regs := FT5336_Px_Regs (Touch_Id); + + Tmp.Low := This.I2C_Read (Regs.XL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.XH_Reg, Status) and + FT5336_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.Y := Natural (To_UInt16 (Tmp)); + + Tmp.Low := This.I2C_Read (Regs.YL_Reg, Status); + + if not Status then + return (0, 0, 0); + end if; + + Tmp.High := This.I2C_Read (Regs.YH_Reg, Status) and + FT5336_TOUCH_POS_MSB_MASK; + + if not Status then + return (0, 0, 0); + end if; + + Ret.X := Natural (To_UInt16 (Tmp)); + + Ret.Weight := Natural (This.I2C_Read (Regs.Weight_Reg, Status)); + + if not Status then + Ret.Weight := 0; + end if; + + Ret.X := + Natural'Min (Natural'Max (0, Ret.X), This.LCD_Natural_Width - 1); + Ret.Y := + Natural'Min (Natural'Max (0, Ret.Y), This.LCD_Natural_Height - 1); + + if (This.Swap and Invert_X) /= 0 then + Ret.X := This.LCD_Natural_Width - Ret.X - 1; + end if; + if (This.Swap and Invert_Y) /= 0 then + Ret.Y := This.LCD_Natural_Height - Ret.Y - 1; + end if; + if (This.Swap and Swap_XY) /= 0 then + declare + Tmp_X : constant Integer := Ret.X; + begin + Ret.X := Ret.Y; + Ret.Y := Tmp_X;" +procedure adainit is,"Binder_Sec_Stacks_Count : Natural; + pragma Import (Ada, Binder_Sec_Stacks_Count, ""__gnat_binder_ss_count""); + + Default_Secondary_Stack_Size : System.Parameters.Size_Type; + pragma Import (C, Default_Secondary_Stack_Size, ""__gnat_default_ss_size""); + Default_Sized_SS_Pool : System.Address; + pragma Import (Ada, Default_Sized_SS_Pool, ""__gnat_default_ss_pool""); + + begin + null; + + ada_main'Elab_Body; + Default_Secondary_Stack_Size := System.Parameters.Runtime_Default_Sec_Stack_Size; + Binder_Sec_Stacks_Count := 1; + Default_Sized_SS_Pool := Sec_Default_Sized_Stacks'Address; + + + E78 := E78 + 1; + Cortex_M.Nvic'Elab_Spec; + E76 := E76 + 1; + E70 := E70 + 1; + E28 := E28 + 1; + Nrf.Interrupts'Elab_Body; + E72 := E72 + 1; + E34 := E34 + 1; + E37 := E37 + 1; + E58 := E58 + 1; + E56 := E56 + 1; + E41 := E41 + 1; + E44 := E44 + 1; + E48 := E48 + 1; + Nrf.Device'Elab_Spec; + Nrf.Device'Elab_Body; + E16 := E16 + 1; + NRF52_DK.LEDS'ELAB_BODY; + E81 := E81 + 1; + NRF52_DK.TIME'ELAB_BODY; + E54 := E54 + 1; + NRF52_DK.BUTTONS'ELAB_BODY; + E52 := E52 + 1; + end adainit; + + procedure Ada_Main_Program; + pragma Import (Ada, Ada_Main_Program, ""_ada_main""); + + procedure main is + Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address; + pragma Volatile (Ensure_Reference); + + begin + adainit; + Ada_Main_Program;" +procedure Test is,"begin + for I in 1 .. 10 loop + I := 3; + end loop;" +procedure Test is,"procedure P(A, A: integer) is begin New_Line; end; +begin + P(0,1);" +procedure Test is,"type R is record A, B: Character; end record; + X: R; + function F return R is + begin + return X;" +procedure Test is,"X : Integer; +begin + X := 'a';" +procedure Test is,"type R is record A, B: Character; end record; + X: R; + function F return R is + begin + return X;" +procedure Test is,"type R is record Foo: R; end record; +begin + New_Line;" +procedure Test is,"procedure P(X: Integer) is begin X := 0; end; +begin + P(42);" +procedure Test is,"function F(X: Integer) return integer is begin X:= 1; return 0; end; +begin + if F(42) = 0 then new_line; end if;" +procedure Test is,"type R is record A: Integer; end record; + X : R; +begin + X.A := 'a';" +procedure Test is,"function F(A: integer; A: character) return integer is begin return 0; end; +begin + New_Line;" +procedure Test is,"procedure P(X: in out Integer) is begin new_line; end; +begin + P(42);" +procedure Test is,"function F(X: in out Integer) return integer is begin return 0; end; +begin + if F(42) = 0 then new_line; end if;" +procedure Test is,"procedure P(A: integer; A: character) is begin New_Line; end; +begin + P(0,'a');" +procedure Test is,"type T; + procedure P is begin New_Line; end; + type T is record A: Integer; end record; +begin + New_Line;" +procedure Test is,"procedure P(X: in Integer) is begin X := 0; end; +begin + P(42);" +procedure Test is,"type T is record A: Integer; end record; + T: Integer; +begin + New_Line;" +procedure Test is,"type R is record A: Integer; end record; + procedure P(X: in R) is begin X.A := 0; end; + v: R; +begin + P(v);" +procedure Test is,"type R is record A: Integer; end record; + procedure P(X: in R) is begin X.A := 0; end; + v: R; +begin + P(v);" +procedure P is,"type t is record x: integer; end record; + type t is record y: integer; end record; +begin + new_line;" +procedure Test is,"function F(X: in Integer) return integer is begin X:= 1; return 0; end; +begin + if F(42) = 0 then new_line; end if;" +procedure Test is,"function F(A, A: integer) return integer is begin return 0; end; +begin + New_Line;" +procedure Test is,"begin + for I in 'a' .. 10 loop + New_Line; + end loop;" +procedure Test is,"procedure P(X: in out Integer) is begin new_line; end; + type r is record a: integer; end record; + function f return access r is begin return new r; end; +begin + P(f.a);" +procedure Test is,"X: Integer; + procedure P is + procedure X is begin New_Line; end; + begin + X;" +procedure Test is,"function Oups(N: Integer) return Integer is + L : Integer := Oups(N); + begin + return 0;" +procedure Test is,"type R is record Foo: access R; end record; +begin + New_Line;" +procedure Test is,"X: Integer; + procedure P is + type X is record A: Integer; end record; + V: X; + begin + New_Line;" +procedure Test is,"function F return character is begin return f; end; +begin + put(f);" +procedure Test is,"type R is record A: Integer; end record; + X : access R; +begin + X := null;" +procedure Test is,"X: Integer; + procedure P is + X: Character; + begin + Put(X);" +procedure Test is,"type R; + type P is access R; + type R is record Foo: P; end record; +begin + New_Line;" +procedure Test is,"procedure P(X: in out Integer) is begin X := 0; end; + v: integer; +begin + P(V);" +procedure Test is,"procedure R is begin R; end; +begin + R;" +procedure Test is,"type R is record A: Integer; end record; + type T is access R; + procedure P(X: in T) is begin X.A := 0; end; + v: T := new R; +begin + P(v);" +procedure Oups is,"type R is record A: Integer; end record; + V : access R := null; +begin + if V.A = 1 then New_Line; end if;" +procedure Oups is,"V : Integer := 0; +begin + if 1 / V = 1 then New_Line; end if;" +procedure Test is begin,for i in 1 . . 10 loop p; end loop; +procedure Test is begin,if 0=1 then Q(0); else Q(1); elsif 1=2 then Q(2); end if; +procedure Test is begin,for i in 1 .. 10 loop p; end loop +procedure Test is begin,for i in 1 .. 10 p; end loop; +procedure Test is begin,for i in 1 .. 10 loop p; end; +procedure Test is begin,if 0=1 then Q(0); else Q(1); else Q(2); end if; +procedure Test is begin,if 0=1 then Q(0); elsif 1=2 then Q(1); end if; +procedure Test is,"begin + for I in 1 .. 10 loop Put('A'); end loop; New_Line; + for I in 10 .. 1 loop Put('B'); end loop; New_Line; + for I in reverse 1 .. 10 loop Put('C'); end loop; New_Line; + for I in reverse 10 .. 1 loop Put('D'); end loop; New_Line;" +procedure Record4 is,"type R is record A, B: Character; end record; + type S is record C: Character; D: R; E: Character; end record; + + V, W: R; + X, Y: S; + + procedure PrintR(x: R) is + begin + Put('['); + Put(x.A); + Put(','); + Put(x.B); + Put(']');" +procedure Test is,"begin + Put('A'); + New_Line;" +procedure Power is,"procedure PrintInt(N: Integer) is + C: Integer := N rem 10; + begin + if N > 9 then PrintInt(N / 10); end if; + Put(Character'Val(48 + C));" +procedure Test is,"type R is record A, B: Integer; end record; + + procedure P1(X, Y: in out R) is + begin + X.A := 0; + X.B := 1; + Y.A := 2; + Y.B := 3; + if X = Y then Put('a'); end if; + X := Y; + if X = Y then Put('d'); end if;" +procedure Syracuse is,"procedure PrintInt(N: Integer) is + C: Integer := N rem 10; + begin + if N > 9 then PrintInt(N / 10); end if; + Put(Character'Val(48 + C));" +procedure length is,"v,j : integer; + procedure step is + begin + v := v+1; if j = 2*(j/2) then j := j/2; else j := 3*j+1; end if;" +procedure Record3 is,"type R is record A, B: Character; end record; + type S is record C: Character; D: R; E: Character; end record; + + procedure PrintR(x: R) is + begin + Put('['); + Put(x.A); + Put(','); + Put(x.B); + Put(']');" +procedure Quine is,"type str; + type u is access str; + type str is record + value : integer; + tail : u; + end record; + procedure puts(s : u) is begin + if s /= null then + put(character'val(s.value)); + puts(s.tail); + end if;" +procedure Print_int is,"procedure PrintInt(N: Integer) is + C: Integer := N rem 10; + begin + if N > 9 then PrintInt(N / 10); end if; + Put(Character'Val(48 + C));" +procedure Test is,"function F(X: Integer) return Integer is + begin + Put('F'); + return X;" +procedure josephus is,"type Node; + type List is access Node; + type Node is record + Value: Integer; + Prev, Next: List; + end record; + function Singleton(V: Integer) return List is + L: List := new Node; + begin + L.Value := V; + L.Prev := L; + L.Next := L; + return L;" +procedure NQueens is,"procedure PrintInt(N: Integer) is + C: Integer := N rem 10; + begin + if N > 9 then PrintInt(N / 10); end if; + Put(Character'Val(48 + C));" +procedure Mandelbrot is,"-- Ada 2012 + -- function Add(x, y: in Integer) return Integer is (X+Y); + -- function Sub(x, y: in Integer) return Integer is (X-Y); + -- function Mul(x, y: in Integer) return Integer is ((X * Y + 8192 / 2) / 8192); + -- function Div(x, y: in Integer) return Integer is ((X * 8192 + y / 2) / Y); + -- function OfInt(x: in Integer) return Integer is (X * 8192); + + function Add(x, y: in Integer) return Integer is + begin + return X+Y; + end Add; + function Sub(x, y: in Integer) return Integer is + begin + return X-Y; + end Sub; + function Mul(x, y: in Integer) return Integer is + T : Integer := X * Y; + begin + return (t + 8192 / 2) / 8192; + end Mul; + function Div(x, y: in Integer) return Integer is + T : Integer := X * 8192; + begin + return (t + y / 2) / y; + end Div; + function OfInt(x: in Integer) return Integer is + begin + return X * 8192; + end OfInt; + + function iter(N, A, B, Xn, Yn: in Integer) return Boolean is + xn2, Yn2 : Integer; + begin + if n = 100 then return true; end if; + xn2 := mul(xn, xn); + yn2 := mul(yn, yn); + if add(xn2, yn2) > ofint(4) then return false; end if; + return iter(n+1, a, b, add(sub(xn2, yn2), a), + add(mul(ofint(2), mul(xn, yn)), b));" +procedure Pascal is,"type Node; + type List is access Node; + type Node is record + Value: Integer; + Next: List; + end record; + + function Get(L: List; I: Integer) return Integer is + begin + if I = 0 then return L.Value; end if; + return Get(L.next, I - 1);" +procedure Fact is,"procedure PrintInt(N: Integer) is + C: Integer := N rem 10; + begin + if N > 9 then PrintInt(N / 10); end if; + Put(Character'Val(48 + C));" +procedure Test is,"type R is record A, B: Integer; end record; + + procedure P1(X, Y: in out R) is + begin + X.A := 0; + X.B := 1; + Y.A := 2; + Y.B := 3; + if X.A = Y.A and X.B = Y.B then Put('a'); end if; + X := Y; + if X.A = Y.A and X.B = Y.B then Put('d'); end if;" +procedure Test_a is,"procedure R(N: Integer) is + begin + if N = 0 then return; end if; + Put('a'); + R(N - 1);" +procedure Test is,"function F return character is + begin return 'a'; + end F; + function G(C: Character) return character is + begin return c; + end G; +begin + Put(F); New_Line; + Put(G('b')); New_Line; + Put(G(F)); New_Line;" +procedure BST is,"type Node; + type BST is access Node; + type Node is record + Value: Integer; + Left, Right: BST; + end record; + -- insertion utilisant le passage par référence + procedure Add(X: Integer; B: in out BST) is + begin + if B = null then B := new Node; B.Value := X; return; end if; + if X < B.Value then + Add(X, B.Left); + elsif X > B.Value then + Add(X, B.Right); + end if;" +procedure Fib is,"procedure PrintInt(N: Integer) is + C: Integer := N rem 10; + begin + if N > 9 then PrintInt(N / 10); end if; + Put(Character'Val(48 + C));" +procedure somme is,"tmp : integer; + begin fib(n-2); tmp := f; fib(n-1); f := f + Tmp; end; + begin + if n <= 1 then f := N; else somme; end if;" +procedure Clear is,"begin + null; + end Clear; + + -- ------------------------------ + -- Generate a random bitstream. + -- ------------------------------ + procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array) is + use Ada.Streams; + use Interfaces; + + Size : constant Stream_Element_Offset := Rand'Length / 4; + begin + -- Generate the random sequence. + for I in 0 .. Size - 1 loop + declare + Value : constant Unsigned_32 := Id_Random.Random (Random); + begin + Rand (4 * I) := Stream_Element (Value and 16#0FF#); + Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); + Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); + Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);" +procedure Dispatch (Server : in Rest_Servlet;,"Method : in Method_Type; + Request : in out Requests.Request'Class; + Response : in out Responses.Response'Class) is + pragma Unreferenced (Server); + + begin + if not Request.Has_Route then + Response.Set_Status (Responses.SC_NOT_FOUND); + Response.Set_Committed; + return; + end if; + declare + Route : constant Routes.Route_Type_Accessor := Request.Get_Route; + begin + if not (Route in Routes.Servlets.Rest.API_Route_Type'Class) then + Response.Set_Status (Responses.SC_NOT_FOUND); + Response.Set_Committed; + return; + end if; + declare + Api : constant access Routes.Servlets.Rest.API_Route_Type'Class + := Routes.Servlets.Rest.API_Route_Type'Class (Route.Element.all)'Access; + Desc : constant Descriptor_Access := Api.Descriptors (Method); + Output : constant Streams.Print_Stream := Response.Get_Output_Stream; + Mime : Mime_Access; + begin + if Desc = null then + Response.Set_Status (Responses.SC_NOT_FOUND); + Response.Set_Committed; + return; + end if; + Mime := Desc.Get_Mime_Type (Request); + if Mime = null or else Mime.all = Util.Http.Mimes.Json then + declare + Stream : Streams.JSON.Print_Stream; + begin + Streams.JSON.Initialize (Stream, Output); + Response.Set_Content_Type (""application/json; charset=utf-8""); + Api.Descriptors (Method).Dispatch (Request, Response, Stream);" +function Get_Permission (Handler : in Descriptor),"return Security.Permissions.Permission_Index is + begin + return Handler.Permission; + end Get_Permission; + + -- ------------------------------ + -- Get the mime type selected for the operation. + -- ------------------------------ + function Get_Mime_Type (Handler : in Descriptor; + Req : in Servlet.Rest.Request'Class) return Mime_Access is + Accept_Header : constant String := Req.Get_Header (""Accept""); + begin + if Handler.Mimes /= null then + return Util.Http.Headers.Get_Accepted (Accept_Header, Handler.Mimes.all); + else + return null; + end if; + end Get_Mime_Type; + + -- ------------------------------ + -- Register the API descriptor in a list. + -- ------------------------------ + procedure Register (List : in out Descriptor_Access; + Item : in Descriptor_Access) is + begin + Item.Next := List; + List := Item; + end Register; + + -- ------------------------------ + -- Register the list of API descriptors for a given servlet and a root path. + -- ------------------------------ + procedure Register (Registry : in out Servlet.Core.Servlet_Registry; + Name : in String; + URI : in String; + ELContext : in EL.Contexts.ELContext'Class; + List : in Descriptor_Access) is + procedure Insert (Route : in out Servlet.Routes.Route_Type_Ref); + Item : Descriptor_Access := List; + + procedure Insert (Route : in out Servlet.Routes.Route_Type_Ref) is + begin + if not Route.Is_Null then + declare + R : constant Servlet.Routes.Route_Type_Accessor := Route.Value; + D : access Servlet.Routes.Servlets.Rest.API_Route_Type'Class; + begin + if not (R in Servlet.Routes.Servlets.Rest.API_Route_Type'Class) then + Log.Error (""Route API for {0}/{1} already used by another page"", + URI, Item.Pattern.all); + return; + end if; + D := Servlet.Routes.Servlets.Rest.API_Route_Type'Class (R.Element.all)'Access; + if D.Descriptors (Item.Method) /= null then + Log.Error (""Route API for {0}/{1} is already used"", URI, Item.Pattern.all); + end if; + D.Descriptors (Item.Method) := Item;" +procedure Dispatch (Handler : in Static_Descriptor;,"Req : in out Servlet.Rest.Request'Class; + Reply : in out Servlet.Rest.Response'Class; + Stream : in out Output_Stream'Class) is + begin + Handler.Handler (Req, Reply, Stream); + end Dispatch; + + -- ------------------------------ + -- Register the API definition in the servlet registry. + -- ------------------------------ + procedure Register (Registry : in out Servlet.Core.Servlet_Registry'Class; + Definition : in Descriptor_Access) is + use type Servlet.Core.Servlet_Access; + procedure Insert (Route : in out Routes.Route_Type_Ref); + + Dispatcher : constant Servlet.Core.Request_Dispatcher + := Registry.Get_Request_Dispatcher (Definition.Pattern.all); + Servlet : constant Core.Servlet_Access := Core.Get_Servlet (Dispatcher); + + procedure Insert (Route : in out Routes.Route_Type_Ref) is + begin + if not Route.Is_Null then + declare + R : constant Routes.Route_Type_Accessor := Route.Value; + D : access Routes.Servlets.Rest.API_Route_Type'Class; + begin + if not (R in Routes.Servlets.Rest.API_Route_Type'Class) then + Log.Error (""Route API for {0} already used by another page"", + Definition.Pattern.all); + D := Core.Rest.Create_Route (Servlet); + Route := Routes.Route_Type_Refs.Create (D.all'Access); + else + D := Routes.Servlets.Rest.API_Route_Type'Class (R.Element.all)'Access; + end if; + if D.Descriptors (Definition.Method) /= null then + Log.Error (""Route API for {0} is already used"", Definition.Pattern.all); + end if; + D.Descriptors (Definition.Method) := Definition;" +procedure Free is,"new Ada.Unchecked_Deallocation (Object => Binding_Array, + Name => Binding_Array_Access); + procedure Free is + new Ada.Unchecked_Deallocation (Object => Binding, + Name => Binding_Access); + + -- ------------------------------ + -- Get the current registry associated with the current request being processed + -- by the current thread. Returns null if there is no current request. + -- ------------------------------ + function Current return Servlet.Core.Servlet_Registry_Access is + begin + return Task_Context.Value.Application; + end Current; + + -- ------------------------------ + -- Set the current registry (for unit testing mostly). + -- ------------------------------ + procedure Set_Context (Context : in Servlet.Core.Servlet_Registry_Access) is + C : Request_Context; + begin + C.Application := Context; + C.Request := null; + C.Response := null; + Set_Context (C); + end Set_Context; + + -- ------------------------------ + -- Set the current registry. This is called by Service once the + -- registry is identified from the URI. + -- ------------------------------ + procedure Set_Context (Context : in Request_Context) is + begin + Task_Context.Set_Value (Context); + end Set_Context; + + -- ------------------------------ + -- Give access to the current request and response object to the `Process` + -- procedure. If there is no current request for the thread, do nothing. + -- ------------------------------ + procedure Update_Context (Process : not null access + procedure (Request : in out Requests.Request'Class; + Response : in out Responses.Response'Class)) is + Ctx : constant Request_Context := Task_Context.Value; + begin + Process (Ctx.Request.all, Ctx.Response.all); + end Update_Context; + + -- ------------------------------ + -- Register the application to serve requests + -- ------------------------------ + procedure Register_Application (Server : in out Container; + URI : in String; + Context : in Core.Servlet_Registry_Access) is + Count : constant Natural := Server.Nb_Bindings; + Apps : constant Binding_Array_Access := new Binding_Array (1 .. Count + 1); + Old : Binding_Array_Access := Server.Applications; + begin + Log.Info (""Register application {0}"", URI); + + if Old /= null then + Apps (1 .. Count) := Server.Applications (1 .. Count); + end if; + Apps (Count + 1) := new Binding '(Len => URI'Length, Context => Context, Base_URI => URI); + + -- Inform the servlet registry about the base URI. + Context.Register_Application (URI); + + -- Start the application if the container is started. + if Server.Is_Started and then Context.Get_Status = Core.Ready then + Context.Start; + end if; + + -- Update the binding. + Server.Applications := Apps; + Server.Nb_Bindings := Count + 1; + if Old /= null then + Free (Old); + end if; + end Register_Application; + + -- ------------------------------ + -- Remove the application + -- ------------------------------ + procedure Remove_Application (Server : in out Container; + Context : in Core.Servlet_Registry_Access) is + use type Servlet.Core.Servlet_Registry_Access; + + Count : constant Natural := Server.Nb_Bindings; + Old : Binding_Array_Access := Server.Applications; + Apps : Binding_Array_Access; + begin + for I in 1 .. Count loop + if Old (I).Context = Context then + Log.Info (""Removed application {0}"", Old (I).Base_URI); + Free (Old (I)); + if I < Count then + Old (I) := Old (Count); + end if; + if Count > 1 then + Apps := new Binding_Array (1 .. Count - 1); + Apps.all := Old (1 .. Count - 1); + else + Apps := null; + end if; + Server.Applications := Apps; + Server.Nb_Bindings := Count - 1; + Free (Old); + return; + end if; + end loop; + end Remove_Application; + + -- ------------------------------ + -- Start the applications that have been registered. + -- ------------------------------ + procedure Start (Server : in out Container) is + begin + if Server.Applications /= null then + for Application of Server.Applications.all loop + if Application.Context.Get_Status = Core.Ready then + Log.Info (""Starting application {0}"", Application.Base_URI); + Application.Context.Start; + end if; + end loop; + end if; + Server.Is_Started := True; + end Start; + + -- ------------------------------ + -- Receives standard HTTP requests from the public service method and + -- dispatches them to the Do_XXX methods defined in this class. This method + -- is an HTTP-specific version of the Servlet.service(Request, Response) + -- method. There's no need to override this method. + -- ------------------------------ + procedure Service (Server : in Container; + Request : in out Requests.Request'Class; + Response : in out Responses.Response'Class) is + + use Util.Strings; + + URI : constant String := Request.Get_Request_URI; + Slash_Pos : constant Natural := Index (URI, '/', URI'First + 1); + Apps : constant Binding_Array_Access := Server.Applications; + Prefix_End : Natural; + begin + if Apps = null then + Response.Set_Status (Responses.SC_NOT_FOUND); + Server.Default.Send_Error_Page (Request, Response); + return; + end if; + + -- Find the module and action to invoke + if Slash_Pos > 1 then + Prefix_End := Slash_Pos - 1; + else + Prefix_End := URI'Last; + end if; + + for Application of Apps.all loop + if Application.Base_URI = URI (URI'First .. Prefix_End) + and then Application.Context.Get_Status = Core.Started + then + declare + Req : Request_Context; + Context : constant Core.Servlet_Registry_Access := Application.Context; + Page : constant String := URI (Prefix_End + 1 .. URI'Last); + Dispatcher : constant Core.Request_Dispatcher + := Context.Get_Request_Dispatcher (Page); + begin + Log.Info (""{0} {1}"", Request.Get_Method, Page); + Req.Request := Request'Unchecked_Access; + Req.Response := Response'Unchecked_Access; + Req.Application := Context; + Set_Context (Req); + Core.Forward (Dispatcher, Request, Response); + case Response.Get_Status / 100 is + when 2 | 3 => + null; + + when others => + if not Response.Is_Committed then + Context.Send_Error_Page (Request, Response); + end if; + + end case; + Set_Context (Null_Context); + return; + + exception + when E : others => + Context.Error (Request, Response, E); + Set_Context (Null_Context); + return;" +function Get_Request_Dispatcher (Context : in Servlet_Registry;,"Path : in String) + return Request_Dispatcher is + use type Filters.Filter_List_Access; + begin + return R : Request_Dispatcher do + Context.Routes.Find_Route (Path, R.Context); + if not Routes.Is_Null (R.Context) then + declare + use Routes.Servlets; + + Route : constant Routes.Route_Type_Accessor := Routes.Get_Route (R.Context); + begin + if Route in Routes.Servlets.Servlet_Route_Type'Class then + declare + Servlet_Route : constant access Routes.Servlets.Servlet_Route_Type'Class + := Routes.Servlets.Servlet_Route_Type'Class (Route.Element.all)'Access; + Proxy : Routes.Servlets.Proxy_Route_Type_Access; + begin + if Servlet_Route.Filters /= null then + R.Filters := Servlet_Route.Filters.all'Access; + end if; + if Servlet_Route.all in Routes.Servlets.Proxy_Route_Type'Class then + Proxy := Proxy_Route_Type'Class (Servlet_Route.all)'Access; + Routes.Change_Route (R.Context, Proxy.Route); + R.Servlet + := Servlet_Route_Type'Class (Proxy.Route.Value.Element.all).Servlet; + else + R.Servlet := Servlet_Route.Servlet; + end if;" +function Get_Name_Dispatcher (Context : in Servlet_Registry;,"Name : in String) + return Request_Dispatcher is + Pos : constant Servlet_Maps.Cursor := Context.Servlets.Find (Name); + begin + if not Servlet_Maps.Has_Element (Pos) then + raise Servlet_Error with ""No servlet "" & Name; + end if; + return R : Request_Dispatcher do + R.Servlet := Servlet_Maps.Element (Pos); + end return; + end Get_Name_Dispatcher; + + -- ------------------------------ + -- Returns the context path of the web application. + -- The context path is the portion of the request URI that is used to select the context + -- of the request. The context path always comes first in a request URI. The path starts + -- with a ""/"" character but does not end with a ""/"" character. For servlets in the default + -- (root) context, this method returns """". + -- ------------------------------ + function Get_Context_Path (Context : in Servlet_Registry) return String is + begin + return To_String (Context.Context_Path); + end Get_Context_Path; + + -- ------------------------------ + -- Returns a String containing the value of the named context-wide initialization + -- parameter, or null if the parameter does not exist. + -- + -- This method can make available configuration information useful to an entire + -- ""web application"". For example, it can provide a webmaster's email address + -- or the name of a system that holds critical data. + -- ------------------------------ + function Get_Init_Parameter (Context : in Servlet_Registry; + Name : in String; + Default : in String := """") return String is + begin + return Context.Config.Get (Name, Default); + end Get_Init_Parameter; + + function Get_Init_Parameter (Context : in Servlet_Registry; + Name : in String; + Default : in String := """") + return Ada.Strings.Unbounded.Unbounded_String is + begin + if Context.Config.Exists (Name) then + return Context.Config.Get (Name); + else + return Ada.Strings.Unbounded.To_Unbounded_String (Default); + end if; + end Get_Init_Parameter; + + -- ------------------------------ + -- Set the init parameter identified by Name to the value Value. + -- ------------------------------ + procedure Set_Init_Parameter (Context : in out Servlet_Registry; + Name : in String; + Value : in String) is + begin + Log.Debug (""Set {0}={1}"", Name, Value); + + Context.Config.Set (Name, Value); + end Set_Init_Parameter; + + -- ------------------------------ + -- Set the init parameters by copying the properties defined in Params. + -- Existing parameters will be overriding by the new values. + -- ------------------------------ + procedure Set_Init_Parameters (Context : in out Servlet_Registry; + Params : in Util.Properties.Manager'Class) is + begin + Context.Config.Copy (Params); + end Set_Init_Parameters; + + -- ------------------------------ + -- Get access to the init parameters. + -- ------------------------------ + procedure Get_Init_Parameters (Context : in Servlet_Registry; + Process : not null access + procedure (Params : in Util.Properties.Manager'Class)) is + begin + Process (Context.Config); + end Get_Init_Parameters; + + -- ------------------------------ + -- Returns the absolute path of the resource identified by the given relative path. + -- The resource is searched in a list of directories configured by the application. + -- The path must begin with a ""/"" and is interpreted as relative to the current + -- context root. + -- + -- This method allows the servlet container to make a resource available to + -- servlets from any source. + -- + -- This method returns an empty string if the resource could not be localized. + -- ------------------------------ + function Get_Resource (Context : in Servlet_Registry; + Path : in String) return String is + Paths : constant String := Context.Get_Init_Parameter (""view.dir""); + Result : constant String := Util.Files.Find_File_Path (Name => Path, Paths => Paths); + begin + if Result = Path then + return """"; + else + return Result; + end if; + end Get_Resource; + + -- ------------------------------ + -- Registers the given servlet instance with this ServletContext under + -- the given servletName. + -- + -- If this ServletContext already contains a preliminary + -- ServletRegistration for a servlet with the given servletName, + -- it will be completed (by assigning the class name of the given + -- servlet instance to it) and returned. + -- ------------------------------ + procedure Add_Servlet (Registry : in out Servlet_Registry; + Name : in String; + Server : in Servlet_Access) is + begin + Log.Info (""Add servlet '{0}'"", Name); + + if Server.Context /= null then + Log.Error (""Servlet '{0}' already registered in a servlet registry"", Server.Get_Name); + raise Servlet_Error; + end if; + + Server.Name := To_Unbounded_String (Name); + Server.Context := Registry'Unchecked_Access; + Servlet_Maps.Include (Registry.Servlets, Name, Server); + end Add_Servlet; + + -- ------------------------------ + -- Registers the given filter instance with this Servlet context. + -- ------------------------------ + procedure Add_Filter (Registry : in out Servlet_Registry; + Name : in String; + Filter : in Filter_Access) is + begin + Log.Info (""Add servlet filter '{0}'"", Name); + + Filter_Maps.Include (Registry.Filters, Name, + Filter.all'Unchecked_Access); + end Add_Filter; + + -- ------------------------------ + -- Causes the next filter in the chain to be invoked, or if the calling + -- filter is the last filter in the chain, causes the resource at the end + -- of the chain to be invoked. + -- ------------------------------ + procedure Do_Filter (Chain : in out Filter_Chain; + Request : in out Requests.Request'Class; + Response : in out Responses.Response'Class) is + begin + if Chain.Filter_Pos = 0 then + Chain.Servlet.Service (Request, Response); + else + declare + Filter : constant Filters.Filter_Access := Chain.Filters (Chain.Filter_Pos); + begin + Chain.Filter_Pos := Chain.Filter_Pos - 1; + Filter.Do_Filter (Request, Response, Chain);" +procedure Make_Route;,"procedure Initialize_Filter (Key : in String; + Filter : in Filter_Access); + procedure Initialize_Servlet (Pos : in Servlet_Maps.Cursor); + + procedure Process (URI : in String; + Route : in Routes.Route_Type_Accessor) is + Iter : Util.Strings.Vectors.Cursor := Registry.Filter_Patterns.First; + Servlet_Route : access Routes.Servlets.Servlet_Route_Type'Class; + begin + if not (Route in Routes.Servlets.Servlet_Route_Type'Class) then + return; + end if; + Servlet_Route := Routes.Servlets.Servlet_Route_Type'Class (Route.Element.all)'Access; + while Util.Strings.Vectors.Has_Element (Iter) loop + declare + Pattern : constant String := Util.Strings.Vectors.Element (Iter); + Filter : Filter_List_Access; + begin + if Match_Pattern (Pattern, URI) then + Filter := Registry.Filter_Rules.Element (Pattern); + for I in Filter'Range loop + Routes.Servlets.Append_Filter (Servlet_Route.all, Filter (I).all'Access); + end loop; + end if;" +procedure Make_Route is,"Context : aliased EL.Contexts.Default.Default_Context; + Iter : Util.Strings.Vectors.Cursor := Registry.Filter_Patterns.First; + begin + while Util.Strings.Vectors.Has_Element (Iter) loop + declare + use Routes.Servlets; + procedure Insert (Ref : in out Routes.Route_Type_Ref); + + Pattern : constant String := Util.Strings.Vectors.Element (Iter); + Route : Routes.Route_Context_Type; + + procedure Insert (Ref : in out Routes.Route_Type_Ref) is + Proxy : Routes.Servlets.Proxy_Route_Type_Access; + begin + if Ref.Is_Null then + Proxy := new Routes.Servlets.Proxy_Route_Type; + Proxy.Route := Route.Get_Route; + + -- If the route is also a proxy, get the real route pointed to by the proxy. + if Proxy.Route.Value in Proxy_Route_Type'Class then + Proxy.Route + := Proxy_Route_Type'Class (Proxy.Route.Value.Element.all).Route; + end if; + Ref := Routes.Route_Type_Refs.Create (Proxy.all'Access); + end if; + end Insert; + + begin + Registry.Routes.Find_Route (Pattern, Route); + if not Route.Is_Null then + Registry.Routes.Add_Route (Pattern, Context, Insert'Access); + end if;" +procedure Disable (Registry : in out Servlet_Registry) is,"begin + case Registry.Status is + when Ready => + Registry.Status := Disabled; + + when Started => + Registry.Status := Suspended; + + when Disabled | Suspended | Stopped => + null; + + end case; + end Disable; + + -- ------------------------------ + -- Enable the application. + -- ------------------------------ + procedure Enable (Registry : in out Servlet_Registry) is + begin + case Registry.Status is + when Disabled => + Registry.Status := Ready; + + when Suspended => + Registry.Status := Started; + + when Ready | Started | Stopped => + null; + + end case; + end Enable; + + -- ------------------------------ + -- Stop the application. + -- ------------------------------ + procedure Stop (Registry : in out Servlet_Registry) is + begin + case Registry.Status is + when Ready | Disabled | Stopped => + null; + + when Started | Suspended => + Registry.Status := Stopped; + + end case; + end Stop; + + procedure Free is + new Ada.Unchecked_Deallocation (Object => Filters.Filter_List, + Name => Filter_List_Access); + + -- ------------------------------ + -- Add a filter mapping with the given pattern + -- If the URL pattern is already mapped to a different servlet, + -- no updates will be performed. + -- ------------------------------ + procedure Add_Filter_Mapping (Registry : in out Servlet_Registry; + Pattern : in String; + Name : in String) is + procedure Append (Key : in String; + List : in out Filter_List_Access); + + Pos : constant Filter_Maps.Cursor := Registry.Filters.Find (Name); + Rule : constant Filter_List_Maps.Cursor := Registry.Filter_Rules.Find (Pattern); + + -- ------------------------------ + -- Append the filter in the filter list. + -- ------------------------------ + procedure Append (Key : in String; + List : in out Filter_List_Access) is + pragma Unreferenced (Key); + use Filters; + + Filter : constant Filters.Filter_Access := Filter_Maps.Element (Pos).all'Access; + New_List : Filter_List_Access; + begin + -- Check that the filter is not already executed. + for I in List'Range loop + if List (I) = Filter then + return; + end if; + end loop; + + New_List := new Filters.Filter_List (1 .. List'Last + 1); + New_List.all (2 .. New_List'Last) := List.all; + New_List (New_List'First) := Filter; + Free (List); + List := New_List; + end Append; + + List : Filter_List_Access; + + begin + Log.Info (""Add filter mapping {0} -> {1}"", Pattern, Name); + + if not Filter_Maps.Has_Element (Pos) then + Log.Error (""No servlet filter {0}"", Name); + raise Servlet_Error with ""No servlet filter "" & Name; + end if; + if not Filter_List_Maps.Has_Element (Rule) then + Registry.Filter_Patterns.Append (Pattern); + List := new Filters.Filter_List (1 .. 1); + List (List'First) := Filter_Maps.Element (Pos).all'Access; + Registry.Filter_Rules.Insert (Pattern, List); + else + Registry.Filter_Rules.Update_Element (Rule, Append'Access); + end if; + end Add_Filter_Mapping; + + -- ------------------------------ + -- Add a servlet mapping with the given pattern + -- If the URL pattern is already mapped to a different servlet, + -- no updates will be performed. + -- ------------------------------ + procedure Add_Mapping (Registry : in out Servlet_Registry; + Pattern : in String; + Name : in String) is + Pos : constant Servlet_Maps.Cursor := Registry.Servlets.Find (Name); + begin + if not Servlet_Maps.Has_Element (Pos) then + Log.Error (""No servlet {0}"", Name); + raise Servlet_Error with ""No servlet "" & Name; + end if; + + Log.Info (""Add servlet mapping {0} -> {1}"", Pattern, Name); + Registry.Add_Mapping (Pattern, Servlet_Maps.Element (Pos)); + end Add_Mapping; + + -- ------------------------------ + -- Add a servlet mapping with the given pattern + -- If the URL pattern is already mapped to a different servlet, + -- no updates will be performed. + -- ------------------------------ + procedure Add_Mapping (Registry : in out Servlet_Registry; + Pattern : in String; + Server : in Servlet_Access) is + procedure Insert (Route : in out Routes.Route_Type_Ref); + + procedure Insert (Route : in out Routes.Route_Type_Ref) is + To : Routes.Servlets.Servlet_Route_Type_Access; + begin + if Route.Is_Null then + To := new Routes.Servlets.Servlet_Route_Type; + To.Servlet := Server; + Route := Routes.Route_Type_Refs.Create (To.all'Access); + else + Log.Warn (""Mapping {0} already defined"", Pattern); + end if; + end Insert; + + Context : aliased EL.Contexts.Default.Default_Context; + begin + if Pattern'Length = 0 or else Server = null then + return; + end if; + Registry.Routes.Add_Route (Pattern, Context, Insert'Access); + end Add_Mapping; + + -- ------------------------------ + -- Add a route associated with the given path pattern. The pattern is split into components. + -- Some path components can be a fixed string (/home) and others can be variable. + -- When a path component is variable, the value can be retrieved from the route context. + -- Once the route path is created, the Process procedure is called with the route + -- reference. + -- ------------------------------ + procedure Add_Route (Registry : in out Servlet_Registry; + Pattern : in String; + ELContext : in EL.Contexts.ELContext'Class; + Process : not null access + procedure (Route : in out Routes.Route_Type_Ref)) is + begin + Registry.Routes.Add_Route (Pattern, ELContext, Process); + end Add_Route; + + -- ------------------------------ + -- Set the error page that will be used if a servlet returns an error. + -- ------------------------------ + procedure Set_Error_Page (Server : in out Servlet_Registry; + Error : in Integer; + Page : in String) is + begin + Log.Info (""Using page {0} for http error {1}"", Page, Integer'Image (Error)); + + Server.Error_Pages.Include (Error, Page); + end Set_Error_Page; + + function Hash (N : Integer) return Ada.Containers.Hash_Type is + begin + return Ada.Containers.Hash_Type (N); + end Hash; + + -- ------------------------------ + -- Send the error page content defined by the response status. + -- ------------------------------ + procedure Send_Error_Page (Server : in Servlet_Registry; + Request : in out Requests.Request'Class; + Response : in out Responses.Response'Class) is + URI : constant String := Request.Get_Request_URI; + Status : constant Natural := Response.Get_Status; + Pos : constant Error_Maps.Cursor := Server.Error_Pages.Find (Status); + begin + Request.Set_Attribute (""servlet.error.status_code"", EL.Objects.To_Object (Integer (Status))); + Request.Set_Attribute (""servlet.error.request_uri"", EL.Objects.To_Object (URI)); + + if Error_Maps.Has_Element (Pos) then + declare + Page : constant String := Error_Maps.Element (Pos); + Dispatcher : constant Request_Dispatcher + := Server.Get_Request_Dispatcher (Page); + begin + Forward (Dispatcher, Request, Response); + return; + + exception + when others => + null;" +procedure Register_Application (Registry : in out Servlet_Registry;,"URI : in String) is + begin + Registry.Context_Path := To_Unbounded_String (URI); + end Register_Application; + + -- ------------------------------ + -- Finalize the servlet registry releasing the internal mappings. + -- ------------------------------ + overriding + procedure Finalize (Registry : in out Servlet_Registry) is + begin + -- Release the filter mapping lists that have been allocated. + while not Registry.Filter_Rules.Is_Empty loop + declare + Pos : Filter_List_Maps.Cursor := Registry.Filter_Rules.First; + Filter : Filter_List_Access := Filter_List_Maps.Element (Pos).all'Access; + begin + Free (Filter); + Registry.Filter_Rules.Delete (Pos);" +procedure Free is,"new Ada.Unchecked_Deallocation (Object => String, Name => String_Access); + begin + Free (Context.Path); + end Finalize; + + -- ------------------------------ + -- Insert the route node at the correct place in the children list + -- according to the rule kind. + -- ------------------------------ + procedure Insert (Parent : in Route_Node_Access; + Node : in Route_Node_Access; + Kind : in Route_Match_Type) is + Previous, Current : Route_Node_Access; + begin + Current := Parent.Children; + case Kind is + -- Add at head of the list. + when YES_MATCH => + null; + + when MAYBE_MATCH => + while Current /= null loop + if not (Current.all in Path_Node_Type'Class) then + exit; + end if; + Previous := Current; + Current := Current.Next_Route; + end loop; + + -- Add before the + when EXT_MATCH => + while Current /= null loop + if not (Current.all in Path_Node_Type'Class) + and then not (Current.all in Param_Node_Type'Class) + and then not (Current.all in EL_Node_Type'Class) + then + exit; + end if; + Previous := Current; + Current := Current.Next_Route; + end loop; + + when WILDCARD_MATCH => + while Current /= null loop + Previous := Current; + Current := Current.Next_Route; + end loop; + + when others => + null; + + end case; + if Previous /= null then + Node.Next_Route := Previous.Next_Route; + Previous.Next_Route := Node; + else + Node.Next_Route := Parent.Children; + Parent.Children := Node; + end if; + end Insert; + + -- ------------------------------ + -- Add a route associated with the given path pattern. The pattern is split into components. + -- Some path components can be a fixed string (/home) and others can be variable. + -- When a path component is variable, the value can be retrieved from the route context. + -- Once the route path is created, the Process procedure is called with the route + -- reference. + -- ------------------------------ + procedure Add_Route (Router : in out Router_Type; + Pattern : in String; + ELContext : in EL.Contexts.ELContext'Class; + Process : not null access procedure (Route : in out Route_Type_Ref)) is + First : Natural := Pattern'First; + Pos : Natural; + Node : Route_Node_Access := Router.Route.Children; + Match : Route_Match_Type := NO_MATCH; + New_Path : Path_Node_Access; + Parent : Route_Node_Access := Router.Route'Unchecked_Access; + Parent2 : Route_Node_Access; + Found : Boolean; + begin + Log.Info (""Adding route {0}"", Pattern); + loop + -- Ignore consecutive '/'. + while First <= Pattern'Last and then Pattern (First) = '/' loop + First := First + 1; + end loop; + + -- Find the path component's end. + Pos := Util.Strings.Index (Pattern, '/', First); + if Pos = 0 then + Pos := Pattern'Last; + else + Pos := Pos - 1; + end if; + if First > Pattern'Last then + Found := False; + + -- Find an exact match for this component. + while Node /= null loop + if Node.all in Path_Node_Type'Class then + Match := Node.Matches (Pattern (First .. Pos), Pos = Pattern'Last); + if Match = YES_MATCH then + Parent := Node; + Node := Node.Children; + Found := True; + exit; + end if; + end if; + Node := Node.Next_Route; + end loop; + + -- Add a path node matching the component at beginning of the children list. + -- (before the Param_Node and EL_Node instances if any). + if not Found then + New_Path := new Path_Node_Type (Len => 0); + Insert (Parent, New_Path.all'Access, YES_MATCH); + Parent := Parent.Children; + end if; + elsif Pattern (First) = '#' then + declare + E : EL_Node_Access; + begin + Found := False; + + -- Find the EL_Node that have the same EL expression. + while Node /= null loop + if Node.all in EL_Node_Type'Class then + E := EL_Node_Type'Class (Node.all)'Access; + if E.Value.Get_Expression = Pattern (First .. Pos) then + Parent := Node; + Node := Node.Children; + Found := True; + exit; + end if; + end if; + Node := Node.Next_Route; + end loop; + + if not Found then + E := new EL_Node_Type; + E.Value := EL.Expressions.Create_Expression (Pattern (First .. Pos), ELContext); + Insert (Parent, E.all'Access, MAYBE_MATCH); + Parent := E.all'Access; + end if;" +procedure Set_Permission_Manager (Filter : in out Auth_Filter;,"Manager : in Policies.Policy_Manager_Access) is + begin + Filter.Manager := Manager; + end Set_Permission_Manager; + + -- ------------------------------ + -- Filter the request to make sure the user is authenticated. + -- Invokes the Do_Login procedure if there is no user. + -- If a permission manager is defined, check that the user has the permission + -- to view the page. Invokes the Do_Deny procedure if the permission + -- is denied. + -- ------------------------------ + overriding + procedure Do_Filter (F : in Auth_Filter; + Request : in out Servlet.Requests.Request'Class; + Response : in out Servlet.Responses.Response'Class; + Chain : in out Servlet.Core.Filter_Chain) is + use Ada.Strings.Unbounded; + use Policies.URLs; + use type Policies.Policy_Manager_Access; + + Session : Servlet.Sessions.Session; + SID : Unbounded_String; + AID : Unbounded_String; + Auth : Servlet.Principals.Principal_Access; + + pragma Unreferenced (SID); + + procedure Fetch_Cookie (Cookie : in Servlet.Cookies.Cookie); + + -- ------------------------------ + -- Collect the AID and SID cookies. + -- ------------------------------ + procedure Fetch_Cookie (Cookie : in Servlet.Cookies.Cookie) is + Name : constant String := Servlet.Cookies.Get_Name (Cookie); + begin + if Name = SID_COOKIE then + SID := To_Unbounded_String (Servlet.Cookies.Get_Value (Cookie)); + elsif Name = AID_COOKIE then + AID := To_Unbounded_String (Servlet.Cookies.Get_Value (Cookie)); + end if; + end Fetch_Cookie; + + Context : aliased Contexts.Security_Context; + begin + Request.Iterate_Cookies (Fetch_Cookie'Access); + + -- Get a session but avoid creating it. + Session := Request.Get_Session (Create => False); + if Session.Is_Valid then + Auth := Session.Get_Principal; + end if; + + -- If the session does not have a principal, try to authenticate the user with + -- the auto-login cookie. + if Auth = null and then Length (AID) > 0 then + Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth); + if Auth /= null then + + -- Now we must make sure we have a valid session and create it if necessary. + if not Session.Is_Valid then + Session := Request.Get_Session (Create => True); + end if; + Session.Set_Principal (Auth); + end if; + end if; + + -- A permission manager is installed, check that the user can display the page. + if F.Manager /= null then + if Auth = null then + Context.Set_Context (F.Manager, null); + else + Context.Set_Context (F.Manager, Auth.all'Access); + end if; + declare + Servlet : constant String := Request.Get_Servlet_Path; + URL : constant String := Servlet & Request.Get_Path_Info; + Perm : constant Policies.URLs.URL_Permission (URL'Length) + := URL_Permission '(Len => URL'Length, URL => URL); + begin + if not F.Manager.Has_Permission (Context, Perm) then + if Auth = null then + -- No permission and no principal, redirect to the login page. + Log.Info (""Page need authentication on {0}"", URL); + Auth_Filter'Class (F).Do_Login (Request, Response); + else + Log.Info (""Deny access on {0}"", URL); + Auth_Filter'Class (F).Do_Deny (Request, Response); + end if; + return; + end if; + Log.Debug (""Access granted on {0}"", URL);" +procedure List (Data : in out Test_API;,"Req : in out Servlet.Rest.Request'Class; + Reply : in out Servlet.Rest.Response'Class; + Stream : in out Servlet.Rest.Output_Stream'Class) is + pragma Unreferenced (Data); + begin + if Req.Get_Path_Parameter_Count = 0 then + Stream.Start_Document; + Stream.Start_Array (""list""); + for I in 1 .. 10 loop + Stream.Start_Entity (""item""); + Stream.Write_Attribute (""id"", I); + Stream.Write_Attribute (""name"", ""Item "" & Natural'Image (I)); + Stream.End_Entity (""item""); + end loop; + Stream.End_Array (""list""); + Stream.End_Document; + else + declare + Id : constant String := Req.Get_Path_Parameter (1); + begin + if Id = ""100"" then + Reply.Set_Status (Servlet.Responses.SC_NOT_FOUND); + elsif Id /= ""44"" then + Reply.Set_Status (Servlet.Responses.SC_GONE); + end if;" +procedure Test_Request_Dispatcher (T : in out Test) is,"Ctx : Servlet_Registry; + + S1 : aliased Test_Servlet1; + begin + Ctx.Add_Servlet (""Faces"", S1'Unchecked_Access); + + Ctx.Add_Mapping (Pattern => ""*.jsf"", Name => ""Faces""); + + Ctx.Add_Mapping (Pattern => ""/p1/p2/p3/*"", Name => ""Faces""); + + Check_Request (T, Ctx, ""/home/test.jsf"", ""/home/test.jsf"", """"); + end Test_Request_Dispatcher; + + -- ------------------------------ + -- Test mapping and servlet path on a request. + -- ------------------------------ + procedure Test_Servlet_Path (T : in out Test) is + Ctx : Servlet_Registry; + + S1 : aliased Test_Servlet1; + begin + Ctx.Add_Servlet (""Faces"", S1'Unchecked_Access); + + Ctx.Add_Mapping (Pattern => ""*.jsf"", Name => ""Faces""); + + Ctx.Add_Mapping (Pattern => ""/p1/p2/p3/*"", Name => ""Faces""); + + Check_Request (T, Ctx, ""/p1/p2/p3/home/test.html"", ""/p1/p2/p3"", ""/home/test.html""); + Check_Request (T, Ctx, ""/root/home/test.jsf"", ""/root/home/test.jsf"", """"); + Check_Request (T, Ctx, ""/test.jsf"", ""/test.jsf"", """"); + end Test_Servlet_Path; + + -- ------------------------------ + -- Test mapping and servlet path on a request. + -- ------------------------------ + procedure Test_Filter_Mapping (T : in out Test) is + Ctx : Servlet_Registry; + + S1 : aliased Test_Servlet1; + S2 : aliased Test_Servlet2; + F1 : aliased Filters.Dump.Dump_Filter; + F2 : aliased Filters.Dump.Dump_Filter; + begin + Ctx.Add_Servlet (""Faces"", S1'Unchecked_Access); + Ctx.Add_Servlet (""Json"", S2'Unchecked_Access); + Ctx.Add_Filter (""Dump"", F1'Unchecked_Access); + Ctx.Add_Filter (""Dump2"", F2'Unchecked_Access); + Ctx.Add_Mapping (Pattern => ""*.html"", Name => ""Faces""); + Ctx.Add_Mapping (Pattern => ""*.json"", Name => ""Json""); + Ctx.Add_Filter_Mapping (Pattern => ""/dump/file.html"", Name => ""Dump""); + Ctx.Add_Filter_Mapping (Pattern => ""/dump/result/test.html"", Name => ""Dump""); + Ctx.Add_Filter_Mapping (Pattern => ""/dump/result/test.html"", Name => ""Dump2""); + Ctx.Start; + T.Check_Mapping (Ctx, ""test.html"", S1'Unchecked_Access); + T.Check_Mapping (Ctx, ""file.html"", S1'Unchecked_Access); + T.Check_Mapping (Ctx, ""/dump/test.html"", S1'Unchecked_Access); + T.Check_Mapping (Ctx, ""/dump/file.html"", S1'Unchecked_Access, 1); + T.Check_Mapping (Ctx, ""/dump/result/test.html"", S1'Unchecked_Access, 2); + T.Check_Mapping (Ctx, ""test.json"", S2'Unchecked_Access); + end Test_Filter_Mapping; + + -- ------------------------------ + -- Test execution of filters + -- ------------------------------ + procedure Test_Filter_Execution (T : in out Test) is + Ctx : Servlet_Registry; + + S1 : aliased Test_Servlet1; + S2 : aliased Test_Servlet2; + F1 : aliased Filters.Tests.Test_Filter; + F2 : aliased Filters.Tests.Test_Filter; + begin + Ctx.Add_Servlet (""Faces"", S1'Unchecked_Access); + Ctx.Add_Servlet (""Json"", S2'Unchecked_Access); + Ctx.Add_Filter (""F1"", F1'Unchecked_Access); + Ctx.Add_Filter (""F2"", F2'Unchecked_Access); + Ctx.Add_Mapping (Pattern => ""*.html"", Name => ""Faces""); + Ctx.Add_Mapping (Pattern => ""*.json"", Name => ""Json""); + Ctx.Add_Filter_Mapping (Pattern => ""/html/*.html"", Name => ""F1""); + Ctx.Add_Filter_Mapping (Pattern => ""/json/*.json"", Name => ""F2""); + Ctx.Add_Filter_Mapping (Pattern => ""/list/*.html"", Name => ""F1""); + Ctx.Add_Filter_Mapping (Pattern => ""/list/*.json"", Name => ""F1""); + Ctx.Add_Filter_Mapping (Pattern => ""/list/admin/*.html"", Name => ""F2""); + Ctx.Add_Filter_Mapping (Pattern => ""/list/admin/*.json"", Name => ""F2""); + Ctx.Start; + Ctx.Dump_Routes (Util.Log.INFO_LEVEL); + + -- Filter not traversed. + T.Check_Mapping (Ctx, ""test.html"", S1'Unchecked_Access); + T.Check_Mapping (Ctx, ""test.json"", S2'Unchecked_Access); + T.Check_Request (Ctx, ""test.html"", ""test.html"", """"); + Assert_Equals (T, 0, F1.Counter, ""Filter was not executed for *.html and *.json""); + Assert_Equals (T, 0, F2.Counter, ""Filter was not executed for *.html and *.json""); + + T.Check_Mapping (Ctx, ""/html/test.json"", S2'Unchecked_Access); + T.Check_Request (Ctx, ""/html/test.json"", ""/html/test.json"", """"); + Assert_Equals (T, 0, F1.Counter, ""Filter was executed for /html/*.json""); + Assert_Equals (T, 0, F2.Counter, ""Filter was not executed for /html/*.json""); + + T.Check_Mapping (Ctx, ""/json/test.html"", S1'Unchecked_Access); + T.Check_Request (Ctx, ""/json/test.html"", ""/json/test.html"", """"); + Assert_Equals (T, 0, F1.Counter, ""Filter was not executed for /json/*.html""); + Assert_Equals (T, 0, F2.Counter, ""Filter was executed for /json/*.html""); + + -- Only one filter is traversed. + F1.Counter := 0; + F2.Counter := 0; + T.Check_Mapping (Ctx, ""/html/test.html"", S1'Unchecked_Access, 1); + T.Check_Request (Ctx, ""/html/test.html"", ""/html/test.html"", """"); + Assert_Equals (T, 8, F1.Counter, ""Filter was executed for /html/*.html""); + Assert_Equals (T, 0, F2.Counter, ""Filter was not executed for /html/*.html""); + + F1.Counter := 0; + F2.Counter := 0; + T.Check_Mapping (Ctx, ""/json/test.json"", S2'Unchecked_Access, 1); + T.Check_Request (Ctx, ""/json/test.json"", ""/json/test.json"", """"); + Assert_Equals (T, 0, F1.Counter, ""Filter was not executed for /json/*.json""); + Assert_Equals (T, 8, F2.Counter, ""Filter was executed for /json/*.json""); + + F1.Counter := 0; + F2.Counter := 0; + T.Check_Mapping (Ctx, ""/list/test.html"", S1'Unchecked_Access, 1); + T.Check_Request (Ctx, ""/list/test.html"", ""/list/test.html"", """"); + Assert_Equals (T, 8, F1.Counter, ""Filter was executed for /list/*.html""); + Assert_Equals (T, 0, F2.Counter, ""Filter was not executed for /list/*.html""); + + F1.Counter := 0; + F2.Counter := 0; + T.Check_Mapping (Ctx, ""/list/test.json"", S2'Unchecked_Access, 1); + T.Check_Request (Ctx, ""/list/test.json"", ""/list/test.json"", """"); + Assert_Equals (T, 8, F1.Counter, ""Filter was executed for /list/*.json""); + Assert_Equals (T, 0, F2.Counter, ""Filter was not executed for /list/*.json""); + + -- Both filters are traversed. + F1.Counter := 0; + F2.Counter := 0; + T.Check_Mapping (Ctx, ""/list/admin/test.json"", S2'Unchecked_Access, 2); + T.Check_Request (Ctx, ""/list/admin/test.json"", ""/list/admin/test.json"", """"); + Assert_Equals (T, 8, F1.Counter, ""Filter was executed for /list/admin/*.json""); + Assert_Equals (T, 8, F2.Counter, ""Filter was executed for /list/admin/*.json""); + + F1.Counter := 0; + F2.Counter := 0; + T.Check_Mapping (Ctx, ""/list/admin/test.html"", S1'Unchecked_Access, 2); + T.Check_Request (Ctx, ""/list/admin/test.html"", ""/list/admin/test.html"", """"); + Assert_Equals (T, 8, F1.Counter, ""Filter was executed for /list/admin/*.html""); + Assert_Equals (T, 8, F2.Counter, ""Filter was executed for /list/admin/*.html""); + end Test_Filter_Execution; + + -- ------------------------------ + -- Test execution of filters on complex mapping. + -- ------------------------------ + procedure Test_Complex_Filter_Execution (T : in out Test) is + use Util.Beans.Objects; + procedure Insert (Route : in out Routes.Route_Type_Ref); + + Ctx : Servlet_Registry; + S1 : aliased Test_Servlet1; + F1 : aliased Filters.Tests.Test_Filter; + F2 : aliased Filters.Tests.Test_Filter; + User : aliased Form_Bean; + EL_Ctx : EL.Contexts.Default.Default_Context; + Request : Requests.Mockup.Request; + Reply : Responses.Mockup.Response; + + procedure Insert (Route : in out Routes.Route_Type_Ref) is + To : Routes.Servlets.Faces.Faces_Route_Type_Access; + begin + To := new Routes.Servlets.Faces.Faces_Route_Type; + To.Servlet := S1'Unchecked_Access; + Route := Routes.Route_Type_Refs.Create (To.all'Access); + end Insert; + begin + Ctx.Add_Servlet (""Faces"", S1'Unchecked_Access); + Ctx.Add_Filter (""F1"", F1'Unchecked_Access); + Ctx.Add_Filter (""F2"", F2'Unchecked_Access); + Ctx.Add_Route (Pattern => ""/wikis/#{user.name}/#{user.email}/view.html"", + ELContext => EL_Ctx, + Process => Insert'Access); + + Ctx.Add_Route (Pattern => ""/wikis/#{user.name}/#{user.email}/view"", + ELContext => EL_Ctx, + Process => Insert'Access); + Ctx.Add_Mapping (Pattern => ""/wikis/*.html"", Name => ""Faces""); + Ctx.Add_Filter_Mapping (Pattern => ""/wikis/*"", Name => ""F1""); + Ctx.Add_Filter_Mapping (Pattern => ""/wikis/admin/*"", Name => ""F2""); + Ctx.Start; + Ctx.Dump_Routes (Util.Log.INFO_LEVEL); + Request.Set_Attribute (""user"", + To_Object (Value => User'Unchecked_Access, Storage => STATIC)); + Request.Set_Method (""GET""); + declare + Dispatcher : constant Request_Dispatcher + := Ctx.Get_Request_Dispatcher (Path => ""/wikis/Gandalf/Mithrandir/view.html""); + Result : Ada.Strings.Unbounded.Unbounded_String; + begin + Request.Set_Request_URI (""/wikis/Gandalf/Mithrandir/view.html""); + Forward (Dispatcher, Request, Reply); + + -- Check the response after the Test_Servlet1.Do_Get method execution. + Reply.Read_Content (Result); + Assert_Equals (T, Responses.SC_OK, Reply.Get_Status, ""Invalid status""); + Assert_Equals (T, ""URI: /wikis/Gandalf/Mithrandir/view.html"", Result, ""Invalid content""); + Assert_Equals (T, ""Gandalf"", User.Name, ""User name was not extracted from the URI""); + + -- And verify that the filter are traversed. + Assert_Equals (T, 1, F1.Counter, ""Filter was executed for /html/*.html""); + Assert_Equals (T, 0, F2.Counter, ""Filter was not executed for /html/*.html"");" +procedure Test_Name_Dispatcher (T : in out Test) is,"Ctx : Servlet_Registry; + S1 : aliased Test_Servlet1; + S2 : aliased Test_Servlet1; + begin + Ctx.Add_Servlet (Name => ""Faces"", Server => S1'Unchecked_Access); + Ctx.Add_Servlet (Name => ""Text"", Server => S2'Unchecked_Access); + declare + Disp : constant Request_Dispatcher := Ctx.Get_Name_Dispatcher (""Faces""); + begin + T.Assert (Get_Servlet (Disp) /= null, ""Get_Name_Dispatcher returned null"");" +"procedure Free is new Ada.Unchecked_Deallocation (Cookie_Array, Cookie_Array_Access);","package Caller is new Util.Test_Caller (Test, ""Cookies""); + + procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is + begin + Caller.Add_Test (Suite, ""Test Servlet.Cookies.Create_Cookie"", + Test_Create_Cookie'Access); + Caller.Add_Test (Suite, ""Test Servlet.Cookies.To_Http_Header"", + Test_To_Http_Header'Access); + Caller.Add_Test (Suite, ""Test Servlet.Cookies.Get_Cookies"", + Test_Parse_Http_Header'Access); + end Add_Tests; + + -- ------------------------------ + -- Test creation of cookie + -- ------------------------------ + procedure Test_Create_Cookie (T : in out Test) is + C : constant Cookie := Create (""cookie"", ""value""); + begin + T.Assert_Equals (""cookie"", Get_Name (C), ""Invalid name""); + T.Assert_Equals (""value"", Get_Value (C), ""Invalid value""); + T.Assert (not Is_Secure (C), ""Invalid is_secure""); + end Test_Create_Cookie; + + -- ------------------------------ + -- Test conversion of cookie for HTTP header + -- ------------------------------ + procedure Test_To_Http_Header (T : in out Test) is + + procedure Test_Cookie (C : in Cookie) is + S : constant String := To_Http_Header (C); + begin + Log.Info (""Cookie {0}: {1}"", Get_Name (C), S); + T.Assert (S'Length > 0, ""Invalid cookie length for: "" & S); + T.Assert (Index (S, ""="") > 0, ""Invalid cookie format; "" & S); + end Test_Cookie; + + procedure Test_Cookie (Name : in String; Value : in String) is + C : Cookie := Create (Name, Value); + begin + Test_Cookie (C); + for I in 1 .. 24 loop + Set_Max_Age (C, I * 3600 + I); + Test_Cookie (C); + end loop; + Set_Secure (C, True); + Test_Cookie (C); + Set_Http_Only (C, True); + Test_Cookie (C); + Set_Domain (C, ""world.com""); + Test_Cookie (C); + Set_Path (C, ""/some-path""); + Test_Cookie (C); + end Test_Cookie; + + begin + Test_Cookie (""a"", ""b""); + Test_Cookie (""session_id"", ""79e2317bcabe731e2f681f5725bbc621-&v=1""); + Test_Cookie (""p_41_zy"", """"); + Test_Cookie (""p_34"", """"""quoted\t""""""); + Test_Cookie (""d"", ""s""); + declare + C : Cookie := Create (""cookie-name"", ""79e2317bcabe731e2f681f5725bbc621""); + Start : Util.Measures.Stamp; + begin + Set_Path (C, ""/home""); + Set_Domain (C, "".mydomain.example.com""); + Set_Max_Age (C, 1000); + Set_Http_Only (C, True); + Set_Secure (C, True); + Set_Comment (C, ""some comment""); + for I in 1 .. 1000 loop + declare + S : constant String := To_Http_Header (C); + begin + if S'Length < 10 then + T.Assert (S'Length > 10, ""Invalid cookie generation""); + end if;" +"procedure Free is new Unchecked_Deallocation (Vector, Access_Vector);","----------------------------------------------------------------------------- + --| By calling the following Reset functions, it is user's responsibility |-- + --| to keep track of dynamically allocated Access_Vector to prevent |-- + --| dangling memory space. |-- + ----------------------------------------------------------------------------- + --| Reset with new seed and new keys |-- + --| Gen.Keys = null to remove Keys |-- + procedure Reset (G : in Generator; + New_Seed : in Seed_Type; + New_Keys : in Access_Vector) + is + Gen : Access_Generator := G'Unrestricted_Access; + begin + Gen.Seed := New_Seed; + Free (Gen.Keys); + Gen.Keys := New_Keys; + Init_By_Keys (G); + end Reset; + + ----------------------------------------------------------------------------- + --| Reset with new keys |-- + --| Gen.Keys = null to remove Keys |-- + procedure Reset (G : in Generator; + New_Keys : in Access_Vector) + is + Gen : Access_Generator := G'Unrestricted_Access; + begin + Free (Gen.Keys); + Gen.Keys := New_Keys; + Init_By_Keys (G); + end Reset; + + ----------------------------------------------------------------------------- + --| Reset with saved Generator in string buffer |-- + procedure Reset (G : in Generator; + G_String : in String) + is + Gen : Access_Generator := G'Unrestricted_Access; + State_Length : Positive := G.State'Size / Standard.Character'Size; + State_Buffer : String (1 .. State_Length); + for State_Buffer use at G.State'Address; + + Seed_Length : Positive := G.Seed'Size / Standard.Character'Size; + Seed_Buffer : String (1 .. Seed_Length); + for Seed_Buffer use at G.Seed'Address; + + Keys_Length : Integer := 0; + Start, Stop : Integer; + begin + --| Sanity check if G_String is saved state of generator |-- + if G_String (G_String'First .. G_String'First + Gen_Tag'Length - 1) + /= Gen_Tag then + raise Constraint_Error; + end if; + + --| Get the number of keys saved, 0 if no keys |-- + --| Skip the tag and ""<"": |-- + Start := G_String'First + Gen_Tag'Length + 1; + Stop := Start; + while G_String (Stop) /= '>' loop + Stop := Stop + 1; + end loop; + Keys_Length := Integer'Value (G_String (Start .. (Stop - 1))); + + --| Get State |-- + Start := Stop + 1; + declare + Target : String (1 .. State_Length); + for Target use at Gen.State'Address; + begin + Stop := Start + State_Length; + Target := G_String (Start .. Stop - 1);" +procedure Main is,"function Convert_Clock(Tmp:Integer) return String is + function Trans (I:Integer) return String is + T:String(1..2); + begin + T := ""00""; + if I>=10 and I<=99 then + T(1..2):=Integer'Image(I)(2..3); + elsif I>0 then + T(2):=Integer'Image(I)(2); + end if; + return T; + end Trans; + S:String(1..8):="" ""; + Hour,Min,Sec:Integer; + begin + Hour := Tmp/3600; + S(1..2):=Trans(Hour); + S(3):=':'; + Min := (Tmp-3600*Hour)/60; + S(4..5) := Trans(Min); + S(6):=':'; + Sec:=Tmp-3600*Hour-60*Min; + S(7..8):=Trans(Sec); + return(S); + end Convert_Clock; + + Main_Error : exception; + type MY_FIXED is delta 0.1 range -9999.9..9999.9; + package FIXED_IO is new TEXT_IO.FIXED_IO ( MY_FIXED ) ; + + Has_Book : Boolean := False; + Cast : Castling := (others=>True); + Col, My_Col : Color; + En_Passant :Integer := -1; + Res : Integer :=0; + P2 : Piece; + N_En_Passant : Integer; + N_Castles: Castling; + Promote : Boolean; + Matw, Matb : Integer; + Valid : Boolean; + Prof : Integer; + Dur,Min_Delay : Float:=0.7635432; + St : State; + Lcb : array (0..63) of Piece; + Today,Full_Start_Time,Start_Time,End_Time : Time; + Full_Start_Time_Real,Start_Time_Real : Ada.Real_Time.Time; + Have_Time : Float; + Real_Dur : Ada.Real_Time.Time_Span; + Max_Delay : Float; + Tmp: Integer; + Alpha, Beta:Integer; + G : AdaMT19937.Generator; + Keys : AdaMT19937.Access_Vector := new AdaMT19937.Vector (0 .. 3); + Fail_Low,Fail_High : Boolean; + Old_From:Integer :=-1; + Old_To : Integer:=-1; + Old_Xotime : Integer :=0; + Period : Ada.Real_Time.Time_Span; +begin + +-- time 20000 +-- go +-- Init_Boards(""8/pR3pk1/8/2r3PP/Pn6/6K1/8/ w - - 1 40"",Col,Cast,En_Passant,Matw,Matb); +-- This board is the classical starting board + Init_Boards(""rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"",Col,Cast,En_Passant,Matw,Matb); + + Init_Masks; + Init_Attacks; + Has_Book := Load_All; + Make_Z_I(Col); + First_Ply := 0; + Movenum:=0; + Keys.all := (16#123#, 16#234#, 16#345#, 16#456#); + AdaMT19937.Reset (G, Keys); + +-- for I in 0..63 loop +-- Print_Intboard(King_Vicinity_I(I)); +-- Put_Line(""""); +-- end loop; +-- Print_Chessboard; +-- Tmp := Valeur(Col,Matw,Matb,Cast); +-- raise Main_Error; + + + Move_From := -1;Move_To := -1;My_Col := Black; + + while True loop + <> + if Col/=My_Col or Xboard_Force then + if Xboard_Force then Read_Xboard(-1,-1); + else Read_Xboard(Move_From,Move_To); end if; + if Movenum /= 0 then --xtime est maintenant a jour + Put(Game_Log,"" {[%eval ""); + if Res<-9999 then + Res := -(9999-(Res+32766)); + elsif + Res>9999 then + Res:=9999+(Res-32766); + end if; + Fixed_Io.Put(Game_Log,My_Fixed(Float(Res))); + Put(Game_Log,""]""); + Put(Game_Log,""[%emt ""); + Tmp := Integer(Dur+0.5); + Put(Game_Log,Convert_Clock(Tmp)); + Put(Game_Log,""]""); + Put(Game_Log,""[%clk ""); + Put(Game_Log,Convert_Clock((Xtime+50)/100)); + Put(Game_Log,""]""); + Put(Game_Log,""}""); + Flush(Game_Log); + end if; + + if Xboard_From=-3 then + Init_Boards(Xboard_Fen(1..Xboard_Fen_Last),Col,Cast,En_Passant,Matw,Matb); + Put_Line(File_Log,""Material Start: ""&Integer'Image(Matw)&"" ""&Integer'Image(Matb)); + Init_Masks; + Init_Attacks; + Make_Z_I(Col); + My_Col := -Col; + Print_Chessboard(File_Log); + goto Do_It_Again; + end if; + Move_From := Xboard_From; + Move_To := Xboard_To; + Res := 0; + Put_Line(File_Log,""Color:""&Color'Image(Col)&"" My_col:""&Color'Image(My_Col)&"" xboard_force:"" + &Boolean'Image(Xboard_Force)); + if Move_From = -1 then My_Col := Col; end if; + Put_Line(File_Log,""Color:""&Color'Image(Col)&"" My_col:""&Color'Image(My_Col)&"" xboard_force:"" + &Boolean'Image(Xboard_Force)); + Print_Chessboard(File_Log); + end if; + if Movenum=0 then + Put_Line(File_Log,""Starting pgn log""); + Put_Line(Game_Log,""[Event """"Freechess test""""]""); + Put_Line(Game_Log,""[Site """"Freechess""""]""); + Today := Clock; + Put_Line(Game_Log,""[Date """"""& + Integer'Image(Year(Today))&"".""& + Integer'Image(Month(Today))&"".""& + Integer'Image(Day(Today))& + """"""]""); + if XT1/=0 then + Put_Line(Game_Log,""[TimeControl """"""&Integer'Image(Xt1)&""/""&Integer'Image(Xt2*60)& + """"""]""); + else + if Xt3=0 then + Put_Line(Game_Log,""[TimeControl """"""&Integer'Image(Xt2*60)&""""""]""); + else + Put_Line(Game_Log,""[TimeControl """"""&Integer'Image(Xt2*60)&""+""&Integer'Image(Xt3)&""""""]""); + end if; + end if; + if My_Col=Black then + Put_Line(Game_Log,""[White """"""&Xname(1..Xname_Last)&""""""]""); + Put_Line(Game_Log,""[Black """"Lovelace""""]""); + Put_Line(Game_Log,""[WhiteElo """"""&Integer'Image(XratingO)&""""""]""); + Put_Line(Game_Log,""[BlackElo """"""&Integer'Image(XratingC)&""""""]""); + else + Put_Line(Game_Log,""[White """"Lovelace""""]""); + Put_Line(Game_Log,""[Black """"""&Xname(1..Xname_Last)&""""""]""); + Put_Line(Game_Log,""[WhiteElo """"""&Integer'Image(XratingC)&""""""]""); + Put_Line(Game_Log,""[BlackElo """"""&Integer'Image(XratingO)&""""""]""); + end if; + Put_Line(Game_Log,""""); + Flush(Game_Log); + end if; + if Col = My_Col and not Xboard_Force Then + begin + Full_Start_Time := Clock; + Full_Start_Time_Real := Ada.Real_Time.Clock; + Move_From := -1;Move_To := -1;Old_From:=-1;Old_To:=-1; + Prof := 10;Alpha:=-32767;Beta:=32767; + Have_Time := Float(Xtime)/100.0; + if Have_Time<5.0 then Min_Delay:=0.2; + elsif Have_Time<15.0 then Min_Delay:=0.3; + elsif Have_Time<30.0 then Min_Delay:=0.5; + elsif Have_Time<60.0 then Min_Delay:=0.75; + elsif Have_Time<120.0 then Min_Delay:=1.0; + else Min_Delay := 1.5; end if; + Put_Line(File_Log,""Xtime=""&Integer'Image(Xtime)); + if Has_Book then + Get_Book(Move_From,Move_To,Col,Cast,En_Passant); + if Move_From/=-1 then + Put_Line(File_Log,""Raising end_thinking in get_book""); + raise End_Thinking; + end if; + end if; + loop + Put_Line(File_Log,""Starting main loop""); + Start_Time_real := Ada.Real_Time.Clock; + Start_Time := Clock; + if XT1/=0 then + Tmp := (Movenum/2) mod XT1; + Tmp := XT1 - Tmp; + Max_Delay := Have_Time/Float(Tmp+1); + Max_Delay := (4.0*Max_Delay)/3.0; + Put_Line(File_Log,""Max_delay=""&Float'Image(Max_Delay) + &"" Tmp=""&Integer'Image(Tmp)&"" Have_time=""&Float'Image(Have_Time) + &"" Movenum=""&Integer'Image(Movenum)); + else + Tmp := Integer'Max(30-abs(Matw+Matb)/100,10); + Max_Delay := Float(XT3)+Have_Time/Float(Tmp); + Put_Line(File_Log, + ""Max_delay=""&Float'Image(Max_Delay) + &"" Have_time=""&Float'Image(Have_Time) + &"" Movenum=""&Integer'Image(Movenum) + &"" mat=""&Integer'Image(Tmp)); + end if; + if Max_DelayAlpha and Res Max_Delay/3.0) and (Float(End_Time-Full_Start_Time)>Min_Delay) then + Put_Line(File_Log, + ""Raising end_thinking. Dur=""&Float'Image(Dur)& + "" max_delay=""&Float'Image(Max_Delay)& + "" min_delay=""&Float'Image(Min_Delay)); + raise End_Thinking; + end if; + if Prof>=2000 then + Put_Line(File_Log,""Raising End_thinking because prof>=2000""); + raise End_Thinking; + end if; + Prof := Prof+10; + Put_Line(File_Log,""Adding 10 to prof. New prof:""&Integer'Image(Prof)); + end select; + end loop; + exception + when End_Thinking => + Put_Line(File_Log,""End thinking""); + Real_Dur := Ada.Real_Time.""-""(Ada.Real_Time.Clock,Full_Start_Time_Real); + Dur := Float(Clock-Full_Start_Time); + if Dur=0) and (J<=7) and (J>=0)); + end Is_In_Bounds; + + procedure Init_Knight_Attacks is + Knight_Moves : array (0..7,0..1) of Integer := ((1,2),(2,1),(-1,2),(-2,1),(1,-2),(2,-1),(-1,-2),(-2,-1)); + begin + for I in 0..63 loop + Knight_Attacks_I(I) := 0; + Knight_Mobility(I) := 0; + end loop; + for I in 0..7 loop + for J in 0..7 loop + for K in 0..7 loop + if Is_In_Bounds(I+Knight_Moves(K,0),J+Knight_Moves(K,1)) then + Knight_Attacks_B(I*8+J)((I+Knight_Moves(K,0))*8+J+Knight_Moves(K,1)) := 1; + Knight_Mobility(I*8+J):=Knight_Mobility(I*8+J)+1; + end if; + end loop; + end loop; + end loop; + end Init_Knight_Attacks; + + procedure Init_King_Attacks is + King_Moves : array (0..7,0..1) of Integer := ((1,1),(1,0),(1,-1),(0,1),(0,-1),(-1,1),(-1,0),(-1,-1)); + begin + for I in 0..63 loop + King_Attacks_I(I) := 0; + end loop; + for I in 0..7 loop + for J in 0..7 loop + for K in 0..7 loop + if Is_In_Bounds(I+King_Moves(K,0),J+King_Moves(K,1)) then + King_Attacks_B(I*8+J)((I+King_Moves(K,0))*8+J+King_Moves(K,1)) := 1; end if; + end loop; + end loop; + end loop; + end Init_King_Attacks; + + procedure Init_White_Pawn_Attacks is + Pawn_Inc : array (0..1,0..1) of Integer := ((1,1),(1,-1)); + I : Integer :=0; + J : Integer :=0; + begin + for I in 0..63 loop + White_Pawn_Attacks_I(I):=0; + end loop; + for I in 0..7 loop + for J in 0..7 loop + for K in 0..1 loop + if Is_In_Bounds(I+Pawn_Inc(K,0),J+Pawn_Inc(K,1)) then + White_Pawn_Attacks_B(I*8+J)((I+Pawn_Inc(K,0))*8+J+Pawn_Inc(K,1)) := 1; + end if; + end loop; + end loop; + end loop; + end Init_White_Pawn_Attacks; + + procedure Init_Black_Pawn_Attacks is + Pawn_Inc : array (0..1,0..1) of Integer := ((-1,1),(-1,-1)); + begin + for I in 0..63 loop + Black_Pawn_Attacks_I(I):=0; + end loop; + for I in 0..7 loop + for J in 0..7 loop + for K in 0..1 loop + if Is_In_Bounds(I+Pawn_Inc(K,0),J+Pawn_Inc(K,1)) then + Black_Pawn_Attacks_B(I*8+J)((I+Pawn_Inc(K,0))*8+J+Pawn_Inc(K,1)) := 1; end if; + end loop; + end loop; + end loop; + end Init_Black_Pawn_Attacks; + + + procedure Init_White_Pawn_Moves1 is + begin + for I in 0..63 loop + White_Pawn_Moves1_I(I):=0; + end loop; + for I in 1..7 loop + for J in 0..7 loop + if Is_In_Bounds(I+1,J) then + White_Pawn_Moves1_B(I*8+J)((I+1)*8+J) := 1; end if; + end loop; + end loop; + end Init_White_Pawn_Moves1; + + procedure Init_Black_Pawn_Moves1 is + begin + for I in 0..63 loop + Black_Pawn_Moves1_I(I):=0; + end loop; + for I in 0..6 loop + for J in 0..7 loop + if Is_In_Bounds(I-1,J) then + Black_Pawn_Moves1_B(I*8+J)((I-1)*8+J) := 1; end if; + end loop; + end loop; + end Init_Black_Pawn_Moves1; + + procedure Init_White_Pawn_Moves2 is + begin + for I in 0..63 loop + White_Pawn_Moves2_I(I):=0; + end loop; + for J in 0..7 loop + White_Pawn_Moves2_B(8+J)(24+J) := 1; + end loop; + end Init_White_Pawn_Moves2; + + procedure Init_Black_Pawn_Moves2 is + begin + for I in 0..63 loop + Black_Pawn_Moves2_I(I):=0; + end loop; + for J in 0..7 loop + Black_Pawn_Moves2_B(48+J)(32+J) := 1; + end loop; + end Init_Black_Pawn_Moves2; + + -- All_Pieces_90_B(8*I+J) := All_Pieces_B(8*(7-J)+I); + + function Find_Rank(B:Natural) return Natural is + begin + return Natural(Shift_Right(All_Pieces_I and (Shift_Left(255,8*(B/8))),8*(B/8))); + end Find_Rank; + + function Find_Rank_90(B:Natural) return Natural is + begin + return Natural(Shift_Right(All_Pieces_90_I and (Shift_Left(255,8*(B mod 8))),8*(B mod 8))); + end Find_Rank_90; + + function Find_Rank_45r (B:Natural) return Natural is + begin + return Natural(Shift_Right((All_Pieces_45r_I and Mask_45r_rev(B)),Start_45r_Rev(B))); + end Find_Rank_45r; + + function Find_Rank_45l (B:Natural) return Natural is + begin + return Natural(Shift_Right((All_Pieces_45l_I and Mask_45l_rev(B)),Start_45l_Rev(B))); + end Find_Rank_45l; + + procedure Init_Rank_Attacks is + Base,Ind : Integer; + R : Unsigned_8; + Final_I : Intboard; + Final_B : Bitboard; + pragma Import(Ada,Final_B); + for Final_B'Address use Final_I'Address; + L,D : Integer; + begin + for I in 0..63 loop + Base := I/8;Ind := I mod 8; + for J in Unsigned_8 (0) .. Unsigned_8(255) loop + Rank_Mobility(I,Integer(J)) := 0; + Rank_Mobility_90(I,Integer(J)) := 0; + Rank_Mobility_45r(I,Integer(J)) := 0; + Rank_Mobility_45l(I,Integer(J)) := 0; + R:=0; + for K in reverse 0 .. Ind-1 loop + R := R or Shift_Left(1,K); + Rank_Mobility(I,Integer(J)) := Rank_Mobility(I,Integer(J))+1; + exit when (J and Shift_Left(1,K))/=0; + end loop; + for K in Ind+1 .. 7 loop + R := R or Shift_Left(1,K); + Rank_Mobility(I,Integer(J)) := Rank_Mobility(I,Integer(J))+1; + exit when (J and Shift_Left(1,K))/=0; + end loop; + Rank_Attacks_I(I,Integer(J)) := Shift_Left(Intboard(R),(8*Base)); + end loop; + end loop; + + for I in 0..7 loop + for J in 0..7 loop + for M in 0..255 loop + for B in 0..7 loop + Rank_Attacks_90_B(8*I+J,M)(8*(7-B)+J) := Rank_Attacks_B(7-I,M)(B); + if Rank_Attacks_B(7-I,M)(B)=1 then + Rank_Mobility_90(8*I+J,M):= Rank_Mobility_90(8*I+J,M)+1; + end if; + end loop; + end loop; + end loop; + end loop; + + for B in 0..63 loop + L := To_45r(B); + for J in 0..(2**Length_45r(L)-1) loop + Rank_Attacks_45r_I(B,J) := 0; + Final_I := Rank_Attacks_I(Pos_45r(L),J) and (2**Length_45r(L)-1); + for K in 0 .. Length_45r(L)-1 loop + D := From_45r(K+Start_45r(L)); + Rank_Attacks_45r_B(B,J)(D) := Final_B(K); + if Final_B(K)=1 then + Rank_Mobility_45r(B,J):=Rank_Mobility_45r(B,J)+1; + end if; + end loop; + end loop; + end loop; + + for B in 0..63 loop + L := To_45l(B); + for J in 0..(2**Length_45l(L)-1) loop + Rank_Attacks_45l_I(B,J) := 0; + Final_I := Rank_Attacks_I(Pos_45l(L),J) and (2**Length_45l(L)-1); + for K in 0 .. Length_45l(L)-1 loop + D := From_45l(K+Start_45l(L)); + Rank_Attacks_45l_B(B,J)(D) := Final_B(K); + if Final_B(K)=1 then + Rank_Mobility_45l(B,J):=Rank_Mobility_45l(B,J)+1; + end if; + end loop; + end loop; + end loop; + + + end Init_Rank_Attacks; + + procedure Init_Attacks is + begin + Init_Knight_Attacks; + Init_King_Attacks; + Init_White_Pawn_Attacks; + Init_Black_Pawn_Attacks; + Init_White_Pawn_Moves1; + Init_Black_Pawn_Moves1; + Init_White_Pawn_Moves2; + Init_Black_Pawn_Moves2; + Init_Rank_Attacks; + end Init_Attacks; + + procedure Print_Bitboard (B:Bitboard) is + begin + for I in reverse 0..7 loop + for J in 0 .. 7 loop + if B(I*8+J)=1 then Put(""X ""); else Put("". ""); end if; + end loop; + Put_Line(""""); + end loop; + end Print_Bitboard; + + procedure Print_Bitboard_45 (B:Bitboard) is + L : Integer := 1; + K : Integer := 1; + Base : Integer := 63; + begin + while L <=15 loop + for I in 1..8-K loop + Put("" ""); + end loop; + for I in Base..Base+K-1 loop + if B(I)=1 then Put(""X ""); else Put("". ""); end if; + Put("" ""); + end loop; + Put_Line(""""); + L := L+1; + if L<=8 then K:=L; else K := 16-L; end if; + Base := Base - K; + end loop; + end Print_Bitboard_45; + + + procedure Print_Chessboard is + K : Integer; + begin + for I in reverse 0..7 loop + for J in 0..7 loop + K := I*8+J; + if All_Pieces_B(K)=1 then + begin + if White_Rooks_B(K)=1 then Put(""R ""); end if; + if Black_Rooks_B(K)=1 then Put(""r ""); end if; + if White_Knights_B(K)=1 then Put(""N ""); end if; + if Black_Knights_B(K)=1 then Put(""n ""); end if; + if White_Bishops_B(K)=1 then Put(""B ""); end if; + if Black_Bishops_B(K)=1 then Put(""b ""); end if; + if White_Queens_B(K)=1 then Put(""Q ""); end if; + if Black_Queens_B(K)=1 then Put(""q ""); end if; + if White_Kings_B(K)=1 then Put(""K ""); end if; + if Black_Kings_B(K)=1 then Put(""k ""); end if; + if White_Pawns_B(K)=1 then Put(""P ""); end if; + if Black_Pawns_B(K)=1 then Put(""p ""); end if;" +procedure Store is,"begin + Table(Ind).Low := Integer_16(Low); Table(Ind).High := Integer_16(High); + Table(Ind).From := Unsigned_6(From); Table(Ind).To := Unsigned_6(To); + Table(Ind).Prof := Integer_10(Prof); Table(Ind).Movenum := Unsigned_8(Movenum); + Table(Ind).Valid := Valid;Table(Ind).I := Z_I; + +-- for I in 0..63 loop +-- Plus := Unsigned_4(Chess_Board(I)); + --Codage bizarre transformant le codage du roi blanc (3) en 4 + --Comme le 4 n'existe pas cela permet de stocker la couleur (!) +-- if Plus = 3 and C=Black then Plus:=4; end if; +-- Table(Ind).Board(I):=Plus; +-- end loop; + + end Store; + pragma Inline(Store); + begin + Ind := Integer(Shift_Right(Z_I,64-Nb_Bits)); + if Z_I = Table(Ind).I then + -- Exactly same position + if Prof >= Integer(Table(Ind).Prof) then + --Same position researched deeper + Store; + else + -- Same position, lower depth, store should not happen? + -- raise Hash_Error; + null; + end if; + else + -- New position=> collision. Shall we replace the other one? + if Movenum /= Integer(Table(Ind).Movenum) or else Prof >= Integer(Table(Ind).Prof) then + --store if different move, or better prof + Store; + end if; + end if;" +function AddElemToAllLists (LL : Partition_Type; I : Integer) return Partition_Type,"is + -- sub function to add an integer to the front of a partition + function AddElemToFront (L : Partition; I : Integer) return Partition + is + RetL : Partition; + begin + for J in L'Range loop + -- adds to front + if (J = 0) then + RetL (J) := I; + -- cuts off last digit in initial partition + else + RetL (J) := L(J - 1); + end if; + end loop; + return RetL; + end AddElemToFront; + + LLFirst : Partition := LL(0); + RetLL : Partition_Type (LL'Range); + + begin + -- -1 is the initialization value for all indices in the array + if (LLFirst (0) = -1) then + return LL; + else + -- iterates through all lists and adds element + for J in LL'Range loop + RetLL (J) := AddElemToFront ((LL (J)), I); + end loop; + end if; + return RetLL; + end AddElemToAllLists; + + -- adds two lists of lists together + function ConcatList (LL1, LL2 : Partition_Type) return Partition_Type + is + RetLL : Partition_Type (0 .. (LL1'Length + LL2'Length - 1)); + LL1First : Partition := LL1 (0); + LL2First : Partition := LL2 (0); + begin + -- checks emptinesses of lists + if ((LL1First (0) = -1) and (LL2First (0) = -1)) then + return LL1; + elsif (LL1First (0) = -1) then + return LL2; + elsif (LL2First (0) = -1) then + return LL1; + else + -- puts in LL1 + for I in LL1'Range loop + RetLL (I) := LL1 (I); + end loop; + -- puts in LL2 + for I in LL2'Range loop + RetLL (I + LL1'Length) := LL2(I); + end loop; + end if; + return RetLL; + end ConcatList; + + -- compiles a list of partitions + function PrimePartition (N, K, J : Integer) return Partition_Type + is + Empty_Partition : Partition := (others => -1); + Empty_Partition_Type : Partition_Type (0 .. 0) := (0 => Empty_Partition); + Primes : Sieve_Type := SievePrimes (N, K); + IPrime : Integer := 0; + NPrimePartition : Partition := (0 => N, others => -1); + NPrimeList : Partition_Type (0 .. 0) := (0 => NPrimePartition); + begin + -- gets the lowest prime between K and N + for I in Primes'Range loop + if (Primes (I)) then + IPrime := I; + exit when True; + end if; + end loop; + -- if no primes then return empty list + if (IPrime = 0) then + return Empty_Partition_Type; + end if; + -- if bad input then return empty list + if ((N <= 1) or (N < K)) then + return Empty_Partition_Type; + -- if n is prime and first call with n as n + elsif ((IsPrime (N)) and (J = 1)) then + -- add the prime to the sub partitions returned concatenated with partitions using the same n concatenated with n + return ConcatList ((ConcatList ((AddElemToAllLists ((PrimePartition ((N - IPrime), (IPrime + 1), 1)), IPrime)), (primePartition (N, (IPrime + 1), (J + 1))))), NPrimeList); + else + -- same as above but don't concat n + return ConcatList ((AddElemToAllLists ((PrimePartition ((N - IPrime), (IPrime + 1), 1)), IPrime)), (primePartition (N, (IPrime + 1), (J + 1)))); + end if; + end PrimePartition; + + -- prints a list of partitions in the desired format + procedure PrintLL (LL : Partition_Type) + is + begin + for I in LL'Range loop + declare + L : Partition := (LL (I)); + begin + for J in L'Range loop + if ((L (J)) = -1) then + exit; + else + Ada.Text_IO.Put(Integer'Image (L (J)) & "" ""); + end if; + end loop;" +procedure words is,"package ASU renames Ada.Strings.Unbounded; + package ACL renames Ada.Command_Line; + package ATI renames Ada.Text_IO; + package WL renames Word_Lists; + + File_Name: ASU.Unbounded_String; + Fich: Ada.Text_IO.File_Type; + List: WL.Word_List_Type; + Word: ASU.Unbounded_String; + Count: Natural; + + + procedure Print_Menu is + + --Imprime el menú interactivo + + begin + ATI.New_Line; + ATI.Put_Line(""Options""); + ATI.Put_Line(""1 Add Word""); + ATI.Put_Line(""2 Delete Word""); + ATI.Put_Line(""3 Search Word""); + ATI.Put_Line(""4 Show all words""); + ATI.Put_Line(""5 Quit""); + ATI.New_Line; + ATI.Put(""Your option? ""); + end Print_Menu; + + --Divide las líneas en palabras y las almacena en la lista + + procedure Divide_In_Words (Line: in out Asu.Unbounded_String; Delimiter: in string) is + + Word: ASU.Unbounded_String; + Eol: Boolean; + Position: Integer; + + begin + Eol := False; + while not Eol loop + + Position := ASU.Index(Line, Delimiter); + + -- Si la línea no tiene más palabras + if ASU.Length(Line) = 0 then + Eol := True; + + -- Si ya no hay mas delimitadores + elsif ASU.Index(Line, Delimiter) = 0 then + + Word := ASU.Tail(Line, ASU.Length(Line) - Position); + WL.Add_Word(List, Word); + Eol := True; + else + Eol := False; + + -- Si hay dos blancos seguidos + if (Position - 1) = 0 then + -- Me salta el blanco + ASU.Tail(Line, ASU.Length(Line) - Position); + else + Word := ASU.Head (Line, Position - 1); + ASU.Tail(Line, ASU.Length(Line) - Position); + WL.Add_Word(List, Word); + end if; + end if; + end loop; + end Divide_In_Words; + + --Lee el fichero + + procedure Read_Fich is + + Line: ASU.Unbounded_String; + + begin + while not ATI.End_Of_File(Fich) loop + Line := ASU.To_Unbounded_String(Ada.Text_IO.Get_Line(Fich)); + Divide_In_Words(Line, "" ""); + end loop; + end Read_Fich; + + procedure Basic_Mode (List: in out WL.Word_List_Type; + Word: in out ASU.Unbounded_String; + Count: in out Natural) is + + begin + WL.Max_Word(List, Word, Count); + ATI.Put(""The most frequent word: ""); + ATI.Put(""|"" & ASU.To_String(Word) & ""| -"" ); + ATI.Put_Line(Integer'Image(Count)); + ATI.New_Line; + ATI.New_Line; + + end Basic_Mode; + + procedure Interactive_Mode (List: in out WL.Word_List_Type; + Word: in out ASU.Unbounded_String; + Count: in out Natural) is + + Option: Integer; + + begin + -- Muestra el menú y realiza las diferentes funciones hasta que pulsamos el quit + loop + begin + Print_Menu; + Option := Integer'Value(ATI.Get_Line); + + case Option is + + -- Añade una palabra a la lista + when 1 => + ATI.Put(""Word? ""); + Word := ASU.To_Unbounded_String(ATI.Get_Line); + WL.Add_Word(List, Word); + ATI.Put_Line(""Word |"" & ASU.To_String(Word) + & ""| added""); + + -- Borra una palabra de la lista + when 2 => + ATI.Put(""Word? ""); + Word := ASU.To_Unbounded_String(ATI.Get_Line); + WL.Delete_Word (List, Word); + + ATI.New_Line; + ATI.Put(""|"" & ASU.To_String(Word) & ""| "" + & ""deleted""); + ATI.New_Line; + + -- Busca una palabra en la lista + when 3 => + ATI.Put(""Word? ""); + Word := ASU.To_Unbounded_String(ATI.Get_Line); + WL.Search_Word(List, Word, Count); + + ATI.New_Line; + ATI.Put(""|"" & ASU.To_String(Word) & ""| - "" ); + ATI.Put_Line(Integer'Image(Count)); + + -- Imprime la lista + when 4 => + WL.Print_All(List); + + -- Imprime la palabra que más aparece y sale del bucle + when 5 => + WL.Max_Word(List, Word, Count); + ATI.Put(""The most frequent word: ""); + ATI.Put(""|"" & ASU.To_String(Word) & ""| -"" ); + ATI.Put_Line(Integer'Image(Count)); + ATI.New_Line; + ATI.New_Line; + when others => + ATI.Put_Line(""Not implemented""); + + end case; + + exception + when Constraint_Error => + ATI.Put_Line(""Incorrect Option"");" +procedure Close is,"begin + GNAT.Sockets.Close_Socket(Sender_Socket); + end Close; + + procedure Send_Vram(Vram : in Emulator_8080.Processor.Vram_Type) is + use Ada.Streams; + Data : Ada.Streams.Stream_Element_Array(1 .. Vram'Length); + Counter : Ada.Streams.Stream_Element_Offset := Data'First; + Last : Ada.Streams.Stream_Element_Offset; + begin + for I in Vram'Range loop + Data(Counter) := Ada.Streams.Stream_Element(Vram(I)); + Counter := Counter + 1; + end loop; + Gnat.Sockets.Send_Socket (Sender_Socket, Data, Last, Address);" +procedure Finish (Data : in out Snapshot_Type) is,"begin + Data.Offset := Data.Offset + Data.Count; + end Finish; + + -- ------------------------------ + -- Set the value in the snapshot. + -- ------------------------------ + procedure Set_Value (Into : in out Snapshot_Type; + Def : in Schemas.Definition_Type_Access; + Value : in Uint64) is + begin + if Def /= null and then Def.Index > 0 then + Into.Values (Def.Index + Into.Offset) := Value; + end if; + end Set_Value; + + -- ------------------------------ + -- Iterate over the values in the snapshot and collected for the definition node. + -- ------------------------------ + procedure Iterate (Data : in Helios.Datas.Snapshot_Type; + Node : in Helios.Schemas.Definition_Type_Access; + Process : not null access procedure (Value : in Uint64)) is + Count : constant Helios.Datas.Value_Array_Index := Data.Count; + Pos : Helios.Datas.Value_Array_Index := Node.Index; + begin + Log.Debug (""Iterate {0} from {1} to {2} step {3}"", Node.Name, + Value_Array_Index'Image (Count), + Value_Array_Index'Image (Pos)); + while Pos < Data.Offset loop + Process (Data.Values (Pos)); + Pos := Pos + Count; + end loop; + end Iterate; + + -- ------------------------------ + -- Iterate over the values in the snapshot and collected for the definition node. + -- ------------------------------ + procedure Iterate (Data : in Helios.Datas.Snapshot_Type; + Node : in Helios.Schemas.Definition_Type_Access; + Process_Snapshot : not null access + procedure (D : in Snapshot_Type; + N : in Definition_Type_Access); + Process_Values : not null access + procedure (D : in Snapshot_Type; + N : in Definition_Type_Access)) is + Child : Helios.Schemas.Definition_Type_Access; + begin + Child := Node.Child; + while Child /= null loop + if Child.Child /= null then + Process_Snapshot (Data, Child); + elsif Child.Index > 0 then + Process_Values (Data, Child); + end if; + Child := Child.Next; + end loop; + end Iterate; + + -- ------------------------------ + -- Iterate over the values of the reports. + -- ------------------------------ + procedure Iterate (Report : in Report_Queue_Type; + Process : not null access procedure (Data : in Snapshot_Type; + Node : in Definition_Type_Access)) is + begin + if not Report.Snapshot.Is_Null then + declare + List : constant Snapshot_Accessor := Report.Snapshot.Value; + Snapshot : Snapshot_Type_Access := List.First; + begin + while Snapshot /= null loop + Process (Snapshot.all, Snapshot.Schema); + Snapshot := Snapshot.Next; + end loop;" +procedure Register (Op : in out Operation'Class;,"Name : String := Image (Subprogram_Name); + Disabled : Boolean := False; + Parallelize : Boolean := True) is + begin + null; + end Register; + pragma Unreferenced (Register); + + function Num_Total_Tests (Self : Gather) return Integer is + use all type Ada.Containers.Count_Type; + begin + return Integer(Self.Parallel_Tests.Length + Self.Sequential_Tests.Length); + end Num_Total_Tests; + + overriding + procedure Register (Self : in out Gather; + Name : String := Image (Subprogram_Name); + Disabled : Boolean := False; + Parallelize : Boolean := True) is + package ASU renames Ada.Strings.Unbounded; + begin + -- TODO: Test filter to go here. + if Disabled then + raise Test_Registered; + end if; + + Self.Current_Name := ASU.To_Unbounded_String(Name); + + if Parallelize then + Self.Parallel_Tests.Append(Self.Current_Test); + Ada.Text_IO.Put_Line (""// PARALLEL // "" & ASU.To_String(Self.Current_Name)); + else + Self.Sequential_Tests.Append(Self.Current_Test); + Ada.Text_IO.Put_Line (""--SEQUENTIAL-- "" & ASU.To_String(Self.Current_Name)); + end if; + + raise Test_Registered; + end Register; + + overriding + procedure Register (T : in out List; + Name : String := Image (Subprogram_Name); + Disabled : Boolean := False; + Parallelize : Boolean := True) is + begin + pragma Unreferenced (T, Disabled, Parallelize); + Ada.Text_IO.Put_Line (Name); + end Register; + + overriding + procedure Register (T : in out Test; + Name : String := Image (Subprogram_Name); + Disabled : Boolean := False; + Parallelize : Boolean := True) is + begin + pragma Unreferenced(Parallelize); + + T.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); + + if Disabled then + raise Test_Disabled; + end if; + end Register; + + procedure Report_Failure (Op : in out Operation'Class; + Message : String; + Loc : Source_Location) is + Error : constant String := (if Message /= """" then Message else ""Condition false""); + begin + pragma Unreferenced (Op); + raise Test_Failure with ""Assertion Failed: ("" & Error & "") at "" & Image (Loc); + end Report_Failure; + + function ""and"" (Left, Right: Test_Result) return Test_Result is + Either_Failed : constant Boolean := Left = Failed or else Right = Failed; + Both_Skipped : constant Boolean := Left = Skipped and then Right = Skipped; + begin + return (if Either_Failed then Failed else (if Both_Skipped then Skipped else Passed)); + end ""and""; + + procedure Register (TG : in Test_Group) is + begin + All_Test_Groups.Append (TG); + end Register; + + function Run (TG : Test_Group) return Test_Result is + Passes : Natural := 0; + Fails : Natural := 0; + Total : Natural := 0; + Instance : Test; + + use Ada.Text_IO; + use Ada.Strings.Unbounded.Text_IO; + use type Ada.Strings.Unbounded.Unbounded_String; + begin + for T of TG loop + declare + begin + T.all (Instance); + Put_Line (""[ PASS ] "" & Instance.Name); + Passes := Passes + 1; + exception + when Test_Disabled => + Put_Line (""[ SKIP ] "" & Instance.Name); + when Error : Test_Failure => + Put_Line (""[ FAIL ] "" & Instance.Name); + Put_Line ("" "" & Ada.Exceptions.Exception_Message (Error)); + Fails := Fails + 1;" +procedure Main is,"-- On utilise des chaines de taille variable + package Ada_Strings_Io is new Ada.Text_Io.Bounded_Io (Sb); + use Ada_Strings_Io; + + type T_Menu is + (Menu_Principal, Menu_Registre, Menu_Registre_Consultation_Selection, + Menu_Registre_Consultation_Personne, + Menu_Registre_Consultation_Recherche, Menu_Registre_Ajout, + Menu_Registre_Modification, Menu_Arbre_Selection, + Menu_Arbre_Consultation, Menu_Arbre_Ajouter_Relation, + Menu_Arbre_Supprimer_Relation, Menu_Arbre_Parente, Menu_Statistiques, + Quitter); + + -- Etat global du programme + type T_Etat is record + Arbre : T_Arbre_Genealogique; + Cle : Integer; + Menu : T_Menu; + end record; + + -- Affiche la phrase ""Votre choix [1, 2, ... `Nb_Choix`]"" + -- et capture la saisie de l'utilisateur dans `Choix`. + procedure Choisir (Nb_Choix : in Integer; Choix : out Integer) is + procedure Afficher_Liste_Choix is + begin + for I in 1 .. Nb_Choix - 2 loop + Put (I, 0); + Put ("", ""); + end loop; + Put (Nb_Choix - 1, 0); + Put ("" ou ""); + Put (Nb_Choix - 0, 0); + end Afficher_Liste_Choix; + Correct : Boolean := False; + -- Premiere_Entree : Boolean := True; + begin + while not Correct loop + Put (""Votre choix [""); + Afficher_Liste_Choix; + -- Fonctionnalité desactivée : + --if not Premiere_Entree then + -- Put ("" / 0 pour quitter""); + --end if; + Put (""] : ""); + begin + Get (Choix); + Correct := Choix in 1 .. Nb_Choix; + --Correct := Choix in 0 .. Nb_Choix; + exception + when Ada.Io_Exceptions.Data_Error => + Correct := False;" +procedure Choisir_Cle (Cle : out Integer) is,"Correct : Boolean := False; + Premiere_Entree : Boolean := True; + begin + while not Correct loop + Put (""Votre choix""); + if not Premiere_Entree then + Put ("" [0 pour retour]""); + end if; + Put ("" : ""); + begin + Get (Cle); + Correct := Cle >= 0; + exception + -- Si la valeur entrée n'est pas un entier + when Ada.Io_Exceptions.Data_Error => + Correct := False;" +procedure Afficher_Menu_Registre (Etat : in out T_Etat) is,"Choix : Integer; + begin + Put_Line (""* Registre *""); + New_Line; + Put_Line (""Menu :""); + Put_Line (""1. Consulter une personne a partir de sa clé""); + Put_Line (""2. Chercher une personne a partir de son nom""); + Put_Line (""3. Ajouter une personne""); + Put_Line (""4. Retour""); + New_Line; + Choisir (4, Choix); + New_Line; + case Choix is + when 1 => + Etat.Menu := Menu_Registre_Consultation_Selection; + when 2 => + Etat.Menu := Menu_Registre_Consultation_Recherche; + when 3 => + Etat.Menu := Menu_Registre_Ajout; + when 4 => + Etat.Menu := Menu_Principal; + when others => + Etat.Menu := Quitter; + end case; + end Afficher_Menu_Registre; + + -- Affiche toutes les informations d'une personne. + procedure Afficher_Personne (Cle : in Integer; Personne : in T_Personne) is + begin + Put (""<""); + Put (Cle, 0); + Put ("">""); + New_Line; + Put (Personne.Nom_Usuel); + New_Line; + Put ("" * Nom complet : ""); + Put (Personne.Nom_Complet); + New_Line; + Put ("" * Sexe : ""); + Put (T_Genre'Image (Personne.Genre)); + New_Line; + Put ("" * Né le ""); + Put (Personne.Date_De_Naissance.Jour, 0); + Put ("" ""); + Put (T_Mois'Image (Personne.Date_De_Naissance.Mois)); + Put ("" ""); + Put (Personne.Date_De_Naissance.Annee, 0); + Put ("" a ""); + Put (Personne.Lieu_De_Naissance); + New_Line; + end Afficher_Personne; + + procedure Afficher_Nom_Usuel (Etat : in T_Etat; Cle : in Integer) is + Personne : T_Personne; + begin + Personne := Lire_Registre (Etat.Arbre, Cle); + Put (Personne.Nom_Usuel); + Put ("" <""); + Put (Cle, 0); + Put ("">""); + end Afficher_Nom_Usuel; + + -- Affiche le menu qui permet de choisir une personne a consulter dans le registre. + procedure Afficher_Menu_Registre_Consultation_Selection + (Etat : in out T_Etat) + is + Cle : Integer; + Correct : Boolean; + begin + Correct := False; + while not Correct loop + Put_Line + (""Entrez la clé de la personne que vous voulez consulter [0 pour retour].""); + Choisir_Cle (Cle); + Correct := Cle = 0 or else Existe_Registre (Etat.Arbre, Cle); + if not Correct then + Put_Line (""Clé inconnue.""); + New_Line; + end if; + end loop; + New_Line; + if Cle = 0 then + Etat.Menu := Menu_Registre; + else + Etat.Cle := Cle; + Etat.Menu := Menu_Registre_Consultation_Personne; + end if; + end Afficher_Menu_Registre_Consultation_Selection; + + -- Affiche les résultats de la recherche. + procedure Afficher_Resultats (Etat : in out T_Etat; Recherche : in String) + is + Nombre_Resultats : Integer := 0; + + procedure Tester_Personne (Cle : in Integer; Personne : in T_Personne) is + begin + if Sb.Index (Personne.Nom_Usuel, Recherche) > 0 + or else Sb.Index (Personne.Nom_Complet, Recherche) > 0 + then + Nombre_Resultats := Nombre_Resultats + 1; + Put ("" * ""); + Put (Personne.Nom_Usuel); + Put ("" <""); + Put (Cle, 0); + Put ("">""); + New_Line; + end if; + end Tester_Personne; + procedure Rechercher is new Appliquer_Sur_Registre (Tester_Personne); + begin + Put_Line (""Résultats de la recherche :""); + Rechercher (Etat.Arbre); + if Nombre_Resultats = 0 then + Put_Line (""Aucun résultat.""); + Etat.Menu := Menu_Registre; + else + Etat.Menu := Menu_Registre_Consultation_Selection; + end if; + New_Line; + end Afficher_Resultats; + + -- Affiche le menu qui permet de rechercher dans le registre. + procedure Afficher_Menu_Registre_Consultation_Recherche + (Etat : in out T_Etat) + is + Recherche : Sb.Bounded_String; + begin + Put_Line (""* Recherche dans le registre *""); + New_Line; + Put (""Nom a rechercher [Entrée pour retour] : ""); + Recherche := Get_Line; + New_Line; + if Sb.Length (Recherche) > 0 then + Afficher_Resultats (Etat, Sb.To_String (Recherche)); + else + Etat.Menu := Menu_Registre; + end if; + end Afficher_Menu_Registre_Consultation_Recherche; + + -- Affiche le menu des possibilités pour une personne du registre. + procedure Afficher_Menu_Registre_Consultation_Personne + (Etat : in out T_Etat) + is + Personne : T_Personne; + Choix : Integer; + begin + Personne := Lire_Registre (Etat.Arbre, Etat.Cle); + Afficher_Personne (Etat.Cle, Personne); + New_Line; + Put_Line (""Menu : ""); + Put_Line (""1. Consulter son arbre généalogique""); + Put_Line (""2. Modifier les informations""); + Put_Line (""3. Retour""); + New_Line; + Choisir (3, Choix); + New_Line; + case Choix is + when 1 => + Etat.Menu := Menu_Arbre_Consultation; + when 2 => + Etat.Menu := Menu_Registre_Modification; + when 3 => + Etat.Menu := Menu_Registre; + when others => + Etat.Menu := Quitter; + end case; + end Afficher_Menu_Registre_Consultation_Personne; + + -- Demande a l'utilisateur toutes les informations pour peupler `Personne`. + procedure Saisir_Personne (Personne : out T_Personne) is + Nom_Complet : Sb.Bounded_String; + Nom_Usuel : Sb.Bounded_String; + Genre : T_Genre; + Date_De_Naissance : T_Date; + Lieu_De_Naissance : Sb.Bounded_String; + + Correct : Boolean; + Date_Lue : Integer; + Genre_Lu : Character; + begin + Put (""Nom usuel : ""); + Nom_Usuel := Get_Line; + Put (""Nom Complet : ""); + Nom_Complet := Get_Line; + Put (""Sexe [F pour féminin, M pour masculin, A pour autre] : ""); + Get (Genre_Lu); + Skip_Line; + case Genre_Lu is + when 'f' | 'F' => + Genre := Feminin; + when 'm' | 'M' => + Genre := Masculin; + when others => + Genre := Autre; + end case; + + Correct := False; -- La date entrée est correcte ? + while not Correct loop + Put (""Date de naissance [au format JJMMAAAA] : ""); + begin + Get (Date_Lue); + Date_De_Naissance := + Creer_Date + (Date_Lue / 1000000, (Date_Lue / 10000) mod 100, + Date_Lue mod 10000); + Correct := True; + exception + when Ada.Io_Exceptions.Data_Error | Date_Incorrecte => + Correct := False;" +procedure Afficher_Menu_Registre_Ajout (Etat : in out T_Etat) is,"Cle : Integer; + Personne : T_Personne; + + Choix : Character; + begin + Put_Line (""* Ajouter une personne au registre *""); + New_Line; + Put_Line + (""Informations requises : nom usuel, nom complet, sexe, date et lieu de naissance.""); + New_Line; + Saisir_Personne (Personne); + + Put (""Confirmer l'ajout [O pour oui, autre pour non] : ""); + Get (Choix); + Skip_Line; + + if Choix = 'o' or Choix = 'O' then + Ajouter_Personne (Etat.Arbre, Personne, Cle); + Put (""Personne ajoutée avec la clé : ""); + Put (Cle, 0); + else + Put (""Ajout annulé.""); + end if; + New_Line; + New_Line; + + Etat.Menu := Menu_Registre; + + end Afficher_Menu_Registre_Ajout; + + -- Permet de modifier une personne enregistrée. + procedure Afficher_Menu_Registre_Modification (Etat : in out T_Etat) is + Personne : T_Personne; + Choix : Character; + begin + Put_Line (""* Modification d'une personne du registre *""); + New_Line; + Put_Line (""Informations actuelles : ""); + Personne := Lire_Registre (Etat.Arbre, Etat.Cle); + Afficher_Personne (Etat.Cle, Personne); + New_Line; + Saisir_Personne (Personne); + New_Line; + Put (""Confirmer la modification [O pour oui, autre pour non] : ""); + Get (Choix); + Skip_Line; + + if Choix = 'o' or Choix = 'O' then + Attribuer_Registre (Etat.Arbre, Etat.Cle, Personne); + Put_Line (""Personne modifiée avec succès.""); + else + Put_Line (""Modification annulée.""); + end if; + New_Line; + + Etat.Menu := Menu_Registre; + end Afficher_Menu_Registre_Modification; + + -- Demande une clé pour afficher les relations d'une personne. + procedure Afficher_Menu_Arbre_Selection (Etat : in out T_Etat) is + Cle : Integer; + Correct : Boolean; + begin + Put_Line (""* Arbre généalogique *""); + New_Line; + Correct := False; + while not Correct loop + Put_Line + (""Entrez la clé de la personne dont vous voulez consulter l'arbre [0 pour retour].""); + Choisir_Cle (Cle); + Correct := Cle = 0 or else Existe_Registre (Etat.Arbre, Cle); + if not Correct then + Put_Line (""Clé inconnue.""); + New_Line; + end if; + end loop; + New_Line; + if Cle = 0 then + Etat.Menu := Menu_Principal; + else + Etat.Cle := Cle; + Etat.Menu := Menu_Arbre_Consultation; + end if; + end Afficher_Menu_Arbre_Selection; + + -- Affiche les relations d'une personne. + procedure Afficher_Menu_Arbre_Consultation (Etat : in out T_Etat) is + + -- Groupe toutes les relations de même étiquette ensemble. + procedure Afficher_Relations_Groupees + (Etat : in T_Etat; Etiquette : in T_Etiquette_Arete; Titre : in String) + is + Liste : T_Liste_Relations; + Relation : T_Arete_Etiquetee; + Titre_Affiche : Boolean := False; + begin + Liste_Relations (Liste, Etat.Arbre, Etat.Cle); + -- On affiche toutes les relations notées Etiquette + while Liste_Non_Vide (Liste) loop + Relation_Suivante (Liste, Relation); + if Relation.Etiquette = Etiquette then + if not Titre_Affiche then + Put_Line (Titre); + Titre_Affiche := True; + end if; + Put ("" * ""); + Afficher_Nom_Usuel (Etat, Relation.Destination); + New_Line; + end if; + end loop; + end Afficher_Relations_Groupees; + + Liste : T_Liste_Relations; + Choix : Integer; + begin + Afficher_Nom_Usuel (Etat, Etat.Cle); + New_Line; + New_Line; + Liste_Relations (Liste, Etat.Arbre, Etat.Cle); + if not Liste_Non_Vide (Liste) then + Put_Line (""Aucune relation.""); + else + Afficher_Relations_Groupees (Etat, A_Pour_Parent, ""Parent(s) :""); + Afficher_Relations_Groupees (Etat, A_Pour_Enfant, ""Enfant(s) :""); + Afficher_Relations_Groupees (Etat, A_Pour_Conjoint, ""Conjoint(e) :""); + end if; + New_Line; + Put_Line (""Menu :""); + Put_Line (""1. Consulter dans le registre""); + Put_Line (""2. Consulter une autre personne""); + Put_Line (""3. Ajouter une relation""); + Put_Line (""4. Supprimer une relation""); + Put_Line (""5. Afficher un arbre de parenté""); + Put_Line (""6. Retour""); + New_Line; + Choisir (6, Choix); + New_Line; + case Choix is + when 1 => + Etat.Menu := Menu_Registre_Consultation_Personne; + when 2 => + Etat.Menu := Menu_Arbre_Selection; + when 3 => + Etat.Menu := Menu_Arbre_Ajouter_Relation; + when 4 => + Etat.Menu := Menu_Arbre_Supprimer_Relation; + when 5 => + Etat.Menu := Menu_Arbre_Parente; + when 6 => + Etat.Menu := Menu_Principal; + when others => + Etat.Menu := Quitter; + end case; + end Afficher_Menu_Arbre_Consultation; + + -- Permet d'ajouter une relation. + procedure Afficher_Menu_Arbre_Ajouter_Relation (Etat : in out T_Etat) is + Dates_Incompatibles : exception; + + Personne_Origine : T_Personne; + Personne_Destination : T_Personne; + + Cle_Destination : Integer; + Relation_Lue : Integer; + Correct : Boolean; + begin + Put_Line (""Ajouter une relation :""); + Put_Line (""1. Ajouter un parent""); + Put_Line (""2. Ajouter un enfant""); + Put_Line (""3. Ajouter un conjoint""); + New_Line; + Choisir (3, Relation_Lue); + New_Line; + + Correct := False; + while not Correct loop + Put_Line (""Entrez la clé de la personne a lier [0 pour retour].""); + Choisir_Cle (Cle_Destination); + Correct := + Cle_Destination = 0 + or else Existe_Registre (Etat.Arbre, Cle_Destination); + if not Correct then + Put_Line (""Clé inconnue.""); + New_Line; + end if; + end loop; + + if Cle_Destination = 0 then + Put_Line (""Ajout annulé.""); + else + Personne_Origine := Lire_Registre (Etat.Arbre, Etat.Cle); + Personne_Destination := Lire_Registre (Etat.Arbre, Cle_Destination); + begin + case Relation_Lue is + when 1 => + -- On vérifie qu'un parent est plus vieux que son enfant + if D1_Inf_D2 + (Personne_Origine.Date_De_Naissance, + Personne_Destination.Date_De_Naissance) + then + raise Dates_Incompatibles; + end if; + Ajouter_Relation + (Etat.Arbre, Etat.Cle, A_Pour_Parent, Cle_Destination); + when 2 => + if D1_Inf_D2 + (Personne_Destination.Date_De_Naissance, + Personne_Origine.Date_De_Naissance) + then + raise Dates_Incompatibles; + end if; + Ajouter_Relation + (Etat.Arbre, Etat.Cle, A_Pour_Enfant, Cle_Destination); + when 3 => + Ajouter_Relation + (Etat.Arbre, Etat.Cle, A_Pour_Conjoint, Cle_Destination); + when others => + null; + end case; + Put_Line (""Relation ajoutée.""); + exception + when Dates_Incompatibles => + Put_Line (""Un parent doit etre plus agé que son enfant.""); + when Relation_Existante => + Put_Line + (""Une relation entre ces deux personnes existe déja."");" +procedure Initialiser (Graphe : out T_Graphe) is,"begin + Graphe := null; + end Initialiser; + + procedure Desallouer_Sommet is new Ada.Unchecked_Deallocation (T_Sommet, + T_Graphe); + procedure Desallouer_Arete is new Ada.Unchecked_Deallocation (T_Arete, + T_Liste_Adjacence); + + procedure Detruire_Arete (Adjacence : in out T_Liste_Adjacence) is + begin + if Adjacence /= null then + Detruire_Arete (Adjacence.all.Suivante); + end if; + Desallouer_Arete (Adjacence); + end Detruire_Arete; + + procedure Detruire (Graphe : in out T_Graphe) is + begin + if Graphe /= null then + -- Détruit proprement un sommet + Detruire_Arete (Graphe.all.Arete); + Detruire (Graphe.all.Suivant); + end if; + Desallouer_Sommet (Graphe); + end Detruire; + + function Trouver_Pointeur_Sommet + (Graphe : T_Graphe; Etiquette : T_Etiquette_Sommet) return T_Graphe + is + begin + if Graphe = null then + raise Sommet_Non_Trouve; + elsif Graphe.all.Etiquette = Etiquette then + return Graphe; + else + return Trouver_Pointeur_Sommet (Graphe.all.Suivant, Etiquette); + end if; + end Trouver_Pointeur_Sommet; + + procedure Ajouter_Sommet + (Graphe : in out T_Graphe; Etiquette : T_Etiquette_Sommet) + is + Nouveau_Graphe : T_Graphe; + begin + begin + -- On ignore l'ajout si une étiquette du même nom existe déjà + Nouveau_Graphe := Trouver_Pointeur_Sommet (Graphe, Etiquette); + exception + when Sommet_Non_Trouve => + Nouveau_Graphe := new T_Sommet; + Nouveau_Graphe.all := (Etiquette, null, Graphe); + Graphe := Nouveau_Graphe;" +procedure Main is,"Fail_Cnt : Natural := 0; + Pass_Cnt : Natural := 0; + + procedure Test (Str : String; + Expected_Error : String := """"; + Allow_Custom : Boolean := False); + + procedure Test (Str : String; + Expected_Error : String := """"; + Allow_Custom : Boolean := False) + is + begin + declare + Exp : constant SPDX.Expression := SPDX.Parse (Str, Allow_Custom); + Error : constant String := + (if SPDX.Valid (Exp) then """" else SPDX.Error (Exp)); + begin + if Error /= Expected_Error then + Put_Line (""FAIL: '"" & Str & ""'""); + if Expected_Error /= """" then + Put_Line ("" Expected error: '"" & Expected_Error & ""'""); + Put_Line ("" but got : '"" & Error & ""'""); + else + Put_Line ("" Unexpected error: '"" & Error & ""'""); + end if; + + Fail_Cnt := Fail_Cnt + 1; + + elsif Expected_Error = """" + and then + Allow_Custom + and then + not SPDX.Has_Custom (Exp) + then + Put_Line (""FAIL: '"" & Str & ""'""); + Put_Line ("" Has_Custom returned False""); + Fail_Cnt := Fail_Cnt + 1; + else + Put_Line (""PASS: '"" & Str & ""'""); + Pass_Cnt := Pass_Cnt + 1; + end if;"