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