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