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