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