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