]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/cicMathView.ml
ceb2e1f0df193b19d96ce856e895390c421419e0
[helm.git] / matita / matita / cicMathView.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://helm.cs.unibo.it/
24  *)
25
26 open Printf
27
28 open GrafiteTypes
29 open MatitaGtkMisc
30 open MatitaGuiTypes
31 open GtkSourceView3
32
33 let matita_script_current = ref (fun _ -> (assert false : < advance: ?statement:string -> unit -> unit; status: GrafiteTypes.status >));;
34 let register_matita_script_current f = matita_script_current := f;;
35 let get_matita_script_current () = !matita_script_current ();;
36
37 type document_element = (int * int * string) list * string (* hyperlinks,text *)
38
39 class type cicMathView =
40 object
41   inherit GObj.widget
42
43   method load_root : root:document_element -> unit
44   method remove_selections: unit
45   method set_selection: document_element option -> unit
46   method get_selections: document_element list
47
48     (** @raise Failure "no selection" *)
49   method strings_of_selection: (MatitaGuiTypes.paste_kind * string) list
50
51     (** set hyperlink callback. None disable hyperlink handling *)
52   method set_href_callback: (string -> unit) option -> unit
53
54     (** load a sequent and render it into parent widget *)
55   method nload_sequent:
56    #ApplyTransformation.status -> NCic.metasenv -> NCic.substitution -> int -> unit
57
58   method load_nobject: #ApplyTransformation.status -> NCic.obj -> unit
59 end
60
61 (*
62 let xlink_ns = Gdome.domString "http://www.w3.org/1999/xlink"
63 let helm_ns = Gdome.domString "http://www.cs.unibo.it/helm"
64 let href_ds = Gdome.domString "href"
65 let xref_ds = Gdome.domString "xref"
66 *)
67
68   (** Gdome.element of a MathML document whose rendering should be blank. Used
69   * by cicBrowser to render "about:blank" document *)
70 let empty_mathml = lazy ([],"")
71
72   (** shown for goals closed by side effects *)
73 let closed_goal_mathml = lazy ([],"chiuso per side effect...")
74
75 (*
76 let rec has_maction (elt :Gdome.element) = 
77   (* fix this comparison *)
78   if elt#get_tagName#to_string = "m:maction" ||
79    elt#get_tagName#to_string = "b:action" then
80     true
81   else 
82     match elt#get_parentNode with
83     | Some node when node#get_nodeType = GdomeNodeTypeT.ELEMENT_NODE -> 
84         has_maction (new Gdome.element_of_node node)
85     | _ -> false
86 ;;
87
88 let hrefs_of_elt elt =
89   let localName = href_ds in
90   if elt#hasAttributeNS ~namespaceURI:xlink_ns ~localName then
91     let text =
92       (elt#getAttributeNS ~namespaceURI:xlink_ns ~localName)#to_string in
93     Some (HExtlib.split text)
94   else
95     None
96
97 let id_of_node (node: Gdome.element) =
98   let xref_attr =
99     node#getAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds in
100   try
101     List.hd (HExtlib.split ~sep:' ' xref_attr#to_string)
102   with Failure _ -> assert false
103
104 type selected_term =
105   | SelTerm of NCic.term * string option (* term, parent hypothesis (if any) *)
106   | SelHyp of string * NCic.context (* hypothesis, context *)
107 *)
108
109 let near (x1, y1) (x2, y2) =
110   let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
111   (distance < 4.)
112
113 (*
114 let name_of_hypothesis = function
115   | Some (Cic.Name s, _) -> s
116   | _ -> assert false
117
118 let domImpl = Gdome.domImplementation ()
119
120 (* ids_to_terms should not be passed here, is just for debugging *)
121 let find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types =
122   assert false (* MATITA 1.0
123   let find_parent id ids =
124     let rec aux id =
125 (*       (prerr_endline (sprintf "id %s = %s" id
126         (try
127           CicPp.ppterm (Hashtbl.find ids_to_terms id)
128         with Not_found -> "NONE"))); *)
129       if List.mem id ids then Some id
130       else
131         (match
132           (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
133         with
134         | None -> None
135         | Some id' -> aux id')
136     in
137     aux id
138   in
139   let return_father id ids =
140     match find_parent id ids with
141     | None -> assert false
142     | Some parent_id -> parent_id
143   in
144   let mk_ids terms = List.map CicUtil.id_of_annterm terms in
145   let inner_types =
146    Hashtbl.fold
147     (fun _ types acc ->
148       match types.Cic2acic.annexpected with
149          None -> types.Cic2acic.annsynthesized :: acc
150        | Some ty -> ty :: types.Cic2acic.annsynthesized :: acc
151     ) ids_to_inner_types [] in
152   match annobj with
153   | Cic.AConstant (_, _, _, Some bo, ty, _, _)
154   | Cic.AVariable (_, _, Some bo, ty, _, _)
155   | Cic.ACurrentProof (_, _, _, _, bo, ty, _, _) ->
156       return_father id (mk_ids (ty :: bo :: inner_types))
157   | Cic.AConstant (_, _, _, None, ty, _, _)
158   | Cic.AVariable (_, _, None, ty, _, _) ->
159       return_father id (mk_ids (ty::inner_types))
160   | Cic.AInductiveDefinition _ ->
161       assert false  (* TODO *)
162       *)
163
164   (** @return string content of a dom node having a single text child node, e.g.
165    * <m:mi xlink:href="...">bool</m:mi> *)
166 let string_of_dom_node node =
167   match node#get_firstChild with
168   | None -> ""
169   | Some node ->
170       (try
171         let text = new Gdome.text_of_node node in
172         text#get_data#to_string
173       with GdomeInit.DOMCastException _ -> "")
174 *)
175
176 class clickableMathView obj =
177 (*let text_width = 80 in*)
178 object (self)
179   inherit GSourceView3.source_view obj
180
181   method strings_of_selection = (assert false : (paste_kind * string) list)
182
183   val mutable href_callback: (string -> unit) option = None
184   method set_href_callback f = href_callback <- f
185
186   val mutable href_statusbar_msg:
187     (GMisc.statusbar_context * Gtk.statusbar_message) option = None
188     (* <statusbar ctxt, statusbar msg> *)
189
190   method private set_cic_info = (function _ -> () : unit (*(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:(hyperlinks,text) =
195     self#buffer#set_text text;
196     let all_tag = self#buffer#create_tag [] in
197     self#buffer#apply_tag all_tag ~start:(self#buffer#get_iter `START)
198      ~stop:(self#buffer#get_iter `END);
199     ignore(all_tag#connect#event
200       ~callback:(fun ~origin event pos ->
201         match GdkEvent.get_type event with
202          | `MOTION_NOTIFY -> 
203              Gdk.Window.set_cursor
204               (match self#get_window `TEXT with None -> assert false | Some x -> x)
205               (Gdk.Cursor.create `ARROW);
206              HExtlib.iter_option (fun (ctxt, msg) -> ctxt#remove msg)
207               href_statusbar_msg;
208              false
209          | _ -> false));
210      let hyperlink_tag = self#buffer#create_tag [] in
211      ignore(hyperlink_tag#connect#event
212        ~callback:(fun ~origin event pos ->
213          let offset = (new GText.iter pos)#offset in
214          let _,_,href =
215           try
216            List.find
217             (fun (start,stop,href) -> start <= offset && offset <= stop
218             ) hyperlinks
219           with
220            Not_found -> assert false
221          in
222          match GdkEvent.get_type event with
223             `BUTTON_PRESS -> 
224               (match href_callback with
225                   None -> ()
226                 | Some f -> f href);
227               true
228           | `MOTION_NOTIFY -> 
229               Gdk.Window.set_cursor
230                (match self#get_window `TEXT with None -> assert false | Some x -> x)
231                (Gdk.Cursor.create `HAND1);
232               let ctxt = (MatitaMisc.get_gui ())#main#statusBar#new_context ~name:"href" in
233               let msg = ctxt#push href in
234               href_statusbar_msg <- Some (ctxt, msg);
235               false
236           | _ -> false));
237      List.iter
238       ( fun (start,stop,(href : string)) ->
239           self#buffer#apply_tag hyperlink_tag
240            ~start:(self#buffer#get_iter_at_char start)
241            ~stop:(self#buffer#get_iter_at_char (stop+1));
242       ) hyperlinks
243
244
245   method action_toggle = (fun _ -> assert false : document_element -> bool)
246   method remove_selections = (() : unit)
247   method set_selection = (fun _ -> () : document_element option -> unit)
248   method get_selections = (assert false : document_element list)
249
250   initializer
251     self#source_buffer#set_language (Some MatitaGtkMisc.matita_lang);
252     self#source_buffer#set_highlight_syntax true;
253     self#set_editable false;
254     MatitaMisc.observe_font_size
255      (fun size ->
256        self#misc#modify_font_by_name
257         (sprintf "%s %d" BuildTimeConf.script_font size))
258
259 (* MATITA 1.0
260   inherit GMathViewAux.multi_selection_math_view obj
261
262   val mutable href_callback: (string -> unit) option = None
263   method set_href_callback f = href_callback <- f
264
265   val mutable _cic_info = None
266   method private set_cic_info info = _cic_info <- info
267   method private cic_info = _cic_info
268
269   val normal_cursor = Gdk.Cursor.create `LEFT_PTR
270   val href_cursor = Gdk.Cursor.create `HAND2
271   val maction_cursor = Gdk.Cursor.create `QUESTION_ARROW
272
273   initializer
274     ignore (self#connect#selection_changed self#choose_selection_cb);
275     ignore (self#event#connect#button_press self#button_press_cb);
276     ignore (self#event#connect#button_release self#button_release_cb);
277     ignore (self#event#connect#selection_clear self#selection_clear_cb);
278     ignore (self#connect#element_over self#element_over_cb);
279     ignore (self#coerce#misc#connect#selection_get self#selection_get_cb)
280
281   val mutable button_press_x = -1.
282   val mutable button_press_y = -1.
283   val mutable selection_changed = false
284   val mutable href_statusbar_msg:
285     (GMisc.statusbar_context * Gtk.statusbar_message) option = None
286     (* <statusbar ctxt, statusbar msg> *)
287
288   method private selection_get_cb ctxt ~info ~time =
289     let text =
290       match ctxt#target with
291       | "PATTERN" -> self#text_of_selection `Pattern
292       | "TERM" | _ -> self#text_of_selection `Term
293     in
294     match text with
295     | None -> ()
296     | Some s -> ctxt#return s
297
298   method private text_of_selection fmt =
299     match self#get_selections with
300     | [] -> None
301     | node :: _ -> Some (self#string_of_node ~paste_kind:fmt node)
302
303   method private selection_clear_cb sel_event =
304     self#remove_selections;
305     (GData.clipboard Gdk.Atom.clipboard)#clear ();
306     false
307
308   method private button_press_cb gdk_button =
309     let button = GdkEvent.Button.button gdk_button in
310     if  button = MatitaMisc.left_button then begin
311       button_press_x <- GdkEvent.Button.x gdk_button;
312       button_press_y <- GdkEvent.Button.y gdk_button;
313       selection_changed <- false
314     end else if button = MatitaMisc.right_button then
315       self#popup_contextual_menu 
316         (self#get_element_at 
317           (int_of_float (GdkEvent.Button.x gdk_button)) 
318           (int_of_float (GdkEvent.Button.y gdk_button)))  
319         (GdkEvent.Button.time gdk_button);
320     false
321
322   method private element_over_cb (elt_opt, _, _, _) =
323     let win () = self#misc#window in
324     let leave_href () =
325       Gdk.Window.set_cursor (win ()) normal_cursor;
326       HExtlib.iter_option (fun (ctxt, msg) -> ctxt#remove msg)
327         href_statusbar_msg
328     in
329     match elt_opt with
330     | Some elt ->
331         if has_maction elt then
332           Gdk.Window.set_cursor (win ()) maction_cursor
333         else
334         (match hrefs_of_elt elt with
335         | Some ((_ :: _) as hrefs) ->
336             Gdk.Window.set_cursor (win ()) href_cursor;
337             let msg_text = (* now create statusbar msg and store it *)
338               match hrefs with
339               | [ href ] -> sprintf "Hyperlink to %s" href
340               | _ -> sprintf "Hyperlinks to: %s" (String.concat ", " hrefs) in
341             let ctxt = (get_gui ())#main#statusBar#new_context ~name:"href" in
342             let msg = ctxt#push msg_text in
343             href_statusbar_msg <- Some (ctxt, msg)
344         | _ -> leave_href ())
345     | None -> leave_href ()
346
347   method private tactic_text_pattern_of_node node =
348    let id = id_of_node node in
349    let cic_info, unsh_sequent = self#get_cic_info id in
350    match self#get_term_by_id cic_info id with
351    | SelTerm (t, father_hyp) ->
352        let sequent = self#sequent_of_id ~paste_kind:`Pattern id in
353        let text = self#string_of_cic_sequent ~output_type:`Pattern sequent in
354        (match father_hyp with
355        | None -> None, [], Some text
356        | Some hyp_name -> None, [ hyp_name, text ], None)
357    | SelHyp (hyp_name, _ctxt) -> None, [ hyp_name, "%" ], None
358
359   method private tactic_text_of_node node =
360    let id = id_of_node node in
361    let cic_info, unsh_sequent = self#get_cic_info id in
362    match self#get_term_by_id cic_info id with
363    | SelTerm (t, father_hyp) ->
364        let sequent = self#sequent_of_id ~paste_kind:`Term id in
365        let text = self#string_of_cic_sequent ~output_type:`Term sequent in
366        text
367    | SelHyp (hyp_name, _ctxt) -> hyp_name
368
369     (** @return a pattern structure which contains pretty printed terms *)
370   method private tactic_text_pattern_of_selection =
371     match self#get_selections with
372     | [] -> assert false (* this method is invoked only if there's a sel. *)
373     | node :: _ -> self#tactic_text_pattern_of_node node
374
375   method private popup_contextual_menu element time =
376     let menu = GMenu.menu () in
377     let add_menu_item ?(menu = menu) ?stock ?label () =
378       GMenu.image_menu_item ?stock ?label ~packing:menu#append () in
379     let check = add_menu_item ~label:"Check" () in
380     let reductions_menu_item = GMenu.menu_item ~label:"βδιζ-reduce" () in
381     let tactics_menu_item = GMenu.menu_item ~label:"Apply tactic" () in
382     let hyperlinks_menu_item = GMenu.menu_item ~label:"Hyperlinks" () in
383     menu#append reductions_menu_item;
384     menu#append tactics_menu_item;
385     menu#append hyperlinks_menu_item;
386     let reductions = GMenu.menu () in
387     let tactics = GMenu.menu () in
388     let hyperlinks = GMenu.menu () in
389     reductions_menu_item#set_submenu reductions;
390     tactics_menu_item#set_submenu tactics;
391     hyperlinks_menu_item#set_submenu hyperlinks;
392     let normalize = add_menu_item ~menu:reductions ~label:"Normalize" () in
393     let simplify = add_menu_item ~menu:reductions ~label:"Simplify" () in
394     let whd = add_menu_item ~menu:reductions ~label:"Weak head" () in
395     (match element with 
396     | None -> hyperlinks_menu_item#misc#set_sensitive false
397     | Some elt -> 
398         match hrefs_of_elt elt, href_callback with
399         | Some l, Some f ->
400             List.iter 
401               (fun h ->
402                 let item = add_menu_item ~menu:hyperlinks ~label:h () in
403                 connect_menu_item item (fun () -> f h)) l
404         | _ -> hyperlinks_menu_item#misc#set_sensitive false);
405     menu#append (GMenu.separator_item ());
406     let copy = add_menu_item ~stock:`COPY () in
407     let gui = get_gui () in
408     List.iter (fun item -> item#misc#set_sensitive gui#canCopy)
409       [ copy; check; normalize; simplify; whd ];
410     let reduction_action kind () =
411       let pat = self#tactic_text_pattern_of_selection in
412       let statement =
413         let loc = HExtlib.dummy_floc in
414         "\n" ^
415         GrafiteAstPp.pp_executable ~term_pp:(fun s -> s)
416           ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
417           ~map_unicode_to_tex:(Helm_registry.get_bool
418             "matita.paste_unicode_as_tex")
419           (GrafiteAst.Tactic (loc,
420             Some (GrafiteAst.Reduce (loc, kind, pat)),
421             GrafiteAst.Semicolon loc)) in
422       (get_matita_script_current ())#advance ~statement () in
423     connect_menu_item copy gui#copy;
424     connect_menu_item normalize (reduction_action `Normalize);
425     connect_menu_item simplify (reduction_action `Simpl);
426     connect_menu_item whd (reduction_action `Whd);
427     menu#popup ~button:MatitaMisc.right_button ~time
428
429   method private button_release_cb gdk_button =
430     if GdkEvent.Button.button gdk_button = MatitaMisc.left_button then begin
431       let button_release_x = GdkEvent.Button.x gdk_button in
432       let button_release_y = GdkEvent.Button.y gdk_button in
433       if selection_changed then
434         ()
435       else  (* selection _not_ changed *)
436         if near (button_press_x, button_press_y)
437           (button_release_x, button_release_y)
438         then
439           let x = int_of_float button_press_x in
440           let y = int_of_float button_press_y in
441           (match self#get_element_at x y with
442           | None -> ()
443           | Some elt ->
444               if has_maction elt then ignore(self#action_toggle elt) else
445               (match hrefs_of_elt elt with
446               | Some hrefs -> self#invoke_href_callback hrefs gdk_button
447               | None -> ()))
448     end;
449     false
450
451   method private invoke_href_callback hrefs gdk_button =
452     let button = GdkEvent.Button.button gdk_button in
453     if button = MatitaMisc.left_button then
454       let time = GdkEvent.Button.time gdk_button in
455       match href_callback with
456       | None -> ()
457       | Some f ->
458           (match hrefs with
459           | [ uri ] ->  f uri
460           | uris ->
461               let menu = GMenu.menu () in
462               List.iter
463                 (fun uri ->
464                   let menu_item =
465                     GMenu.menu_item ~label:uri ~packing:menu#append () in
466                   connect_menu_item menu_item 
467                   (fun () -> try f uri with Not_found -> assert false))
468                 uris;
469               menu#popup ~button ~time)
470
471   method private choose_selection_cb gdome_elt =
472     let set_selection elt =
473       let misc = self#coerce#misc in
474       self#set_selection (Some elt);
475       misc#add_selection_target ~target:"STRING" Gdk.Atom.primary;
476       ignore (misc#grab_selection Gdk.Atom.primary);
477     in
478     let rec aux elt =
479       if (elt#getAttributeNS ~namespaceURI:helm_ns
480             ~localName:xref_ds)#to_string <> ""
481       then
482         set_selection elt
483       else
484         try
485           (match elt#get_parentNode with
486           | None -> assert false
487           | Some p -> aux (new Gdome.element_of_node p))
488         with GdomeInit.DOMCastException _ -> ()
489     in
490     (match gdome_elt with
491     | Some elt when (elt#getAttributeNS ~namespaceURI:xlink_ns
492         ~localName:href_ds)#to_string <> "" ->
493           set_selection elt
494     | Some elt -> aux elt
495     | None -> self#set_selection None);
496     selection_changed <- true
497
498     (** find a term by id from stored CIC infos @return either `Hyp if the id
499      * correspond to an hypothesis or `Term (cic, hyp) if the id correspond to a
500      * term. In the latter case hyp is either None (if the term is a subterm of
501      * the sequent conclusion) or Some hyp_name if the term belongs to an
502      * hypothesis *)
503   method private get_term_by_id cic_info id =
504     let unsh_item, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, _, _ =
505       cic_info in
506     let rec find_father_hyp id =
507       if Hashtbl.mem ids_to_hypotheses id
508       then Some (name_of_hypothesis (Hashtbl.find ids_to_hypotheses id))
509       else
510         let father_id =
511           try Hashtbl.find ids_to_father_ids id
512           with Not_found -> assert false in
513         match father_id with
514         | Some id -> find_father_hyp id
515         | None -> None
516     in
517     try
518       let term = Hashtbl.find ids_to_terms id in
519       let father_hyp = find_father_hyp id in
520       SelTerm (term, father_hyp)
521     with Not_found ->
522       try
523         let hyp = Hashtbl.find ids_to_hypotheses id in
524         let _, context, _ =
525           match unsh_item with Some seq -> seq | None -> assert false in
526         let context' = MatitaMisc.list_tl_at hyp context in
527         SelHyp (name_of_hypothesis hyp, context')
528       with Not_found -> assert false
529     
530   method private find_obj_conclusion id =
531     match self#cic_info with
532     | None
533     | Some (_, _, _, _, _, None) -> assert false
534     | Some (_, ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
535         let id =
536          find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
537         in
538          (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
539
540   method private string_of_node ~(paste_kind:paste_kind) node =
541     if node#hasAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds
542     then
543       match paste_kind with
544       | `Pattern ->
545           let tactic_text_pattern =  self#tactic_text_pattern_of_node node in
546           GrafiteAstPp.pp_tactic_pattern
547             ~term_pp:(fun s -> s) ~lazy_term_pp:(fun _ -> assert false)
548             ~map_unicode_to_tex:(Helm_registry.get_bool
549               "matita.paste_unicode_as_tex")
550             tactic_text_pattern
551       | `Term -> self#tactic_text_of_node node
552     else string_of_dom_node node
553
554   method private string_of_cic_sequent ~output_type cic_sequent =
555     let script = get_matita_script_current () in
556     let metasenv =
557       if script#onGoingProof () then script#proofMetasenv else [] in
558     let map_unicode_to_tex =
559       Helm_registry.get_bool "matita.paste_unicode_as_tex" in
560     ApplyTransformation.txt_of_cic_sequent_conclusion ~map_unicode_to_tex
561      ~output_type text_width metasenv cic_sequent
562
563   method private pattern_of term father_hyp unsh_sequent =
564     let _, unsh_context, conclusion = unsh_sequent in
565     let where =
566      match father_hyp with
567         None -> conclusion
568       | Some name ->
569          let rec aux =
570           function
571              [] -> assert false
572            | Some (Cic.Name name', Cic.Decl ty)::_ when name' = name -> ty
573            | Some (Cic.Name name', Cic.Def (bo,_))::_ when name' = name-> bo
574            | _::tl -> aux tl
575          in
576           aux unsh_context
577     in
578      ProofEngineHelpers.pattern_of ~term:where [term]
579
580   method private get_cic_info id =
581     match self#cic_info with
582     | Some ((Some unsh_sequent, _, _, _, _, _) as info) -> info, unsh_sequent
583     | Some ((None, _, _, _, _, _) as info) ->
584         let t = self#find_obj_conclusion id in
585         info, (~-1, [], t) (* dummy sequent for obj *)
586     | None -> assert false
587
588   method private sequent_of_id ~(paste_kind:paste_kind) id =
589     let cic_info, unsh_sequent = self#get_cic_info id in
590     let cic_sequent =
591       match self#get_term_by_id cic_info id with
592       | SelTerm (t, father_hyp) ->
593 (*
594 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
595 *)
596           let occurrences =
597             ProofEngineHelpers.locate_in_conjecture t unsh_sequent in
598           (match occurrences with
599           | [ context, _t ] ->
600               (match paste_kind with
601               | `Term -> ~-1, context, t
602               | `Pattern -> ~-1, [], self#pattern_of t father_hyp unsh_sequent)
603           | _ ->
604               HLog.error (sprintf "found %d occurrences while 1 was expected"
605                 (List.length occurrences));
606               assert false) (* since it uses physical equality *)
607       | SelHyp (_name, context) -> ~-1, context, Cic.Rel 1 in
608     cic_sequent
609
610   method private string_of_selection ~(paste_kind:paste_kind) =
611     match self#get_selections with
612     | [] -> None
613     | node :: _ -> Some (self#string_of_node ~paste_kind node)
614
615     (** @return an associative list format -> string with all possible selection
616      * formats. Rationale: in order to convert the selection to TERM or PATTERN
617      * format we need the sequent, the metasenv, ... keeping all of them in a
618      * closure would be more expensive than keeping their already converted
619      * forms *)
620   method strings_of_selection =
621     try
622       let misc = self#coerce#misc in
623       List.iter
624         (fun target -> misc#add_selection_target ~target Gdk.Atom.clipboard)
625         [ "TERM"; "PATTERN"; "STRING" ];
626       ignore (misc#grab_selection Gdk.Atom.clipboard);
627       List.map
628         (fun paste_kind ->
629           paste_kind, HExtlib.unopt (self#string_of_selection ~paste_kind))
630         [ `Term; `Pattern ]
631     with Failure _ -> failwith "no selection"
632 *)
633 end
634
635 class _cicMathView obj =
636 object (self)
637   inherit clickableMathView obj
638
639   val mutable current_mathml = None
640
641   method nload_sequent:
642    'status. #ApplyTransformation.status as 'status -> NCic.metasenv ->
643      NCic.substitution -> int -> unit
644    = fun status metasenv subst metano ->
645     let sequent = List.assoc metano metasenv in
646     let txt =
647      ApplyTransformation.ntxt_of_cic_sequent
648       ~map_unicode_to_tex:false 80 status ~metasenv ~subst (metano,sequent)
649     in
650     (* MATITA 1.0 if BuildTimeConf.debug then begin
651       let name =
652        "/tmp/sequent_viewer_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
653       HLog.debug ("load_sequent: dumping MathML to ./" ^ name);
654       ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
655     end;*)
656     self#load_root ~root:txt
657
658   method load_nobject :
659    'status. #ApplyTransformation.status as 'status -> NCic.obj -> unit
660    = fun status obj ->
661     let txt = ApplyTransformation.ntxt_of_cic_object ~map_unicode_to_tex:false
662     80 status obj in
663 (*
664     self#set_cic_info
665       (Some (None, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
666     (match current_mathml with
667     | Some current_mathml when use_diff ->
668         self#freeze;
669         XmlDiff.update_dom ~from:current_mathml mathml;
670         self#thaw
671     |  _ ->
672 *)
673         (* MATITA 1.0 if BuildTimeConf.debug then begin
674           let name =
675            "/tmp/cic_browser_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
676           HLog.debug ("cic_browser: dumping MathML to ./" ^ name);
677           ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
678         end;*)
679         self#load_root ~root:txt;
680         (*current_mathml <- Some mathml*)(*)*);
681 end
682
683  (** constructors *)
684
685 let cicMathView (*?auto_indent ?highlight_current_line ?indent_on_tab ?indent_width ?insert_spaces_instead_of_tabs ?right_margin_position ?show_line_marks ?show_line_numbers ?show_right_margin ?smart_home_end ?tab_width ?editable ?cursor_visible ?justification ?wrap_mode ?accepts_tab ?border_width*) ?width ?height ?packing ?show () =
686  ((*SourceView.make_params [] ~cont:(
687     GtkText.View.make_params ~cont:( *)
688       GContainer.pack_container ~create:(fun pl ->
689         let obj = SourceView.new_ () in
690         Gobject.set_params (Gobject.try_cast obj "GtkSourceView") pl;
691         new _cicMathView obj)(*)) ?auto_indent ?highlight_current_line ?indent_on_tab ?indent_width ?insert_spaces_instead_of_tabs ?right_margin_position ?show_line_marks ?show_line_numbers ?show_right_margin ?smart_home_end ?tab_width ?editable ?cursor_visible ?justification ?wrap_mode ?accepts_tab ?border_width*) [] ?width ?height ?packing ?show () :> cicMathView)
692
693 let screenshot status sequents metasenv subst (filename (*as ofn*)) =
694  () (*MATITA 1.0
695   let w = GWindow.window ~title:"screenshot" () in
696   let width = 500 in
697   let height = 2000 in
698   let m = GMathView.math_view 
699      ~font_size:(MatitaMisc.get_current_font_size ()) ~width ~height
700      ~packing:w#add
701      ~show:true ()
702   in
703   w#show ();
704   let filenames = 
705    HExtlib.list_mapi
706     (fun (mno,_ as sequent) i ->
707        let mathml = 
708          ApplyTransformation.nmml_of_cic_sequent 
709            status metasenv subst sequent
710        in
711        m#load_root ~root:mathml#get_documentElement;
712        let pixmap = m#get_buffer in
713        let pixbuf = GdkPixbuf.create ~width ~height () in
714        GdkPixbuf.get_from_drawable ~dest:pixbuf pixmap;
715        let filename = 
716          filename ^ "-raw" ^ string_of_int i ^ ".png" 
717        in
718        GdkPixbuf.save ~filename ~typ:"png" pixbuf;
719        filename,mno)
720     sequents
721   in
722   let items = 
723     List.map (fun (x,mno) -> 
724       ignore(Sys.command
725         (Printf.sprintf
726          ("convert "^^
727          " '(' -gravity west -bordercolor grey -border 1 label:%d ')' "^^
728          " '(' -trim -bordercolor white -border 5 "^^
729            " -bordercolor grey -border 1 %s ')' -append %s ")
730          mno
731          (Filename.quote x)
732          (Filename.quote (x ^ ".label.png"))));
733         x ^ ".label.png")
734     filenames
735   in
736   let rec div2 = function 
737     | [] -> []
738     | [x] -> [[x]]
739     | x::y::tl -> [x;y] :: div2 tl
740   in
741   let items = div2 items in
742   ignore(Sys.command (Printf.sprintf 
743     "convert %s -append  %s" 
744      (String.concat ""
745        (List.map (fun items ->
746          Printf.sprintf " '(' %s +append ')' "
747            (String.concat 
748               (" '(' -gravity center -size 10x10 xc: ')' ") items)) items))
749     (Filename.quote (ofn ^ ".png")))); 
750   List.iter (fun x,_ -> Sys.remove x) filenames;
751   List.iter Sys.remove (List.flatten items);
752   w#destroy ()*)