]> matita.cs.unibo.it Git - helm.git/blob - helm/software/matita/matitaMathView.ml
maction support added to notation, adopted for = AKA = \sub t
[helm.git] / helm / software / 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 (* $Id$ *)
27
28 open Printf
29
30 open GrafiteTypes
31 open MatitaGtkMisc
32 open MatitaGuiTypes
33
34 module Stack = Continuationals.Stack
35
36 (** inherit from this class if you want to access current script *)
37 class scriptAccessor =
38 object (self)
39   method private script = MatitaScript.current ()
40 end
41
42 let cicBrowsers = ref []
43 let gui_instance = ref None
44 let set_gui gui = gui_instance := Some gui
45 let get_gui () =
46   match !gui_instance with
47   | None -> assert false
48   | Some gui -> gui
49
50 let default_font_size () =
51   Helm_registry.get_opt_default Helm_registry.int
52     ~default:BuildTimeConf.default_font_size "matita.font_size"
53 let current_font_size = ref ~-1
54 let increase_font_size () = incr current_font_size
55 let decrease_font_size () = decr current_font_size
56 let reset_font_size () = current_font_size := default_font_size ()
57
58   (* is there any lablgtk2 constant corresponding to the various mouse
59    * buttons??? *)
60 let left_button = 1
61 let middle_button = 2
62 let right_button = 3
63
64 let near (x1, y1) (x2, y2) =
65   let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
66   (distance < 4.)
67
68 let mathml_ns = Gdome.domString "http://www.w3.org/1998/Math/MathML"
69 let xlink_ns = Gdome.domString "http://www.w3.org/1999/xlink"
70 let helm_ns = Gdome.domString "http://www.cs.unibo.it/helm"
71 let href_ds = Gdome.domString "href"
72 let maction_ds = Gdome.domString "maction"
73 let xref_ds = Gdome.domString "xref"
74
75 let domImpl = Gdome.domImplementation ()
76
77   (** Gdome.element of a MathML document whose rendering should be blank. Used
78   * by cicBrowser to render "about:blank" document *)
79 let empty_mathml = lazy (
80   domImpl#createDocument ~namespaceURI:(Some DomMisc.mathml_ns)
81     ~qualifiedName:(Gdome.domString "math") ~doctype:None)
82
83 let empty_boxml = lazy (
84   domImpl#createDocument ~namespaceURI:(Some DomMisc.boxml_ns) 
85     ~qualifiedName:(Gdome.domString "box") ~doctype:None)
86
87   (** shown for goals closed by side effects *)
88 let closed_goal_mathml = lazy (
89   domImpl#createDocumentFromURI ~uri:BuildTimeConf.closed_xml ())
90
91 (* ids_to_terms should not be passed here, is just for debugging *)
92 let find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types =
93   let find_parent id ids =
94     let rec aux id =
95 (*       (prerr_endline (sprintf "id %s = %s" id
96         (try
97           CicPp.ppterm (Hashtbl.find ids_to_terms id)
98         with Not_found -> "NONE"))); *)
99       if List.mem id ids then Some id
100       else
101         (match
102           (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
103         with
104         | None -> None
105         | Some id' -> aux id')
106     in
107     aux id
108   in
109   let return_father id ids =
110     match find_parent id ids with
111     | None -> assert false
112     | Some parent_id -> parent_id
113   in
114   let mk_ids terms = List.map CicUtil.id_of_annterm terms in
115   let inner_types =
116    Hashtbl.fold
117     (fun _ types acc ->
118       match types.Cic2acic.annexpected with
119          None -> types.Cic2acic.annsynthesized :: acc
120        | Some ty -> ty :: types.Cic2acic.annsynthesized :: acc
121     ) ids_to_inner_types [] in
122   match annobj with
123   | Cic.AConstant (_, _, _, Some bo, ty, _, _)
124   | Cic.AVariable (_, _, Some bo, ty, _, _)
125   | Cic.ACurrentProof (_, _, _, _, bo, ty, _, _) ->
126       return_father id (mk_ids (ty :: bo :: inner_types))
127   | Cic.AConstant (_, _, _, None, ty, _, _)
128   | Cic.AVariable (_, _, None, ty, _, _) ->
129       return_father id (mk_ids (ty::inner_types))
130   | Cic.AInductiveDefinition _ ->
131       assert false  (* TODO *)
132
133   (** @return string content of a dom node having a single text child node, e.g.
134    * <m:mi xlink:href="...">bool</m:mi> *)
135 let string_of_dom_node node =
136   match node#get_firstChild with
137   | None -> ""
138   | Some node ->
139       (try
140         let text = new Gdome.text_of_node node in
141         text#get_data#to_string
142       with GdomeInit.DOMCastException _ -> "")
143
144 let name_of_hypothesis = function
145   | Some (Cic.Name s, _) -> s
146   | _ -> assert false
147
148 let id_of_node (node: Gdome.element) =
149   let xref_attr =
150     node#getAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds in
151   try
152     List.hd (HExtlib.split ~sep:' ' xref_attr#to_string)
153   with Failure _ -> assert false
154
155 type selected_term =
156   | SelTerm of Cic.term * string option (* term, parent hypothesis (if any) *)
157   | SelHyp of string * Cic.context (* hypothesis, context *)
158
159 let hrefs_of_elt elt =
160   let localName = href_ds in
161   if elt#hasAttributeNS ~namespaceURI:xlink_ns ~localName then
162     let text =
163       (elt#getAttributeNS ~namespaceURI:xlink_ns ~localName)#to_string in
164     Some (HExtlib.split text)
165   else
166     None
167
168 let rec has_maction (elt :Gdome.element) = 
169   (* fix this comparison *)
170   if elt#get_tagName#to_string = "m:maction" then
171     true
172   else 
173     match elt#get_parentNode with
174     | Some node when node#get_nodeType = GdomeNodeTypeT.ELEMENT_NODE -> 
175         has_maction (new Gdome.element_of_node node)
176     | _ -> false
177 ;;
178
179 class clickableMathView obj =
180 let text_width = 80 in
181 object (self)
182   inherit GMathViewAux.multi_selection_math_view obj
183
184   val mutable href_callback: (string -> unit) option = None
185   method set_href_callback f = href_callback <- f
186
187   val mutable _cic_info = None
188   method private set_cic_info info = _cic_info <- info
189   method private cic_info = _cic_info
190
191   val normal_cursor = Gdk.Cursor.create `LEFT_PTR
192   val href_cursor = Gdk.Cursor.create `HAND2
193   val maction_cursor = Gdk.Cursor.create `QUESTION_ARROW
194
195   initializer
196     self#set_font_size !current_font_size;
197     ignore (self#connect#selection_changed self#choose_selection_cb);
198     ignore (self#event#connect#button_press self#button_press_cb);
199     ignore (self#event#connect#button_release self#button_release_cb);
200     ignore (self#event#connect#selection_clear self#selection_clear_cb);
201     ignore (self#connect#element_over self#element_over_cb);
202     ignore (self#coerce#misc#connect#selection_get self#selection_get_cb)
203
204   val mutable button_press_x = -1.
205   val mutable button_press_y = -1.
206   val mutable selection_changed = false
207   val mutable href_statusbar_msg:
208     (GMisc.statusbar_context * Gtk.statusbar_message) option = None
209     (* <statusbar ctxt, statusbar msg> *)
210
211   method private selection_get_cb ctxt ~info ~time =
212     let text =
213       match ctxt#target with
214       | "PATTERN" -> self#text_of_selection `Pattern
215       | "TERM" | _ -> self#text_of_selection `Term
216     in
217     match text with
218     | None -> ()
219     | Some s -> ctxt#return s
220
221   method private text_of_selection fmt =
222     match self#get_selections with
223     | [] -> None
224     | node :: _ -> Some (self#string_of_node ~paste_kind:fmt node)
225
226   method private selection_clear_cb sel_event =
227     self#remove_selections;
228     (GData.clipboard Gdk.Atom.clipboard)#clear ();
229     false
230
231   method private button_press_cb gdk_button =
232     let button = GdkEvent.Button.button gdk_button in
233     if  button = left_button then begin
234       button_press_x <- GdkEvent.Button.x gdk_button;
235       button_press_y <- GdkEvent.Button.y gdk_button;
236       selection_changed <- false
237     end else if button = right_button then
238       self#popup_contextual_menu 
239         (self#get_element_at 
240           (int_of_float (GdkEvent.Button.x gdk_button)) 
241           (int_of_float (GdkEvent.Button.y gdk_button)))  
242         (GdkEvent.Button.time gdk_button);
243     false
244
245   method private element_over_cb (elt_opt, _, _, _) =
246     let win () = self#misc#window in
247     let leave_href () =
248       Gdk.Window.set_cursor (win ()) normal_cursor;
249       HExtlib.iter_option (fun (ctxt, msg) -> ctxt#remove msg)
250         href_statusbar_msg
251     in
252     match elt_opt with
253     | Some elt ->
254         if has_maction elt then
255           Gdk.Window.set_cursor (win ()) maction_cursor
256         else
257         (match hrefs_of_elt elt with
258         | Some ((_ :: _) as hrefs) ->
259             Gdk.Window.set_cursor (win ()) href_cursor;
260             let msg_text = (* now create statusbar msg and store it *)
261               match hrefs with
262               | [ href ] -> sprintf "Hyperlink to %s" href
263               | _ -> sprintf "Hyperlinks to: %s" (String.concat ", " hrefs) in
264             let ctxt = (get_gui ())#main#statusBar#new_context ~name:"href" in
265             let msg = ctxt#push msg_text in
266             href_statusbar_msg <- Some (ctxt, msg)
267         | _ -> leave_href ())
268     | None -> leave_href ()
269
270   method private tactic_text_pattern_of_node node =
271    let id = id_of_node node in
272    let cic_info, unsh_sequent = self#get_cic_info id in
273    match self#get_term_by_id cic_info id with
274    | SelTerm (t, father_hyp) ->
275        let sequent = self#sequent_of_id ~paste_kind:`Pattern id in
276        let text = self#string_of_cic_sequent ~output_type:`Pattern sequent in
277        (match father_hyp with
278        | None -> None, [], Some text
279        | Some hyp_name -> None, [ hyp_name, text ], None)
280    | SelHyp (hyp_name, _ctxt) -> None, [ hyp_name, "%" ], None
281
282   method private tactic_text_of_node node =
283    let id = id_of_node node in
284    let cic_info, unsh_sequent = self#get_cic_info id in
285    match self#get_term_by_id cic_info id with
286    | SelTerm (t, father_hyp) ->
287        let sequent = self#sequent_of_id ~paste_kind:`Term id in
288        let text = self#string_of_cic_sequent ~output_type:`Term sequent in
289        text
290    | SelHyp (hyp_name, _ctxt) -> hyp_name
291
292     (** @return a pattern structure which contains pretty printed terms *)
293   method private tactic_text_pattern_of_selection =
294     match self#get_selections with
295     | [] -> assert false (* this method is invoked only if there's a sel. *)
296     | node :: _ -> self#tactic_text_pattern_of_node node
297
298   method private popup_contextual_menu element time =
299     let menu = GMenu.menu () in
300     let add_menu_item ?(menu = menu) ?stock ?label () =
301       GMenu.image_menu_item ?stock ?label ~packing:menu#append () in
302     let check = add_menu_item ~label:"Check" () in
303     let reductions_menu_item = GMenu.menu_item ~label:"βδιζ-reduce" () in
304     let tactics_menu_item = GMenu.menu_item ~label:"Apply tactic" () in
305     let hyperlinks_menu_item = GMenu.menu_item ~label:"Hyperlinks" () in
306     menu#append reductions_menu_item;
307     menu#append tactics_menu_item;
308     menu#append hyperlinks_menu_item;
309     let reductions = GMenu.menu () in
310     let tactics = GMenu.menu () in
311     let hyperlinks = GMenu.menu () in
312     reductions_menu_item#set_submenu reductions;
313     tactics_menu_item#set_submenu tactics;
314     hyperlinks_menu_item#set_submenu hyperlinks;
315     let normalize = add_menu_item ~menu:reductions ~label:"Normalize" () in
316     let simplify = add_menu_item ~menu:reductions ~label:"Simplify" () in
317     let whd = add_menu_item ~menu:reductions ~label:"Weak head" () in
318     (match element with 
319     | None -> hyperlinks_menu_item#misc#set_sensitive false
320     | Some elt -> 
321         match hrefs_of_elt elt, href_callback with
322         | Some l, Some f ->
323             List.iter 
324               (fun h ->
325                 let item = add_menu_item ~menu:hyperlinks ~label:h () in
326                 connect_menu_item item (fun () -> f h)) l
327         | _ -> hyperlinks_menu_item#misc#set_sensitive false);
328     menu#append (GMenu.separator_item ());
329     let copy = add_menu_item ~stock:`COPY () in
330     let gui = get_gui () in
331     List.iter (fun item -> item#misc#set_sensitive gui#canCopy)
332       [ copy; check; normalize; simplify; whd ];
333     let reduction_action kind () =
334       let pat = self#tactic_text_pattern_of_selection in
335       let statement =
336         let loc = HExtlib.dummy_floc in
337         "\n" ^
338         GrafiteAstPp.pp_executable ~term_pp:(fun s -> s)
339           ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
340           ~map_unicode_to_tex:(Helm_registry.get_bool
341             "matita.paste_unicode_as_tex")
342           (GrafiteAst.Tactic (loc,
343             Some (GrafiteAst.Reduce (loc, kind, pat)),
344             GrafiteAst.Semicolon loc)) in
345       (MatitaScript.current ())#advance ~statement () in
346     connect_menu_item copy gui#copy;
347     connect_menu_item normalize (reduction_action `Normalize);
348     connect_menu_item simplify (reduction_action `Simpl);
349     connect_menu_item whd (reduction_action `Whd);
350     menu#popup ~button:right_button ~time
351
352   method private button_release_cb gdk_button =
353     if GdkEvent.Button.button gdk_button = left_button then begin
354       let button_release_x = GdkEvent.Button.x gdk_button in
355       let button_release_y = GdkEvent.Button.y gdk_button in
356       if selection_changed then
357         ()
358       else  (* selection _not_ changed *)
359         if near (button_press_x, button_press_y)
360           (button_release_x, button_release_y)
361         then
362           let x = int_of_float button_press_x in
363           let y = int_of_float button_press_y in
364           (match self#get_element_at x y with
365           | None -> ()
366           | Some elt ->
367               if has_maction elt then ignore(self#action_toggle elt) else
368               (match hrefs_of_elt elt with
369               | Some hrefs -> self#invoke_href_callback hrefs gdk_button
370               | None -> ()))
371     end;
372     false
373
374   method private invoke_href_callback hrefs gdk_button =
375     let button = GdkEvent.Button.button gdk_button in
376     if button = left_button then
377       let time = GdkEvent.Button.time gdk_button in
378       match href_callback with
379       | None -> ()
380       | Some f ->
381           (match hrefs with
382           | [ uri ] ->  f uri
383           | uris ->
384               let menu = GMenu.menu () in
385               List.iter
386                 (fun uri ->
387                   let menu_item =
388                     GMenu.menu_item ~label:uri ~packing:menu#append () in
389                   connect_menu_item menu_item 
390                   (fun () -> try f uri with Not_found -> assert false))
391                 uris;
392               menu#popup ~button ~time)
393
394   method private choose_selection_cb gdome_elt =
395     let set_selection elt =
396       let misc = self#coerce#misc in
397       self#set_selection (Some elt);
398       misc#add_selection_target ~target:"STRING" Gdk.Atom.primary;
399       ignore (misc#grab_selection Gdk.Atom.primary);
400     in
401     let rec aux elt =
402       if (elt#getAttributeNS ~namespaceURI:helm_ns
403             ~localName:xref_ds)#to_string <> ""
404       then
405         set_selection elt
406       else
407         try
408           (match elt#get_parentNode with
409           | None -> assert false
410           | Some p -> aux (new Gdome.element_of_node p))
411         with GdomeInit.DOMCastException _ -> ()
412     in
413     (match gdome_elt with
414     | Some elt when (elt#getAttributeNS ~namespaceURI:xlink_ns
415         ~localName:href_ds)#to_string <> "" ->
416           set_selection elt
417     | Some elt -> aux elt
418     | None -> self#set_selection None);
419     selection_changed <- true
420
421   method update_font_size = self#set_font_size !current_font_size
422
423     (** find a term by id from stored CIC infos @return either `Hyp if the id
424      * correspond to an hypothesis or `Term (cic, hyp) if the id correspond to a
425      * term. In the latter case hyp is either None (if the term is a subterm of
426      * the sequent conclusion) or Some hyp_name if the term belongs to an
427      * hypothesis *)
428   method private get_term_by_id cic_info id =
429     let unsh_item, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, _, _ =
430       cic_info in
431     let rec find_father_hyp id =
432       if Hashtbl.mem ids_to_hypotheses id
433       then Some (name_of_hypothesis (Hashtbl.find ids_to_hypotheses id))
434       else
435         let father_id =
436           try Hashtbl.find ids_to_father_ids id
437           with Not_found -> assert false in
438         match father_id with
439         | Some id -> find_father_hyp id
440         | None -> None
441     in
442     try
443       let term = Hashtbl.find ids_to_terms id in
444       let father_hyp = find_father_hyp id in
445       SelTerm (term, father_hyp)
446     with Not_found ->
447       try
448         let hyp = Hashtbl.find ids_to_hypotheses id in
449         let _, context, _ =
450           match unsh_item with Some seq -> seq | None -> assert false in
451         let context' = MatitaMisc.list_tl_at hyp context in
452         SelHyp (name_of_hypothesis hyp, context')
453       with Not_found -> assert false
454     
455   method private find_obj_conclusion id =
456     match self#cic_info with
457     | None
458     | Some (_, _, _, _, _, None) -> assert false
459     | Some (_, ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
460         let id =
461          find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
462         in
463          (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
464
465   method private string_of_node ~(paste_kind:paste_kind) node =
466     if node#hasAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds
467     then
468       match paste_kind with
469       | `Pattern ->
470           let tactic_text_pattern =  self#tactic_text_pattern_of_node node in
471           GrafiteAstPp.pp_tactic_pattern
472             ~term_pp:(fun s -> s) ~lazy_term_pp:(fun _ -> assert false)
473             ~map_unicode_to_tex:(Helm_registry.get_bool
474               "matita.paste_unicode_as_tex")
475             tactic_text_pattern
476       | `Term -> self#tactic_text_of_node node
477     else string_of_dom_node node
478
479   method private string_of_cic_sequent ~output_type cic_sequent =
480     let script = MatitaScript.current () in
481     let metasenv =
482       if script#onGoingProof () then script#proofMetasenv else [] in
483     let map_unicode_to_tex =
484       Helm_registry.get_bool "matita.paste_unicode_as_tex" in
485     ApplyTransformation.txt_of_cic_sequent_conclusion ~map_unicode_to_tex
486      ~output_type text_width metasenv cic_sequent
487
488   method private pattern_of term father_hyp unsh_sequent =
489     let _, unsh_context, conclusion = unsh_sequent in
490     let where =
491      match father_hyp with
492         None -> conclusion
493       | Some name ->
494          let rec aux =
495           function
496              [] -> assert false
497            | Some (Cic.Name name', Cic.Decl ty)::_ when name' = name -> ty
498            | Some (Cic.Name name', Cic.Def (bo,_))::_ when name' = name-> bo
499            | _::tl -> aux tl
500          in
501           aux unsh_context
502     in
503      ProofEngineHelpers.pattern_of ~term:where [term]
504
505   method private get_cic_info id =
506     match self#cic_info with
507     | Some ((Some unsh_sequent, _, _, _, _, _) as info) -> info, unsh_sequent
508     | Some ((None, _, _, _, _, _) as info) ->
509         let t = self#find_obj_conclusion id in
510         info, (~-1, [], t) (* dummy sequent for obj *)
511     | None -> assert false
512
513   method private sequent_of_id ~(paste_kind:paste_kind) id =
514     let cic_info, unsh_sequent = self#get_cic_info id in
515     let cic_sequent =
516       match self#get_term_by_id cic_info id with
517       | SelTerm (t, father_hyp) ->
518 (*
519 IDIOTA: PRIMA SI FA LA LOCATE, POI LA PATTERN_OF. MEGLIO UN'UNICA pattern_of CHE PRENDA IN INPUT UN TERMINE E UN SEQUENTE. PER IL MOMENTO RISOLVO USANDO LA father_hyp PER RITROVARE L'IPOTESI PERDUTA
520 *)
521           let occurrences =
522             ProofEngineHelpers.locate_in_conjecture t unsh_sequent in
523           (match occurrences with
524           | [ context, _t ] ->
525               (match paste_kind with
526               | `Term -> ~-1, context, t
527               | `Pattern -> ~-1, [], self#pattern_of t father_hyp unsh_sequent)
528           | _ ->
529               HLog.error (sprintf "found %d occurrences while 1 was expected"
530                 (List.length occurrences));
531               assert false) (* since it uses physical equality *)
532       | SelHyp (_name, context) -> ~-1, context, Cic.Rel 1 in
533     cic_sequent
534
535   method private string_of_selection ~(paste_kind:paste_kind) =
536     match self#get_selections with
537     | [] -> None
538     | node :: _ -> Some (self#string_of_node ~paste_kind node)
539
540   method has_selection = self#get_selections <> []
541
542     (** @return an associative list format -> string with all possible selection
543      * formats. Rationale: in order to convert the selection to TERM or PATTERN
544      * format we need the sequent, the metasenv, ... keeping all of them in a
545      * closure would be more expensive than keeping their already converted
546      * forms *)
547   method strings_of_selection =
548     try
549       let misc = self#coerce#misc in
550       List.iter
551         (fun target -> misc#add_selection_target ~target Gdk.Atom.clipboard)
552         [ "TERM"; "PATTERN"; "STRING" ];
553       ignore (misc#grab_selection Gdk.Atom.clipboard);
554       List.map
555         (fun paste_kind ->
556           paste_kind, HExtlib.unopt (self#string_of_selection ~paste_kind))
557         [ `Term; `Pattern ]
558     with Failure _ -> failwith "no selection"
559
560 end
561
562 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
563   GtkBase.Widget.size_params
564     ~cont:(OgtkMathViewProps.pack_return (fun p ->
565       OgtkMathViewProps.set_params
566         (new clickableMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
567         ~font_size:None ~log_verbosity:None))
568     []
569
570 class cicMathView obj =
571 object (self)
572   inherit clickableMathView obj
573
574   val mutable current_mathml = None
575
576   method load_sequent metasenv metano =
577     let sequent = CicUtil.lookup_meta metano metasenv in
578     let (mathml, unsh_sequent,
579       (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ )))
580     =
581       ApplyTransformation.mml_of_cic_sequent metasenv sequent
582     in
583     self#set_cic_info
584       (Some (Some unsh_sequent,
585         ids_to_terms, ids_to_hypotheses, ids_to_father_ids,
586         Hashtbl.create 1, None));
587     if BuildTimeConf.debug then begin
588       let name =
589        "/tmp/sequent_viewer_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
590       HLog.debug ("load_sequent: dumping MathML to ./" ^ name);
591       ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
592     end;
593     self#load_root ~root:mathml#get_documentElement
594
595   method load_object obj =
596     let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
597     let (mathml,
598       (annobj, (ids_to_terms, ids_to_father_ids, _, ids_to_hypotheses, _, ids_to_inner_types)))
599     =
600       ApplyTransformation.mml_of_cic_object obj
601     in
602     self#set_cic_info
603       (Some (None, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
604     (match current_mathml with
605     | Some current_mathml when use_diff ->
606         self#freeze;
607         XmlDiff.update_dom ~from:current_mathml mathml;
608         self#thaw
609     |  _ ->
610         if BuildTimeConf.debug then begin
611           let name =
612            "/tmp/cic_browser_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
613           HLog.debug ("cic_browser: dumping MathML to ./" ^ name);
614           ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
615         end;
616         self#load_root ~root:mathml#get_documentElement;
617         current_mathml <- Some mathml);
618 end
619
620 let tab_label meta_markup =
621   let rec aux =
622     function
623     | `Closed m -> sprintf "<s>%s</s>" (aux m)
624     | `Current m -> sprintf "<b>%s</b>" (aux m)
625     | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
626     | `Meta n -> sprintf "?%d" n
627   in
628   let markup = aux meta_markup in
629   (GMisc.label ~markup ~show:true ())#coerce
630
631 let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
632
633 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
634   object (self)
635     inherit scriptAccessor
636
637     method cicMathView = cicMathView  (** clickableMathView accessor *)
638
639     val mutable pages = 0
640     val mutable switch_page_callback = None
641     val mutable page2goal = []  (* associative list: page no -> goal no *)
642     val mutable goal2page = []  (* the other way round *)
643     val mutable goal2win = []   (* associative list: goal no -> scrolled win *)
644     val mutable _metasenv = []
645     val mutable scrolledWin: GBin.scrolled_window option = None
646       (* scrolled window to which the sequentViewer is currently attached *)
647     val logo = (GMisc.image
648       ~file:(MatitaMisc.image_path "matita_medium.png") ()
649       :> GObj.widget)
650             
651     val logo_with_qed = (GMisc.image
652       ~file:(MatitaMisc.image_path "matita_small.png") ()
653       :> GObj.widget)
654
655     method load_logo =
656      notebook#set_show_tabs false;
657      ignore(notebook#append_page logo)
658
659     method load_logo_with_qed =
660      notebook#set_show_tabs false;
661      ignore(notebook#append_page logo_with_qed)
662
663     method reset =
664       cicMathView#remove_selections;
665       (match scrolledWin with
666       | Some w ->
667           (* removing page from the notebook will destroy all contained widget,
668           * we do not want the cicMathView to be destroyed as well *)
669           w#remove cicMathView#coerce;
670           scrolledWin <- None
671       | None -> ());
672       (match switch_page_callback with
673       | Some id ->
674           GtkSignal.disconnect notebook#as_widget id;
675           switch_page_callback <- None
676       | None -> ());
677       for i = 0 to pages do notebook#remove_page 0 done; 
678       notebook#set_show_tabs true;
679       pages <- 0;
680       page2goal <- [];
681       goal2page <- [];
682       goal2win <- [];
683       _metasenv <- []; 
684       self#script#setGoal None
685
686     method load_sequents 
687       { proof = (_,metasenv,_subst,_,_, _) as proof; stack = stack } 
688     =
689       _metasenv <- metasenv;
690       pages <- 0;
691       let win goal_switch =
692         let w =
693           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
694             ~shadow_type:`IN ~show:true ()
695         in
696         let reparent () =
697           scrolledWin <- Some w;
698           match cicMathView#misc#parent with
699           | None -> w#add cicMathView#coerce
700           | Some parent ->
701              let parent =
702               match cicMathView#misc#parent with
703                  None -> assert false
704                | Some p -> GContainer.cast_container p
705              in
706               parent#remove cicMathView#coerce;
707               w#add cicMathView#coerce
708         in
709         goal2win <- (goal_switch, reparent) :: goal2win;
710         w#coerce
711       in
712       assert (
713         let stack_goals = Stack.open_goals stack in
714         let proof_goals = ProofEngineTypes.goals_of_proof proof in
715         if
716           HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
717           <> List.sort Pervasives.compare proof_goals
718         then begin
719           prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
720           prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
721           false
722         end
723         else true
724       );
725       let render_switch =
726         function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
727       in
728       let page = ref 0 in
729       let added_goals = ref [] in
730         (* goals can be duplicated on the tack due to focus, but we should avoid
731          * multiple labels in the user interface *)
732       let add_tab markup goal_switch =
733         let goal = Stack.goal_of_switch goal_switch in
734         if not (List.mem goal !added_goals) then begin
735           ignore(notebook#append_page 
736             ~tab_label:(tab_label markup) (win goal_switch));
737           page2goal <- (!page, goal_switch) :: page2goal;
738           goal2page <- (goal_switch, !page) :: goal2page;
739           incr page;
740           pages <- pages + 1;
741           added_goals := goal :: !added_goals
742         end
743       in
744       let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
745       Stack.iter  (** populate notebook with tabs *)
746         ~env:(fun depth tag (pos, sw) ->
747           let markup =
748             match depth, pos with
749             | 0, 0 -> `Current (render_switch sw)
750             | 0, _ -> `Shift (pos, `Current (render_switch sw))
751             | 1, pos when Stack.head_tag stack = `BranchTag ->
752                 `Shift (pos, render_switch sw)
753             | _ -> render_switch sw
754           in
755           add_tab markup sw)
756         ~cont:add_switch ~todo:add_switch
757         stack;
758       switch_page_callback <-
759         Some (notebook#connect#switch_page ~callback:(fun page ->
760           let goal_switch =
761             try List.assoc page page2goal with Not_found -> assert false
762           in
763           self#script#setGoal (Some (goal_of_switch goal_switch));
764           self#render_page ~page ~goal_switch))
765
766     method private render_page ~page ~goal_switch =
767       (match goal_switch with
768       | Stack.Open goal -> cicMathView#load_sequent _metasenv goal
769       | Stack.Closed goal ->
770           let doc = Lazy.force closed_goal_mathml in
771           cicMathView#load_root ~root:doc#get_documentElement);
772       (try
773         cicMathView#set_selection None;
774         List.assoc goal_switch goal2win ()
775       with Not_found -> assert false)
776
777     method goto_sequent goal =
778       let goal_switch, page =
779         try
780           List.find
781             (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
782             goal2page
783         with Not_found -> assert false
784       in
785       notebook#goto_page page;
786       self#render_page page goal_switch
787
788   end
789
790  (** constructors *)
791
792 type 'widget constructor =
793   ?hadjustment:GData.adjustment ->
794   ?vadjustment:GData.adjustment ->
795   ?font_size:int ->
796   ?log_verbosity:int ->
797   ?width:int ->
798   ?height:int ->
799   ?packing:(GObj.widget -> unit) ->
800   ?show:bool ->
801   unit ->
802     'widget
803
804 let cicMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
805   GtkBase.Widget.size_params
806     ~cont:(OgtkMathViewProps.pack_return (fun p ->
807       OgtkMathViewProps.set_params
808         (new cicMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
809         ~font_size ~log_verbosity))
810     []
811
812 let blank_uri = BuildTimeConf.blank_uri
813 let current_proof_uri = BuildTimeConf.current_proof_uri
814
815 type term_source =
816   [ `Ast of CicNotationPt.term
817   | `Cic of Cic.term * Cic.metasenv
818   | `String of string
819   ]
820
821 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
822   ()
823 =
824   let whelp_RE = Pcre.regexp "^\\s*whelp" in
825   let uri_RE =
826     Pcre.regexp
827       "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
828   in
829   let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
830   let metadata_RE = Pcre.regexp "^metadata:/(deps)/(forward|backward)/(.*)$" in
831   let whelp_query_RE = Pcre.regexp
832     "^\\s*whelp\\s+([^\\s]+)\\s+(\"|\\()(.*)(\\)|\")$" 
833   in
834   let is_metadata txt = Pcre.pmatch ~rex:metadata_RE txt in
835   let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
836   let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
837   let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
838   let gui = get_gui () in
839   let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
840   let gviz = LablGraphviz.graphviz ~packing:win#graphScrolledWin#add () in
841   let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
842   let combo,_ = GEdit.combo_box_text ~strings:queries () in
843   let activate_combo_query input q =
844     let q' = String.lowercase q in
845     let rec aux i = function
846       | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
847       | h::_ when String.lowercase h = q' -> i
848       | _::tl -> aux (i+1) tl
849     in
850     win#queryInputText#set_text input;
851     combo#set_active (aux 0 queries);
852   in
853   let searchText = 
854     GSourceView.source_view ~auto_indent:false ~editable:false ()
855   in
856   let _ =
857      win#scrolledwinContent#add (searchText :> GObj.widget);
858      let callback () = 
859        let text = win#entrySearch#text in
860        let highlight start end_ =
861          searchText#source_buffer#move_mark `INSERT ~where:start;
862          searchText#source_buffer#move_mark `SEL_BOUND ~where:end_;
863          searchText#scroll_mark_onscreen `INSERT
864        in
865        let iter = searchText#source_buffer#get_iter `SEL_BOUND in
866        match iter#forward_search text with
867        | None -> 
868            (match searchText#source_buffer#start_iter#forward_search text with
869            | None -> ()
870            | Some (start,end_) -> highlight start end_)
871        | Some (start,end_) -> highlight start end_
872      in
873      ignore(win#entrySearch#connect#activate ~callback);
874      ignore(win#buttonSearch#connect#clicked ~callback);
875   in
876   let set_whelp_query txt =
877     let query, arg = 
878       try
879         let q = Pcre.extract ~rex:whelp_query_RE txt in
880         q.(1), q.(3)
881       with Not_found -> failwith "Malformed Whelp query"
882     in
883     activate_combo_query arg query;
884   in
885   let toplevel = win#toplevel in
886   let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
887   let fail message = 
888     MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
889       ~parent:toplevel ()  
890   in
891   let tags =
892     [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
893       "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
894   in
895   let b = (not (Helm_registry.get_bool "matita.debug")) in
896   let handle_error f =
897     try
898       f ()
899     with exn ->
900       if b then
901         fail (snd (MatitaExcPp.to_string exn))
902       else raise exn
903   in
904   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
905   let load_easter_egg = lazy (
906     win#browserImage#set_file (MatitaMisc.image_path "meegg.png"))
907   in
908   let load_coerchgraph tred () = 
909       let str = CoercGraph.generate_dot_file () in
910       let filename, oc = Filename.open_temp_file "matita" ".dot" in
911       output_string oc str;
912       close_out oc;
913       if tred then
914         gviz#load_graph_from_file ~gviz_cmd:"tred|dot" filename
915       else
916         gviz#load_graph_from_file filename;
917       HExtlib.safe_remove filename
918   in
919   object (self)
920     inherit scriptAccessor
921     
922     (* Whelp bar queries *)
923
924     val mutable gviz_graph = MetadataDeps.DepGraph.dummy
925     val mutable gviz_uri = UriManager.uri_of_string "cic:/dummy.con";
926
927     val dep_contextual_menu = GMenu.menu ()
928
929     initializer
930       activate_combo_query "" "locate";
931       win#whelpBarComboVbox#add combo#coerce;
932       let start_query () = 
933        let query = 
934          try
935            String.lowercase (List.nth queries combo#active) 
936          with Not_found -> assert false in
937        let input = win#queryInputText#text in
938        let statement = 
939          if query = "locate" then
940              "whelp " ^ query ^ " \"" ^ input ^ "\"." 
941            else
942              "whelp " ^ query ^ " (" ^ input ^ ")." 
943        in
944         (MatitaScript.current ())#advance ~statement ()
945       in
946       ignore(win#queryInputText#connect#activate ~callback:start_query);
947       ignore(combo#connect#changed ~callback:start_query);
948       win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
949       win#mathOrListNotebook#set_show_tabs false;
950       win#browserForwardButton#misc#set_sensitive false;
951       win#browserBackButton#misc#set_sensitive false;
952       ignore (win#browserUri#connect#activate (handle_error' (fun () ->
953         self#loadInput win#browserUri#text)));
954       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
955         self#load (`About `Current_proof))));
956       ignore (win#browserRefreshButton#connect#clicked
957         (handle_error' (self#refresh ~force:true)));
958       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
959       ignore (win#browserForwardButton#connect#clicked
960         (handle_error' self#forward));
961       ignore (win#toplevel#event#connect#delete (fun _ ->
962         let my_id = Oo.id self in
963         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
964         false));
965       ignore(win#whelpResultTreeview#connect#row_activated 
966         ~callback:(fun _ _ ->
967           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
968       mathView#set_href_callback (Some (fun uri ->
969         handle_error (fun () ->
970           self#load (`Uri (UriManager.uri_of_string uri)))));
971       gviz#connect_href (fun button_ev attrs ->
972         let time = GdkEvent.Button.time button_ev in
973         let uri = List.assoc "href" attrs in
974         gviz_uri <- UriManager.uri_of_string uri;
975         match GdkEvent.Button.button button_ev with
976         | button when button = left_button -> self#load (`Uri gviz_uri)
977         | button when button = right_button ->
978             dep_contextual_menu#popup ~button ~time
979         | _ -> ());
980       connect_menu_item win#depGraphMenuItem (fun () ->
981         match self#currentCicUri with
982         | Some uri -> self#load (`Metadata (`Deps (`Fwd, uri)))
983         | None -> ());
984       connect_menu_item win#invDepGraphMenuItem (fun () ->
985         match self#currentCicUri with
986         | Some uri -> self#load (`Metadata (`Deps (`Back, uri)))
987         | None -> ());
988       connect_menu_item win#browserCloseMenuItem (fun () ->
989         let my_id = Oo.id self in
990         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
991         win#toplevel#misc#hide(); win#toplevel#destroy ());
992       (* remove hbugs *)
993       (*
994       connect_menu_item win#hBugsTutorsMenuItem (fun () ->
995         self#load (`HBugs `Tutors));
996       *)
997       win#hBugsTutorsMenuItem#misc#hide ();
998       connect_menu_item win#browserUrlMenuItem (fun () ->
999         win#browserUri#misc#grab_focus ());
1000       connect_menu_item win#univMenuItem (fun () ->
1001         match self#currentCicUri with
1002         | Some uri -> self#load (`Univs uri)
1003         | None -> ());
1004
1005       (* fill dep graph contextual menu *)
1006       let go_menu_item =
1007         GMenu.image_menu_item ~label:"Browse it"
1008           ~packing:dep_contextual_menu#append () in
1009       let expand_menu_item =
1010         GMenu.image_menu_item ~label:"Expand"
1011           ~packing:dep_contextual_menu#append () in
1012       let collapse_menu_item =
1013         GMenu.image_menu_item ~label:"Collapse"
1014           ~packing:dep_contextual_menu#append () in
1015       dep_contextual_menu#append (go_menu_item :> GMenu.menu_item);
1016       dep_contextual_menu#append (expand_menu_item :> GMenu.menu_item);
1017       dep_contextual_menu#append (collapse_menu_item :> GMenu.menu_item);
1018       connect_menu_item go_menu_item (fun () -> self#load (`Uri gviz_uri));
1019       connect_menu_item expand_menu_item (fun () ->
1020         MetadataDeps.DepGraph.expand gviz_uri gviz_graph;
1021         self#redraw_gviz ~center_on:gviz_uri ());
1022       connect_menu_item collapse_menu_item (fun () ->
1023         MetadataDeps.DepGraph.collapse gviz_uri gviz_graph;
1024         self#redraw_gviz ~center_on:gviz_uri ());
1025
1026       self#_load (`About `Blank);
1027       toplevel#show ()
1028
1029     val mutable current_entry = `About `Blank 
1030
1031       (** @return None if no object uri can be built from the current entry *)
1032     method private currentCicUri =
1033       match current_entry with
1034       | `Uri uri
1035       | `Metadata (`Deps (_, uri)) -> Some uri
1036       | _ -> None
1037
1038     val model =
1039       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
1040     val model_univs =
1041       new MatitaGtkMisc.multiStringListModel ~cols:2 win#universesTreeview
1042
1043     val mutable lastDir = ""  (* last loaded "directory" *)
1044
1045     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
1046
1047     method private _getSelectedUri () =
1048       match model#easy_selection () with
1049       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
1050 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
1051       | [sel] -> lastDir ^ sel
1052       | _ -> assert false
1053
1054     (** history RATIONALE 
1055      *
1056      * All operations about history are done using _historyFoo.
1057      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
1058      *)
1059           
1060     method private _historyAdd item = 
1061       history#add item;
1062       win#browserBackButton#misc#set_sensitive true;
1063       win#browserForwardButton#misc#set_sensitive false
1064
1065     method private _historyPrev () =
1066       let item = history#previous in
1067       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
1068       win#browserForwardButton#misc#set_sensitive true;
1069       item
1070     
1071     method private _historyNext () =
1072       let item = history#next in
1073       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
1074       win#browserBackButton#misc#set_sensitive true;
1075       item
1076
1077     (** notebook RATIONALE 
1078      * 
1079      * Use only these functions to switch between the tabs
1080      *)
1081     method private _showMath = win#mathOrListNotebook#goto_page  0
1082     method private _showList = win#mathOrListNotebook#goto_page  1
1083     method private _showList2 = win#mathOrListNotebook#goto_page 5
1084     method private _showSearch = win#mathOrListNotebook#goto_page 6
1085     method private _showGviz = win#mathOrListNotebook#goto_page  3
1086     method private _showHBugs = win#mathOrListNotebook#goto_page 4
1087
1088     method private back () =
1089       try
1090         self#_load (self#_historyPrev ())
1091       with MatitaMisc.History_failure -> ()
1092
1093     method private forward () =
1094       try
1095         self#_load (self#_historyNext ())
1096       with MatitaMisc.History_failure -> ()
1097
1098       (* loads a uri which can be a cic uri or an about:* uri
1099       * @param uri string *)
1100     method private _load ?(force=false) entry =
1101       handle_error (fun () ->
1102        if entry <> current_entry || entry = `About `Current_proof || entry =
1103          `About `Coercions || entry = `About `CoercionsFull || force then
1104         begin
1105           (match entry with
1106           | `About `Current_proof -> self#home ()
1107           | `About `Blank -> self#blank ()
1108           | `About `Us -> self#egg ()
1109           | `About `CoercionsFull -> self#coerchgraph false ()
1110           | `About `Coercions -> self#coerchgraph true ()
1111           | `About `TeX -> self#tex ()
1112           | `About `Grammar -> self#grammar () 
1113           | `Check term -> self#_loadCheck term
1114           | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
1115           | `Dir dir -> self#_loadDir dir
1116           | `HBugs `Tutors -> self#_loadHBugsTutors
1117           | `Metadata (`Deps ((`Fwd | `Back) as dir, uri)) ->
1118               self#dependencies dir uri ()
1119           | `Uri uri -> self#_loadUriManagerUri uri
1120           | `Univs uri -> self#_loadUnivs uri
1121           | `Whelp (query, results) -> 
1122               set_whelp_query query;
1123               self#_loadList (List.map (fun r -> "obj",
1124                 UriManager.string_of_uri r) results));
1125           self#setEntry entry
1126         end)
1127
1128     method private blank () =
1129       self#_showMath;
1130       mathView#load_root (Lazy.force empty_mathml)#get_documentElement
1131
1132     method private _loadCheck term =
1133       failwith "not implemented _loadCheck";
1134 (*       self#_showMath *)
1135
1136     method private egg () =
1137       win#mathOrListNotebook#goto_page 2;
1138       Lazy.force load_easter_egg
1139
1140     method private redraw_gviz ?center_on () =
1141       if Sys.command "which dot" = 0 then
1142        let tmpfile, oc = Filename.open_temp_file "matita" ".dot" in
1143        let fmt = Format.formatter_of_out_channel oc in
1144        MetadataDeps.DepGraph.render fmt gviz_graph;
1145        close_out oc;
1146        gviz#load_graph_from_file ~gviz_cmd:"tred | dot" tmpfile;
1147        (match center_on with
1148        | None -> ()
1149        | Some uri -> gviz#center_on_href (UriManager.string_of_uri uri));
1150        HExtlib.safe_remove tmpfile
1151       else
1152        MatitaGtkMisc.report_error ~title:"graphviz error"
1153         ~message:("Graphviz is not installed but is necessary to render "^
1154          "the graph of dependencies amoung objects. Please install it.")
1155         ~parent:win#toplevel ()
1156
1157     method private dependencies direction uri () =
1158       let dbd = LibraryDb.instance () in
1159       let graph =
1160         match direction with
1161         | `Fwd -> MetadataDeps.DepGraph.direct_deps ~dbd uri
1162         | `Back -> MetadataDeps.DepGraph.inverse_deps ~dbd uri in
1163       gviz_graph <- graph;  (** XXX check this for memory consuption *)
1164       self#redraw_gviz ~center_on:uri ();
1165       self#_showGviz
1166
1167     method private coerchgraph tred () =
1168       load_coerchgraph tred ();
1169       self#_showGviz
1170
1171     method private tex () =
1172       let b = Buffer.create 1000 in
1173       Printf.bprintf b "UTF-8 equivalence classes (rotate with ALT-L):\n\n";
1174       List.iter 
1175         (fun l ->
1176            List.iter (fun sym ->
1177              Printf.bprintf b "  %s" (Glib.Utf8.from_unichar sym) 
1178            ) l;
1179            Printf.bprintf b "\n";
1180         )
1181         (List.sort 
1182           (fun l1 l2 -> compare (List.hd l1) (List.hd l2))
1183           (Virtuals.get_all_eqclass ()));
1184       Printf.bprintf b "\n\nVirtual keys (trigger with ALT-L):\n\n";
1185       List.iter 
1186         (fun tag, items -> 
1187            Printf.bprintf b "  %s:\n" tag;
1188            List.iter 
1189              (fun names, symbol ->
1190                 Printf.bprintf b "  \t%s\t%s\n" 
1191                   (Glib.Utf8.from_unichar symbol)
1192                   (String.concat ", " names))
1193              (List.sort 
1194                (fun (_,a) (_,b) -> compare a b)
1195                items);
1196            Printf.bprintf b "\n")
1197         (List.sort 
1198           (fun (a,_) (b,_) -> compare a b)
1199           (Virtuals.get_all_virtuals ()));
1200       self#_loadText (Buffer.contents b)
1201
1202     method private _loadText text =
1203       searchText#source_buffer#set_text text;
1204       win#entrySearch#misc#grab_focus ();
1205       self#_showSearch
1206
1207     method private grammar () =
1208       self#_loadText (Print_grammar.ebnf_of_term ());
1209
1210     method private home () =
1211       self#_showMath;
1212       match self#script#grafite_status.proof_status with
1213       | Proof  (uri, metasenv, _subst, bo, ty, attrs) ->
1214           let name = UriManager.name_of_uri (HExtlib.unopt uri) in
1215           let obj = Cic.CurrentProof (name, metasenv, Lazy.force bo, ty, [], attrs) in
1216           self#_loadObj obj
1217       | Incomplete_proof { proof = (uri, metasenv, _subst, bo, ty, attrs) } ->
1218           let name = UriManager.name_of_uri (HExtlib.unopt uri) in
1219           let obj = Cic.CurrentProof (name, metasenv, Lazy.force bo, ty, [], attrs) in
1220           self#_loadObj obj
1221       | _ -> self#blank ()
1222
1223       (** loads a cic uri from the environment
1224       * @param uri UriManager.uri *)
1225     method private _loadUriManagerUri uri =
1226       let uri = UriManager.strip_xpointer uri in
1227       let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1228       self#_loadObj obj
1229
1230     method private _loadUnivs uri =
1231       let uri = UriManager.strip_xpointer uri in
1232       let (_, u) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1233       let _,us = CicUniv.do_rank u in
1234       let l = 
1235         List.map 
1236           (fun u -> 
1237            [ CicUniv.string_of_universe u ; string_of_int (CicUniv.get_rank u)])
1238           us 
1239       in
1240       self#_loadList2 l
1241       
1242     method private _loadDir dir = 
1243       let content = Http_getter.ls ~local:false dir in
1244       let l =
1245         List.fast_sort
1246           Pervasives.compare
1247           (List.map
1248             (function 
1249               | Http_getter_types.Ls_section s -> "dir", s
1250               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
1251             content)
1252       in
1253       lastDir <- dir;
1254       self#_loadList l
1255
1256     method private _loadHBugsTutors =
1257       self#_showHBugs
1258
1259     method private setEntry entry =
1260       win#browserUri#set_text (MatitaTypes.string_of_entry entry);
1261       current_entry <- entry
1262
1263     method private _loadObj obj =
1264       (* showMath must be done _before_ loading the document, since if the
1265        * widget is not mapped (hidden by the notebook) the document is not
1266        * rendered *)
1267       self#_showMath;
1268       mathView#load_object obj
1269
1270     method private _loadTermCic term metasenv =
1271       let context = self#script#proofContext in
1272       let dummyno = CicMkImplicit.new_meta metasenv [] in
1273       let sequent = (dummyno, context, term) in
1274       mathView#load_sequent (sequent :: metasenv) dummyno;
1275       self#_showMath
1276
1277     method private _loadList l =
1278       model#list_store#clear ();
1279       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
1280       self#_showList
1281
1282     method private _loadList2 l =
1283       model_univs#list_store#clear ();
1284       List.iter model_univs#easy_mappend l;
1285       self#_showList2
1286     
1287     (** { public methods, all must call _load!! } *)
1288       
1289     method load entry =
1290       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
1291
1292     (**  this is what the browser does when you enter a string an hit enter *)
1293     method loadInput txt =
1294       let parse_metadata s =
1295         let subs = Pcre.extract ~rex:metadata_RE s in
1296         let uri = UriManager.uri_of_string ("cic:/" ^ subs.(3)) in
1297         match subs.(1), subs.(2) with
1298         | "deps", "forward" -> `Deps (`Fwd, uri)
1299         | "deps", "backward" -> `Deps (`Back, uri)
1300         | _ -> assert false
1301       in
1302       let txt = HExtlib.trim_blanks txt in
1303       (* (* ZACK: what the heck? *)
1304       let fix_uri txt =
1305         UriManager.string_of_uri
1306           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
1307       in
1308       *)
1309       if is_whelp txt then begin
1310         set_whelp_query txt;  
1311         (MatitaScript.current ())#advance ~statement:(txt ^ ".") ()
1312       end else begin
1313         let entry =
1314           match txt with
1315           | txt when is_uri txt ->
1316               `Uri (UriManager.uri_of_string ((*fix_uri*) txt))
1317           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
1318           | txt when is_metadata txt -> `Metadata (parse_metadata txt)
1319           | "hbugs:/tutors/" -> `HBugs `Tutors
1320           | txt ->
1321              (try
1322                MatitaTypes.entry_of_string txt
1323               with Invalid_argument _ ->
1324                raise
1325                 (GrafiteTypes.Command_error(sprintf "unsupported uri: %s" txt)))
1326         in
1327         self#_load entry;
1328         self#_historyAdd entry
1329       end
1330
1331       (** {2 methods accessing underlying GtkMathView} *)
1332
1333     method updateFontSize = mathView#set_font_size !current_font_size
1334
1335       (** {2 methods used by constructor only} *)
1336
1337     method win = win
1338     method history = history
1339     method currentEntry = current_entry
1340     method refresh ~force () = self#_load ~force current_entry
1341
1342   end
1343   
1344 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
1345   MatitaGuiTypes.sequentsViewer
1346 =
1347   new sequentsViewer ~notebook ~cicMathView ()
1348
1349 let cicBrowser () =
1350   let size = BuildTimeConf.browser_history_size in
1351   let rec aux history =
1352     let browser = new cicBrowser_impl ~history () in
1353     let win = browser#win in
1354     ignore (win#browserNewButton#connect#clicked (fun () ->
1355       let history =
1356         new MatitaMisc.browser_history ~memento:history#save size
1357           (`About `Blank)
1358       in
1359       let newBrowser = aux history in
1360       newBrowser#load browser#currentEntry));
1361 (*
1362       (* attempt (failed) to close windows on CTRL-W ... *)
1363     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
1364       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
1365 *)
1366     cicBrowsers := browser :: !cicBrowsers;
1367     (browser :> MatitaGuiTypes.cicBrowser)
1368   in
1369   let history = new MatitaMisc.browser_history size (`About `Blank) in
1370   aux history
1371
1372 let default_cicMathView () = cicMathView ~show:true ()
1373 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
1374
1375 let default_sequentsViewer () =
1376   let gui = get_gui () in
1377   let cicMathView = cicMathView_instance () in
1378   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
1379 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
1380
1381 let mathViewer () = 
1382   object(self)
1383     method private get_browser reuse = 
1384       if reuse then
1385         (match !cicBrowsers with
1386         | [] -> cicBrowser ()
1387         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
1388       else
1389         (cicBrowser ())
1390           
1391     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
1392       
1393     method show_uri_list ?(reuse=false) ~entry l =
1394       (self#get_browser reuse)#load entry
1395   end
1396
1397 let refresh_all_browsers () =
1398   List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
1399
1400 let update_font_sizes () =
1401   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
1402   (cicMathView_instance ())#update_font_size
1403
1404 let get_math_views () =
1405   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
1406   :: (List.map (fun b -> b#mathView) !cicBrowsers)
1407
1408 let find_selection_owner () =
1409   let rec aux =
1410     function
1411     | [] -> raise Not_found
1412     | mv :: tl ->
1413         (match mv#get_selections with
1414         | [] -> aux tl
1415         | sel :: _ -> mv)
1416   in
1417   aux (get_math_views ())
1418
1419 let has_selection () =
1420   try ignore (find_selection_owner ()); true
1421   with Not_found -> false
1422
1423 let math_view_clipboard = ref None (* associative list target -> string *)
1424 let has_clipboard () = !math_view_clipboard <> None
1425 let empty_clipboard () = math_view_clipboard := None
1426
1427 let copy_selection () =
1428   try
1429     math_view_clipboard :=
1430       Some ((find_selection_owner ())#strings_of_selection)
1431   with Not_found -> failwith "no selection"
1432
1433 let paste_clipboard paste_kind =
1434   match !math_view_clipboard with
1435   | None -> failwith "empty clipboard"
1436   | Some cb ->
1437       (try List.assoc paste_kind cb with Not_found -> assert false)
1438