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