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