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