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