]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaMathView.ml
new tacticals
[helm.git] / helm / matita / matitaMathView.ml
1 (* Copyright (C) 2004-2005, 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 open Printf
27
28 open MatitaTypes
29 open MatitaGtkMisc
30
31 module Stack = Continuationals.Stack
32
33 (** inherit from this class if you want to access current script *)
34 class scriptAccessor =
35 object (self)
36   method private script = MatitaScript.current ()
37 end
38
39 let cicBrowsers = ref []
40 let gui_instance = ref None
41 let set_gui gui = gui_instance := Some gui
42 let get_gui () =
43   match !gui_instance with
44   | None -> assert false
45   | Some gui -> gui
46
47 let default_font_size () =
48   Helm_registry.get_opt_default Helm_registry.int
49     ~default:BuildTimeConf.default_font_size "matita.font_size"
50 let current_font_size = ref ~-1
51 let increase_font_size () = incr current_font_size
52 let decrease_font_size () = decr current_font_size
53 let reset_font_size () = current_font_size := default_font_size ()
54
55   (* is there any lablgtk2 constant corresponding to the various mouse
56    * buttons??? *)
57 let left_button = 1
58 let middle_button = 2
59 let right_button = 3
60
61 let near (x1, y1) (x2, y2) =
62   let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
63   (distance < 4.)
64
65 let href_ds = Gdome.domString "href"
66 let xref_ds = Gdome.domString "xref"
67
68 (* ids_to_terms should not be passed here, is just for debugging *)
69 let find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types =
70   let find_parent id ids =
71     let rec aux id =
72 (*       (prerr_endline (sprintf "id %s = %s" id
73         (try
74           CicPp.ppterm (Hashtbl.find ids_to_terms id)
75         with Not_found -> "NONE"))); *)
76       if List.mem id ids then Some id
77       else
78         (match
79           (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
80         with
81         | None -> None
82         | Some id' -> aux id')
83     in
84     aux id
85   in
86   let return_father id ids =
87     match find_parent id ids with
88     | None -> assert false
89     | Some parent_id -> parent_id
90   in
91   let mk_ids terms = List.map CicUtil.id_of_annterm terms in
92   let inner_types =
93    Hashtbl.fold
94     (fun _ types acc ->
95       match types.Cic2acic.annexpected with
96          None -> types.Cic2acic.annsynthesized :: acc
97        | Some ty -> ty :: types.Cic2acic.annsynthesized :: acc
98     ) ids_to_inner_types [] in
99   match annobj with
100   | Cic.AConstant (_, _, _, Some bo, ty, _, _)
101   | Cic.AVariable (_, _, Some bo, ty, _, _)
102   | Cic.ACurrentProof (_, _, _, _, bo, ty, _, _) ->
103       return_father id (mk_ids (ty :: bo :: inner_types))
104   | Cic.AConstant (_, _, _, None, ty, _, _)
105   | Cic.AVariable (_, _, None, ty, _, _) ->
106       return_father id (mk_ids (ty::inner_types))
107   | Cic.AInductiveDefinition _ ->
108       assert false  (* TODO *)
109
110   (** @return string content of a dom node having a single text child node, e.g.
111    * <m:mi xlink:href="...">bool</m:mi> *)
112 let string_of_dom_node node =
113   match node#get_firstChild with
114   | None -> ""
115   | Some node ->
116       (try
117         let text = new Gdome.text_of_node node in
118         text#get_data#to_string
119       with GdomeInit.DOMCastException _ -> "")
120
121 class clickableMathView obj =
122 let text_width = 80 in
123 object (self)
124   inherit GMathViewAux.multi_selection_math_view obj
125
126   val mutable href_callback: (string -> unit) option = None
127   method set_href_callback f = href_callback <- f
128
129   val mutable _cic_info = None
130   method private set_cic_info info = _cic_info <- info
131   method private cic_info = _cic_info
132
133   initializer
134     self#set_font_size !current_font_size;
135     ignore (self#connect#selection_changed self#choose_selection_cb);
136     ignore (self#event#connect#button_press self#button_press_cb);
137     ignore (self#event#connect#button_release self#button_release_cb);
138     ignore (self#event#connect#selection_clear self#selection_clear_cb);
139     ignore (self#coerce#misc#connect#selection_get self#selection_get_cb)
140
141   val mutable button_press_x = -1.
142   val mutable button_press_y = -1.
143   val mutable selection_changed = false
144
145   method private selection_get_cb ctxt ~info ~time =
146     (match self#get_selections with
147     | [] -> ()
148     | node :: _ -> ctxt#return (self#string_of_node node))
149
150   method private selection_clear_cb sel_event =
151     self#remove_selections;
152     false
153
154   method private button_press_cb gdk_button =
155     let button = GdkEvent.Button.button gdk_button in
156     if  button = left_button then begin
157       button_press_x <- GdkEvent.Button.x gdk_button;
158       button_press_y <- GdkEvent.Button.y gdk_button;
159       selection_changed <- false
160     end else if button = right_button then
161       self#popup_contextual_menu (GdkEvent.Button.time gdk_button);
162     false
163
164   method private popup_contextual_menu time =
165     match self#string_of_selection with
166     | None -> ()
167     | Some s ->
168         let clipboard = GData.clipboard Gdk.Atom.clipboard in
169         let menu = GMenu.menu () in
170         let copy_menu_item =
171           GMenu.image_menu_item
172             ~label:"_Copy" ~stock:`COPY ~packing:menu#append ()
173         in
174         connect_menu_item copy_menu_item (fun () -> clipboard#set_text s);
175         menu#popup ~button:right_button ~time
176
177   method private button_release_cb gdk_button =
178     let clipboard = GData.clipboard Gdk.Atom.primary in
179     if GdkEvent.Button.button gdk_button = left_button then begin
180       let button_release_x = GdkEvent.Button.x gdk_button in
181       let button_release_y = GdkEvent.Button.y gdk_button in
182       if selection_changed then
183         ()
184       else  (* selection _not_ changed *)
185         if near (button_press_x, button_press_y)
186           (button_release_x, button_release_y)
187         then
188           let x = int_of_float button_press_x in
189           let y = int_of_float button_press_y in
190           (match self#get_element_at x y with
191           | None -> ()
192           | Some elt ->
193               let namespaceURI = DomMisc.xlink_ns in
194               let localName = href_ds in
195               if elt#hasAttributeNS ~namespaceURI ~localName then
196                 self#invoke_href_callback
197                   (elt#getAttributeNS ~namespaceURI ~localName)#to_string
198                   gdk_button
199               else
200                 ignore (self#action_toggle elt));
201     end;
202     false
203
204   method private invoke_href_callback href_value gdk_button =
205     let button = GdkEvent.Button.button gdk_button in
206     if button = left_button then
207       let time = GdkEvent.Button.time gdk_button in
208       match href_callback with
209       | None -> ()
210       | Some f ->
211           (match HExtlib.split href_value with
212           | [ uri ] ->  f uri
213           | uris ->
214               let menu = GMenu.menu () in
215               List.iter
216                 (fun uri ->
217                   let menu_item =
218                     GMenu.menu_item ~label:uri ~packing:menu#append ()
219                   in
220                   connect_menu_item menu_item (fun () -> f uri))
221                 uris;
222               menu#popup ~button ~time)
223
224   method private choose_selection_cb gdome_elt =
225     let (gui: MatitaGuiTypes.gui) = get_gui () in
226     let clipboard = GData.clipboard Gdk.Atom.primary in
227     let set_selection elt =
228       self#set_selection (Some elt);
229       self#coerce#misc#add_selection_target
230         ~target:(Gdk.Atom.name Gdk.Atom.string) Gdk.Atom.primary;
231       ignore (self#coerce#misc#grab_selection Gdk.Atom.primary)
232     in
233     let rec aux elt =
234       if (elt#getAttributeNS ~namespaceURI:DomMisc.helm_ns
235             ~localName:xref_ds)#to_string <> ""
236       then
237         set_selection elt
238       else
239         try
240           (match elt#get_parentNode with
241           | None -> assert false
242           | Some p -> aux (new Gdome.element_of_node p))
243         with GdomeInit.DOMCastException _ -> ()
244     in
245     (match gdome_elt with
246     | Some elt when (elt#getAttributeNS ~namespaceURI:DomMisc.xlink_ns
247         ~localName:href_ds)#to_string <> "" ->
248           set_selection elt
249     | Some elt -> aux elt
250     | None -> self#set_selection None);
251     selection_changed <- true
252
253   method update_font_size = self#set_font_size !current_font_size
254
255   method private get_term_by_id context cic_info id =
256     let ids_to_terms, ids_to_hypotheses, _, _, _ = cic_info in
257     try
258       `Term (Hashtbl.find ids_to_terms id)
259     with Not_found ->
260       try
261         let hyp = Hashtbl.find ids_to_hypotheses id in
262         let context' = MatitaMisc.list_tl_at hyp context in
263         `Hyp context'
264       with Not_found -> assert false
265     
266   method private find_obj_conclusion id =
267     match self#cic_info with
268     | None
269     | Some (_, _, _, _, None) -> assert false
270     | Some (ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
271         let id =
272          find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
273         in
274          (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
275
276   method private string_of_node node =
277     if node#hasAttributeNS ~namespaceURI:DomMisc.helm_ns ~localName:xref_ds
278     then self#string_of_id_node node
279     else string_of_dom_node node
280
281   method private string_of_id_node node =
282     let get_id (node: Gdome.element) =
283       let xref_attr =
284         node#getAttributeNS ~namespaceURI:DomMisc.helm_ns ~localName:xref_ds
285       in
286       List.hd (HExtlib.split ~sep:' ' xref_attr#to_string)
287     in
288     let id = get_id node in
289     let script = MatitaScript.current () in
290     let metasenv = script#proofMetasenv in
291     let context = script#proofContext in
292     let metasenv, context, conclusion =
293       if script#onGoingProof () then
294         script#proofMetasenv, script#proofContext, script#proofConclusion
295       else
296         [], [],
297         let t = self#find_obj_conclusion id in
298         MatitaLog.debug (CicPp.ppterm t);
299         t
300     in
301 (* TODO: code for patterns
302     let conclusion = (MatitaScript.instance ())#proofConclusion in
303     let conclusion_pattern =
304       ProofEngineHelpers.pattern_of ~term:conclusion cic_terms
305     in
306 *)
307     let string_of_cic_sequent cic_sequent =
308       let acic_sequent, _, _, ids_to_inner_sorts, _ =
309         Cic2acic.asequent_of_sequent metasenv cic_sequent
310       in
311       let _, _, _, annterm = acic_sequent in
312       let ast, ids_to_uris =
313         CicNotationRew.ast_of_acic ids_to_inner_sorts annterm
314       in
315       let pped_ast = CicNotationRew.pp_ast ast in
316       let markup = CicNotationPres.render ids_to_uris pped_ast in
317       BoxPp.render_to_string text_width markup
318     in
319     let cic_info =
320       match self#cic_info with Some info -> info | None -> assert false
321     in
322     let cic_sequent =
323       match self#get_term_by_id context cic_info id with
324       | `Term t ->
325           let context' =
326             match
327               ProofEngineHelpers.locate_in_conjecture t
328                 (~-1, context, conclusion)
329             with
330               [context,_] -> context
331             | _ -> assert false (* since it uses physical equality *)
332           in
333           ~-1, context', t
334       | `Hyp context -> ~-1, context, Cic.Rel 1
335     in
336     string_of_cic_sequent cic_sequent
337
338   method string_of_selections =
339     List.map self#string_of_node (List.rev self#get_selections)
340
341   method string_of_selection =
342     match self#get_selections with
343     | [] -> None
344     | node :: _ -> Some (self#string_of_node node)
345
346 end
347
348 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
349   GtkBase.Widget.size_params
350     ~cont:(OgtkMathViewProps.pack_return (fun p ->
351       OgtkMathViewProps.set_params
352         (new clickableMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
353         ~font_size:None ~log_verbosity:None))
354     []
355
356 class cicMathView obj =
357 object (self)
358   inherit clickableMathView obj
359
360   val mutable current_mathml = None
361
362   method load_sequent metasenv metano =
363     let sequent = CicUtil.lookup_meta metano metasenv in
364     let (mathml, (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ ))) =
365       ApplyTransformation.mml_of_cic_sequent metasenv sequent
366     in
367     self#set_cic_info
368       (Some (ids_to_terms, ids_to_hypotheses, ids_to_father_ids,
369         Hashtbl.create 1, None));
370     let name = "sequent_viewer.xml" in
371     MatitaLog.debug ("load_sequent: dumping MathML to ./" ^ name);
372     ignore (DomMisc.domImpl#saveDocumentToFile ~name ~doc:mathml ());
373     self#load_root ~root:mathml#get_documentElement
374
375   method load_object obj =
376     let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
377     let (mathml,
378       (annobj, (ids_to_terms, ids_to_father_ids, _, ids_to_hypotheses, _, ids_to_inner_types)))
379     =
380       ApplyTransformation.mml_of_cic_object obj
381     in
382     self#set_cic_info
383       (Some (ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
384     (match current_mathml with
385     | Some current_mathml when use_diff ->
386         self#freeze;
387         XmlDiff.update_dom ~from:current_mathml mathml;
388         self#thaw
389     |  _ ->
390         let name = "cic_browser.xml" in
391         MatitaLog.debug ("cic_browser: dumping MathML to ./" ^ name);
392         ignore (DomMisc.domImpl#saveDocumentToFile ~name ~doc:mathml ());
393         self#load_root ~root:mathml#get_documentElement;
394         current_mathml <- Some mathml);
395 end
396
397 let tab_label meta_markup =
398   let rec aux =
399     function
400     | `Current m -> sprintf "<b>%s</b>" (aux m)
401     | `Closed m -> sprintf "<s>%s</s>" (aux m)
402     | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
403     | `Meta n -> sprintf "?%d" n
404   in
405   let markup = aux meta_markup in
406   (GMisc.label ~markup ~show:true ())#coerce
407
408 let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
409
410 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
411   object (self)
412     inherit scriptAccessor
413
414     val mutable pages = 0
415     val mutable switch_page_callback = None
416     val mutable page2goal = []  (* associative list: page no -> goal no *)
417     val mutable goal2page = []  (* the other way round *)
418     val mutable goal2win = []   (* associative list: goal no -> scrolled win *)
419     val mutable _metasenv = []
420     val mutable scrolledWin: GBin.scrolled_window option = None
421       (* scrolled window to which the sequentViewer is currently attached *)
422     val logo = (GMisc.image
423       ~file:(MatitaMisc.image_path "matita_medium.png") ()
424       :> GObj.widget)
425             
426     val logo_with_qed = (GMisc.image
427       ~file:(MatitaMisc.image_path "matita_small.png") ()
428       :> GObj.widget)
429
430     method load_logo =
431      notebook#set_show_tabs false;
432      notebook#append_page logo
433
434     method load_logo_with_qed =
435      notebook#set_show_tabs false;
436      notebook#append_page logo_with_qed
437
438     method reset =
439       (match scrolledWin with
440       | Some w ->
441           (* removing page from the notebook will destroy all contained widget,
442           * we do not want the cicMathView to be destroyed as well *)
443           w#remove cicMathView#coerce;
444           scrolledWin <- None
445       | None -> ());
446       (match switch_page_callback with
447       | Some id ->
448           GtkSignal.disconnect notebook#as_widget id;
449           switch_page_callback <- None
450       | None -> ());
451       for i = 0 to pages do notebook#remove_page 0 done; 
452       notebook#set_show_tabs true;
453       pages <- 0;
454       page2goal <- [];
455       goal2page <- [];
456       goal2win <- [];
457       _metasenv <- []; 
458       self#script#setGoal ~-1;
459
460     method load_sequents { proof = (_,metasenv,_,_) as proof; stack = stack } =
461       let sequents_no = List.length metasenv in
462       _metasenv <- metasenv;
463       pages <- 0;
464       let win goal_switch =
465         let w =
466           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
467             ~shadow_type:`IN ~show:true ()
468         in
469         let reparent () =
470           scrolledWin <- Some w;
471           match cicMathView#misc#parent with
472           | None -> w#add cicMathView#coerce
473           | Some parent ->
474              let parent =
475               match cicMathView#misc#parent with
476                  None -> assert false
477                | Some p -> GContainer.cast_container p
478              in
479               parent#remove cicMathView#coerce;
480               w#add cicMathView#coerce
481         in
482         goal2win <- (goal_switch, reparent) :: goal2win;
483         w#coerce
484       in
485       assert (
486         let stack_goals = Stack.open_goals stack in
487         let proof_goals = ProofEngineTypes.goals_of_proof proof in
488         if
489           HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
490           <> List.sort Pervasives.compare proof_goals
491         then begin
492           prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
493           prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
494           false
495         end
496         else true
497       );
498       let render_switch =
499         function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
500       in
501       let page = ref 0 in
502       let added_goals = ref [] in
503         (* goals can be duplicated on the tack due to focus, but we should avoid
504          * multiple labels in the user interface *)
505       let add_tab markup goal_switch =
506         let goal = Stack.goal_of_switch goal_switch in
507         if not (List.mem goal !added_goals) then begin
508           notebook#append_page ~tab_label:(tab_label markup) (win goal_switch);
509           page2goal <- (!page, goal_switch) :: page2goal;
510           goal2page <- (goal_switch, !page) :: goal2page;
511           incr page;
512           pages <- pages + 1;
513           added_goals := goal :: !added_goals
514         end
515       in
516       let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
517       Stack.iter  (** populate notebook with tabs *)
518         ~env:(fun depth tag (pos, sw) ->
519           let markup =
520             match depth, pos with
521             | 0, _ -> `Current (render_switch sw)
522             | 1, pos when Stack.head_tag stack = Stack.BranchTag ->
523                 `Shift (pos, render_switch sw)
524             | _ -> render_switch sw
525           in
526           add_tab markup sw)
527         ~cont:add_switch ~todo:add_switch
528         stack;
529       switch_page_callback <-
530         Some (notebook#connect#switch_page ~callback:(fun page ->
531           let goal_switch =
532             try List.assoc page page2goal with Not_found -> assert false
533           in
534           self#script#setGoal (goal_of_switch goal_switch);
535           self#render_page ~page ~goal_switch))
536
537     method private render_page ~page ~goal_switch =
538       (match goal_switch with
539       | Stack.Open goal -> cicMathView#load_sequent _metasenv goal
540       | Stack.Closed goal ->
541           let doc = Lazy.force MatitaMisc.closed_goal_mathml in
542           cicMathView#load_root ~root:doc#get_documentElement);
543       (try
544         cicMathView#set_selection None;
545         List.assoc goal_switch goal2win ()
546       with Not_found -> assert false)
547
548     method goto_sequent goal =
549       let goal_switch, page =
550         try
551           List.find
552             (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
553             goal2page
554         with Not_found -> assert false
555       in
556       notebook#goto_page page;
557       self#render_page page goal_switch
558
559   end
560
561  (** constructors *)
562
563 type 'widget constructor =
564   ?hadjustment:GData.adjustment ->
565   ?vadjustment:GData.adjustment ->
566   ?font_size:int ->
567   ?log_verbosity:int ->
568   ?width:int ->
569   ?height:int ->
570   ?packing:(GObj.widget -> unit) ->
571   ?show:bool ->
572   unit ->
573     'widget
574
575 let cicMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
576   GtkBase.Widget.size_params
577     ~cont:(OgtkMathViewProps.pack_return (fun p ->
578       OgtkMathViewProps.set_params
579         (new cicMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
580         ~font_size ~log_verbosity))
581     []
582
583 let blank_uri = BuildTimeConf.blank_uri
584 let current_proof_uri = BuildTimeConf.current_proof_uri
585
586 type term_source =
587   [ `Ast of DisambiguateTypes.term
588   | `Cic of Cic.term * Cic.metasenv
589   | `String of string
590   ]
591
592 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
593   ()
594 =
595   let term_RE = Pcre.regexp "^term:(.*)" in
596   let whelp_RE = Pcre.regexp "^\\s*whelp" in
597   let uri_RE =
598     Pcre.regexp
599       "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
600   in
601   let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
602   let whelp_query_RE = Pcre.regexp "^\\s*whelp\\s+([^\\s]+)\\s+(.*)$" in
603   let trailing_slash_RE = Pcre.regexp "/$" in
604   let has_xpointer_RE = Pcre.regexp "#xpointer\\(\\d+/\\d+(/\\d+)?\\)$" in
605   let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
606   let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
607   let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
608   let gui = get_gui () in
609   let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
610   let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
611   let combo,_ = GEdit.combo_box_text ~strings:queries () in
612   let activate_combo_query input q =
613     let q' = String.lowercase q in
614     let rec aux i = function
615       | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
616       | h::_ when String.lowercase h = q' -> i
617       | _::tl -> aux (i+1) tl
618     in
619     combo#set_active (aux 0 queries);
620     win#queryInputText#set_text input
621   in
622   let set_whelp_query txt =
623     let query, arg = 
624       try
625         let q = Pcre.extract ~rex:whelp_query_RE txt in
626         q.(1), q.(2)
627       with Invalid_argument _ -> failwith "Malformed Whelp query"
628     in
629     activate_combo_query arg query
630   in
631   let toplevel = win#toplevel in
632   let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
633   let fail message = 
634     MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
635       ~parent:toplevel ()  
636   in
637   let tags =
638     [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
639       "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
640   in
641   let handle_error f =
642     try
643       f ()
644     with exn ->
645       if not (Helm_registry.get_bool "matita.debug") then
646         fail (MatitaExcPp.to_string exn)
647       else raise exn
648   in
649   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
650   let load_easter_egg = lazy (
651     win#easterEggImage#set_file (MatitaMisc.image_path "meegg.png"))
652   in
653   object (self)
654     inherit scriptAccessor
655     
656     (* Whelp bar queries *)
657
658     initializer
659       activate_combo_query "" "locate";
660       win#whelpBarComboVbox#add combo#coerce;
661       let start_query () = 
662         let query = String.lowercase (List.nth queries combo#active) in
663         let input = win#queryInputText#text in
664         let statement = "whelp " ^ query ^ " " ^ input ^ "." in
665         (MatitaScript.current ())#advance ~statement ()
666       in
667       ignore(win#queryInputText#connect#activate ~callback:start_query);
668       ignore(combo#connect#changed ~callback:start_query);
669       win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
670       win#mathOrListNotebook#set_show_tabs false;
671       win#browserForwardButton#misc#set_sensitive false;
672       win#browserBackButton#misc#set_sensitive false;
673       ignore (win#browserUri#entry#connect#activate (handle_error' (fun () ->
674         self#loadInput win#browserUri#entry#text)));
675       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
676         self#load (`About `Current_proof))));
677       ignore (win#browserRefreshButton#connect#clicked
678         (handle_error' (self#refresh ~force:true)));
679       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
680       ignore (win#browserForwardButton#connect#clicked
681         (handle_error' self#forward));
682       ignore (win#toplevel#event#connect#delete (fun _ ->
683         let my_id = Oo.id self in
684         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
685         if !cicBrowsers = [] &&
686           Helm_registry.get "matita.mode" = "cicbrowser"
687         then
688           GMain.quit ();
689         false));
690       ignore(win#whelpResultTreeview#connect#row_activated 
691         ~callback:(fun _ _ ->
692           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
693       mathView#set_href_callback (Some (fun uri ->
694         handle_error (fun () ->
695           self#load (`Uri (UriManager.uri_of_string uri)))));
696       self#_load (`About `Blank);
697       toplevel#show ()
698
699     val mutable current_entry = `About `Blank 
700
701     val model =
702       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
703
704     val mutable lastDir = ""  (* last loaded "directory" *)
705
706     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
707
708     method private _getSelectedUri () =
709       match model#easy_selection () with
710       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
711 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
712       | [sel] -> lastDir ^ sel
713       | _ -> assert false
714
715     (** history RATIONALE 
716      *
717      * All operations about history are done using _historyFoo.
718      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
719      *)
720           
721     method private _historyAdd item = 
722       history#add item;
723       win#browserBackButton#misc#set_sensitive true;
724       win#browserForwardButton#misc#set_sensitive false
725
726     method private _historyPrev () =
727       let item = history#previous in
728       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
729       win#browserForwardButton#misc#set_sensitive true;
730       item
731     
732     method private _historyNext () =
733       let item = history#next in
734       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
735       win#browserBackButton#misc#set_sensitive true;
736       item
737
738     (** notebook RATIONALE 
739      * 
740      * Use only these functions to switch between the tabs
741      *)
742     method private _showMath = win#mathOrListNotebook#goto_page 0
743     method private _showList = win#mathOrListNotebook#goto_page 1
744
745     method private back () =
746       try
747         self#_load (self#_historyPrev ())
748       with MatitaMisc.History_failure -> ()
749
750     method private forward () =
751       try
752         self#_load (self#_historyNext ())
753       with MatitaMisc.History_failure -> ()
754
755       (* loads a uri which can be a cic uri or an about:* uri
756       * @param uri string *)
757     method private _load ?(force=false) entry =
758       handle_error (fun () ->
759        if entry <> current_entry || entry = `About `Current_proof || force then
760         begin
761           (match entry with
762           | `About `Current_proof -> self#home ()
763           | `About `Blank -> self#blank ()
764           | `About `Us -> self#egg ()
765           | `Check term -> self#_loadCheck term
766           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
767           | `Dir dir -> self#_loadDir dir
768           | `Uri uri -> self#_loadUriManagerUri uri
769           | `Whelp (query, results) -> 
770               set_whelp_query query;
771               self#_loadList (List.map (fun r -> "obj",
772                 UriManager.string_of_uri r) results));
773           self#setEntry entry
774         end)
775
776     method private blank () =
777       self#_showMath;
778       mathView#load_root
779         (Lazy.force MatitaMisc.empty_mathml)#get_documentElement
780
781     method private _loadCheck term =
782       failwith "not implemented _loadCheck";
783       self#_showMath
784
785     method private egg () =
786       win#mathOrListNotebook#goto_page 2;
787       Lazy.force load_easter_egg
788
789     method private home () =
790       self#_showMath;
791       match self#script#status.proof_status with
792       | Proof  (uri, metasenv, bo, ty) ->
793           let name = UriManager.name_of_uri (HExtlib.unopt uri) in
794           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
795           self#_loadObj obj
796       | Incomplete_proof { proof = (uri, metasenv, bo, ty) } ->
797           let name = UriManager.name_of_uri (HExtlib.unopt uri) in
798           let obj = Cic.CurrentProof (name, metasenv, bo, ty, [], []) in
799           self#_loadObj obj
800       | _ -> self#blank ()
801
802       (** loads a cic uri from the environment
803       * @param uri UriManager.uri *)
804     method private _loadUriManagerUri uri =
805       let uri = UriManager.strip_xpointer uri in
806       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
807       self#_loadObj obj
808       
809     method private _loadDir dir = 
810       let content = Http_getter.ls dir in
811       let l =
812         List.fast_sort
813           Pervasives.compare
814           (List.map
815             (function 
816               | Http_getter_types.Ls_section s -> "dir", s
817               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
818             content)
819       in
820       lastDir <- dir;
821       self#_loadList l
822
823     method private setEntry entry =
824       win#browserUri#entry#set_text (string_of_entry entry);
825       current_entry <- entry
826
827     method private _loadObj obj =
828       (* showMath must be done _before_ loading the document, since if the
829        * widget is not mapped (hidden by the notebook) the document is not
830        * rendered *)
831       self#_showMath;
832       mathView#load_object obj
833
834     method private _loadTermCic term metasenv =
835       let context = self#script#proofContext in
836       let dummyno = CicMkImplicit.new_meta metasenv [] in
837       let sequent = (dummyno, context, term) in
838       mathView#load_sequent (sequent :: metasenv) dummyno;
839       self#_showMath
840
841     method private _loadList l =
842       model#list_store#clear ();
843       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
844       self#_showList
845     
846     (** { public methods, all must call _load!! } *)
847       
848     method load entry =
849       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
850
851     (**  this is what the browser does when you enter a string an hit enter *)
852     method loadInput txt =
853       let txt = HExtlib.trim_blanks txt in
854       let fix_uri txt =
855         UriManager.string_of_uri
856           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
857       in
858       if is_whelp txt then begin
859         set_whelp_query txt;  
860         (MatitaScript.current ())#advance ~statement:(txt ^ ".") ()
861       end else begin
862         let entry =
863           match txt with
864           | txt when is_uri txt -> `Uri (UriManager.uri_of_string (fix_uri txt))
865           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
866           | txt ->
867               (try
868                 entry_of_string txt
869               with Invalid_argument _ ->
870                 command_error (sprintf "unsupported uri: %s" txt))
871         in
872         self#_load entry;
873         self#_historyAdd entry
874       end
875
876       (** {2 methods accessing underlying GtkMathView} *)
877
878     method updateFontSize = mathView#set_font_size !current_font_size
879
880       (** {2 methods used by constructor only} *)
881
882     method win = win
883     method history = history
884     method currentEntry = current_entry
885     method refresh ~force () = self#_load ~force current_entry
886
887   end
888   
889 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
890   MatitaGuiTypes.sequentsViewer
891 =
892   new sequentsViewer ~notebook ~cicMathView ()
893
894 let cicBrowser () =
895   let size = BuildTimeConf.browser_history_size in
896   let rec aux history =
897     let browser = new cicBrowser_impl ~history () in
898     let win = browser#win in
899     ignore (win#browserNewButton#connect#clicked (fun () ->
900       let history =
901         new MatitaMisc.browser_history ~memento:history#save size
902           (`About `Blank)
903       in
904       let newBrowser = aux history in
905       newBrowser#load browser#currentEntry));
906 (*
907       (* attempt (failed) to close windows on CTRL-W ... *)
908     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
909       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
910 *)
911     cicBrowsers := browser :: !cicBrowsers;
912     (browser :> MatitaGuiTypes.cicBrowser)
913   in
914   let history = new MatitaMisc.browser_history size (`About `Blank) in
915   aux history
916
917 let default_cicMathView () = cicMathView ~show:true ()
918 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
919
920 let default_sequentsViewer () =
921   let gui = get_gui () in
922   let cicMathView = cicMathView_instance () in
923   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
924 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
925
926 let mathViewer () = 
927   object(self)
928     method private get_browser reuse = 
929       if reuse then
930         (match !cicBrowsers with
931         | [] -> cicBrowser ()
932         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
933       else
934         (cicBrowser ())
935           
936     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
937       
938     method show_uri_list ?(reuse=false) ~entry l =
939       (self#get_browser reuse)#load entry
940   end
941
942 let refresh_all_browsers () =
943  List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
944
945 let update_font_sizes () =
946   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
947   (cicMathView_instance ())#update_font_size
948
949 let get_math_views () =
950   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
951   :: (List.map (fun b -> b#mathView) !cicBrowsers)
952
953 let get_selections () =
954   if (MatitaScript.current ())#onGoingProof () then
955     let rec aux =
956       function
957       | [] -> None
958       | mv :: tl ->
959           (match mv#string_of_selections with
960           | [] -> aux tl
961           | sels -> Some sels)
962     in
963     aux (get_math_views ())
964   else
965     None
966
967 let reset_selections () =
968   List.iter (fun mv -> mv#remove_selections) (get_math_views ())
969