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