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