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