]> matita.cs.unibo.it Git - helm.git/blob - helm/gTopLevel/gTopLevel.ml
- New interface for the MathQL interpreter (1.3 version)
[helm.git] / helm / gTopLevel / gTopLevel.ml
1 (* Copyright (C) 2000-2002, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (******************************************************************************)
27 (*                                                                            *)
28 (*                               PROJECT HELM                                 *)
29 (*                                                                            *)
30 (*                Claudio Sacerdoti Coen <sacerdot@cs.unibo.it>               *)
31 (*                                 06/01/2002                                 *)
32 (*                                                                            *)
33 (*                                                                            *)
34 (******************************************************************************)
35
36 open Printf;;
37
38 (* DEBUGGING *)
39
40 module MQICallbacks =
41    struct
42       let log s = prerr_string s
43    end
44
45 module MQI = MQueryInterpreter.Make(MQICallbacks)
46
47 (* GLOBAL CONSTANTS *)
48
49 let mqi_options = "" (* default MathQL interpreter options *)
50
51 let xlinkns = Gdome.domString "http://www.w3.org/1999/xlink";;
52
53 let htmlheader =
54  "<html>" ^
55  " <body bgColor=\"white\">"
56 ;;
57
58 let htmlfooter =
59  " </body>" ^
60  "</html>"
61 ;;
62
63 let prooffile =
64  try
65   Sys.getenv "GTOPLEVEL_PROOFFILE"
66  with
67   Not_found -> "/public/currentproof"
68 ;;
69
70 let prooffiletype =
71  try
72   Sys.getenv "GTOPLEVEL_PROOFFILETYPE"
73  with
74   Not_found -> "/public/currentprooftype"
75 ;;
76
77 (* GLOBAL REFERENCES (USED BY CALLBACKS) *)
78
79 let htmlheader_and_content = ref htmlheader;;
80
81 let check_term = ref (fun _ _ _ -> assert false);;
82
83 exception RenderingWindowsNotInitialized;;
84
85 let set_rendering_window,rendering_window =
86  let rendering_window_ref = ref None in
87   (function rw -> rendering_window_ref := Some rw),
88   (function () ->
89     match !rendering_window_ref with
90        None -> raise RenderingWindowsNotInitialized
91      | Some rw -> rw
92   )
93 ;;
94
95 exception SettingsWindowsNotInitialized;;
96
97 let set_settings_window,settings_window =
98  let settings_window_ref = ref None in
99   (function rw -> settings_window_ref := Some rw),
100   (function () ->
101     match !settings_window_ref with
102        None -> raise SettingsWindowsNotInitialized
103      | Some rw -> rw
104   )
105 ;;
106
107 exception OutputHtmlNotInitialized;;
108
109 let set_outputhtml,outputhtml =
110  let outputhtml_ref = ref None in
111   (function rw -> outputhtml_ref := Some rw),
112   (function () ->
113     match !outputhtml_ref with
114        None -> raise OutputHtmlNotInitialized
115      | Some outputhtml -> outputhtml
116   )
117 ;;
118
119 exception QedSetSensitiveNotInitialized;;
120 let qed_set_sensitive =
121  ref (function _ -> raise QedSetSensitiveNotInitialized)
122 ;;
123
124 exception SaveSetSensitiveNotInitialized;;
125 let save_set_sensitive =
126  ref (function _ -> raise SaveSetSensitiveNotInitialized)
127 ;;
128
129 (* COMMAND LINE OPTIONS *)
130
131 let usedb = ref true
132
133 let argspec =
134   [
135     "-nodb", Arg.Clear usedb, "disable use of MathQL DB"
136   ]
137 in
138 Arg.parse argspec ignore ""
139
140 (* MISC FUNCTIONS *)
141
142 let term_of_cic_textual_parser_uri uri =
143  let module C = Cic in
144  let module CTP = CicTextualParser0 in
145   match uri with
146      CTP.ConUri uri -> C.Const (uri,[])
147    | CTP.VarUri uri -> C.Var (uri,[])
148    | CTP.IndTyUri (uri,tyno) -> C.MutInd (uri,tyno,[])
149    | CTP.IndConUri (uri,tyno,consno) -> C.MutConstruct (uri,tyno,consno,[])
150 ;;
151
152 let string_of_cic_textual_parser_uri uri =
153  let module C = Cic in
154  let module CTP = CicTextualParser0 in
155   let uri' =
156    match uri with
157       CTP.ConUri uri -> UriManager.string_of_uri uri
158     | CTP.VarUri uri -> UriManager.string_of_uri uri
159     | CTP.IndTyUri (uri,tyno) ->
160        UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1)
161     | CTP.IndConUri (uri,tyno,consno) ->
162        UriManager.string_of_uri uri ^ "#1/" ^ string_of_int (tyno + 1) ^ "/" ^
163         string_of_int consno
164   in
165    (* 4 = String.length "cic:" *)
166    String.sub uri' 4 (String.length uri' - 4)
167 ;;
168
169 let output_html outputhtml msg =
170  htmlheader_and_content := !htmlheader_and_content ^ msg ;
171  outputhtml#source (!htmlheader_and_content ^ htmlfooter) ;
172  outputhtml#set_topline (-1)
173 ;;
174
175 (* UTILITY FUNCTIONS TO DISAMBIGUATE AN URI *)
176
177 (* Check window *)
178
179 let check_window outputhtml uris =
180  let window =
181   GWindow.window
182    ~width:800 ~modal:true ~title:"Check" ~border_width:2 () in
183  let notebook =
184   GPack.notebook ~scrollable:true ~packing:window#add () in
185  window#show () ;
186  let render_terms =
187   List.map
188    (function uri ->
189      let scrolled_window =
190       GBin.scrolled_window ~border_width:10
191        ~packing:
192          (notebook#append_page ~tab_label:((GMisc.label ~text:uri ())#coerce))
193        ()
194      in
195       lazy 
196        (let mmlwidget =
197          TermViewer.sequent_viewer
198           ~packing:scrolled_window#add ~width:400 ~height:280 () in
199         let expr =
200          let term =
201           term_of_cic_textual_parser_uri
202            (MQueryMisc.cic_textual_parser_uri_of_string uri)
203          in
204           (Cic.Cast (term, CicTypeChecker.type_of_aux' [] [] term))
205         in
206          try
207           mmlwidget#load_sequent [] (111,[],expr)
208          with
209           e ->
210            output_html outputhtml
211             ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
212        )
213    ) uris
214  in
215   ignore
216    (notebook#connect#switch_page
217      (function i -> Lazy.force (List.nth render_terms i)))
218 ;;
219
220 exception NoChoice;;
221
222 let
223  interactive_user_uri_choice ~(selection_mode:[`SINGLE|`EXTENDED]) ?(ok="Ok")
224   ?(enable_button_for_non_vars=false) ~title ~msg uris
225 =
226  let choices = ref [] in
227  let chosen = ref false in
228  let use_only_constants = ref false in
229  let window =
230   GWindow.dialog ~modal:true ~title ~width:600 () in
231  let lMessage =
232   GMisc.label ~text:msg
233    ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
234  let scrolled_window =
235   GBin.scrolled_window ~border_width:10
236    ~packing:(window#vbox#pack ~expand:true ~fill:true ~padding:5) () in
237  let clist =
238   let expected_height = 18 * List.length uris in
239    let height = if expected_height > 400 then 400 else expected_height in
240     GList.clist ~columns:1 ~packing:scrolled_window#add
241      ~height ~selection_mode:(selection_mode :> Gtk.Tags.selection_mode) () in
242  let _ = List.map (function x -> clist#append [x]) uris in
243  let hbox2 =
244   GPack.hbox ~border_width:0
245    ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
246  let explain_label =
247   GMisc.label ~text:"None of the above. Try this one:"
248    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
249  let manual_input =
250   GEdit.entry ~editable:true
251    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
252  let hbox =
253   GPack.hbox ~border_width:0 ~packing:window#action_area#add () in
254  let okb =
255   GButton.button ~label:ok
256    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
257  let _ = okb#misc#set_sensitive false in
258  let nonvarsb =
259   GButton.button
260    ~packing:
261     (function w ->
262       if enable_button_for_non_vars then
263        hbox#pack ~expand:false ~fill:false ~padding:5 w)
264    ~label:"Try constants only" () in
265  let checkb =
266   GButton.button ~label:"Check"
267    ~packing:(hbox#pack ~padding:5) () in
268  let _ = checkb#misc#set_sensitive false in
269  let cancelb =
270   GButton.button ~label:"Abort"
271    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
272  (* actions *)
273  let check_callback () =
274   assert (List.length !choices > 0) ;
275   check_window (outputhtml ()) !choices
276  in
277   ignore (window#connect#destroy GMain.Main.quit) ;
278   ignore (cancelb#connect#clicked window#destroy) ;
279   ignore
280    (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
281   ignore
282    (nonvarsb#connect#clicked
283      (function () ->
284        use_only_constants := true ;
285        chosen := true ;
286        window#destroy ()
287    )) ;
288   ignore (checkb#connect#clicked check_callback) ;
289   ignore
290    (clist#connect#select_row
291      (fun ~row ~column ~event ->
292        checkb#misc#set_sensitive true ;
293        okb#misc#set_sensitive true ;
294        choices := (List.nth uris row)::!choices)) ;
295   ignore
296    (clist#connect#unselect_row
297      (fun ~row ~column ~event ->
298        choices :=
299         List.filter (function uri -> uri != (List.nth uris row)) !choices)) ;
300   ignore
301    (manual_input#connect#changed
302      (fun _ ->
303        if manual_input#text = "" then
304         begin
305          choices := [] ;
306          checkb#misc#set_sensitive false ;
307          okb#misc#set_sensitive false ;
308          clist#misc#set_sensitive true
309         end
310        else
311         begin
312          choices := [manual_input#text] ;
313          clist#unselect_all () ;
314          checkb#misc#set_sensitive true ;
315          okb#misc#set_sensitive true ;
316          clist#misc#set_sensitive false
317         end));
318   window#set_position `CENTER ;
319   window#show () ;
320   GtkThread.main ();
321   if !chosen then
322    if !use_only_constants then
323     List.filter
324      (function uri -> not (String.sub uri (String.length uri - 4) 4 = ".var"))
325      uris
326    else
327     if List.length !choices > 0 then !choices else raise NoChoice
328   else
329    raise NoChoice
330 ;;
331
332 let interactive_interpretation_choice interpretations =
333  let chosen = ref None in
334  let window =
335   GWindow.window
336    ~modal:true ~title:"Ambiguous well-typed input." ~border_width:2 () in
337  let vbox = GPack.vbox ~packing:window#add () in
338  let lMessage =
339   GMisc.label
340    ~text:
341     ("Ambiguous input since there are many well-typed interpretations." ^
342      " Please, choose one of them.")
343    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
344  let notebook =
345   GPack.notebook ~scrollable:true
346    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
347  let _ =
348   List.map
349    (function interpretation ->
350      let clist =
351       let expected_height = 18 * List.length interpretation in
352        let height = if expected_height > 400 then 400 else expected_height in
353         GList.clist ~columns:2 ~packing:notebook#append_page ~height
354          ~titles:["id" ; "URI"] ()
355      in
356       ignore
357        (List.map
358          (function (id,uri) ->
359            let n = clist#append [id;uri] in
360             clist#set_row ~selectable:false n
361          ) interpretation
362        ) ;
363       clist#columns_autosize ()
364    ) interpretations in
365  let hbox =
366   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
367  let okb =
368   GButton.button ~label:"Ok"
369    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
370  let cancelb =
371   GButton.button ~label:"Abort"
372    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
373  (* actions *)
374  ignore (window#connect#destroy GMain.Main.quit) ;
375  ignore (cancelb#connect#clicked window#destroy) ;
376  ignore
377   (okb#connect#clicked
378     (function () -> chosen := Some notebook#current_page ; window#destroy ())) ;
379  window#set_position `CENTER ;
380  window#show () ;
381  GtkThread.main ();
382  match !chosen with
383     None -> raise NoChoice
384   | Some n -> n
385 ;;
386
387
388 (* MISC FUNCTIONS *)
389
390 (* CSC: IMPERATIVE AND NOT VERY CLEAN, TO GET THE LAST ISSUED QUERY *)
391 (* FG : THIS FUNCTION IS BECOMING A REAL NONSENSE                   *)
392 let get_last_query = 
393  let query = ref "" in
394   let out s = query := ! query ^ s in
395   MQueryGenerator.set_confirm_query
396    (function q -> 
397     query := ""; MQueryUtil.text_of_query out q ""; true);
398   function result ->
399    out (!query ^ " <h1>Result:</h1> "); MQueryUtil.text_of_result out result "<br>";
400    !query
401 ;;
402
403 let
404  save_object_to_disk uri annobj ids_to_inner_sorts ids_to_inner_types pathname
405 =
406  let name =
407   let struri = UriManager.string_of_uri uri in
408   let idx = (String.rindex struri '/') + 1 in
409    String.sub struri idx (String.length struri - idx)
410  in
411   let path = pathname ^ "/" ^ name in
412   let xml, bodyxml =
413    Cic2Xml.print_object uri ~ids_to_inner_sorts ~ask_dtd_to_the_getter:false
414     annobj 
415   in
416   let xmlinnertypes =
417    Cic2Xml.print_inner_types uri ~ids_to_inner_sorts ~ids_to_inner_types
418     ~ask_dtd_to_the_getter:false
419   in
420    (* innertypes *)
421    let innertypesuri = UriManager.innertypesuri_of_uri uri in
422     Xml.pp ~quiet:true xmlinnertypes (Some (path ^ ".types.xml")) ;
423     Getter.register innertypesuri
424      (Configuration.annotations_url ^
425        Str.replace_first (Str.regexp "^cic:") ""
426         (UriManager.string_of_uri innertypesuri) ^ ".xml"
427      ) ;
428     (* constant type / variable / mutual inductive types definition *)
429     Xml.pp ~quiet:true xml (Some (path ^ ".xml")) ;
430     Getter.register uri
431      (Configuration.annotations_url ^
432        Str.replace_first (Str.regexp "^cic:") ""
433         (UriManager.string_of_uri uri) ^ ".xml"
434      ) ;
435     match bodyxml with
436        None -> ()
437      | Some bodyxml' ->
438         (* constant body *)
439         let bodyuri =
440          match UriManager.bodyuri_of_uri uri with
441             None -> assert false
442           | Some bodyuri -> bodyuri
443         in
444          Xml.pp ~quiet:true bodyxml' (Some (path ^ ".body.xml")) ;
445          Getter.register bodyuri
446           (Configuration.annotations_url ^
447             Str.replace_first (Str.regexp "^cic:") ""
448              (UriManager.string_of_uri bodyuri) ^ ".xml"
449           )
450 ;;
451
452
453 (* CALLBACKS *)
454
455 exception OpenConjecturesStillThere;;
456 exception WrongProof;;
457
458 let pathname_of_annuri uristring =
459  Configuration.annotations_dir ^    
460   Str.replace_first (Str.regexp "^cic:") "" uristring
461 ;;
462
463 let make_dirs dirpath =
464  ignore (Unix.system ("mkdir -p " ^ dirpath))
465 ;;
466
467 let save_obj uri obj =
468  let
469   (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
470    ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
471  =
472   Cic2acic.acic_object_of_cic_object obj
473  in
474   (* let's save the theorem and register it to the getter *) 
475   let pathname = pathname_of_annuri (UriManager.buri_of_uri uri) in
476    make_dirs pathname ;
477    save_object_to_disk uri acic ids_to_inner_sorts ids_to_inner_types
478     pathname
479 ;;
480
481 let qed () =
482  match !ProofEngine.proof with
483     None -> assert false
484   | Some (uri,[],bo,ty) ->
485      if
486       CicReduction.are_convertible []
487        (CicTypeChecker.type_of_aux' [] [] bo) ty
488      then
489       begin
490        (*CSC: Wrong: [] is just plainly wrong *)
491        let proof = Cic.Constant (UriManager.name_of_uri uri,Some bo,ty,[]) in
492        let (acic,ids_to_inner_types,ids_to_inner_sorts) =
493         (rendering_window ())#output#load_proof uri proof
494        in
495         !qed_set_sensitive false ;
496         (* let's save the theorem and register it to the getter *) 
497         let pathname = pathname_of_annuri (UriManager.buri_of_uri uri) in
498          make_dirs pathname ;
499          save_object_to_disk uri acic ids_to_inner_sorts ids_to_inner_types
500           pathname
501       end
502      else
503       raise WrongProof
504   | _ -> raise OpenConjecturesStillThere
505 ;;
506
507   (** save an unfinished proof on the filesystem *)
508 let save_unfinished_proof () =
509  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
510  let (xml, bodyxml) = ProofEngine.get_current_status_as_xml () in
511  Xml.pp ~quiet:true xml (Some prooffiletype) ;
512  output_html outputhtml
513   ("<h1 color=\"Green\">Current proof type saved to " ^
514    prooffiletype ^ "</h1>") ;
515  Xml.pp ~quiet:true bodyxml (Some prooffile) ;
516  output_html outputhtml
517   ("<h1 color=\"Green\">Current proof body saved to " ^
518    prooffile ^ "</h1>")
519 ;;
520
521 (* Used to typecheck the loaded proofs *)
522 let typecheck_loaded_proof metasenv bo ty =
523  let module T = CicTypeChecker in
524   ignore (
525    List.fold_left
526     (fun metasenv ((_,context,ty) as conj) ->
527       ignore (T.type_of_aux' metasenv context ty) ;
528       metasenv @ [conj]
529     ) [] metasenv) ;
530   ignore (T.type_of_aux' metasenv [] ty) ;
531   ignore (T.type_of_aux' metasenv [] bo)
532 ;;
533
534 let decompose_uris_choice_callback uris = 
535 (* N.B.: in questo passaggio perdo l'informazione su exp_named_subst !!!! *)
536   let module U = UriManager in 
537    List.map 
538     (function uri ->
539       match MQueryMisc.cic_textual_parser_uri_of_string uri with
540          CicTextualParser0.IndTyUri (uri,typeno) -> (uri,typeno,[])
541        | _ -> assert false)
542     (interactive_user_uri_choice 
543       ~selection_mode:`EXTENDED ~ok:"Ok" ~enable_button_for_non_vars:false 
544       ~title:"Decompose" ~msg:"Please, select the Inductive Types to decompose" 
545       (List.map 
546         (function (uri,typeno,_) ->
547           U.string_of_uri uri ^ "#1/" ^ string_of_int (typeno+1)
548         ) uris)
549     ) 
550 ;;
551
552 let mk_fresh_name_callback context name ~typ =
553  let fresh_name =
554   match ProofEngineHelpers.mk_fresh_name context name ~typ with
555      Cic.Name fresh_name -> fresh_name
556    | Cic.Anonymous -> assert false
557  in
558   match
559    GToolbox.input_string ~title:"Enter a fresh hypothesis name" ~text:fresh_name
560     ("Enter a fresh name for the hypothesis " ^
561       CicPp.pp typ
562        (List.map (function None -> None | Some (n,_) -> Some n) context))
563   with
564      Some fresh_name' -> Cic.Name fresh_name'
565    | None -> raise NoChoice
566 ;;
567
568 let refresh_proof (output : TermViewer.proof_viewer) =
569  try
570   let uri,currentproof =
571    match !ProofEngine.proof with
572       None -> assert false
573     | Some (uri,metasenv,bo,ty) ->
574        if List.length metasenv = 0 then
575         begin
576          !qed_set_sensitive true ;
577 prerr_endline "CSC: ###### REFRESH_PROOF, Hbugs.clear ()" ;
578          Hbugs.clear ()
579         end
580        else
581 begin
582 prerr_endline "CSC: ###### REFRESH_PROOF, Hbugs.notify ()" ;
583         Hbugs.notify () ;
584 end ;
585        (*CSC: Wrong: [] is just plainly wrong *)
586        uri,
587         (Cic.CurrentProof (UriManager.name_of_uri uri, metasenv, bo, ty, []))
588   in
589    ignore (output#load_proof uri currentproof)
590  with
591   e ->
592  match !ProofEngine.proof with
593     None -> assert false
594   | Some (uri,metasenv,bo,ty) ->
595 prerr_endline ("Offending proof: " ^ CicPp.ppobj (Cic.CurrentProof ("questa",metasenv,bo,ty,[]))) ; flush stderr ;
596    raise (InvokeTactics.RefreshProofException e)
597
598 let refresh_goals ?(empty_notebook=true) notebook =
599  try
600   match !ProofEngine.goal with
601      None ->
602       if empty_notebook then
603        begin 
604         notebook#remove_all_pages ~skip_switch_page_event:false ;
605         notebook#set_empty_page
606        end
607       else
608        notebook#proofw#unload
609    | Some metano ->
610       let metasenv =
611        match !ProofEngine.proof with
612           None -> assert false
613         | Some (_,metasenv,_,_) -> metasenv
614       in
615       let currentsequent =
616        List.find (function (m,_,_) -> m=metano) metasenv
617       in
618         let regenerate_notebook () = 
619          let skip_switch_page_event =
620           match metasenv with
621              (m,_,_)::_ when m = metano -> false
622            | _ -> true
623          in
624           notebook#remove_all_pages ~skip_switch_page_event ;
625           List.iter (function (m,_,_) -> notebook#add_page m) metasenv ;
626         in
627           if empty_notebook then
628            begin
629             regenerate_notebook () ;
630             notebook#set_current_page
631              ~may_skip_switch_page_event:false metano
632            end
633           else
634            begin
635             notebook#set_current_page
636              ~may_skip_switch_page_event:true metano ;
637             notebook#proofw#load_sequent metasenv currentsequent
638            end
639  with
640   e ->
641 let metano =
642   match !ProofEngine.goal with
643      None -> assert false
644    | Some m -> m
645 in
646 let metasenv =
647  match !ProofEngine.proof with
648     None -> assert false
649   | Some (_,metasenv,_,_) -> metasenv
650 in
651 try
652 let currentsequent = List.find (function (m,_,_) -> m=metano) metasenv in
653    prerr_endline ("Offending sequent: " ^ SequentPp.TextualPp.print_sequent currentsequent) ; flush stderr ;
654       raise (InvokeTactics.RefreshSequentException e)
655 with Not_found -> prerr_endline ("Offending sequent " ^ string_of_int metano ^ " unknown."); raise (InvokeTactics.RefreshSequentException e)
656
657 module InvokeTacticsCallbacks =
658  struct
659   let sequent_viewer () = (rendering_window ())#notebook#proofw
660   let term_editor () = (rendering_window ())#inputt
661   let scratch_window () = (rendering_window ())#scratch_window
662
663   let refresh_proof () =
664    let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
665     refresh_proof output
666
667   let refresh_goals () =
668    let notebook = (rendering_window ())#notebook in
669     refresh_goals notebook
670
671   let decompose_uris_choice_callback = decompose_uris_choice_callback
672   let mk_fresh_name_callback = mk_fresh_name_callback
673   let output_html msg = output_html (outputhtml ()) msg
674  end
675 ;;
676 module InvokeTactics' = InvokeTactics.Make (InvokeTacticsCallbacks);;
677 (* Just to initialize the Hbugs module *)
678 module Ignore = Hbugs.Initialize (InvokeTactics');;
679
680   (** load an unfinished proof from filesystem *)
681 let load_unfinished_proof () =
682  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
683  let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
684  let notebook = (rendering_window ())#notebook in
685   try
686    match 
687     GToolbox.input_string ~title:"Load Unfinished Proof" ~text:"/dummy.con"
688      "Choose an URI:"
689    with
690       None -> raise NoChoice
691     | Some uri0 ->
692        let uri = UriManager.uri_of_string ("cic:" ^ uri0) in
693         match CicParser.obj_of_xml prooffiletype (Some prooffile) with
694            Cic.CurrentProof (_,metasenv,bo,ty,_) ->
695             typecheck_loaded_proof metasenv bo ty ;
696             ProofEngine.proof :=
697              Some (uri, metasenv, bo, ty) ;
698             ProofEngine.goal :=
699              (match metasenv with
700                  [] -> None
701                | (metano,_,_)::_ -> Some metano
702              ) ;
703             refresh_proof output ;
704             refresh_goals notebook ;
705              output_html outputhtml
706               ("<h1 color=\"Green\">Current proof type loaded from " ^
707                 prooffiletype ^ "</h1>") ;
708              output_html outputhtml
709               ("<h1 color=\"Green\">Current proof body loaded from " ^
710                 prooffile ^ "</h1>") ;
711             !save_set_sensitive true;
712          | _ -> assert false
713   with
714      InvokeTactics.RefreshSequentException e ->
715       output_html outputhtml
716        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
717         "sequent: " ^ Printexc.to_string e ^ "</h1>")
718    | InvokeTactics.RefreshProofException e ->
719       output_html outputhtml
720        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
721         "proof: " ^ Printexc.to_string e ^ "</h1>")
722    | e ->
723       output_html outputhtml
724        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
725 ;;
726
727 let edit_aliases () =
728  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
729  let id_to_uris = inputt#id_to_uris in
730  let chosen = ref false in
731  let window =
732   GWindow.window
733    ~width:400 ~modal:true ~title:"Edit Aliases..." ~border_width:2 () in
734  let vbox =
735   GPack.vbox ~border_width:0 ~packing:window#add () in
736  let scrolled_window =
737   GBin.scrolled_window ~border_width:10
738    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
739  let input = GEdit.text ~editable:true ~width:400 ~height:100
740    ~packing:scrolled_window#add () in
741  let hbox =
742   GPack.hbox ~border_width:0
743    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
744  let okb =
745   GButton.button ~label:"Ok"
746    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
747  let cancelb =
748   GButton.button ~label:"Cancel"
749    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
750  ignore (window#connect#destroy GMain.Main.quit) ;
751  ignore (cancelb#connect#clicked window#destroy) ;
752  ignore
753   (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
754  let dom,resolve_id = !id_to_uris in
755   ignore
756    (input#insert_text ~pos:0
757     (String.concat "\n"
758       (List.map
759         (function v ->
760           let uri =
761            match resolve_id v with
762               None -> assert false
763             | Some (CicTextualParser0.Uri uri) -> uri
764             | Some (CicTextualParser0.Term _)
765             | Some CicTextualParser0.Implicit -> assert false
766           in
767            "alias " ^
768             (match v with
769                 CicTextualParser0.Id id -> id
770               | CicTextualParser0.Symbol (descr,_) ->
771                  (* CSC: To be implemented *)
772                  assert false
773             )^ " " ^ (string_of_cic_textual_parser_uri uri)
774         ) dom))) ;
775   window#show () ;
776   GtkThread.main ();
777   if !chosen then
778    let dom,resolve_id =
779     let inputtext = input#get_chars 0 input#length in
780     let regexpr =
781      let alfa = "[a-zA-Z_-]" in
782      let digit = "[0-9]" in
783      let ident = alfa ^ "\(" ^ alfa ^ "\|" ^ digit ^ "\)*" in
784      let blanks = "\( \|\t\|\n\)+" in
785      let nonblanks = "[^ \t\n]+" in
786      let uri = "/\(" ^ ident ^ "/\)*" ^ nonblanks in (* not very strict check *)
787       Str.regexp
788        ("alias" ^ blanks ^ "\(" ^ ident ^ "\)" ^ blanks ^ "\(" ^ uri ^ "\)")
789     in
790      let rec aux n =
791       try
792        let n' = Str.search_forward regexpr inputtext n in
793         let id = CicTextualParser0.Id (Str.matched_group 2 inputtext) in
794         let uri =
795          MQueryMisc.cic_textual_parser_uri_of_string
796           ("cic:" ^ (Str.matched_group 5 inputtext))
797         in
798          let dom,resolve_id = aux (n' + 1) in
799           if List.mem id dom then
800            dom,resolve_id
801           else
802            id::dom,
803             (function id' ->
804               if id = id' then
805                Some (CicTextualParser0.Uri uri)
806               else resolve_id id')
807       with
808        Not_found -> TermEditor.empty_id_to_uris
809      in
810       aux 0
811    in
812     id_to_uris := (dom,resolve_id)
813 ;;
814
815 let proveit () =
816  let module L = LogicalOperations in
817  let module G = Gdome in
818  let notebook = (rendering_window ())#notebook in
819  let output = (rendering_window ())#output in
820  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
821   try
822    output#make_sequent_of_selected_term ;
823    refresh_proof output ;
824    refresh_goals notebook
825   with
826      InvokeTactics.RefreshSequentException e ->
827       output_html outputhtml
828        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
829         "sequent: " ^ Printexc.to_string e ^ "</h1>")
830    | InvokeTactics.RefreshProofException e ->
831       output_html outputhtml
832        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
833         "proof: " ^ Printexc.to_string e ^ "</h1>")
834    | e ->
835       output_html outputhtml
836        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
837 ;;
838
839 let focus () =
840  let module L = LogicalOperations in
841  let module G = Gdome in
842  let notebook = (rendering_window ())#notebook in
843  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
844  let output = (rendering_window ())#output in
845   try
846    output#focus_sequent_of_selected_term ;
847    refresh_goals notebook
848   with
849      InvokeTactics.RefreshSequentException e ->
850       output_html outputhtml
851        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
852         "sequent: " ^ Printexc.to_string e ^ "</h1>")
853    | InvokeTactics.RefreshProofException e ->
854       output_html outputhtml
855        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
856         "proof: " ^ Printexc.to_string e ^ "</h1>")
857    | e ->
858       output_html outputhtml
859        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
860 ;;
861
862 exception NoPrevGoal;;
863 exception NoNextGoal;;
864
865 let setgoal metano =
866  let module L = LogicalOperations in
867  let module G = Gdome in
868  let notebook = (rendering_window ())#notebook in
869  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
870   let metasenv =
871    match !ProofEngine.proof with
872       None -> assert false
873     | Some (_,metasenv,_,_) -> metasenv
874   in
875    try
876     refresh_goals ~empty_notebook:false notebook
877    with
878       InvokeTactics.RefreshSequentException e ->
879        output_html outputhtml
880         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
881          "sequent: " ^ Printexc.to_string e ^ "</h1>")
882     | e ->
883        output_html outputhtml
884         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
885 ;;
886
887 let
888  show_in_show_window_obj, show_in_show_window_uri, show_in_show_window_callback
889 =
890  let window =
891   GWindow.window ~width:800 ~border_width:2 () in
892  let scrolled_window =
893   GBin.scrolled_window ~border_width:10 ~packing:window#add () in
894  let mmlwidget =
895   GMathViewAux.single_selection_math_view
896     ~packing:scrolled_window#add ~width:600 ~height:400 ()
897  in
898  let _ = window#event#connect#delete (fun _ -> window#misc#hide () ; true ) in
899  let href = Gdome.domString "href" in
900   let show_in_show_window_obj uri obj =
901    let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
902     try
903      let
904       (acic,ids_to_terms,ids_to_father_ids,ids_to_inner_sorts,
905        ids_to_inner_types,ids_to_conjectures,ids_to_hypotheses)
906      =
907       Cic2acic.acic_object_of_cic_object obj
908      in
909       let mml =
910        ApplyStylesheets.mml_of_cic_object
911         ~explode_all:false uri acic ids_to_inner_sorts ids_to_inner_types
912       in
913        window#set_title (UriManager.string_of_uri uri) ;
914        window#misc#hide () ; window#show () ;
915        mmlwidget#load_doc mml ;
916     with
917      e ->
918       output_html outputhtml
919        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
920   in
921   let show_in_show_window_uri uri =
922    let obj = CicEnvironment.get_obj uri in
923     show_in_show_window_obj uri obj
924   in
925    let show_in_show_window_callback mmlwidget (n : Gdome.element option) _ =
926     match n with
927        None -> ()
928      | Some n' ->
929         if n'#hasAttributeNS ~namespaceURI:xlinkns ~localName:href then
930          let uri =
931           (n'#getAttributeNS ~namespaceURI:xlinkns ~localName:href)#to_string
932          in 
933           show_in_show_window_uri (UriManager.uri_of_string uri)
934         else
935          ignore (mmlwidget#action_toggle n')
936    in
937     let _ =
938      mmlwidget#connect#click (show_in_show_window_callback mmlwidget)
939     in
940      show_in_show_window_obj, show_in_show_window_uri,
941       show_in_show_window_callback
942 ;;
943
944 exception NoObjectsLocated;;
945
946 let user_uri_choice ~title ~msg uris =
947  let uri =
948   match uris with
949      [] -> raise NoObjectsLocated
950    | [uri] -> uri
951    | uris ->
952       match
953        interactive_user_uri_choice ~selection_mode:`SINGLE ~title ~msg uris
954       with
955          [uri] -> uri
956        | _ -> assert false
957  in
958   String.sub uri 4 (String.length uri - 4)
959 ;;
960
961 let locate_callback id =
962  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
963  let result = MQueryGenerator.locate id in
964  let uris =
965   List.map
966    (function uri,_ ->
967      MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri)
968    result in
969  let html =
970   (" <h1>Locate Query: </h1><pre>" ^ get_last_query result ^ "</pre>")
971  in
972   output_html outputhtml html ;
973   user_uri_choice ~title:"Ambiguous input."
974    ~msg:
975      ("Ambiguous input \"" ^ id ^
976       "\". Please, choose one interpetation:")
977    uris
978 ;;
979
980
981 let input_or_locate_uri ~title =
982  let uri = ref None in
983  let window =
984   GWindow.window
985    ~width:400 ~modal:true ~title ~border_width:2 () in
986  let vbox = GPack.vbox ~packing:window#add () in
987  let hbox1 =
988   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
989  let _ =
990   GMisc.label ~text:"Enter a valid URI:" ~packing:(hbox1#pack ~padding:5) () in
991  let manual_input =
992   GEdit.entry ~editable:true
993    ~packing:(hbox1#pack ~expand:true ~fill:true ~padding:5) () in
994  let checkb =
995   GButton.button ~label:"Check"
996    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
997  let _ = checkb#misc#set_sensitive false in
998  let hbox2 =
999   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1000  let _ =
1001   GMisc.label ~text:"You can also enter an indentifier to locate:"
1002    ~packing:(hbox2#pack ~padding:5) () in
1003  let locate_input =
1004   GEdit.entry ~editable:true
1005    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
1006  let locateb =
1007   GButton.button ~label:"Locate"
1008    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
1009  let _ = locateb#misc#set_sensitive false in
1010  let hbox3 =
1011   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1012  let okb =
1013   GButton.button ~label:"Ok"
1014    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
1015  let _ = okb#misc#set_sensitive false in
1016  let cancelb =
1017   GButton.button ~label:"Cancel"
1018    ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) ()
1019  in
1020   ignore (window#connect#destroy GMain.Main.quit) ;
1021   ignore
1022    (cancelb#connect#clicked (function () -> uri := None ; window#destroy ())) ;
1023   let check_callback () =
1024    let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1025    let uri = "cic:" ^ manual_input#text in
1026     try
1027       ignore (Getter.resolve (UriManager.uri_of_string uri)) ;
1028       output_html outputhtml "<h1 color=\"Green\">OK</h1>" ;
1029       true
1030     with
1031        Getter.Unresolved ->
1032         output_html outputhtml
1033          ("<h1 color=\"Red\">URI " ^ uri ^
1034           " does not correspond to any object.</h1>") ;
1035         false
1036      | UriManager.IllFormedUri _ ->
1037         output_html outputhtml
1038          ("<h1 color=\"Red\">URI " ^ uri ^ " is not well-formed.</h1>") ;
1039         false
1040      | e ->
1041         output_html outputhtml
1042          ("<h1 color=\"Red\">" ^ Printexc.to_string e ^ "</h1>") ;
1043         false
1044   in
1045   ignore
1046    (okb#connect#clicked
1047      (function () ->
1048        if check_callback () then
1049         begin
1050          uri := Some manual_input#text ;
1051          window#destroy ()
1052         end
1053    )) ;
1054   ignore (checkb#connect#clicked (function () -> ignore (check_callback ()))) ;
1055   ignore
1056    (manual_input#connect#changed
1057      (fun _ ->
1058        if manual_input#text = "" then
1059         begin
1060          checkb#misc#set_sensitive false ;
1061          okb#misc#set_sensitive false
1062         end
1063        else
1064         begin
1065          checkb#misc#set_sensitive true ;
1066          okb#misc#set_sensitive true
1067         end));
1068   ignore
1069    (locate_input#connect#changed
1070      (fun _ -> locateb#misc#set_sensitive (locate_input#text <> ""))) ;
1071   ignore
1072    (locateb#connect#clicked
1073      (function () ->
1074        let id = locate_input#text in
1075         manual_input#set_text (locate_callback id) ;
1076         locate_input#delete_text 0 (String.length id)
1077    )) ;
1078   window#show () ;
1079   GtkThread.main ();
1080   match !uri with
1081      None -> raise NoChoice
1082    | Some uri -> UriManager.uri_of_string ("cic:" ^ uri)
1083 ;;
1084
1085 exception AmbiguousInput;;
1086
1087 (* A WIDGET TO ENTER CIC TERMS *)
1088
1089 module ChosenTermEditor  = TexTermEditor;;
1090 module ChosenTextualParser0 = TexCicTextualParser0;;
1091 (*
1092 module ChosenTermEditor = TermEditor;;
1093 module ChosenTextualParser0 = CicTextualParser0;;
1094 *)
1095
1096 module Callbacks =
1097  struct
1098   let get_metasenv () = !ChosenTextualParser0.metasenv
1099   let set_metasenv metasenv = ChosenTextualParser0.metasenv := metasenv
1100
1101   let output_html msg = output_html (outputhtml ()) msg;;
1102   let interactive_user_uri_choice =
1103    fun ~selection_mode ?ok ?enable_button_for_non_vars ~title ~msg ~id ->
1104     interactive_user_uri_choice ~selection_mode ?ok
1105      ?enable_button_for_non_vars ~title ~msg;;
1106   let interactive_interpretation_choice = interactive_interpretation_choice;;
1107   let input_or_locate_uri = input_or_locate_uri;;
1108  end
1109 ;;
1110
1111 module TexTermEditor' = ChosenTermEditor.Make(Callbacks);;
1112
1113 (* OTHER FUNCTIONS *)
1114
1115 let locate () =
1116  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1117  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1118    try
1119     match
1120      GToolbox.input_string ~title:"Locate" "Enter an identifier to locate:"
1121     with
1122        None -> raise NoChoice
1123      | Some input ->
1124         let uri = locate_callback input in
1125          inputt#set_term uri
1126    with
1127     e ->
1128      output_html outputhtml
1129       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
1130 ;;
1131
1132
1133 exception UriAlreadyInUse;;
1134 exception NotAUriToAConstant;;
1135
1136 let new_inductive () =
1137  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1138  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1139  let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
1140  let notebook = (rendering_window ())#notebook in
1141
1142  let chosen = ref false in
1143  let inductive = ref true in
1144  let paramsno = ref 0 in
1145  let get_uri = ref (function _ -> assert false) in
1146  let get_base_uri = ref (function _ -> assert false) in
1147  let get_names = ref (function _ -> assert false) in
1148  let get_types_and_cons = ref (function _ -> assert false) in
1149  let get_context_and_subst = ref (function _ -> assert false) in 
1150  let window =
1151   GWindow.window
1152    ~width:600 ~modal:true ~position:`CENTER
1153    ~title:"New Block of Mutual (Co)Inductive Definitions"
1154    ~border_width:2 () in
1155  let vbox = GPack.vbox ~packing:window#add () in
1156  let hbox =
1157   GPack.hbox ~border_width:0
1158    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1159  let _ =
1160   GMisc.label ~text:"Enter the URI for the new block:"
1161    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1162  let uri_entry =
1163   GEdit.entry ~editable:true
1164    ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1165  let hbox0 =
1166   GPack.hbox ~border_width:0
1167    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1168  let _ =
1169   GMisc.label
1170    ~text:
1171      "Enter the number of left parameters in every arity and constructor type:"
1172    ~packing:(hbox0#pack ~expand:false ~fill:false ~padding:5) () in
1173  let paramsno_entry =
1174   GEdit.entry ~editable:true ~text:"0"
1175    ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
1176  let hbox1 =
1177   GPack.hbox ~border_width:0
1178    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1179  let _ =
1180   GMisc.label ~text:"Are the definitions inductive or coinductive?"
1181    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1182  let inductiveb =
1183   GButton.radio_button ~label:"Inductive"
1184    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1185  let coinductiveb =
1186   GButton.radio_button ~label:"Coinductive"
1187    ~group:inductiveb#group
1188    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1189  let hbox2 =
1190   GPack.hbox ~border_width:0
1191    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1192  let _ =
1193   GMisc.label ~text:"Enter the list of the names of the types:"
1194    ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
1195  let names_entry =
1196   GEdit.entry ~editable:true
1197    ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
1198  let hboxn =
1199   GPack.hbox ~border_width:0
1200    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1201  let okb =
1202   GButton.button ~label:"> Next"
1203    ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1204  let _ = okb#misc#set_sensitive true in
1205  let cancelb =
1206   GButton.button ~label:"Abort"
1207    ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1208  ignore (window#connect#destroy GMain.Main.quit) ;
1209  ignore (cancelb#connect#clicked window#destroy) ;
1210  (* First phase *)
1211  let rec phase1 () =
1212   ignore
1213    (okb#connect#clicked
1214      (function () ->
1215        try
1216         let uristr = "cic:" ^ uri_entry#text in
1217         let namesstr = names_entry#text in
1218         let paramsno' = int_of_string (paramsno_entry#text) in
1219          match Str.split (Str.regexp " +") namesstr with
1220             [] -> assert false
1221           | (he::tl) as names ->
1222              let uri = UriManager.uri_of_string (uristr ^ "/" ^ he ^ ".ind") in
1223               begin
1224                try
1225                 ignore (Getter.resolve uri) ;
1226                 raise UriAlreadyInUse
1227                with
1228                 Getter.Unresolved ->
1229                  get_uri := (function () -> uri) ; 
1230                  get_names := (function () -> names) ;
1231                  inductive := inductiveb#active ;
1232                  paramsno := paramsno' ;
1233                  phase2 ()
1234               end
1235        with
1236         e ->
1237          output_html outputhtml
1238           ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1239      ))
1240  (* Second phase *)
1241  and phase2 () =
1242   let type_widgets =
1243    List.map
1244     (function name ->
1245       let frame =
1246        GBin.frame ~label:name
1247         ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1248       let vbox = GPack.vbox ~packing:frame#add () in
1249       let hbox = GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false) () in
1250       let _ =
1251        GMisc.label ~text:("Enter its type:")
1252         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1253       let scrolled_window =
1254        GBin.scrolled_window ~border_width:5
1255         ~packing:(vbox#pack ~expand:true ~padding:0) () in
1256       let newinputt =
1257        TexTermEditor'.term_editor
1258         ~width:400 ~height:20 ~packing:scrolled_window#add 
1259         ~share_id_to_uris_with:inputt ()
1260         ~isnotempty_callback:
1261          (function b ->
1262            (*non_empty_type := b ;*)
1263            okb#misc#set_sensitive true) (*(b && uri_entry#text <> ""))*)
1264       in
1265       let hbox =
1266        GPack.hbox ~border_width:0
1267         ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1268       let _ =
1269        GMisc.label ~text:("Enter the list of its constructors:")
1270         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1271       let cons_names_entry =
1272        GEdit.entry ~editable:true
1273         ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1274       (newinputt,cons_names_entry)
1275     ) (!get_names ())
1276   in
1277    vbox#remove hboxn#coerce ;
1278    let hboxn =
1279     GPack.hbox ~border_width:0
1280      ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1281    let okb =
1282     GButton.button ~label:"> Next"
1283      ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1284    let cancelb =
1285     GButton.button ~label:"Abort"
1286      ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1287    ignore (cancelb#connect#clicked window#destroy) ;
1288    ignore
1289     (okb#connect#clicked
1290       (function () ->
1291         try
1292          let names = !get_names () in
1293          let types_and_cons =
1294           List.map2
1295            (fun name (newinputt,cons_names_entry) ->
1296              let consnamesstr = cons_names_entry#text in
1297              let cons_names = Str.split (Str.regexp " +") consnamesstr in
1298              let metasenv,expr =
1299               newinputt#get_metasenv_and_term ~context:[] ~metasenv:[]
1300              in
1301               match metasenv with
1302                  [] -> expr,cons_names
1303                | _ -> raise AmbiguousInput
1304            ) names type_widgets
1305          in
1306           let uri = !get_uri () in
1307           let _ =
1308            (* Let's see if so far the definition is well-typed *)
1309            let params = [] in
1310            let paramsno = 0 in
1311            (* To test if the arities of the inductive types are well *)
1312            (* typed, we check the inductive block definition where   *)
1313            (* no constructor is given to each type.                  *)
1314            let tys =
1315             List.map2
1316              (fun name (ty,cons) -> (name, !inductive, ty, []))
1317              names types_and_cons
1318            in
1319             CicTypeChecker.typecheck_mutual_inductive_defs uri
1320              (tys,params,paramsno)
1321           in
1322            get_context_and_subst :=
1323             (function () ->
1324               let i = ref 0 in
1325                List.fold_left2
1326                 (fun (context,subst) name (ty,_) ->
1327                   let res =
1328                    (Some (Cic.Name name, Cic.Decl ty))::context,
1329                     (Cic.MutInd (uri,!i,[]))::subst
1330                   in
1331                    incr i ; res
1332                 ) ([],[]) names types_and_cons) ;
1333            let types_and_cons' =
1334             List.map2
1335              (fun name (ty,cons) -> (name, !inductive, ty, phase3 name cons))
1336              names types_and_cons
1337            in
1338             get_types_and_cons := (function () -> types_and_cons') ;
1339             chosen := true ;
1340             window#destroy ()
1341         with
1342          e ->
1343           output_html outputhtml
1344            ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1345       ))
1346  (* Third phase *)
1347  and phase3 name cons =
1348   let get_cons_types = ref (function () -> assert false) in
1349   let window2 =
1350    GWindow.window
1351     ~width:600 ~modal:true ~position:`CENTER
1352     ~title:(name ^ " Constructors")
1353     ~border_width:2 () in
1354   let vbox = GPack.vbox ~packing:window2#add () in
1355   let cons_type_widgets =
1356    List.map
1357     (function consname ->
1358       let hbox =
1359        GPack.hbox ~border_width:0
1360         ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1361       let _ =
1362        GMisc.label ~text:("Enter the type of " ^ consname ^ ":")
1363         ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1364       let scrolled_window =
1365        GBin.scrolled_window ~border_width:5
1366         ~packing:(vbox#pack ~expand:true ~padding:0) () in
1367       let newinputt =
1368        TexTermEditor'.term_editor
1369         ~width:400 ~height:20 ~packing:scrolled_window#add
1370         ~share_id_to_uris_with:inputt ()
1371         ~isnotempty_callback:
1372          (function b ->
1373            (* (*non_empty_type := b ;*)
1374            okb#misc#set_sensitive true) (*(b && uri_entry#text <> ""))*) *)())
1375       in
1376        newinputt
1377     ) cons in
1378   let hboxn =
1379    GPack.hbox ~border_width:0
1380     ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1381   let okb =
1382    GButton.button ~label:"> Next"
1383     ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1384   let _ = okb#misc#set_sensitive true in
1385   let cancelb =
1386    GButton.button ~label:"Abort"
1387     ~packing:(hboxn#pack ~expand:false ~fill:false ~padding:5) () in
1388   ignore (window2#connect#destroy GMain.Main.quit) ;
1389   ignore (cancelb#connect#clicked window2#destroy) ;
1390   ignore
1391    (okb#connect#clicked
1392      (function () ->
1393        try
1394         chosen := true ;
1395         let context,subst= !get_context_and_subst () in
1396         let cons_types =
1397          List.map2
1398           (fun name inputt ->
1399             let metasenv,expr =
1400              inputt#get_metasenv_and_term ~context ~metasenv:[]
1401             in
1402              match metasenv with
1403                 [] ->
1404                  let undebrujined_expr =
1405                   List.fold_left
1406                    (fun expr t -> CicSubstitution.subst t expr) expr subst
1407                  in
1408                   name, undebrujined_expr
1409               | _ -> raise AmbiguousInput
1410           ) cons cons_type_widgets
1411         in
1412          get_cons_types := (function () -> cons_types) ;
1413          window2#destroy ()
1414        with
1415         e ->
1416          output_html outputhtml
1417           ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1418      )) ;
1419   window2#show () ;
1420   GtkThread.main ();
1421   let okb_pressed = !chosen in
1422    chosen := false ;
1423    if (not okb_pressed) then
1424     begin
1425      window#destroy () ;
1426      assert false (* The control never reaches this point *)
1427     end
1428    else
1429     (!get_cons_types ())
1430  in
1431   phase1 () ;
1432   (* No more phases left or Abort pressed *) 
1433   window#show () ;
1434   GtkThread.main ();
1435   window#destroy () ;
1436   if !chosen then
1437    try
1438     let uri = !get_uri () in
1439 (*CSC: Da finire *)
1440     let params = [] in
1441     let tys = !get_types_and_cons () in
1442      let obj = Cic.InductiveDefinition tys params !paramsno in
1443       begin
1444        try
1445         prerr_endline (CicPp.ppobj obj) ;
1446         CicTypeChecker.typecheck_mutual_inductive_defs uri
1447          (tys,params,!paramsno) ;
1448         with
1449          e ->
1450           prerr_endline "Offending mutual (co)inductive type declaration:" ;
1451           prerr_endline (CicPp.ppobj obj) ;
1452       end ;
1453       (* We already know that obj is well-typed. We need to add it to the  *)
1454       (* environment in order to compute the inner-types without having to *)
1455       (* debrujin it or having to modify lots of other functions to avoid  *)
1456       (* asking the environment for the MUTINDs we are defining now.       *)
1457       CicEnvironment.put_inductive_definition uri obj ;
1458       save_obj uri obj ;
1459       show_in_show_window_obj uri obj
1460    with
1461     e ->
1462      output_html outputhtml
1463       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1464 ;;
1465
1466 let new_proof () =
1467  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1468  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1469  let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
1470  let notebook = (rendering_window ())#notebook in
1471
1472  let chosen = ref false in
1473  let get_metasenv_and_term = ref (function _ -> assert false) in
1474  let get_uri = ref (function _ -> assert false) in
1475  let non_empty_type = ref false in
1476  let window =
1477   GWindow.window
1478    ~width:600 ~modal:true ~title:"New Proof or Definition"
1479    ~border_width:2 () in
1480  let vbox = GPack.vbox ~packing:window#add () in
1481  let hbox =
1482   GPack.hbox ~border_width:0
1483    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1484  let _ =
1485   GMisc.label ~text:"Enter the URI for the new theorem or definition:"
1486    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1487  let uri_entry =
1488   GEdit.entry ~editable:true
1489    ~packing:(hbox#pack ~expand:true ~fill:true ~padding:5) () in
1490  let hbox1 =
1491   GPack.hbox ~border_width:0
1492    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1493  let _ =
1494   GMisc.label ~text:"Enter the theorem or definition type:"
1495    ~packing:(hbox1#pack ~expand:false ~fill:false ~padding:5) () in
1496  let scrolled_window =
1497   GBin.scrolled_window ~border_width:5
1498    ~packing:(vbox#pack ~expand:true ~padding:0) () in
1499  (* the content of the scrolled_window is moved below (see comment) *)
1500  let hbox =
1501   GPack.hbox ~border_width:0
1502    ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1503  let okb =
1504   GButton.button ~label:"Ok"
1505    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1506  let _ = okb#misc#set_sensitive false in
1507  let cancelb =
1508   GButton.button ~label:"Cancel"
1509    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1510  (* moved here to have visibility of the ok button *)
1511  let newinputt =
1512   TexTermEditor'.term_editor ~width:400 ~height:100 ~packing:scrolled_window#add
1513    ~share_id_to_uris_with:inputt ()
1514    ~isnotempty_callback:
1515     (function b ->
1516       non_empty_type := b ;
1517       okb#misc#set_sensitive (b && uri_entry#text <> ""))
1518  in
1519  let _ =
1520   newinputt#set_term inputt#get_as_string ;
1521   inputt#reset in
1522  let _ =
1523   uri_entry#connect#changed
1524    (function () ->
1525      okb#misc#set_sensitive (!non_empty_type && uri_entry#text <> ""))
1526  in
1527  ignore (window#connect#destroy GMain.Main.quit) ;
1528  ignore (cancelb#connect#clicked window#destroy) ;
1529  ignore
1530   (okb#connect#clicked
1531     (function () ->
1532       chosen := true ;
1533       try
1534        let metasenv,parsed = newinputt#get_metasenv_and_term [] [] in
1535        let uristr = "cic:" ^ uri_entry#text in
1536        let uri = UriManager.uri_of_string uristr in
1537         if String.sub uristr (String.length uristr - 4) 4 <> ".con" then
1538          raise NotAUriToAConstant
1539         else
1540          begin
1541           try
1542            ignore (Getter.resolve uri) ;
1543            raise UriAlreadyInUse
1544           with
1545            Getter.Unresolved ->
1546             get_metasenv_and_term := (function () -> metasenv,parsed) ;
1547             get_uri := (function () -> uri) ; 
1548             window#destroy ()
1549          end
1550       with
1551        e ->
1552         output_html outputhtml
1553          ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1554   )) ;
1555  window#show () ;
1556  GtkThread.main ();
1557  if !chosen then
1558   try
1559    let metasenv,expr = !get_metasenv_and_term () in
1560     let _  = CicTypeChecker.type_of_aux' metasenv [] expr in
1561      ProofEngine.proof :=
1562       Some (!get_uri (), (1,[],expr)::metasenv, Cic.Meta (1,[]), expr) ;
1563      ProofEngine.goal := Some 1 ;
1564      refresh_goals notebook ;
1565      refresh_proof output ;
1566      !save_set_sensitive true ;
1567      inputt#reset ;
1568      ProofEngine.intros ~mk_fresh_name_callback () ;
1569      refresh_goals notebook ;
1570      refresh_proof output
1571   with
1572      InvokeTactics.RefreshSequentException e ->
1573       output_html outputhtml
1574        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1575         "sequent: " ^ Printexc.to_string e ^ "</h1>")
1576    | InvokeTactics.RefreshProofException e ->
1577       output_html outputhtml
1578        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1579         "proof: " ^ Printexc.to_string e ^ "</h1>")
1580    | e ->
1581       output_html outputhtml
1582        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1583 ;;
1584
1585 let check_term_in_scratch scratch_window metasenv context expr = 
1586  try
1587   let ty = CicTypeChecker.type_of_aux' metasenv context expr in
1588   let expr = Cic.Cast (expr,ty) in
1589    scratch_window#show () ;
1590    scratch_window#set_term expr ;
1591    scratch_window#set_context context ;
1592    scratch_window#set_metasenv metasenv ;
1593    scratch_window#sequent_viewer#load_sequent metasenv (111,context,expr)
1594  with
1595   e ->
1596    print_endline ("? " ^ CicPp.ppterm expr) ;
1597    raise e
1598 ;;
1599
1600 let check scratch_window () =
1601  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1602  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1603   let metasenv =
1604    match !ProofEngine.proof with
1605       None -> []
1606     | Some (_,metasenv,_,_) -> metasenv
1607   in
1608   let context =
1609    match !ProofEngine.goal with
1610       None -> []
1611     | Some metano ->
1612        let (_,canonical_context,_) =
1613         List.find (function (m,_,_) -> m=metano) metasenv
1614        in
1615         canonical_context
1616   in
1617    try
1618     let metasenv',expr = inputt#get_metasenv_and_term context metasenv in
1619      check_term_in_scratch scratch_window metasenv' context expr
1620    with
1621     e ->
1622      output_html outputhtml
1623       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1624 ;;
1625
1626 let show () =
1627  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1628   try
1629    show_in_show_window_uri (input_or_locate_uri ~title:"Show")
1630   with
1631    e ->
1632     output_html outputhtml
1633      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1634 ;;
1635
1636 exception NotADefinition;;
1637
1638 let open_ () =
1639  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1640  let output = ((rendering_window ())#output : TermViewer.proof_viewer) in
1641  let notebook = (rendering_window ())#notebook in
1642    try
1643     let uri = input_or_locate_uri ~title:"Open" in
1644      CicTypeChecker.typecheck uri ;
1645      let metasenv,bo,ty =
1646       match CicEnvironment.get_cooked_obj uri with
1647          Cic.Constant (_,Some bo,ty,_) -> [],bo,ty
1648        | Cic.CurrentProof (_,metasenv,bo,ty,_) -> metasenv,bo,ty
1649        | Cic.Constant _
1650        | Cic.Variable _
1651        | Cic.InductiveDefinition _ -> raise NotADefinition
1652      in
1653       ProofEngine.proof :=
1654        Some (uri, metasenv, bo, ty) ;
1655       ProofEngine.goal := None ;
1656       refresh_goals notebook ;
1657       refresh_proof output
1658    with
1659       InvokeTactics.RefreshSequentException e ->
1660        output_html outputhtml
1661         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1662          "sequent: " ^ Printexc.to_string e ^ "</h1>")
1663     | InvokeTactics.RefreshProofException e ->
1664        output_html outputhtml
1665         ("<h1 color=\"red\">Exception raised during the refresh of the " ^
1666          "proof: " ^ Printexc.to_string e ^ "</h1>")
1667     | e ->
1668        output_html outputhtml
1669         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1670 ;;
1671
1672 let show_query_results results =
1673  let window =
1674   GWindow.window
1675    ~modal:false ~title:"Query results." ~border_width:2 () in
1676  let vbox = GPack.vbox ~packing:window#add () in
1677  let hbox =
1678   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1679  let lMessage =
1680   GMisc.label
1681    ~text:"Click on a URI to show that object"
1682    ~packing:hbox#add () in
1683  let scrolled_window =
1684   GBin.scrolled_window ~border_width:10 ~height:400 ~width:600
1685    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1686  let clist = GList.clist ~columns:1 ~packing:scrolled_window#add () in
1687   ignore
1688    (List.map
1689      (function (uri,_) ->
1690        let n =
1691         clist#append [uri]
1692        in
1693         clist#set_row ~selectable:false n
1694      ) results
1695    ) ;
1696   clist#columns_autosize () ;
1697   ignore
1698    (clist#connect#select_row
1699      (fun ~row ~column ~event ->
1700        let (uristr,_) = List.nth results row in
1701         match
1702          MQueryMisc.cic_textual_parser_uri_of_string
1703           (MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format'
1704             uristr)
1705         with
1706            CicTextualParser0.ConUri uri
1707          | CicTextualParser0.VarUri uri
1708          | CicTextualParser0.IndTyUri (uri,_)
1709          | CicTextualParser0.IndConUri (uri,_,_) ->
1710             show_in_show_window_uri uri
1711      )
1712    ) ;
1713   window#show ()
1714 ;;
1715
1716 let refine_constraints (must_obj,must_rel,must_sort) =
1717  let chosen = ref false in
1718  let use_only = ref false in
1719  let window =
1720   GWindow.window
1721    ~modal:true ~title:"Constraints refinement."
1722    ~width:800 ~border_width:2 () in
1723  let vbox = GPack.vbox ~packing:window#add () in
1724  let hbox =
1725   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1726  let lMessage =
1727   GMisc.label
1728    ~text: "\"Only\" constraints can be enforced or not."
1729    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1730  let onlyb =
1731   GButton.toggle_button ~label:"Enforce \"only\" constraints"
1732    ~active:false ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
1733  in
1734   ignore
1735    (onlyb#connect#toggled (function () -> use_only := onlyb#active)) ;
1736  (* Notebook for the constraints choice *)
1737  let notebook =
1738   GPack.notebook ~scrollable:true
1739    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1740  (* Rel constraints *)
1741  let label =
1742   GMisc.label
1743    ~text: "Constraints on Rels" () in
1744  let vbox' =
1745   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
1746    () in
1747  let hbox =
1748   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
1749  let lMessage =
1750   GMisc.label
1751    ~text: "You can now specify the constraints on Rels."
1752    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1753  let expected_height = 25 * (List.length must_rel + 2) in
1754  let height = if expected_height > 400 then 400 else expected_height in
1755  let scrolled_window =
1756   GBin.scrolled_window ~border_width:10 ~height ~width:600
1757    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
1758  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
1759  let rel_constraints =
1760   List.map
1761    (function (position,depth) ->
1762      let hbox =
1763       GPack.hbox
1764        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
1765      let lMessage =
1766       GMisc.label
1767        ~text:position
1768        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1769      match depth with
1770         None -> position, ref None
1771       | Some depth' ->
1772          let mutable_ref = ref (Some depth') in
1773          let depthb =
1774           GButton.toggle_button
1775            ~label:("depth = " ^ string_of_int depth') ~active:true
1776            ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
1777          in
1778           ignore
1779            (depthb#connect#toggled
1780              (function () ->
1781                let sel_depth = if depthb#active then Some depth' else None in
1782                 mutable_ref := sel_depth
1783             )) ;
1784           position, mutable_ref
1785    ) must_rel in
1786  (* Sort constraints *)
1787  let label =
1788   GMisc.label
1789    ~text: "Constraints on Sorts" () in
1790  let vbox' =
1791   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
1792    () in
1793  let hbox =
1794   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
1795  let lMessage =
1796   GMisc.label
1797    ~text: "You can now specify the constraints on Sorts."
1798    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1799  let expected_height = 25 * (List.length must_sort + 2) in
1800  let height = if expected_height > 400 then 400 else expected_height in
1801  let scrolled_window =
1802   GBin.scrolled_window ~border_width:10 ~height ~width:600
1803    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
1804  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
1805  let sort_constraints =
1806   List.map
1807    (function (position,depth,sort) ->
1808      let hbox =
1809       GPack.hbox
1810        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
1811      let lMessage =
1812       GMisc.label
1813        ~text:(sort ^ " " ^ position)
1814        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1815      match depth with
1816         None -> position, ref None, sort
1817       | Some depth' ->
1818          let mutable_ref = ref (Some depth') in
1819          let depthb =
1820           GButton.toggle_button ~label:("depth = " ^ string_of_int depth')
1821            ~active:true
1822            ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
1823          in
1824           ignore
1825            (depthb#connect#toggled
1826              (function () ->
1827                let sel_depth = if depthb#active then Some depth' else None in
1828                 mutable_ref := sel_depth
1829             )) ;
1830           position, mutable_ref, sort
1831    ) must_sort in
1832  (* Obj constraints *)
1833  let label =
1834   GMisc.label
1835    ~text: "Constraints on constants" () in
1836  let vbox' =
1837   GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce)
1838    () in
1839  let hbox =
1840   GPack.hbox ~packing:(vbox'#pack ~expand:false ~fill:false ~padding:5) () in
1841  let lMessage =
1842   GMisc.label
1843    ~text: "You can now specify the constraints on constants."
1844    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1845  let expected_height = 25 * (List.length must_obj + 2) in
1846  let height = if expected_height > 400 then 400 else expected_height in
1847  let scrolled_window =
1848   GBin.scrolled_window ~border_width:10 ~height ~width:600
1849    ~packing:(vbox'#pack ~expand:true ~fill:true ~padding:5) () in
1850  let scrolled_vbox = GPack.vbox ~packing:scrolled_window#add_with_viewport () in
1851  let obj_constraints =
1852   List.map
1853    (function (uri,position,depth) ->
1854      let hbox =
1855       GPack.hbox
1856        ~packing:(scrolled_vbox#pack ~expand:false ~fill:false ~padding:5) () in
1857      let lMessage =
1858       GMisc.label
1859        ~text:(uri ^ " " ^ position)
1860        ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1861      match depth with
1862         None -> uri, position, ref None
1863       | Some depth' ->
1864          let mutable_ref = ref (Some depth') in
1865          let depthb =
1866           GButton.toggle_button ~label:("depth = " ^ string_of_int depth')
1867            ~active:true
1868            ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
1869          in
1870           ignore
1871            (depthb#connect#toggled
1872              (function () ->
1873                let sel_depth = if depthb#active then Some depth' else None in
1874                 mutable_ref := sel_depth
1875             )) ;
1876           uri, position, mutable_ref
1877    ) must_obj in
1878  (* Confirm/abort buttons *)
1879  let hbox =
1880   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1881  let okb =
1882   GButton.button ~label:"Ok"
1883    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1884  let cancelb =
1885   GButton.button ~label:"Abort"
1886    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) ()
1887  in
1888   ignore (window#connect#destroy GMain.Main.quit) ;
1889   ignore (cancelb#connect#clicked window#destroy) ;
1890   ignore
1891    (okb#connect#clicked (function () -> chosen := true ; window#destroy ()));
1892   window#set_position `CENTER ;
1893   window#show () ;
1894   GtkThread.main ();
1895   if !chosen then
1896    let chosen_must_rel =
1897     List.map
1898      (function (position,ref_depth) -> position,!ref_depth) rel_constraints in
1899    let chosen_must_sort =
1900     List.map
1901      (function (position,ref_depth,sort) -> position,!ref_depth,sort)
1902      sort_constraints
1903    in
1904    let chosen_must_obj =
1905     List.map
1906      (function (uri,position,ref_depth) -> uri,position,!ref_depth)
1907      obj_constraints
1908    in
1909     (chosen_must_obj,chosen_must_rel,chosen_must_sort),
1910      (if !use_only then
1911 (*CSC: ???????????????????????? I assume that must and only are the same... *)
1912        Some chosen_must_obj,Some chosen_must_rel,Some chosen_must_sort
1913       else
1914        None,None,None
1915      )
1916   else
1917    raise NoChoice
1918 ;;
1919
1920 let completeSearchPattern () =
1921  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
1922  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1923   try
1924    let metasenv,expr = inputt#get_metasenv_and_term ~context:[] ~metasenv:[] in
1925    let must = MQueryLevels2.get_constraints expr in
1926    let must',only = refine_constraints must in
1927    let results = MQueryGenerator.searchPattern must' only in 
1928     show_query_results results
1929   with
1930    e ->
1931     output_html outputhtml
1932      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
1933 ;;
1934
1935 let insertQuery () =
1936  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
1937   try
1938    let chosen = ref None in
1939    let window =
1940     GWindow.window
1941      ~modal:true ~title:"Insert Query (Experts Only)" ~border_width:2 () in
1942    let vbox = GPack.vbox ~packing:window#add () in
1943    let label =
1944     GMisc.label ~text:"Insert Query. For Experts Only."
1945      ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1946    let scrolled_window =
1947     GBin.scrolled_window ~border_width:10 ~height:400 ~width:600
1948      ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
1949    let input = GEdit.text ~editable:true
1950     ~packing:scrolled_window#add () in
1951    let hbox =
1952     GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
1953    let okb =
1954     GButton.button ~label:"Ok"
1955      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1956    let loadb =
1957     GButton.button ~label:"Load from file..."
1958      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1959    let cancelb =
1960     GButton.button ~label:"Abort"
1961      ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
1962    ignore (window#connect#destroy GMain.Main.quit) ;
1963    ignore (cancelb#connect#clicked window#destroy) ;
1964    ignore
1965     (okb#connect#clicked
1966       (function () ->
1967         chosen := Some (input#get_chars 0 input#length) ; window#destroy ())) ;
1968    ignore
1969     (loadb#connect#clicked
1970       (function () ->
1971         match
1972          GToolbox.select_file ~title:"Select Query File" ()
1973         with
1974            None -> ()
1975          | Some filename ->
1976             let inch = open_in filename in
1977              let rec read_file () =
1978               try
1979                let line = input_line inch in
1980                 line ^ "\n" ^ read_file ()
1981               with
1982                End_of_file -> ""
1983              in
1984               let text = read_file () in
1985                input#delete_text 0 input#length ;
1986                ignore (input#insert_text text ~pos:0))) ;
1987    window#set_position `CENTER ;
1988    window#show () ;
1989    GtkThread.main ();
1990    match !chosen with
1991       None -> ()
1992     | Some q ->
1993        let results =
1994         MQI.execute mqi_options (MQueryUtil.query_of_text (Lexing.from_string q))
1995        in
1996         show_query_results results
1997   with
1998    e ->
1999     output_html outputhtml
2000      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
2001 ;;
2002
2003 let choose_must list_of_must only =
2004  let chosen = ref None in
2005  let user_constraints = ref [] in
2006  let window =
2007   GWindow.window
2008    ~modal:true ~title:"Query refinement." ~border_width:2 () in
2009  let vbox = GPack.vbox ~packing:window#add () in
2010  let hbox =
2011   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2012  let lMessage =
2013   GMisc.label
2014    ~text:
2015     ("You can now specify the genericity of the query. " ^
2016      "The more generic the slower.")
2017    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2018  let hbox =
2019   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2020  let lMessage =
2021   GMisc.label
2022    ~text:
2023     "Suggestion: start with faster queries before moving to more generic ones."
2024    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2025  let notebook =
2026   GPack.notebook ~scrollable:true
2027    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2028  let _ =
2029   let page = ref 0 in
2030   let last = List.length list_of_must in
2031   List.map
2032    (function must ->
2033      incr page ;
2034      let label =
2035       GMisc.label ~text:
2036        (if !page = 1 then "More generic" else
2037          if !page = last then "More precise" else "          ") () in
2038      let expected_height = 25 * (List.length must + 2) in
2039      let height = if expected_height > 400 then 400 else expected_height in
2040      let scrolled_window =
2041       GBin.scrolled_window ~border_width:10 ~height ~width:600
2042        ~packing:(notebook#append_page ~tab_label:label#coerce) () in
2043      let clist =
2044         GList.clist ~columns:2 ~packing:scrolled_window#add
2045          ~titles:["URI" ; "Position"] ()
2046      in
2047       ignore
2048        (List.map
2049          (function (uri,position) ->
2050            let n =
2051             clist#append 
2052              [uri; if position then "MainConclusion" else "Conclusion"]
2053            in
2054             clist#set_row ~selectable:false n
2055          ) must
2056        ) ;
2057       clist#columns_autosize ()
2058    ) list_of_must in
2059  let _ =
2060   let label = GMisc.label ~text:"User provided" () in
2061   let vbox =
2062    GPack.vbox ~packing:(notebook#append_page ~tab_label:label#coerce) () in
2063   let hbox =
2064    GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2065   let lMessage =
2066    GMisc.label
2067    ~text:"Select the constraints that must be satisfied and press OK."
2068    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2069   let expected_height = 25 * (List.length only + 2) in
2070   let height = if expected_height > 400 then 400 else expected_height in
2071   let scrolled_window =
2072    GBin.scrolled_window ~border_width:10 ~height ~width:600
2073     ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2074   let clist =
2075    GList.clist ~columns:2 ~packing:scrolled_window#add
2076     ~selection_mode:`EXTENDED
2077     ~titles:["URI" ; "Position"] ()
2078   in
2079    ignore
2080     (List.map
2081       (function (uri,position) ->
2082         let n =
2083          clist#append 
2084           [uri; if position then "MainConclusion" else "Conclusion"]
2085         in
2086          clist#set_row ~selectable:true n
2087       ) only
2088     ) ;
2089    clist#columns_autosize () ;
2090    ignore
2091     (clist#connect#select_row
2092       (fun ~row ~column ~event ->
2093         user_constraints := (List.nth only row)::!user_constraints)) ;
2094    ignore
2095     (clist#connect#unselect_row
2096       (fun ~row ~column ~event ->
2097         user_constraints :=
2098          List.filter
2099           (function uri -> uri != (List.nth only row)) !user_constraints)) ;
2100  in
2101  let hbox =
2102   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2103  let okb =
2104   GButton.button ~label:"Ok"
2105    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2106  let cancelb =
2107   GButton.button ~label:"Abort"
2108    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2109  (* actions *)
2110  ignore (window#connect#destroy GMain.Main.quit) ;
2111  ignore (cancelb#connect#clicked window#destroy) ;
2112  ignore
2113   (okb#connect#clicked
2114     (function () -> chosen := Some notebook#current_page ; window#destroy ())) ;
2115  window#set_position `CENTER ;
2116  window#show () ;
2117  GtkThread.main ();
2118  match !chosen with
2119     None -> raise NoChoice
2120   | Some n ->
2121      if n = List.length list_of_must then
2122       (* user provided constraints *)
2123       !user_constraints
2124      else
2125       List.nth list_of_must n
2126 ;;
2127
2128 let searchPattern () =
2129  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
2130  let outputhtml = ((rendering_window ())#outputhtml : GHtml.xmhtml) in
2131   try
2132     let proof =
2133      match !ProofEngine.proof with
2134         None -> assert false
2135       | Some proof -> proof
2136     in
2137      match !ProofEngine.goal with
2138       | None -> ()
2139       | Some metano ->
2140          let uris' =
2141            TacticChaser.searchPattern
2142             ~output_html:(output_html outputhtml) ~choose_must ()
2143             ~status:(proof, metano)
2144          in
2145          let uri' =
2146           user_uri_choice ~title:"Ambiguous input."
2147           ~msg: "Many lemmas can be successfully applied. Please, choose one:"
2148            uris'
2149          in
2150           inputt#set_term uri' ;
2151           InvokeTactics'.apply ()
2152   with
2153    e -> 
2154     output_html outputhtml 
2155      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
2156 ;;
2157       
2158 let choose_selection mmlwidget (element : Gdome.element option) =
2159  let module G = Gdome in
2160   let rec aux element =
2161    if element#hasAttributeNS
2162        ~namespaceURI:Misc.helmns
2163        ~localName:(G.domString "xref")
2164    then
2165      mmlwidget#set_selection (Some element)
2166    else
2167     try
2168       match element#get_parentNode with
2169          None -> assert false
2170        (*CSC: OCAML DIVERGES!
2171        | Some p -> aux (new G.element_of_node p)
2172        *)
2173        | Some p -> aux (new Gdome.element_of_node p)
2174     with
2175        GdomeInit.DOMCastException _ ->
2176         prerr_endline
2177          "******* trying to select above the document root ********"
2178   in
2179    match element with
2180      Some x -> aux x
2181    | None   -> mmlwidget#set_selection None
2182 ;;
2183
2184 (* STUFF TO BUILD THE GTK INTERFACE *)
2185
2186 (* Stuff for the widget settings *)
2187
2188 let export_to_postscript output =
2189  let lastdir = ref (Unix.getcwd ()) in
2190   function () ->
2191    match
2192     GToolbox.select_file ~title:"Export to PostScript"
2193      ~dir:lastdir ~filename:"screenshot.ps" ()
2194    with
2195       None -> ()
2196     | Some filename ->
2197        (output :> GMathView.math_view)#export_to_postscript
2198          ~filename:filename ();
2199 ;;
2200
2201 let activate_t1 output button_set_anti_aliasing
2202  button_set_transparency export_to_postscript_menu_item
2203  button_t1 ()
2204 =
2205  let is_set = button_t1#active in
2206   output#set_font_manager_type
2207    ~fm_type:(if is_set then `font_manager_t1 else `font_manager_gtk) ;
2208   if is_set then
2209    begin
2210     button_set_anti_aliasing#misc#set_sensitive true ;
2211     button_set_transparency#misc#set_sensitive true ;
2212     export_to_postscript_menu_item#misc#set_sensitive true ;
2213    end
2214   else
2215    begin
2216     button_set_anti_aliasing#misc#set_sensitive false ;
2217     button_set_transparency#misc#set_sensitive false ;
2218     export_to_postscript_menu_item#misc#set_sensitive false ;
2219    end
2220 ;;
2221
2222 let set_anti_aliasing output button_set_anti_aliasing () =
2223  output#set_anti_aliasing button_set_anti_aliasing#active
2224 ;;
2225
2226 let set_transparency output button_set_transparency () =
2227  output#set_transparency button_set_transparency#active
2228 ;;
2229
2230 let changefont output font_size_spinb () =
2231  output#set_font_size font_size_spinb#value_as_int
2232 ;;
2233
2234 let set_log_verbosity output log_verbosity_spinb () =
2235  output#set_log_verbosity log_verbosity_spinb#value_as_int
2236 ;;
2237
2238 class settings_window output sw
2239  export_to_postscript_menu_item selection_changed_callback
2240 =
2241  let settings_window = GWindow.window ~title:"GtkMathView settings" () in
2242  let vbox =
2243   GPack.vbox ~packing:settings_window#add () in
2244  let table =
2245   GPack.table
2246    ~rows:1 ~columns:3 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2247    ~border_width:5 ~packing:vbox#add () in
2248  let button_t1 =
2249   GButton.toggle_button ~label:"activate t1 fonts"
2250    ~packing:(table#attach ~left:0 ~top:0) () in
2251  let button_set_anti_aliasing =
2252   GButton.toggle_button ~label:"set_anti_aliasing"
2253    ~packing:(table#attach ~left:0 ~top:1) () in
2254  let button_set_transparency =
2255   GButton.toggle_button ~label:"set_transparency"
2256    ~packing:(table#attach ~left:2 ~top:1) () in
2257  let table =
2258   GPack.table
2259    ~rows:2 ~columns:2 ~homogeneous:false ~row_spacings:5 ~col_spacings:5
2260    ~border_width:5 ~packing:vbox#add () in
2261  let font_size_label =
2262   GMisc.label ~text:"font size:"
2263    ~packing:(table#attach ~left:0 ~top:0 ~expand:`NONE) () in
2264  let font_size_spinb =
2265   let sadj =
2266    GData.adjustment ~value:14.0 ~lower:5.0 ~upper:50.0 ~step_incr:1.0 ()
2267   in
2268    GEdit.spin_button 
2269     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:0 ~fill:`NONE) () in
2270  let log_verbosity_label =
2271   GMisc.label ~text:"log verbosity:"
2272    ~packing:(table#attach ~left:0 ~top:1) () in
2273  let log_verbosity_spinb =
2274   let sadj =
2275    GData.adjustment ~value:0.0 ~lower:0.0 ~upper:3.0 ~step_incr:1.0 ()
2276   in
2277    GEdit.spin_button 
2278     ~adjustment:sadj ~packing:(table#attach ~left:1 ~top:1) () in
2279  let hbox =
2280   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2281  let closeb =
2282   GButton.button ~label:"Close"
2283    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2284 object(self)
2285  method show = settings_window#show
2286  initializer
2287   button_set_anti_aliasing#misc#set_sensitive false ;
2288   button_set_transparency#misc#set_sensitive false ;
2289   (* Signals connection *)
2290   ignore(button_t1#connect#clicked
2291    (activate_t1 output button_set_anti_aliasing
2292     button_set_transparency export_to_postscript_menu_item button_t1)) ;
2293   ignore(font_size_spinb#connect#changed (changefont output font_size_spinb)) ;
2294   ignore(button_set_anti_aliasing#connect#toggled
2295    (set_anti_aliasing output button_set_anti_aliasing));
2296   ignore(button_set_transparency#connect#toggled
2297    (set_transparency output button_set_transparency)) ;
2298   ignore(log_verbosity_spinb#connect#changed
2299    (set_log_verbosity output log_verbosity_spinb)) ;
2300   ignore(closeb#connect#clicked settings_window#misc#hide)
2301 end;;
2302
2303 (* Scratch window *)
2304
2305 class scratch_window =
2306  let window =
2307   GWindow.window
2308     ~title:"MathML viewer"
2309     ~border_width:2 () in
2310  let vbox =
2311   GPack.vbox ~packing:window#add () in
2312  let hbox =
2313   GPack.hbox ~packing:(vbox#pack ~expand:false ~fill:false ~padding:5) () in
2314  let whdb =
2315   GButton.button ~label:"Whd"
2316    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2317  let reduceb =
2318   GButton.button ~label:"Reduce"
2319    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2320  let simplb =
2321   GButton.button ~label:"Simpl"
2322    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
2323  let scrolled_window =
2324   GBin.scrolled_window ~border_width:10
2325    ~packing:(vbox#pack ~expand:true ~padding:5) () in
2326  let sequent_viewer =
2327   TermViewer.sequent_viewer
2328    ~packing:(scrolled_window#add) ~width:400 ~height:280 () in
2329 object(self)
2330  val mutable term = Cic.Rel 1                 (* dummy value *)
2331  val mutable context = ([] : Cic.context)     (* dummy value *)
2332  val mutable metasenv = ([] : Cic.metasenv)   (* dummy value *)
2333  method sequent_viewer = sequent_viewer
2334  method show () = window#misc#hide () ; window#show ()
2335  method term = term
2336  method set_term t = term <- t
2337  method context = context
2338  method set_context t = context <- t
2339  method metasenv = metasenv
2340  method set_metasenv t = metasenv <- t
2341  initializer
2342   ignore
2343    (sequent_viewer#connect#selection_changed (choose_selection sequent_viewer));
2344   ignore(window#event#connect#delete (fun _ -> window#misc#hide () ; true )) ;
2345   ignore(whdb#connect#clicked InvokeTactics'.whd_in_scratch) ;
2346   ignore(reduceb#connect#clicked InvokeTactics'.reduce_in_scratch) ;
2347   ignore(simplb#connect#clicked InvokeTactics'.simpl_in_scratch)
2348 end;;
2349
2350 let open_contextual_menu_for_selected_terms mmlwidget infos =
2351  let button = GdkEvent.Button.button infos in 
2352  let terms_selected = List.length mmlwidget#get_selections > 0 in
2353   if button = 3 then
2354    begin
2355     let time = GdkEvent.Button.time infos in
2356     let menu = GMenu.menu () in
2357     let f = new GMenu.factory menu in
2358     let whd_menu_item =
2359      f#add_item "Whd" ~key:GdkKeysyms._W ~callback:InvokeTactics'.whd in
2360     let reduce_menu_item =
2361      f#add_item "Reduce" ~key:GdkKeysyms._R ~callback:InvokeTactics'.reduce in
2362     let simpl_menu_item =
2363      f#add_item "Simpl" ~key:GdkKeysyms._S ~callback:InvokeTactics'.simpl in
2364     let _ = f#add_separator () in
2365     let generalize_menu_item =
2366      f#add_item "Generalize"
2367       ~key:GdkKeysyms._G ~callback:InvokeTactics'.generalize in
2368     let _ = f#add_separator () in
2369     let clear_menu_item =
2370      f#add_item "Clear" ~key:GdkKeysyms._C ~callback:InvokeTactics'.clear in
2371     let clearbody_menu_item =
2372      f#add_item "ClearBody"
2373       ~key:GdkKeysyms._B ~callback:InvokeTactics'.clearbody
2374     in
2375      whd_menu_item#misc#set_sensitive terms_selected ; 
2376      reduce_menu_item#misc#set_sensitive terms_selected ; 
2377      simpl_menu_item#misc#set_sensitive terms_selected ;
2378      generalize_menu_item#misc#set_sensitive terms_selected ;
2379      clear_menu_item#misc#set_sensitive terms_selected ;
2380      clearbody_menu_item#misc#set_sensitive terms_selected ;
2381      menu#popup ~button ~time
2382    end ;
2383   true
2384 ;;
2385
2386 class page () =
2387  let vbox1 = GPack.vbox () in
2388 object(self)
2389  val mutable proofw_ref = None
2390  val mutable compute_ref = None
2391  method proofw =
2392   Lazy.force self#compute ;
2393   match proofw_ref with
2394      None -> assert false
2395    | Some proofw -> proofw
2396  method content = vbox1
2397  method compute =
2398   match compute_ref with
2399      None -> assert false
2400    | Some compute -> compute
2401  initializer
2402   compute_ref <-
2403    Some (lazy (
2404    let scrolled_window1 =
2405     GBin.scrolled_window ~border_width:10
2406      ~packing:(vbox1#pack ~expand:true ~padding:5) () in
2407    let proofw =
2408     TermViewer.sequent_viewer ~width:400 ~height:275
2409      ~packing:(scrolled_window1#add) () in
2410    let _ = proofw_ref <- Some proofw in
2411    let hbox3 =
2412     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2413    let ringb =
2414     GButton.button ~label:"Ring"
2415      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2416    let fourierb =
2417     GButton.button ~label:"Fourier"
2418      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2419    let reflexivityb =
2420     GButton.button ~label:"Reflexivity"
2421      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2422    let symmetryb =
2423     GButton.button ~label:"Symmetry"
2424      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2425    let assumptionb =
2426     GButton.button ~label:"Assumption"
2427      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2428    let contradictionb =
2429     GButton.button ~label:"Contradiction"
2430      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2431    let hbox4 =
2432     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2433    let existsb =
2434     GButton.button ~label:"Exists"
2435      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2436    let splitb =
2437     GButton.button ~label:"Split"
2438      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2439    let leftb =
2440     GButton.button ~label:"Left"
2441      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2442    let rightb =
2443     GButton.button ~label:"Right"
2444      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2445    let searchpatternb =
2446     GButton.button ~label:"SearchPattern_Apply"
2447      ~packing:(hbox4#pack ~expand:false ~fill:false ~padding:5) () in
2448    let hbox5 =
2449     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2450    let exactb =
2451     GButton.button ~label:"Exact"
2452      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2453    let introsb =
2454     GButton.button ~label:"Intros"
2455      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2456    let applyb =
2457     GButton.button ~label:"Apply"
2458      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2459    let elimintrossimplb =
2460     GButton.button ~label:"ElimIntrosSimpl"
2461      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2462    let elimtypeb =
2463     GButton.button ~label:"ElimType"
2464      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2465    let foldwhdb =
2466     GButton.button ~label:"Fold_whd"
2467      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2468    let foldreduceb =
2469     GButton.button ~label:"Fold_reduce"
2470      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2471    let hbox6 =
2472     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2473    let foldsimplb =
2474     GButton.button ~label:"Fold_simpl"
2475      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2476    let cutb =
2477     GButton.button ~label:"Cut"
2478      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2479    let changeb =
2480     GButton.button ~label:"Change"
2481      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2482    let letinb =
2483     GButton.button ~label:"Let ... In"
2484      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2485    let rewritesimplb =
2486     GButton.button ~label:"RewriteSimpl ->"
2487      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2488    let rewritebacksimplb =
2489     GButton.button ~label:"RewriteSimpl <-"
2490      ~packing:(hbox6#pack ~expand:false ~fill:false ~padding:5) () in
2491    let hbox7 =
2492     GPack.hbox ~packing:(vbox1#pack ~expand:false ~fill:false ~padding:5) () in
2493    let absurdb =
2494     GButton.button ~label:"Absurd"
2495      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2496    let decomposeb =
2497     GButton.button ~label:"Decompose"
2498      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2499    let transitivityb =
2500     GButton.button ~label:"Transitivity"
2501      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2502    let replaceb =
2503     GButton.button ~label:"Replace"
2504      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2505    let injectionb =
2506     GButton.button ~label:"Injection"
2507      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2508    let discriminateb =
2509     GButton.button ~label:"Discriminate"
2510      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2511 (* Zack: spostare in una toolbar
2512    let generalizeb =
2513     GButton.button ~label:"Generalize"
2514      ~packing:(hbox7#pack ~expand:false ~fill:false ~padding:5) () in
2515    let clearbodyb =
2516     GButton.button ~label:"ClearBody"
2517      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2518    let clearb =
2519     GButton.button ~label:"Clear"
2520      ~packing:(hbox5#pack ~expand:false ~fill:false ~padding:5) () in
2521    let whdb =
2522     GButton.button ~label:"Whd"
2523      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2524    let reduceb =
2525     GButton.button ~label:"Reduce"
2526      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2527    let simplb =
2528     GButton.button ~label:"Simpl"
2529      ~packing:(hbox3#pack ~expand:false ~fill:false ~padding:5) () in
2530 *)
2531
2532    ignore(exactb#connect#clicked InvokeTactics'.exact) ;
2533    ignore(applyb#connect#clicked InvokeTactics'.apply) ;
2534    ignore(elimintrossimplb#connect#clicked InvokeTactics'.elimintrossimpl) ;
2535    ignore(elimtypeb#connect#clicked InvokeTactics'.elimtype) ;
2536    ignore(foldwhdb#connect#clicked InvokeTactics'.fold_whd) ;
2537    ignore(foldreduceb#connect#clicked InvokeTactics'.fold_reduce) ;
2538    ignore(foldsimplb#connect#clicked InvokeTactics'.fold_simpl) ;
2539    ignore(cutb#connect#clicked InvokeTactics'.cut) ;
2540    ignore(changeb#connect#clicked InvokeTactics'.change) ;
2541    ignore(letinb#connect#clicked InvokeTactics'.letin) ;
2542    ignore(ringb#connect#clicked InvokeTactics'.ring) ;
2543    ignore(fourierb#connect#clicked InvokeTactics'.fourier) ;
2544    ignore(rewritesimplb#connect#clicked InvokeTactics'.rewritesimpl) ;
2545    ignore(rewritebacksimplb#connect#clicked InvokeTactics'.rewritebacksimpl) ;
2546    ignore(replaceb#connect#clicked InvokeTactics'.replace) ;
2547    ignore(reflexivityb#connect#clicked InvokeTactics'.reflexivity) ;
2548    ignore(symmetryb#connect#clicked InvokeTactics'.symmetry) ;
2549    ignore(transitivityb#connect#clicked InvokeTactics'.transitivity) ;
2550    ignore(existsb#connect#clicked InvokeTactics'.exists) ;
2551    ignore(splitb#connect#clicked InvokeTactics'.split) ;
2552    ignore(leftb#connect#clicked InvokeTactics'.left) ;
2553    ignore(rightb#connect#clicked InvokeTactics'.right) ;
2554    ignore(assumptionb#connect#clicked InvokeTactics'.assumption) ;
2555    ignore(absurdb#connect#clicked InvokeTactics'.absurd) ;
2556    ignore(contradictionb#connect#clicked InvokeTactics'.contradiction) ;
2557    ignore(introsb#connect#clicked InvokeTactics'.intros) ;
2558    ignore(decomposeb#connect#clicked InvokeTactics'.decompose) ;
2559    ignore(searchpatternb#connect#clicked searchPattern) ;
2560    ignore(injectionb#connect#clicked InvokeTactics'.injection) ;
2561    ignore(discriminateb#connect#clicked InvokeTactics'.discriminate) ;
2562 (* Zack: spostare in una toolbar
2563    ignore(whdb#connect#clicked whd) ;
2564    ignore(reduceb#connect#clicked reduce) ;
2565    ignore(simplb#connect#clicked simpl) ;
2566    ignore(clearbodyb#connect#clicked clearbody) ;
2567    ignore(clearb#connect#clicked clear) ;
2568    ignore(generalizeb#connect#clicked generalize) ;
2569 *)
2570    ignore(proofw#connect#selection_changed (choose_selection proofw)) ;
2571    ignore
2572      ((new GObj.event_ops proofw#as_widget)#connect#button_press
2573         (open_contextual_menu_for_selected_terms proofw)) ;
2574   ))
2575 end
2576 ;;
2577
2578 class empty_page =
2579  let vbox1 = GPack.vbox () in
2580  let scrolled_window1 =
2581   GBin.scrolled_window ~border_width:10
2582    ~packing:(vbox1#pack ~expand:true ~padding:5) () in
2583  let proofw =
2584   TermViewer.sequent_viewer ~width:400 ~height:275
2585    ~packing:(scrolled_window1#add) () in
2586 object(self)
2587  method proofw = (assert false : TermViewer.sequent_viewer)
2588  method content = vbox1
2589  method compute = (assert false : unit)
2590 end
2591 ;;
2592
2593 let empty_page = new empty_page;;
2594
2595 class notebook =
2596 object(self)
2597  val notebook = GPack.notebook ()
2598  val pages = ref []
2599  val mutable skip_switch_page_event = false 
2600  val mutable empty = true
2601  method notebook = notebook
2602  method add_page n =
2603   let new_page = new page () in
2604    empty <- false ;
2605    pages := !pages @ [n,lazy (setgoal n),new_page] ;
2606    notebook#append_page
2607     ~tab_label:((GMisc.label ~text:("?" ^ string_of_int n) ())#coerce)
2608     new_page#content#coerce
2609  method remove_all_pages ~skip_switch_page_event:skip =
2610   if empty then
2611    notebook#remove_page 0 (* let's remove the empty page *)
2612   else
2613    List.iter (function _ -> notebook#remove_page 0) !pages ;
2614   pages := [] ;
2615   skip_switch_page_event <- skip
2616  method set_current_page ~may_skip_switch_page_event n =
2617   let (_,_,page) = List.find (function (m,_,_) -> m=n) !pages in
2618    let new_page = notebook#page_num page#content#coerce in
2619     if may_skip_switch_page_event && new_page <> notebook#current_page then
2620      skip_switch_page_event <- true ;
2621     notebook#goto_page new_page
2622  method set_empty_page =
2623   empty <- true ;
2624   pages := [] ;
2625   notebook#append_page
2626    ~tab_label:((GMisc.label ~text:"No proof in progress" ())#coerce)
2627    empty_page#content#coerce
2628  method proofw =
2629   let (_,_,page) = List.nth !pages notebook#current_page in
2630    page#proofw
2631  initializer
2632   ignore
2633    (notebook#connect#switch_page
2634     (function i ->
2635       let skip = skip_switch_page_event in
2636        skip_switch_page_event <- false ;
2637        if not skip then
2638         try
2639          let (metano,setgoal,page) = List.nth !pages i in
2640           ProofEngine.goal := Some metano ;
2641           Lazy.force (page#compute) ;
2642           Lazy.force setgoal
2643         with _ -> ()
2644     ))
2645 end
2646 ;;
2647
2648 (* Main window *)
2649
2650 class rendering_window output (notebook : notebook) =
2651  let scratch_window = new scratch_window in
2652  let window =
2653   GWindow.window
2654    ~title:"gTopLevel - Helm's Proof Assistant"
2655    ~border_width:0 ~allow_shrink:false () in
2656  let vbox_for_menu = GPack.vbox ~packing:window#add () in
2657  (* menus *)
2658  let handle_box = GBin.handle_box ~border_width:2
2659   ~packing:(vbox_for_menu#pack ~padding:0) () in
2660  let menubar = GMenu.menu_bar ~packing:handle_box#add () in
2661  let factory0 = new GMenu.factory menubar in
2662  let accel_group = factory0#accel_group in
2663  (* file menu *)
2664  let file_menu = factory0#add_submenu "File" in
2665  let factory1 = new GMenu.factory file_menu ~accel_group in
2666  let export_to_postscript_menu_item =
2667   begin
2668    let _ =
2669     factory1#add_item "New Block of (Co)Inductive Definitions..."
2670      ~key:GdkKeysyms._B ~callback:new_inductive
2671    in
2672    let _ =
2673     factory1#add_item "New Proof or Definition..." ~key:GdkKeysyms._N
2674      ~callback:new_proof
2675    in
2676    let reopen_menu_item =
2677     factory1#add_item "Reopen a Finished Proof..." ~key:GdkKeysyms._R
2678      ~callback:open_
2679    in
2680    let qed_menu_item =
2681     factory1#add_item "Qed" ~key:GdkKeysyms._E ~callback:qed in
2682    ignore (factory1#add_separator ()) ;
2683    ignore
2684     (factory1#add_item "Load Unfinished Proof..." ~key:GdkKeysyms._L
2685       ~callback:load_unfinished_proof) ;
2686    let save_menu_item =
2687     factory1#add_item "Save Unfinished Proof" ~key:GdkKeysyms._S
2688       ~callback:save_unfinished_proof
2689    in
2690    ignore
2691     (save_set_sensitive := function b -> save_menu_item#misc#set_sensitive b);
2692    ignore (!save_set_sensitive false);
2693    ignore (qed_set_sensitive:=function b -> qed_menu_item#misc#set_sensitive b);
2694    ignore (!qed_set_sensitive false);
2695    ignore (factory1#add_separator ()) ;
2696    let export_to_postscript_menu_item =
2697     factory1#add_item "Export to PostScript..."
2698      ~callback:(export_to_postscript output) in
2699    ignore (factory1#add_separator ()) ;
2700    ignore
2701     (factory1#add_item "Exit" ~key:GdkKeysyms._Q ~callback:GMain.Main.quit) ;
2702    export_to_postscript_menu_item
2703   end in
2704  (* edit menu *)
2705  let edit_menu = factory0#add_submenu "Edit Current Proof" in
2706  let factory2 = new GMenu.factory edit_menu ~accel_group in
2707  let focus_and_proveit_set_sensitive = ref (function _ -> assert false) in
2708  let proveit_menu_item =
2709   factory2#add_item "Prove It" ~key:GdkKeysyms._I
2710    ~callback:(function () -> proveit ();!focus_and_proveit_set_sensitive false)
2711  in
2712  let focus_menu_item =
2713   factory2#add_item "Focus" ~key:GdkKeysyms._F
2714    ~callback:(function () -> focus () ; !focus_and_proveit_set_sensitive false)
2715  in
2716  let _ =
2717   focus_and_proveit_set_sensitive :=
2718    function b ->
2719     proveit_menu_item#misc#set_sensitive b ;
2720     focus_menu_item#misc#set_sensitive b
2721  in
2722  let _ = !focus_and_proveit_set_sensitive false in
2723  (* edit term menu *)
2724  let edit_term_menu = factory0#add_submenu "Edit Term" in
2725  let factory5 = new GMenu.factory edit_term_menu ~accel_group in
2726  let check_menu_item =
2727   factory5#add_item "Check Term" ~key:GdkKeysyms._C
2728    ~callback:(check scratch_window) in
2729  let _ = check_menu_item#misc#set_sensitive false in
2730  (* search menu *)
2731  let search_menu = factory0#add_submenu "Search" in
2732  let factory4 = new GMenu.factory search_menu ~accel_group in
2733  let _ =
2734   factory4#add_item "Locate..." ~key:GdkKeysyms._T
2735    ~callback:locate in
2736  let searchPattern_menu_item =
2737   factory4#add_item "SearchPattern..." ~key:GdkKeysyms._D
2738    ~callback:completeSearchPattern in
2739  let _ = searchPattern_menu_item#misc#set_sensitive false in
2740  let show_menu_item =
2741   factory4#add_item "Show..." ~key:GdkKeysyms._H ~callback:show
2742  in
2743  let insert_query_item =
2744   factory4#add_item "Insert Query (Experts Only)..." ~key:GdkKeysyms._Y
2745    ~callback:insertQuery in
2746  (* hbugs menu *)
2747  let hbugs_menu = factory0#add_submenu "HBugs" in
2748  let factory6 = new GMenu.factory hbugs_menu ~accel_group in
2749  let toggle_hbugs_menu_item =
2750   factory6#add_check_item
2751     ~active:false ~key:GdkKeysyms._F5 ~callback:Hbugs.toggle "HBugs enabled"
2752  in
2753  (* settings menu *)
2754  let settings_menu = factory0#add_submenu "Settings" in
2755  let factory3 = new GMenu.factory settings_menu ~accel_group in
2756  let _ =
2757   factory3#add_item "Edit Aliases" ~key:GdkKeysyms._A
2758    ~callback:edit_aliases in
2759  let _ = factory3#add_separator () in
2760  let _ =
2761   factory3#add_item "MathML Widget Preferences..." ~key:GdkKeysyms._P
2762    ~callback:(function _ -> (settings_window ())#show ()) in
2763  (* accel group *)
2764  let _ = window#add_accel_group accel_group in
2765  (* end of menus *)
2766  let hbox0 =
2767   GPack.hbox
2768    ~packing:(vbox_for_menu#pack ~expand:true ~fill:true ~padding:5) () in
2769  let vbox =
2770   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
2771  let scrolled_window0 =
2772   GBin.scrolled_window ~border_width:10
2773    ~packing:(vbox#pack ~expand:true ~padding:5) () in
2774  let _ = scrolled_window0#add output#coerce in
2775  let frame =
2776   GBin.frame ~label:"Insert Term"
2777    ~packing:(vbox#pack ~expand:true ~fill:true ~padding:5) () in
2778  let scrolled_window1 =
2779   GBin.scrolled_window ~border_width:5
2780    ~packing:frame#add () in
2781  let inputt =
2782   TexTermEditor'.term_editor
2783    ~width:400 ~height:100 ~packing:scrolled_window1#add ()
2784    ~isnotempty_callback:
2785     (function b ->
2786       check_menu_item#misc#set_sensitive b ;
2787       searchPattern_menu_item#misc#set_sensitive b) in
2788  let vboxl =
2789   GPack.vbox ~packing:(hbox0#pack ~expand:true ~fill:true ~padding:5) () in
2790  let _ =
2791   vboxl#pack ~expand:true ~fill:true ~padding:5 notebook#notebook#coerce in
2792  let frame =
2793   GBin.frame ~shadow_type:`IN ~packing:(vboxl#pack ~expand:true ~padding:5) ()
2794  in
2795  let outputhtml =
2796   GHtml.xmhtml
2797    ~source:"<html><body bgColor=\"white\"></body></html>"
2798    ~width:400 ~height: 100
2799    ~border_width:20
2800    ~packing:frame#add
2801    ~show:true () in
2802 object
2803  method outputhtml = outputhtml
2804  method inputt = inputt
2805  method output = (output : TermViewer.proof_viewer)
2806  method scratch_window = scratch_window
2807  method notebook = notebook
2808  method show = window#show
2809  initializer
2810   notebook#set_empty_page ;
2811   export_to_postscript_menu_item#misc#set_sensitive false ;
2812   check_term := (check_term_in_scratch scratch_window) ;
2813
2814   (* signal handlers here *)
2815   ignore(output#connect#selection_changed
2816    (function elem ->
2817      choose_selection output elem ;
2818      !focus_and_proveit_set_sensitive true
2819    )) ;
2820   ignore (output#connect#click (show_in_show_window_callback output)) ;
2821   let settings_window = new settings_window output scrolled_window0
2822    export_to_postscript_menu_item (choose_selection output) in
2823   set_settings_window settings_window ;
2824   set_outputhtml outputhtml ;
2825   ignore(window#event#connect#delete (fun _ -> GMain.Main.quit () ; true )) ;
2826   Logger.log_callback :=
2827    (Logger.log_to_html ~print_and_flush:(output_html outputhtml))
2828 end;;
2829
2830 (* MAIN *)
2831
2832 let initialize_everything () =
2833  let module U = Unix in
2834   let output = TermViewer.proof_viewer ~width:350 ~height:280 () in
2835   let notebook = new notebook in
2836    let rendering_window' = new rendering_window output notebook in
2837     set_rendering_window rendering_window' ;
2838     let print_error_as_html prefix msg =
2839      output_html (outputhtml ())
2840       ("<h1 color=\"red\">" ^ prefix ^ msg ^ "</h1>")
2841     in
2842      Gdome_xslt.setErrorCallback (Some (print_error_as_html "XSLT Error: "));
2843      Gdome_xslt.setDebugCallback
2844       (Some (print_error_as_html "XSLT Debug Message: "));
2845      rendering_window'#show () ;
2846 (*      Hbugs.toggle true; *)
2847      GtkThread.main ()
2848 ;;
2849
2850 let main () =
2851  if !usedb then ignore (MQI.init mqi_options) ;
2852  ignore (GtkMain.Main.init ()) ;
2853  initialize_everything () ;
2854  if !usedb then MQI.close mqi_options;
2855  Hbugs.quit ()
2856 ;;
2857
2858 try
2859   Sys.catch_break true;
2860   main ();
2861 with Sys.Break -> ()  (* exit nicely, invoking at_exit functions *)
2862