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