]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaMathView.ml
280ade3ee11ac559fa3494d0fe2e4d81175a8bb8
[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. #LexiconTypes.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. #LexiconTypes.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 : #NTacStatus.tac_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. #LexiconTypes.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. #LexiconTypes.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       connect_menu_item win#browserUrlMenuItem (fun () ->
1040         win#browserUri#misc#grab_focus ());
1041
1042       self#_load (`About `Blank);
1043       toplevel#show ()
1044
1045     val mutable current_entry = `About `Blank 
1046
1047       (** @return None if no object uri can be built from the current entry *)
1048     method private currentCicUri =
1049       match current_entry with
1050       | `NRef uri -> Some uri
1051       | _ -> None
1052
1053     val model =
1054       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
1055     val model_univs =
1056       new MatitaGtkMisc.multiStringListModel ~cols:2 win#universesTreeview
1057
1058     val mutable lastDir = ""  (* last loaded "directory" *)
1059
1060     method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
1061
1062     method private _getSelectedUri () =
1063       match model#easy_selection () with
1064       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
1065 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
1066       | [sel] -> lastDir ^ sel
1067       | _ -> assert false
1068
1069     (** history RATIONALE 
1070      *
1071      * All operations about history are done using _historyFoo.
1072      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
1073      *)
1074           
1075     method private _historyAdd item = 
1076       history#add item;
1077       win#browserBackButton#misc#set_sensitive true;
1078       win#browserForwardButton#misc#set_sensitive false
1079
1080     method private _historyPrev () =
1081       let item = history#previous in
1082       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
1083       win#browserForwardButton#misc#set_sensitive true;
1084       item
1085     
1086     method private _historyNext () =
1087       let item = history#next in
1088       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
1089       win#browserBackButton#misc#set_sensitive true;
1090       item
1091
1092     (** notebook RATIONALE 
1093      * 
1094      * Use only these functions to switch between the tabs
1095      *)
1096     method private _showMath = win#mathOrListNotebook#goto_page  0
1097     method private _showList = win#mathOrListNotebook#goto_page  1
1098     method private _showList2 = win#mathOrListNotebook#goto_page 5
1099     method private _showSearch = win#mathOrListNotebook#goto_page 6
1100     method private _showGviz = win#mathOrListNotebook#goto_page  3
1101
1102     method private back () =
1103       try
1104         self#_load (self#_historyPrev ())
1105       with MatitaMisc.History_failure -> ()
1106
1107     method private forward () =
1108       try
1109         self#_load (self#_historyNext ())
1110       with MatitaMisc.History_failure -> ()
1111
1112       (* loads a uri which can be a cic uri or an about:* uri
1113       * @param uri string *)
1114     method private _load ?(force=false) entry =
1115       handle_error (fun () ->
1116        if entry <> current_entry || entry = `About `Current_proof || entry =
1117          `About `Coercions || entry = `About `CoercionsFull || force then
1118         begin
1119           (match entry with
1120           | `About `Current_proof -> self#home ()
1121           | `About `Blank -> self#blank ()
1122           | `About `Us -> self#egg ()
1123           | `About `CoercionsFull -> self#coerchgraph false ()
1124           | `About `Coercions -> self#coerchgraph true ()
1125           | `About `Hints -> self#hints ()
1126           | `About `TeX -> self#tex ()
1127           | `About `Grammar -> self#grammar () 
1128           | `Check term -> self#_loadCheck term
1129           | `NCic (term, ctx, metasenv, subst) -> 
1130                self#_loadTermNCic term metasenv subst ctx
1131           | `Dir dir -> self#_loadDir dir
1132           | `NRef nref -> self#_loadNReference nref);
1133           self#setEntry entry
1134         end)
1135
1136     method private blank () =
1137       self#_showMath;
1138       mathView#load_root ""
1139
1140     method private _loadCheck term =
1141       failwith "not implemented _loadCheck";
1142 (*       self#_showMath *)
1143
1144     method private egg () =
1145       win#mathOrListNotebook#goto_page 2;
1146       Lazy.force load_easter_egg
1147
1148     method private redraw_gviz ?center_on () =
1149       if Sys.command "which dot" = 0 then
1150        let tmpfile, oc = Filename.open_temp_file "matita" ".dot" in
1151        let fmt = Format.formatter_of_out_channel oc in
1152        (* MATITA 1.0 MetadataDeps.DepGraph.render fmt gviz_graph;*)
1153        close_out oc;
1154        gviz#load_graph_from_file ~gviz_cmd:"tred | dot" tmpfile;
1155        (match center_on with
1156        | None -> ()
1157        | Some uri -> gviz#center_on_href (NReference.string_of_reference uri));
1158        HExtlib.safe_remove tmpfile
1159       else
1160        MatitaGtkMisc.report_error ~title:"graphviz error"
1161         ~message:("Graphviz is not installed but is necessary to render "^
1162          "the graph of dependencies amoung objects. Please install it.")
1163         ~parent:win#toplevel ()
1164
1165     method private dependencies direction uri () =
1166       assert false (* MATITA 1.0
1167       let dbd = LibraryDb.instance () in
1168       let graph =
1169         match direction with
1170         | `Fwd -> MetadataDeps.DepGraph.direct_deps ~dbd uri
1171         | `Back -> MetadataDeps.DepGraph.inverse_deps ~dbd uri in
1172       gviz_graph <- graph;  (** XXX check this for memory consuption *)
1173       self#redraw_gviz ~center_on:uri ();
1174       self#_showGviz *)
1175
1176     method private coerchgraph tred () =
1177       load_coerchgraph tred ();
1178       self#_showGviz
1179
1180     method private hints () =
1181       load_hints ();
1182       self#_showGviz
1183
1184     method private tex () =
1185       let b = Buffer.create 1000 in
1186       Printf.bprintf b "UTF-8 equivalence classes (rotate with ALT-L):\n\n";
1187       List.iter 
1188         (fun l ->
1189            List.iter (fun sym ->
1190              Printf.bprintf b "  %s" (Glib.Utf8.from_unichar sym) 
1191            ) l;
1192            Printf.bprintf b "\n";
1193         )
1194         (List.sort 
1195           (fun l1 l2 -> compare (List.hd l1) (List.hd l2))
1196           (Virtuals.get_all_eqclass ()));
1197       Printf.bprintf b "\n\nVirtual keys (trigger with ALT-L):\n\n";
1198       List.iter 
1199         (fun tag, items -> 
1200            Printf.bprintf b "  %s:\n" tag;
1201            List.iter 
1202              (fun names, symbol ->
1203                 Printf.bprintf b "  \t%s\t%s\n" 
1204                   (Glib.Utf8.from_unichar symbol)
1205                   (String.concat ", " names))
1206              (List.sort 
1207                (fun (_,a) (_,b) -> compare a b)
1208                items);
1209            Printf.bprintf b "\n")
1210         (List.sort 
1211           (fun (a,_) (b,_) -> compare a b)
1212           (Virtuals.get_all_virtuals ()));
1213       self#_loadText (Buffer.contents b)
1214
1215     method private _loadText text =
1216       searchText#source_buffer#set_text text;
1217       win#entrySearch#misc#grab_focus ();
1218       self#_showSearch
1219
1220     method private grammar () =
1221       self#_loadText (Print_grammar.ebnf_of_term self#script#grafite_status);
1222
1223     method private home () =
1224       self#_showMath;
1225       match self#script#grafite_status#ng_mode with
1226          `ProofMode ->
1227            self#_loadNObj self#script#grafite_status
1228            self#script#grafite_status#obj
1229        | _ -> self#blank ()
1230
1231     method private _loadNReference (NReference.Ref (uri,_)) =
1232       let obj = NCicEnvironment.get_checked_obj uri in
1233       self#_loadNObj self#script#grafite_status obj
1234
1235     method private _loadDir dir = 
1236       let content = Http_getter.ls ~local:false dir in
1237       let l =
1238         List.fast_sort
1239           Pervasives.compare
1240           (List.map
1241             (function 
1242               | Http_getter_types.Ls_section s -> "dir", s
1243               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
1244             content)
1245       in
1246       lastDir <- dir;
1247       self#_loadList l
1248
1249     method private setEntry entry =
1250       win#browserUri#set_text (MatitaTypes.string_of_entry entry);
1251       current_entry <- entry
1252
1253     method private _loadNObj status obj =
1254       (* showMath must be done _before_ loading the document, since if the
1255        * widget is not mapped (hidden by the notebook) the document is not
1256        * rendered *)
1257       self#_showMath;
1258       mathView#load_nobject status obj
1259
1260     method private _loadTermNCic term m s c =
1261       let d = 0 in
1262       let m = (0,([],c,term))::m in
1263       let status = (MatitaScript.current ())#grafite_status in
1264       mathView#nload_sequent status m s d;
1265       self#_showMath
1266
1267     method private _loadList l =
1268       model#list_store#clear ();
1269       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
1270       self#_showList
1271
1272     method private _loadList2 l =
1273       model_univs#list_store#clear ();
1274       List.iter model_univs#easy_mappend l;
1275       self#_showList2
1276     
1277     (** { public methods, all must call _load!! } *)
1278       
1279     method load entry =
1280       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
1281
1282     (**  this is what the browser does when you enter a string an hit enter *)
1283     method loadInput txt =
1284       let txt = HExtlib.trim_blanks txt in
1285       (* (* ZACK: what the heck? *)
1286       let fix_uri txt =
1287         UriManager.string_of_uri
1288           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
1289       in
1290       *)
1291         let entry =
1292           match txt with
1293           | txt when is_uri txt ->
1294               `NRef (NReference.reference_of_string ((*fix_uri*) txt))
1295           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
1296           | txt ->
1297              (try
1298                MatitaTypes.entry_of_string txt
1299               with Invalid_argument _ ->
1300                raise
1301                 (GrafiteTypes.Command_error(sprintf "unsupported uri: %s" txt)))
1302         in
1303         self#_load entry;
1304         self#_historyAdd entry
1305
1306       (** {2 methods accessing underlying GtkMathView} *)
1307
1308     method updateFontSize = mathView#set_font_size !current_font_size
1309
1310       (** {2 methods used by constructor only} *)
1311
1312     method win = win
1313     method history = history
1314     method currentEntry = current_entry
1315     method refresh ~force () = self#_load ~force current_entry
1316
1317   end
1318   
1319 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
1320   MatitaGuiTypes.sequentsViewer
1321 =
1322   new sequentsViewer ~notebook ~cicMathView ()
1323
1324 let cicBrowser () =
1325   let size = BuildTimeConf.browser_history_size in
1326   let rec aux history =
1327     let browser = new cicBrowser_impl ~history () in
1328     let win = browser#win in
1329     ignore (win#browserNewButton#connect#clicked (fun () ->
1330       let history =
1331         new MatitaMisc.browser_history ~memento:history#save size
1332           (`About `Blank)
1333       in
1334       let newBrowser = aux history in
1335       newBrowser#load browser#currentEntry));
1336 (*
1337       (* attempt (failed) to close windows on CTRL-W ... *)
1338     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
1339       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
1340 *)
1341     cicBrowsers := browser :: !cicBrowsers;
1342     (browser :> MatitaGuiTypes.cicBrowser)
1343   in
1344   let history = new MatitaMisc.browser_history size (`About `Blank) in
1345   aux history
1346
1347 let default_cicMathView () = cicMathView ~show:true ()
1348 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
1349
1350 let default_sequentsViewer () =
1351   let gui = get_gui () in
1352   let cicMathView = cicMathView_instance () in
1353   sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
1354 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
1355
1356 let mathViewer () = 
1357   object(self)
1358     method private get_browser reuse = 
1359       if reuse then
1360         (match !cicBrowsers with
1361         | [] -> cicBrowser ()
1362         | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
1363       else
1364         (cicBrowser ())
1365           
1366     method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
1367       
1368     method show_uri_list ?(reuse=false) ~entry l =
1369       (self#get_browser reuse)#load entry
1370
1371     method screenshot status sequents metasenv subst (filename as ofn) =
1372       () (*MATITA 1.0
1373        let w = GWindow.window ~title:"screenshot" () in
1374        let width = 500 in
1375        let height = 2000 in
1376        let m = GMathView.math_view 
1377           ~font_size:!current_font_size ~width ~height
1378           ~packing:w#add
1379           ~show:true ()
1380        in
1381        w#show ();
1382        let filenames = 
1383         HExtlib.list_mapi
1384          (fun (mno,_ as sequent) i ->
1385             let mathml = 
1386               ApplyTransformation.nmml_of_cic_sequent 
1387                 status metasenv subst sequent
1388             in
1389             m#load_root ~root:mathml#get_documentElement;
1390             let pixmap = m#get_buffer in
1391             let pixbuf = GdkPixbuf.create ~width ~height () in
1392             GdkPixbuf.get_from_drawable ~dest:pixbuf pixmap;
1393             let filename = 
1394               filename ^ "-raw" ^ string_of_int i ^ ".png" 
1395             in
1396             GdkPixbuf.save ~filename ~typ:"png" pixbuf;
1397             filename,mno)
1398          sequents
1399        in
1400        let items = 
1401          List.map (fun (x,mno) -> 
1402            ignore(Sys.command
1403              (Printf.sprintf
1404               ("convert "^^
1405               " '(' -gravity west -bordercolor grey -border 1 label:%d ')' "^^
1406               " '(' -trim -bordercolor white -border 5 "^^
1407                 " -bordercolor grey -border 1 %s ')' -append %s ")
1408               mno
1409               (Filename.quote x)
1410               (Filename.quote (x ^ ".label.png"))));
1411              x ^ ".label.png")
1412          filenames
1413        in
1414        let rec div2 = function 
1415          | [] -> []
1416          | [x] -> [[x]]
1417          | x::y::tl -> [x;y] :: div2 tl
1418        in
1419        let items = div2 items in
1420        ignore(Sys.command (Printf.sprintf 
1421          "convert %s -append  %s" 
1422           (String.concat ""
1423             (List.map (fun items ->
1424               Printf.sprintf " '(' %s +append ')' "
1425                 (String.concat 
1426                    (" '(' -gravity center -size 10x10 xc: ')' ") items)) items))
1427          (Filename.quote (ofn ^ ".png")))); 
1428        List.iter (fun x,_ -> Sys.remove x) filenames;
1429        List.iter Sys.remove (List.flatten items);
1430        w#destroy ();
1431     *)
1432   end
1433
1434 let refresh_all_browsers () =
1435   List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
1436
1437 let update_font_sizes () =
1438   List.iter (fun b -> b#updateFontSize) !cicBrowsers;
1439   (cicMathView_instance ())#update_font_size
1440
1441 let get_math_views () =
1442   ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
1443   :: (List.map (fun b -> b#mathView) !cicBrowsers)
1444
1445 let find_selection_owner () =
1446   let rec aux =
1447     function
1448     | [] -> raise Not_found
1449     | mv :: tl ->
1450         (match mv#get_selections with
1451         | [] -> aux tl
1452         | sel :: _ -> mv)
1453   in
1454   aux (get_math_views ())
1455
1456 let has_selection () =
1457   try ignore (find_selection_owner ()); true
1458   with Not_found -> false
1459
1460 let math_view_clipboard = ref None (* associative list target -> string *)
1461 let has_clipboard () = !math_view_clipboard <> None
1462 let empty_clipboard () = math_view_clipboard := None
1463
1464 let copy_selection () =
1465   try
1466     math_view_clipboard :=
1467       Some ((find_selection_owner ())#strings_of_selection)
1468   with Not_found -> failwith "no selection"
1469
1470 let paste_clipboard paste_kind =
1471   match !math_view_clipboard with
1472   | None -> failwith "empty clipboard"
1473   | Some cb ->
1474       (try List.assoc paste_kind cb with Not_found -> assert false)
1475