1 (* Copyright (C) 2004-2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://cs.unibo.it/helm/.
34 module Stack = Continuationals.Stack
36 (** inherit from this class if you want to access current script *)
37 class scriptAccessor =
39 method private script = MatitaScript.current ()
42 let cicBrowsers = ref []
43 let gui_instance = ref None
44 let set_gui gui = gui_instance := Some gui
46 match !gui_instance with
47 | None -> assert false
50 let default_font_size () =
51 Helm_registry.get_opt_default Helm_registry.int
52 ~default:BuildTimeConf.default_font_size "matita.font_size"
53 let current_font_size = ref ~-1
54 let increase_font_size () = incr current_font_size
55 let decrease_font_size () = decr current_font_size
56 let reset_font_size () = current_font_size := default_font_size ()
58 (* is there any lablgtk2 constant corresponding to the various mouse
64 let near (x1, y1) (x2, y2) =
65 let distance = sqrt (((x2 -. x1) ** 2.) +. ((y2 -. y1) ** 2.)) in
68 let mathml_ns = Gdome.domString "http://www.w3.org/1998/Math/MathML"
69 let xlink_ns = Gdome.domString "http://www.w3.org/1999/xlink"
70 let helm_ns = Gdome.domString "http://www.cs.unibo.it/helm"
71 let href_ds = Gdome.domString "href"
72 let maction_ds = Gdome.domString "maction"
73 let xref_ds = Gdome.domString "xref"
75 let domImpl = Gdome.domImplementation ()
77 (** Gdome.element of a MathML document whose rendering should be blank. Used
78 * by cicBrowser to render "about:blank" document *)
79 let empty_mathml = lazy (
80 domImpl#createDocument ~namespaceURI:(Some DomMisc.mathml_ns)
81 ~qualifiedName:(Gdome.domString "math") ~doctype:None)
83 let empty_boxml = lazy (
84 domImpl#createDocument ~namespaceURI:(Some DomMisc.boxml_ns)
85 ~qualifiedName:(Gdome.domString "box") ~doctype:None)
87 (** shown for goals closed by side effects *)
88 let closed_goal_mathml = lazy (
89 domImpl#createDocumentFromURI ~uri:BuildTimeConf.closed_xml ())
91 (* ids_to_terms should not be passed here, is just for debugging *)
92 let find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types =
93 let find_parent id ids =
95 (* (prerr_endline (sprintf "id %s = %s" id
97 CicPp.ppterm (Hashtbl.find ids_to_terms id)
98 with Not_found -> "NONE"))); *)
99 if List.mem id ids then Some id
102 (try Hashtbl.find ids_to_father_ids id with Not_found -> None)
105 | Some id' -> aux id')
109 let return_father id ids =
110 match find_parent id ids with
111 | None -> assert false
112 | Some parent_id -> parent_id
114 let mk_ids terms = List.map CicUtil.id_of_annterm terms in
118 match types.Cic2acic.annexpected with
119 None -> types.Cic2acic.annsynthesized :: acc
120 | Some ty -> ty :: types.Cic2acic.annsynthesized :: acc
121 ) ids_to_inner_types [] in
123 | Cic.AConstant (_, _, _, Some bo, ty, _, _)
124 | Cic.AVariable (_, _, Some bo, ty, _, _)
125 | Cic.ACurrentProof (_, _, _, _, bo, ty, _, _) ->
126 return_father id (mk_ids (ty :: bo :: inner_types))
127 | Cic.AConstant (_, _, _, None, ty, _, _)
128 | Cic.AVariable (_, _, None, ty, _, _) ->
129 return_father id (mk_ids (ty::inner_types))
130 | Cic.AInductiveDefinition _ ->
131 assert false (* TODO *)
133 (** @return string content of a dom node having a single text child node, e.g.
134 * <m:mi xlink:href="...">bool</m:mi> *)
135 let string_of_dom_node node =
136 match node#get_firstChild with
140 let text = new Gdome.text_of_node node in
141 text#get_data#to_string
142 with GdomeInit.DOMCastException _ -> "")
144 let name_of_hypothesis = function
145 | Some (Cic.Name s, _) -> s
148 let id_of_node (node: Gdome.element) =
150 node#getAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds in
152 List.hd (HExtlib.split ~sep:' ' xref_attr#to_string)
153 with Failure _ -> assert false
156 | SelTerm of Cic.term * string option (* term, parent hypothesis (if any) *)
157 | SelHyp of string * Cic.context (* hypothesis, context *)
159 let hrefs_of_elt elt =
160 let localName = href_ds in
161 if elt#hasAttributeNS ~namespaceURI:xlink_ns ~localName then
163 (elt#getAttributeNS ~namespaceURI:xlink_ns ~localName)#to_string in
164 Some (HExtlib.split text)
168 let rec has_maction (elt :Gdome.element) =
169 (* fix this comparison *)
170 if elt#get_tagName#to_string = "m:maction" ||
171 elt#get_tagName#to_string = "b:action" then
174 match elt#get_parentNode with
175 | Some node when node#get_nodeType = GdomeNodeTypeT.ELEMENT_NODE ->
176 has_maction (new Gdome.element_of_node node)
180 class clickableMathView obj =
181 let text_width = 80 in
183 inherit GMathViewAux.multi_selection_math_view obj
185 val mutable href_callback: (string -> unit) option = None
186 method set_href_callback f = href_callback <- f
188 val mutable _cic_info = None
189 method private set_cic_info info = _cic_info <- info
190 method private cic_info = _cic_info
192 val normal_cursor = Gdk.Cursor.create `LEFT_PTR
193 val href_cursor = Gdk.Cursor.create `HAND2
194 val maction_cursor = Gdk.Cursor.create `QUESTION_ARROW
197 self#set_font_size !current_font_size;
198 ignore (self#connect#selection_changed self#choose_selection_cb);
199 ignore (self#event#connect#button_press self#button_press_cb);
200 ignore (self#event#connect#button_release self#button_release_cb);
201 ignore (self#event#connect#selection_clear self#selection_clear_cb);
202 ignore (self#connect#element_over self#element_over_cb);
203 ignore (self#coerce#misc#connect#selection_get self#selection_get_cb)
205 val mutable button_press_x = -1.
206 val mutable button_press_y = -1.
207 val mutable selection_changed = false
208 val mutable href_statusbar_msg:
209 (GMisc.statusbar_context * Gtk.statusbar_message) option = None
210 (* <statusbar ctxt, statusbar msg> *)
212 method private selection_get_cb ctxt ~info ~time =
214 match ctxt#target with
215 | "PATTERN" -> self#text_of_selection `Pattern
216 | "TERM" | _ -> self#text_of_selection `Term
220 | Some s -> ctxt#return s
222 method private text_of_selection fmt =
223 match self#get_selections with
225 | node :: _ -> Some (self#string_of_node ~paste_kind:fmt node)
227 method private selection_clear_cb sel_event =
228 self#remove_selections;
229 (GData.clipboard Gdk.Atom.clipboard)#clear ();
232 method private button_press_cb gdk_button =
233 let button = GdkEvent.Button.button gdk_button in
234 if button = left_button then begin
235 button_press_x <- GdkEvent.Button.x gdk_button;
236 button_press_y <- GdkEvent.Button.y gdk_button;
237 selection_changed <- false
238 end else if button = right_button then
239 self#popup_contextual_menu
241 (int_of_float (GdkEvent.Button.x gdk_button))
242 (int_of_float (GdkEvent.Button.y gdk_button)))
243 (GdkEvent.Button.time gdk_button);
246 method private element_over_cb (elt_opt, _, _, _) =
247 let win () = self#misc#window in
249 Gdk.Window.set_cursor (win ()) normal_cursor;
250 HExtlib.iter_option (fun (ctxt, msg) -> ctxt#remove msg)
255 if has_maction elt then
256 Gdk.Window.set_cursor (win ()) maction_cursor
258 (match hrefs_of_elt elt with
259 | Some ((_ :: _) as hrefs) ->
260 Gdk.Window.set_cursor (win ()) href_cursor;
261 let msg_text = (* now create statusbar msg and store it *)
263 | [ href ] -> sprintf "Hyperlink to %s" href
264 | _ -> sprintf "Hyperlinks to: %s" (String.concat ", " hrefs) in
265 let ctxt = (get_gui ())#main#statusBar#new_context ~name:"href" in
266 let msg = ctxt#push msg_text in
267 href_statusbar_msg <- Some (ctxt, msg)
268 | _ -> leave_href ())
269 | None -> leave_href ()
271 method private tactic_text_pattern_of_node node =
272 let id = id_of_node node in
273 let cic_info, unsh_sequent = self#get_cic_info id in
274 match self#get_term_by_id cic_info id with
275 | SelTerm (t, father_hyp) ->
276 let sequent = self#sequent_of_id ~paste_kind:`Pattern id in
277 let text = self#string_of_cic_sequent ~output_type:`Pattern sequent in
278 (match father_hyp with
279 | None -> None, [], Some text
280 | Some hyp_name -> None, [ hyp_name, text ], None)
281 | SelHyp (hyp_name, _ctxt) -> None, [ hyp_name, "%" ], None
283 method private tactic_text_of_node node =
284 let id = id_of_node node in
285 let cic_info, unsh_sequent = self#get_cic_info id in
286 match self#get_term_by_id cic_info id with
287 | SelTerm (t, father_hyp) ->
288 let sequent = self#sequent_of_id ~paste_kind:`Term id in
289 let text = self#string_of_cic_sequent ~output_type:`Term sequent in
291 | SelHyp (hyp_name, _ctxt) -> hyp_name
293 (** @return a pattern structure which contains pretty printed terms *)
294 method private tactic_text_pattern_of_selection =
295 match self#get_selections with
296 | [] -> assert false (* this method is invoked only if there's a sel. *)
297 | node :: _ -> self#tactic_text_pattern_of_node node
299 method private popup_contextual_menu element time =
300 let menu = GMenu.menu () in
301 let add_menu_item ?(menu = menu) ?stock ?label () =
302 GMenu.image_menu_item ?stock ?label ~packing:menu#append () in
303 let check = add_menu_item ~label:"Check" () in
304 let reductions_menu_item = GMenu.menu_item ~label:"βδιζ-reduce" () in
305 let tactics_menu_item = GMenu.menu_item ~label:"Apply tactic" () in
306 let hyperlinks_menu_item = GMenu.menu_item ~label:"Hyperlinks" () in
307 menu#append reductions_menu_item;
308 menu#append tactics_menu_item;
309 menu#append hyperlinks_menu_item;
310 let reductions = GMenu.menu () in
311 let tactics = GMenu.menu () in
312 let hyperlinks = GMenu.menu () in
313 reductions_menu_item#set_submenu reductions;
314 tactics_menu_item#set_submenu tactics;
315 hyperlinks_menu_item#set_submenu hyperlinks;
316 let normalize = add_menu_item ~menu:reductions ~label:"Normalize" () in
317 let simplify = add_menu_item ~menu:reductions ~label:"Simplify" () in
318 let whd = add_menu_item ~menu:reductions ~label:"Weak head" () in
320 | None -> hyperlinks_menu_item#misc#set_sensitive false
322 match hrefs_of_elt elt, href_callback with
326 let item = add_menu_item ~menu:hyperlinks ~label:h () in
327 connect_menu_item item (fun () -> f h)) l
328 | _ -> hyperlinks_menu_item#misc#set_sensitive false);
329 menu#append (GMenu.separator_item ());
330 let copy = add_menu_item ~stock:`COPY () in
331 let gui = get_gui () in
332 List.iter (fun item -> item#misc#set_sensitive gui#canCopy)
333 [ copy; check; normalize; simplify; whd ];
334 let reduction_action kind () =
335 let pat = self#tactic_text_pattern_of_selection in
337 let loc = HExtlib.dummy_floc in
339 GrafiteAstPp.pp_executable ~term_pp:(fun s -> s)
340 ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
341 ~map_unicode_to_tex:(Helm_registry.get_bool
342 "matita.paste_unicode_as_tex")
343 (GrafiteAst.Tactic (loc,
344 Some (GrafiteAst.Reduce (loc, kind, pat)),
345 GrafiteAst.Semicolon loc)) in
346 (MatitaScript.current ())#advance ~statement () in
347 connect_menu_item copy gui#copy;
348 connect_menu_item normalize (reduction_action `Normalize);
349 connect_menu_item simplify (reduction_action `Simpl);
350 connect_menu_item whd (reduction_action `Whd);
351 menu#popup ~button:right_button ~time
353 method private button_release_cb gdk_button =
354 if GdkEvent.Button.button gdk_button = left_button then begin
355 let button_release_x = GdkEvent.Button.x gdk_button in
356 let button_release_y = GdkEvent.Button.y gdk_button in
357 if selection_changed then
359 else (* selection _not_ changed *)
360 if near (button_press_x, button_press_y)
361 (button_release_x, button_release_y)
363 let x = int_of_float button_press_x in
364 let y = int_of_float button_press_y in
365 (match self#get_element_at x y with
368 if has_maction elt then ignore(self#action_toggle elt) else
369 (match hrefs_of_elt elt with
370 | Some hrefs -> self#invoke_href_callback hrefs gdk_button
375 method private invoke_href_callback hrefs gdk_button =
376 let button = GdkEvent.Button.button gdk_button in
377 if button = left_button then
378 let time = GdkEvent.Button.time gdk_button in
379 match href_callback with
385 let menu = GMenu.menu () in
389 GMenu.menu_item ~label:uri ~packing:menu#append () in
390 connect_menu_item menu_item
391 (fun () -> try f uri with Not_found -> assert false))
393 menu#popup ~button ~time)
395 method private choose_selection_cb gdome_elt =
396 let set_selection elt =
397 let misc = self#coerce#misc in
398 self#set_selection (Some elt);
399 misc#add_selection_target ~target:"STRING" Gdk.Atom.primary;
400 ignore (misc#grab_selection Gdk.Atom.primary);
403 if (elt#getAttributeNS ~namespaceURI:helm_ns
404 ~localName:xref_ds)#to_string <> ""
409 (match elt#get_parentNode with
410 | None -> assert false
411 | Some p -> aux (new Gdome.element_of_node p))
412 with GdomeInit.DOMCastException _ -> ()
414 (match gdome_elt with
415 | Some elt when (elt#getAttributeNS ~namespaceURI:xlink_ns
416 ~localName:href_ds)#to_string <> "" ->
418 | Some elt -> aux elt
419 | None -> self#set_selection None);
420 selection_changed <- true
422 method update_font_size = self#set_font_size !current_font_size
424 (** find a term by id from stored CIC infos @return either `Hyp if the id
425 * correspond to an hypothesis or `Term (cic, hyp) if the id correspond to a
426 * term. In the latter case hyp is either None (if the term is a subterm of
427 * the sequent conclusion) or Some hyp_name if the term belongs to an
429 method private get_term_by_id cic_info id =
430 let unsh_item, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, _, _ =
432 let rec find_father_hyp id =
433 if Hashtbl.mem ids_to_hypotheses id
434 then Some (name_of_hypothesis (Hashtbl.find ids_to_hypotheses id))
437 try Hashtbl.find ids_to_father_ids id
438 with Not_found -> assert false in
440 | Some id -> find_father_hyp id
444 let term = Hashtbl.find ids_to_terms id in
445 let father_hyp = find_father_hyp id in
446 SelTerm (term, father_hyp)
449 let hyp = Hashtbl.find ids_to_hypotheses id in
451 match unsh_item with Some seq -> seq | None -> assert false in
452 let context' = MatitaMisc.list_tl_at hyp context in
453 SelHyp (name_of_hypothesis hyp, context')
454 with Not_found -> assert false
456 method private find_obj_conclusion id =
457 match self#cic_info with
459 | Some (_, _, _, _, _, None) -> assert false
460 | Some (_, ids_to_terms, _, ids_to_father_ids, ids_to_inner_types, Some annobj) ->
462 find_root_id annobj id ids_to_father_ids ids_to_terms ids_to_inner_types
464 (try Hashtbl.find ids_to_terms id with Not_found -> assert false)
466 method private string_of_node ~(paste_kind:paste_kind) node =
467 if node#hasAttributeNS ~namespaceURI:helm_ns ~localName:xref_ds
469 match paste_kind with
471 let tactic_text_pattern = self#tactic_text_pattern_of_node node in
472 GrafiteAstPp.pp_tactic_pattern
473 ~term_pp:(fun s -> s) ~lazy_term_pp:(fun _ -> assert false)
474 ~map_unicode_to_tex:(Helm_registry.get_bool
475 "matita.paste_unicode_as_tex")
477 | `Term -> self#tactic_text_of_node node
478 else string_of_dom_node node
480 method private string_of_cic_sequent ~output_type cic_sequent =
481 let script = MatitaScript.current () in
483 if script#onGoingProof () then script#proofMetasenv else [] in
484 let map_unicode_to_tex =
485 Helm_registry.get_bool "matita.paste_unicode_as_tex" in
486 ApplyTransformation.txt_of_cic_sequent_conclusion ~map_unicode_to_tex
487 ~output_type text_width metasenv cic_sequent
489 method private pattern_of term father_hyp unsh_sequent =
490 let _, unsh_context, conclusion = unsh_sequent in
492 match father_hyp with
498 | Some (Cic.Name name', Cic.Decl ty)::_ when name' = name -> ty
499 | Some (Cic.Name name', Cic.Def (bo,_))::_ when name' = name-> bo
504 ProofEngineHelpers.pattern_of ~term:where [term]
506 method private get_cic_info id =
507 match self#cic_info with
508 | Some ((Some unsh_sequent, _, _, _, _, _) as info) -> info, unsh_sequent
509 | Some ((None, _, _, _, _, _) as info) ->
510 let t = self#find_obj_conclusion id in
511 info, (~-1, [], t) (* dummy sequent for obj *)
512 | None -> assert false
514 method private sequent_of_id ~(paste_kind:paste_kind) id =
515 let cic_info, unsh_sequent = self#get_cic_info id in
517 match self#get_term_by_id cic_info id with
518 | SelTerm (t, father_hyp) ->
520 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
523 ProofEngineHelpers.locate_in_conjecture t unsh_sequent in
524 (match occurrences with
526 (match paste_kind with
527 | `Term -> ~-1, context, t
528 | `Pattern -> ~-1, [], self#pattern_of t father_hyp unsh_sequent)
530 HLog.error (sprintf "found %d occurrences while 1 was expected"
531 (List.length occurrences));
532 assert false) (* since it uses physical equality *)
533 | SelHyp (_name, context) -> ~-1, context, Cic.Rel 1 in
536 method private string_of_selection ~(paste_kind:paste_kind) =
537 match self#get_selections with
539 | node :: _ -> Some (self#string_of_node ~paste_kind node)
541 method has_selection = self#get_selections <> []
543 (** @return an associative list format -> string with all possible selection
544 * formats. Rationale: in order to convert the selection to TERM or PATTERN
545 * format we need the sequent, the metasenv, ... keeping all of them in a
546 * closure would be more expensive than keeping their already converted
548 method strings_of_selection =
550 let misc = self#coerce#misc in
552 (fun target -> misc#add_selection_target ~target Gdk.Atom.clipboard)
553 [ "TERM"; "PATTERN"; "STRING" ];
554 ignore (misc#grab_selection Gdk.Atom.clipboard);
557 paste_kind, HExtlib.unopt (self#string_of_selection ~paste_kind))
559 with Failure _ -> failwith "no selection"
563 let clickableMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
564 GtkBase.Widget.size_params
565 ~cont:(OgtkMathViewProps.pack_return (fun p ->
566 OgtkMathViewProps.set_params
567 (new clickableMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
568 ~font_size:None ~log_verbosity:None))
571 class cicMathView obj =
573 inherit clickableMathView obj
575 val mutable current_mathml = None
577 method load_sequent metasenv metano =
578 let sequent = CicUtil.lookup_meta metano metasenv in
579 let (mathml, unsh_sequent,
580 (_, (ids_to_terms, ids_to_father_ids, ids_to_hypotheses,_ )))
582 ApplyTransformation.mml_of_cic_sequent metasenv sequent
585 (Some (Some unsh_sequent,
586 ids_to_terms, ids_to_hypotheses, ids_to_father_ids,
587 Hashtbl.create 1, None));
588 if BuildTimeConf.debug then begin
590 "/tmp/sequent_viewer_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
591 HLog.debug ("load_sequent: dumping MathML to ./" ^ name);
592 ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
594 self#load_root ~root:mathml#get_documentElement
596 method nload_sequent:
597 'status. #NCicCoercion.status as 'status -> NCic.metasenv ->
598 NCic.substitution -> int -> unit
599 = fun status metasenv subst metano ->
600 let sequent = List.assoc metano metasenv in
602 ApplyTransformation.nmml_of_cic_sequent status metasenv subst
605 if BuildTimeConf.debug then begin
607 "/tmp/sequent_viewer_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
608 HLog.debug ("load_sequent: dumping MathML to ./" ^ name);
609 ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
611 self#load_root ~root:mathml#get_documentElement
613 method load_object obj =
614 let use_diff = false in (* ZACK TODO use XmlDiff when re-rendering? *)
616 (annobj, (ids_to_terms, ids_to_father_ids, _, ids_to_hypotheses, _, ids_to_inner_types)))
618 ApplyTransformation.mml_of_cic_object obj
621 (Some (None, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
622 (match current_mathml with
623 | Some current_mathml when use_diff ->
625 XmlDiff.update_dom ~from:current_mathml mathml;
628 if BuildTimeConf.debug then begin
630 "/tmp/cic_browser_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
631 HLog.debug ("cic_browser: dumping MathML to ./" ^ name);
632 ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
634 self#load_root ~root:mathml#get_documentElement;
635 current_mathml <- Some mathml);
637 method load_nobject :
638 'status. #NCicCoercion.status as 'status -> NCic.obj -> unit
640 let mathml = ApplyTransformation.nmml_of_cic_object status obj in
643 (Some (None, ids_to_terms, ids_to_hypotheses, ids_to_father_ids, ids_to_inner_types, Some annobj));
644 (match current_mathml with
645 | Some current_mathml when use_diff ->
647 XmlDiff.update_dom ~from:current_mathml mathml;
651 if BuildTimeConf.debug then begin
653 "/tmp/cic_browser_" ^ string_of_int (Unix.getuid ()) ^ ".xml" in
654 HLog.debug ("cic_browser: dumping MathML to ./" ^ name);
655 ignore (domImpl#saveDocumentToFile ~name ~doc:mathml ())
657 self#load_root ~root:mathml#get_documentElement;
658 (*current_mathml <- Some mathml*)(*)*);
661 let tab_label meta_markup =
664 | `Closed m -> sprintf "<s>%s</s>" (aux m)
665 | `Current m -> sprintf "<b>%s</b>" (aux m)
666 | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
667 | `Meta n -> sprintf "?%d" n
669 let markup = aux meta_markup in
670 (GMisc.label ~markup ~show:true ())#coerce
672 let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
674 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
676 inherit scriptAccessor
678 method cicMathView = cicMathView (** clickableMathView accessor *)
680 val mutable pages = 0
681 val mutable switch_page_callback = None
682 val mutable page2goal = [] (* associative list: page no -> goal no *)
683 val mutable goal2page = [] (* the other way round *)
684 val mutable goal2win = [] (* associative list: goal no -> scrolled win *)
685 val mutable _metasenv = `Old []
686 val mutable scrolledWin: GBin.scrolled_window option = None
687 (* scrolled window to which the sequentViewer is currently attached *)
688 val logo = (GMisc.image
689 ~file:(MatitaMisc.image_path "matita_medium.png") ()
692 val logo_with_qed = (GMisc.image
693 ~file:(MatitaMisc.image_path "matita_small.png") ()
697 notebook#set_show_tabs false;
698 ignore(notebook#append_page logo)
700 method load_logo_with_qed =
701 notebook#set_show_tabs false;
702 ignore(notebook#append_page logo_with_qed)
705 cicMathView#remove_selections;
706 (match scrolledWin with
708 (* removing page from the notebook will destroy all contained widget,
709 * we do not want the cicMathView to be destroyed as well *)
710 w#remove cicMathView#coerce;
713 (match switch_page_callback with
715 GtkSignal.disconnect notebook#as_widget id;
716 switch_page_callback <- None
718 for i = 0 to pages do notebook#remove_page 0 done;
719 notebook#set_show_tabs true;
724 _metasenv <- `Old [];
725 self#script#setGoal None
727 method load_sequents : 'status. #NCicCoercion.status as 'status -> 'a
728 = fun status { proof= (_,metasenv,_subst,_,_, _) as proof; stack = stack }
730 _metasenv <- `Old metasenv;
732 let win goal_switch =
734 GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
735 ~shadow_type:`IN ~show:true ()
738 scrolledWin <- Some w;
739 match cicMathView#misc#parent with
740 | None -> w#add cicMathView#coerce
743 match cicMathView#misc#parent with
745 | Some p -> GContainer.cast_container p
747 parent#remove cicMathView#coerce;
748 w#add cicMathView#coerce
750 goal2win <- (goal_switch, reparent) :: goal2win;
754 let stack_goals = Stack.open_goals stack in
755 let proof_goals = ProofEngineTypes.goals_of_proof proof in
757 HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
758 <> List.sort Pervasives.compare proof_goals
760 prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
761 prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
767 function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
770 let added_goals = ref [] in
771 (* goals can be duplicated on the tack due to focus, but we should avoid
772 * multiple labels in the user interface *)
773 let add_tab markup goal_switch =
774 let goal = Stack.goal_of_switch goal_switch in
775 if not (List.mem goal !added_goals) then begin
776 ignore(notebook#append_page
777 ~tab_label:(tab_label markup) (win goal_switch));
778 page2goal <- (!page, goal_switch) :: page2goal;
779 goal2page <- (goal_switch, !page) :: goal2page;
782 added_goals := goal :: !added_goals
785 let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
786 Stack.iter (** populate notebook with tabs *)
787 ~env:(fun depth tag (pos, sw) ->
789 match depth, pos with
790 | 0, 0 -> `Current (render_switch sw)
791 | 0, _ -> `Shift (pos, `Current (render_switch sw))
792 | 1, pos when Stack.head_tag stack = `BranchTag ->
793 `Shift (pos, render_switch sw)
794 | _ -> render_switch sw
797 ~cont:add_switch ~todo:add_switch
799 switch_page_callback <-
800 Some (notebook#connect#switch_page ~callback:(fun page ->
802 try List.assoc page page2goal with Not_found -> assert false
804 self#script#setGoal (Some (goal_of_switch goal_switch));
805 self#render_page status ~page ~goal_switch))
807 method nload_sequents : 'status. #NTacStatus.tac_status as 'status -> unit
809 let _,_,metasenv,subst,_ = status#obj in
810 _metasenv <- `New (metasenv,subst);
812 let win goal_switch =
814 GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
815 ~shadow_type:`IN ~show:true ()
818 scrolledWin <- Some w;
819 match cicMathView#misc#parent with
820 | None -> w#add cicMathView#coerce
823 match cicMathView#misc#parent with
825 | Some p -> GContainer.cast_container p
827 parent#remove cicMathView#coerce;
828 w#add cicMathView#coerce
830 goal2win <- (goal_switch, reparent) :: goal2win;
834 let stack_goals = Stack.open_goals status#stack in
835 let proof_goals = List.map fst metasenv in
837 HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
838 <> List.sort Pervasives.compare proof_goals
840 prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
841 prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
847 function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
850 let added_goals = ref [] in
851 (* goals can be duplicated on the tack due to focus, but we should avoid
852 * multiple labels in the user interface *)
853 let add_tab markup goal_switch =
854 let goal = Stack.goal_of_switch goal_switch in
855 if not (List.mem goal !added_goals) then begin
856 ignore(notebook#append_page
857 ~tab_label:(tab_label markup) (win goal_switch));
858 page2goal <- (!page, goal_switch) :: page2goal;
859 goal2page <- (goal_switch, !page) :: goal2page;
862 added_goals := goal :: !added_goals
865 let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
866 Stack.iter (** populate notebook with tabs *)
867 ~env:(fun depth tag (pos, sw) ->
869 match depth, pos with
870 | 0, 0 -> `Current (render_switch sw)
871 | 0, _ -> `Shift (pos, `Current (render_switch sw))
872 | 1, pos when Stack.head_tag status#stack = `BranchTag ->
873 `Shift (pos, render_switch sw)
874 | _ -> render_switch sw
877 ~cont:add_switch ~todo:add_switch
879 switch_page_callback <-
880 Some (notebook#connect#switch_page ~callback:(fun page ->
882 try List.assoc page page2goal with Not_found -> assert false
884 self#script#setGoal (Some (goal_of_switch goal_switch));
885 self#render_page status ~page ~goal_switch))
887 method private render_page:
888 'status. #NCicCoercion.status as 'status -> page:int ->
889 goal_switch:Stack.switch -> unit
890 = fun status ~page ~goal_switch ->
891 (match goal_switch with
893 (match _metasenv with
894 `Old menv -> cicMathView#load_sequent menv goal
895 | `New (menv,subst) ->
896 cicMathView#nload_sequent status menv subst goal)
897 | Stack.Closed goal ->
898 let doc = Lazy.force closed_goal_mathml in
899 cicMathView#load_root ~root:doc#get_documentElement);
901 cicMathView#set_selection None;
902 List.assoc goal_switch goal2win ()
903 with Not_found -> assert false)
905 method goto_sequent: 'status. #NCicCoercion.status as 'status -> int -> unit
907 let goal_switch, page =
910 (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
912 with Not_found -> assert false
914 notebook#goto_page page;
915 self#render_page status ~page ~goal_switch
921 type 'widget constructor =
922 ?hadjustment:GData.adjustment ->
923 ?vadjustment:GData.adjustment ->
925 ?log_verbosity:int ->
928 ?packing:(GObj.widget -> unit) ->
933 let cicMathView ?hadjustment ?vadjustment ?font_size ?log_verbosity =
934 GtkBase.Widget.size_params
935 ~cont:(OgtkMathViewProps.pack_return (fun p ->
936 OgtkMathViewProps.set_params
937 (new cicMathView (GtkMathViewProps.MathView_GMetaDOM.create p))
938 ~font_size ~log_verbosity))
941 let blank_uri = BuildTimeConf.blank_uri
942 let current_proof_uri = BuildTimeConf.current_proof_uri
945 [ `Ast of CicNotationPt.term
946 | `Cic of Cic.term * Cic.metasenv
947 | `NCic of NCic.term * NCic.context * NCic.metasenv * NCic.substitution
951 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
954 let whelp_RE = Pcre.regexp "^\\s*whelp" in
957 "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
959 let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
960 let metadata_RE = Pcre.regexp "^metadata:/(deps)/(forward|backward)/(.*)$" in
961 let whelp_query_RE = Pcre.regexp
962 "^\\s*whelp\\s+([^\\s]+)\\s+(\"|\\()(.*)(\\)|\")$"
964 let is_metadata txt = Pcre.pmatch ~rex:metadata_RE txt in
965 let is_whelp txt = Pcre.pmatch ~rex:whelp_RE txt in
966 let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
967 let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
968 let gui = get_gui () in
969 let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
970 let gviz = LablGraphviz.graphviz ~packing:win#graphScrolledWin#add () in
971 let queries = ["Locate";"Hint";"Match";"Elim";"Instance"] in
972 let combo,_ = GEdit.combo_box_text ~strings:queries () in
973 let activate_combo_query input q =
974 let q' = String.lowercase q in
975 let rec aux i = function
976 | [] -> failwith ("Whelp query '" ^ q ^ "' not found")
977 | h::_ when String.lowercase h = q' -> i
978 | _::tl -> aux (i+1) tl
980 win#queryInputText#set_text input;
981 combo#set_active (aux 0 queries);
984 GSourceView2.source_view ~auto_indent:false ~editable:false ()
987 win#scrolledwinContent#add (searchText :> GObj.widget);
989 let text = win#entrySearch#text in
990 let highlight start end_ =
991 searchText#source_buffer#move_mark `INSERT ~where:start;
992 searchText#source_buffer#move_mark `SEL_BOUND ~where:end_;
993 searchText#scroll_mark_onscreen `INSERT
995 let iter = searchText#source_buffer#get_iter `SEL_BOUND in
996 match iter#forward_search text with
998 (match searchText#source_buffer#start_iter#forward_search text with
1000 | Some (start,end_) -> highlight start end_)
1001 | Some (start,end_) -> highlight start end_
1003 ignore(win#entrySearch#connect#activate ~callback);
1004 ignore(win#buttonSearch#connect#clicked ~callback);
1006 let set_whelp_query txt =
1009 let q = Pcre.extract ~rex:whelp_query_RE txt in
1011 with Not_found -> failwith "Malformed Whelp query"
1013 activate_combo_query arg query;
1015 let toplevel = win#toplevel in
1016 let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
1018 MatitaGtkMisc.report_error ~title:"Cic browser" ~message
1022 [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
1023 "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
1025 let b = (not (Helm_registry.get_bool "matita.debug")) in
1026 let handle_error f =
1031 fail (snd (MatitaExcPp.to_string exn))
1034 let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
1035 let load_easter_egg = lazy (
1036 win#browserImage#set_file (MatitaMisc.image_path "meegg.png"))
1039 let module Pp = GraphvizPp.Dot in
1040 let filename, oc = Filename.open_temp_file "matita" ".dot" in
1041 let fmt = Format.formatter_of_out_channel oc in
1042 let status = (MatitaScript.current ())#grafite_status in
1046 ~graph_attrs:["overlap", "false"]
1047 ~node_attrs:["fontsize", "9"; "width", ".4";
1048 "height", ".4"; "shape", "box"]
1049 ~edge_attrs:["fontsize", "10"; "len", "2"] fmt;
1050 NCicUnifHint.generate_dot_file status fmt;
1054 gviz#load_graph_from_file ~gviz_cmd:"neato -Tpng" filename;
1055 (*HExtlib.safe_remove filename*)
1057 let load_coerchgraph tred () =
1058 let module Pp = GraphvizPp.Dot in
1059 let filename, oc = Filename.open_temp_file "matita" ".dot" in
1060 let fmt = Format.formatter_of_out_channel oc in
1063 ~node_attrs:["fontsize", "9"; "width", ".4"; "height", ".4"]
1064 ~edge_attrs:["fontsize", "10"] fmt;
1065 let status = (MatitaScript.current ())#grafite_status in
1066 NCicCoercion.generate_dot_file status fmt;
1069 ~name:"OLDCoercions"
1070 ~node_attrs:["fontsize", "9"; "width", ".4"; "height", ".4"]
1071 ~edge_attrs:["fontsize", "10"] fmt;
1072 CoercGraph.generate_dot_file fmt;
1077 gviz#load_graph_from_file
1078 ~gviz_cmd:"dot -Txdot | tred |gvpack -gv | dot" filename
1080 gviz#load_graph_from_file
1081 ~gviz_cmd:"dot -Txdot | gvpack -gv | dot" filename;
1082 HExtlib.safe_remove filename
1085 inherit scriptAccessor
1087 (* Whelp bar queries *)
1089 val mutable gviz_graph = MetadataDeps.DepGraph.dummy
1090 val mutable gviz_uri = UriManager.uri_of_string "cic:/dummy.con";
1092 val dep_contextual_menu = GMenu.menu ()
1095 activate_combo_query "" "locate";
1096 win#whelpBarComboVbox#add combo#coerce;
1097 let start_query () =
1100 String.lowercase (List.nth queries combo#active)
1101 with Not_found -> assert false in
1102 let input = win#queryInputText#text in
1104 if query = "locate" then
1105 "whelp " ^ query ^ " \"" ^ input ^ "\"."
1107 "whelp " ^ query ^ " (" ^ input ^ ")."
1109 (MatitaScript.current ())#advance ~statement ()
1111 ignore(win#queryInputText#connect#activate ~callback:start_query);
1112 ignore(combo#connect#changed ~callback:start_query);
1113 win#whelpBarImage#set_file (MatitaMisc.image_path "whelp.png");
1114 win#mathOrListNotebook#set_show_tabs false;
1115 win#browserForwardButton#misc#set_sensitive false;
1116 win#browserBackButton#misc#set_sensitive false;
1117 ignore (win#browserUri#connect#activate (handle_error' (fun () ->
1118 self#loadInput win#browserUri#text)));
1119 ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
1120 self#load (`About `Current_proof))));
1121 ignore (win#browserRefreshButton#connect#clicked
1122 (handle_error' (self#refresh ~force:true)));
1123 ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
1124 ignore (win#browserForwardButton#connect#clicked
1125 (handle_error' self#forward));
1126 ignore (win#toplevel#event#connect#delete (fun _ ->
1127 let my_id = Oo.id self in
1128 cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
1130 ignore(win#whelpResultTreeview#connect#row_activated
1131 ~callback:(fun _ _ ->
1132 handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
1133 mathView#set_href_callback (Some (fun uri ->
1134 handle_error (fun () ->
1137 `Uri (UriManager.uri_of_string uri)
1139 UriManager.IllFormedUri _ ->
1140 `NRef (NReference.reference_of_string uri)
1143 gviz#connect_href (fun button_ev attrs ->
1144 let time = GdkEvent.Button.time button_ev in
1145 let uri = List.assoc "href" attrs in
1146 gviz_uri <- UriManager.uri_of_string uri;
1147 match GdkEvent.Button.button button_ev with
1148 | button when button = left_button -> self#load (`Uri gviz_uri)
1149 | button when button = right_button ->
1150 dep_contextual_menu#popup ~button ~time
1152 connect_menu_item win#depGraphMenuItem (fun () ->
1153 match self#currentCicUri with
1154 | Some uri -> self#load (`Metadata (`Deps (`Fwd, uri)))
1156 connect_menu_item win#invDepGraphMenuItem (fun () ->
1157 match self#currentCicUri with
1158 | Some uri -> self#load (`Metadata (`Deps (`Back, uri)))
1160 connect_menu_item win#browserCloseMenuItem (fun () ->
1161 let my_id = Oo.id self in
1162 cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
1163 win#toplevel#misc#hide(); win#toplevel#destroy ());
1166 connect_menu_item win#hBugsTutorsMenuItem (fun () ->
1167 self#load (`HBugs `Tutors));
1169 win#hBugsTutorsMenuItem#misc#hide ();
1170 connect_menu_item win#browserUrlMenuItem (fun () ->
1171 win#browserUri#misc#grab_focus ());
1172 connect_menu_item win#univMenuItem (fun () ->
1173 match self#currentCicUri with
1174 | Some uri -> self#load (`Univs uri)
1177 (* fill dep graph contextual menu *)
1179 GMenu.image_menu_item ~label:"Browse it"
1180 ~packing:dep_contextual_menu#append () in
1181 let expand_menu_item =
1182 GMenu.image_menu_item ~label:"Expand"
1183 ~packing:dep_contextual_menu#append () in
1184 let collapse_menu_item =
1185 GMenu.image_menu_item ~label:"Collapse"
1186 ~packing:dep_contextual_menu#append () in
1187 dep_contextual_menu#append (go_menu_item :> GMenu.menu_item);
1188 dep_contextual_menu#append (expand_menu_item :> GMenu.menu_item);
1189 dep_contextual_menu#append (collapse_menu_item :> GMenu.menu_item);
1190 connect_menu_item go_menu_item (fun () -> self#load (`Uri gviz_uri));
1191 connect_menu_item expand_menu_item (fun () ->
1192 MetadataDeps.DepGraph.expand gviz_uri gviz_graph;
1193 self#redraw_gviz ~center_on:gviz_uri ());
1194 connect_menu_item collapse_menu_item (fun () ->
1195 MetadataDeps.DepGraph.collapse gviz_uri gviz_graph;
1196 self#redraw_gviz ~center_on:gviz_uri ());
1198 self#_load (`About `Blank);
1201 val mutable current_entry = `About `Blank
1203 (** @return None if no object uri can be built from the current entry *)
1204 method private currentCicUri =
1205 match current_entry with
1207 | `Metadata (`Deps (_, uri)) -> Some uri
1211 new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
1213 new MatitaGtkMisc.multiStringListModel ~cols:2 win#universesTreeview
1215 val mutable lastDir = "" (* last loaded "directory" *)
1217 method mathView = (mathView :> MatitaGuiTypes.clickableMathView)
1219 method private _getSelectedUri () =
1220 match model#easy_selection () with
1221 | [sel] when is_uri sel -> sel (* absolute URI selected *)
1222 (* | [sel] -> win#browserUri#entry#text ^ sel |+ relative URI selected +| *)
1223 | [sel] -> lastDir ^ sel
1226 (** history RATIONALE
1228 * All operations about history are done using _historyFoo.
1229 * Only toplevel functions (ATM load and loadInput) call _historyAdd.
1232 method private _historyAdd item =
1234 win#browserBackButton#misc#set_sensitive true;
1235 win#browserForwardButton#misc#set_sensitive false
1237 method private _historyPrev () =
1238 let item = history#previous in
1239 if history#is_begin then win#browserBackButton#misc#set_sensitive false;
1240 win#browserForwardButton#misc#set_sensitive true;
1243 method private _historyNext () =
1244 let item = history#next in
1245 if history#is_end then win#browserForwardButton#misc#set_sensitive false;
1246 win#browserBackButton#misc#set_sensitive true;
1249 (** notebook RATIONALE
1251 * Use only these functions to switch between the tabs
1253 method private _showMath = win#mathOrListNotebook#goto_page 0
1254 method private _showList = win#mathOrListNotebook#goto_page 1
1255 method private _showList2 = win#mathOrListNotebook#goto_page 5
1256 method private _showSearch = win#mathOrListNotebook#goto_page 6
1257 method private _showGviz = win#mathOrListNotebook#goto_page 3
1258 method private _showHBugs = win#mathOrListNotebook#goto_page 4
1260 method private back () =
1262 self#_load (self#_historyPrev ())
1263 with MatitaMisc.History_failure -> ()
1265 method private forward () =
1267 self#_load (self#_historyNext ())
1268 with MatitaMisc.History_failure -> ()
1270 (* loads a uri which can be a cic uri or an about:* uri
1271 * @param uri string *)
1272 method private _load ?(force=false) entry =
1273 handle_error (fun () ->
1274 if entry <> current_entry || entry = `About `Current_proof || entry =
1275 `About `Coercions || entry = `About `CoercionsFull || force then
1278 | `About `Current_proof -> self#home ()
1279 | `About `Blank -> self#blank ()
1280 | `About `Us -> self#egg ()
1281 | `About `CoercionsFull -> self#coerchgraph false ()
1282 | `About `Coercions -> self#coerchgraph true ()
1283 | `About `Hints -> self#hints ()
1284 | `About `TeX -> self#tex ()
1285 | `About `Grammar -> self#grammar ()
1286 | `Check term -> self#_loadCheck term
1287 | `Cic (term, metasenv) -> self#_loadTermCic term metasenv
1288 | `NCic (term, ctx, metasenv, subst) ->
1289 self#_loadTermNCic term metasenv subst ctx
1290 | `Dir dir -> self#_loadDir dir
1291 | `HBugs `Tutors -> self#_loadHBugsTutors
1292 | `Metadata (`Deps ((`Fwd | `Back) as dir, uri)) ->
1293 self#dependencies dir uri ()
1294 | `Uri uri -> self#_loadUriManagerUri uri
1295 | `NRef nref -> self#_loadNReference nref
1296 | `Univs uri -> self#_loadUnivs uri
1297 | `Whelp (query, results) ->
1298 set_whelp_query query;
1299 self#_loadList (List.map (fun r -> "obj",
1300 UriManager.string_of_uri r) results));
1304 method private blank () =
1306 mathView#load_root (Lazy.force empty_mathml)#get_documentElement
1308 method private _loadCheck term =
1309 failwith "not implemented _loadCheck";
1310 (* self#_showMath *)
1312 method private egg () =
1313 win#mathOrListNotebook#goto_page 2;
1314 Lazy.force load_easter_egg
1316 method private redraw_gviz ?center_on () =
1317 if Sys.command "which dot" = 0 then
1318 let tmpfile, oc = Filename.open_temp_file "matita" ".dot" in
1319 let fmt = Format.formatter_of_out_channel oc in
1320 MetadataDeps.DepGraph.render fmt gviz_graph;
1322 gviz#load_graph_from_file ~gviz_cmd:"tred | dot" tmpfile;
1323 (match center_on with
1325 | Some uri -> gviz#center_on_href (UriManager.string_of_uri uri));
1326 HExtlib.safe_remove tmpfile
1328 MatitaGtkMisc.report_error ~title:"graphviz error"
1329 ~message:("Graphviz is not installed but is necessary to render "^
1330 "the graph of dependencies amoung objects. Please install it.")
1331 ~parent:win#toplevel ()
1333 method private dependencies direction uri () =
1334 let dbd = LibraryDb.instance () in
1336 match direction with
1337 | `Fwd -> MetadataDeps.DepGraph.direct_deps ~dbd uri
1338 | `Back -> MetadataDeps.DepGraph.inverse_deps ~dbd uri in
1339 gviz_graph <- graph; (** XXX check this for memory consuption *)
1340 self#redraw_gviz ~center_on:uri ();
1343 method private coerchgraph tred () =
1344 load_coerchgraph tred ();
1347 method private hints () =
1351 method private tex () =
1352 let b = Buffer.create 1000 in
1353 Printf.bprintf b "UTF-8 equivalence classes (rotate with ALT-L):\n\n";
1356 List.iter (fun sym ->
1357 Printf.bprintf b " %s" (Glib.Utf8.from_unichar sym)
1359 Printf.bprintf b "\n";
1362 (fun l1 l2 -> compare (List.hd l1) (List.hd l2))
1363 (Virtuals.get_all_eqclass ()));
1364 Printf.bprintf b "\n\nVirtual keys (trigger with ALT-L):\n\n";
1367 Printf.bprintf b " %s:\n" tag;
1369 (fun names, symbol ->
1370 Printf.bprintf b " \t%s\t%s\n"
1371 (Glib.Utf8.from_unichar symbol)
1372 (String.concat ", " names))
1374 (fun (_,a) (_,b) -> compare a b)
1376 Printf.bprintf b "\n")
1378 (fun (a,_) (b,_) -> compare a b)
1379 (Virtuals.get_all_virtuals ()));
1380 self#_loadText (Buffer.contents b)
1382 method private _loadText text =
1383 searchText#source_buffer#set_text text;
1384 win#entrySearch#misc#grab_focus ();
1387 method private grammar () =
1388 self#_loadText (Print_grammar.ebnf_of_term ());
1390 method private home () =
1392 match self#script#grafite_status#proof_status with
1393 | Proof (uri, metasenv, _subst, bo, ty, attrs) ->
1394 let name = UriManager.name_of_uri (HExtlib.unopt uri) in
1396 Cic.CurrentProof (name, metasenv, Lazy.force bo, ty, [], attrs)
1399 | Incomplete_proof { proof = (uri, metasenv, _subst, bo, ty, attrs) } ->
1400 let name = UriManager.name_of_uri (HExtlib.unopt uri) in
1402 Cic.CurrentProof (name, metasenv, Lazy.force bo, ty, [], attrs)
1406 match self#script#grafite_status#ng_mode with
1408 self#_loadNObj self#script#grafite_status
1409 self#script#grafite_status#obj
1410 | _ -> self#blank ()
1412 (** loads a cic uri from the environment
1413 * @param uri UriManager.uri *)
1414 method private _loadUriManagerUri uri =
1415 let uri = UriManager.strip_xpointer uri in
1416 let (obj, _) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1419 method private _loadNReference (NReference.Ref (uri,_)) =
1420 let obj = NCicEnvironment.get_checked_obj uri in
1421 self#_loadNObj self#script#grafite_status obj
1423 method private _loadUnivs uri =
1424 let uri = UriManager.strip_xpointer uri in
1425 let (_, u) = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
1426 let _,us = CicUniv.do_rank u in
1430 [ CicUniv.string_of_universe u ; string_of_int (CicUniv.get_rank u)])
1435 method private _loadDir dir =
1436 let content = Http_getter.ls ~local:false dir in
1442 | Http_getter_types.Ls_section s -> "dir", s
1443 | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
1449 method private _loadHBugsTutors =
1452 method private setEntry entry =
1453 win#browserUri#set_text (MatitaTypes.string_of_entry entry);
1454 current_entry <- entry
1456 method private _loadObj obj =
1457 (* showMath must be done _before_ loading the document, since if the
1458 * widget is not mapped (hidden by the notebook) the document is not
1461 mathView#load_object obj
1463 method private _loadNObj status obj =
1464 (* showMath must be done _before_ loading the document, since if the
1465 * widget is not mapped (hidden by the notebook) the document is not
1468 mathView#load_nobject status obj
1470 method private _loadTermCic term metasenv =
1471 let context = self#script#proofContext in
1472 let dummyno = CicMkImplicit.new_meta metasenv [] in
1473 let sequent = (dummyno, context, term) in
1474 mathView#load_sequent (sequent :: metasenv) dummyno;
1477 method private _loadTermNCic term m s c =
1479 let m = (0,([],c,term))::m in
1480 let status = (MatitaScript.current ())#grafite_status in
1481 mathView#nload_sequent status m s d;
1484 method private _loadList l =
1485 model#list_store#clear ();
1486 List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
1489 method private _loadList2 l =
1490 model_univs#list_store#clear ();
1491 List.iter model_univs#easy_mappend l;
1494 (** { public methods, all must call _load!! } *)
1497 handle_error (fun () -> self#_load entry; self#_historyAdd entry)
1499 (** this is what the browser does when you enter a string an hit enter *)
1500 method loadInput txt =
1501 let parse_metadata s =
1502 let subs = Pcre.extract ~rex:metadata_RE s in
1503 let uri = UriManager.uri_of_string ("cic:/" ^ subs.(3)) in
1504 match subs.(1), subs.(2) with
1505 | "deps", "forward" -> `Deps (`Fwd, uri)
1506 | "deps", "backward" -> `Deps (`Back, uri)
1509 let txt = HExtlib.trim_blanks txt in
1510 (* (* ZACK: what the heck? *)
1512 UriManager.string_of_uri
1513 (UriManager.strip_xpointer (UriManager.uri_of_string txt))
1516 if is_whelp txt then begin
1517 set_whelp_query txt;
1518 (MatitaScript.current ())#advance ~statement:(txt ^ ".") ()
1522 | txt when is_uri txt ->
1523 `Uri (UriManager.uri_of_string ((*fix_uri*) txt))
1524 | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
1525 | txt when is_metadata txt -> `Metadata (parse_metadata txt)
1526 | "hbugs:/tutors/" -> `HBugs `Tutors
1529 MatitaTypes.entry_of_string txt
1530 with Invalid_argument _ ->
1532 (GrafiteTypes.Command_error(sprintf "unsupported uri: %s" txt)))
1535 self#_historyAdd entry
1538 (** {2 methods accessing underlying GtkMathView} *)
1540 method updateFontSize = mathView#set_font_size !current_font_size
1542 (** {2 methods used by constructor only} *)
1545 method history = history
1546 method currentEntry = current_entry
1547 method refresh ~force () = self#_load ~force current_entry
1551 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
1552 MatitaGuiTypes.sequentsViewer
1554 new sequentsViewer ~notebook ~cicMathView ()
1557 let size = BuildTimeConf.browser_history_size in
1558 let rec aux history =
1559 let browser = new cicBrowser_impl ~history () in
1560 let win = browser#win in
1561 ignore (win#browserNewButton#connect#clicked (fun () ->
1563 new MatitaMisc.browser_history ~memento:history#save size
1566 let newBrowser = aux history in
1567 newBrowser#load browser#currentEntry));
1569 (* attempt (failed) to close windows on CTRL-W ... *)
1570 MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
1571 GdkKeysyms._W (fun () -> win#toplevel#destroy ());
1573 cicBrowsers := browser :: !cicBrowsers;
1574 (browser :> MatitaGuiTypes.cicBrowser)
1576 let history = new MatitaMisc.browser_history size (`About `Blank) in
1579 let default_cicMathView () = cicMathView ~show:true ()
1580 let cicMathView_instance = MatitaMisc.singleton default_cicMathView
1582 let default_sequentsViewer () =
1583 let gui = get_gui () in
1584 let cicMathView = cicMathView_instance () in
1585 sequentsViewer ~notebook:gui#main#sequentsNotebook ~cicMathView ()
1586 let sequentsViewer_instance = MatitaMisc.singleton default_sequentsViewer
1590 method private get_browser reuse =
1592 (match !cicBrowsers with
1593 | [] -> cicBrowser ()
1594 | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
1598 method show_entry ?(reuse=false) t = (self#get_browser reuse)#load t
1600 method show_uri_list ?(reuse=false) ~entry l =
1601 (self#get_browser reuse)#load entry
1603 method screenshot status sequents metasenv subst (filename as ofn) =
1604 let w = GWindow.window ~title:"screenshot" () in
1606 let height = 2000 in
1607 let m = GMathView.math_view
1608 ~font_size:!current_font_size ~width ~height
1615 (fun (mno,_ as sequent) i ->
1617 ApplyTransformation.nmml_of_cic_sequent
1618 status metasenv subst sequent
1620 m#load_root ~root:mathml#get_documentElement;
1621 let pixmap = m#get_buffer in
1622 let pixbuf = GdkPixbuf.create ~width ~height () in
1623 GdkPixbuf.get_from_drawable ~dest:pixbuf pixmap;
1625 filename ^ "-raw" ^ string_of_int i ^ ".png"
1627 GdkPixbuf.save ~filename ~typ:"png" pixbuf;
1632 List.map (fun (x,mno) ->
1636 " '(' -gravity west -bordercolor grey -border 1 label:%d ')' "^^
1637 " '(' -trim -bordercolor white -border 5 "^^
1638 " -bordercolor grey -border 1 %s ')' -append %s ")
1641 (Filename.quote (x ^ ".label.png"))));
1645 let rec div2 = function
1648 | x::y::tl -> [x;y] :: div2 tl
1650 let items = div2 items in
1651 ignore(Sys.command (Printf.sprintf
1652 "convert %s -append %s"
1654 (List.map (fun items ->
1655 Printf.sprintf " '(' %s +append ')' "
1657 (" '(' -gravity center -size 10x10 xc: ')' ") items)) items))
1658 (Filename.quote (ofn ^ ".png"))));
1659 List.iter (fun x,_ -> Sys.remove x) filenames;
1660 List.iter Sys.remove (List.flatten items);
1664 let refresh_all_browsers () =
1665 List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
1667 let update_font_sizes () =
1668 List.iter (fun b -> b#updateFontSize) !cicBrowsers;
1669 (cicMathView_instance ())#update_font_size
1671 let get_math_views () =
1672 ((cicMathView_instance ()) :> MatitaGuiTypes.clickableMathView)
1673 :: (List.map (fun b -> b#mathView) !cicBrowsers)
1675 let find_selection_owner () =
1678 | [] -> raise Not_found
1680 (match mv#get_selections with
1684 aux (get_math_views ())
1686 let has_selection () =
1687 try ignore (find_selection_owner ()); true
1688 with Not_found -> false
1690 let math_view_clipboard = ref None (* associative list target -> string *)
1691 let has_clipboard () = !math_view_clipboard <> None
1692 let empty_clipboard () = math_view_clipboard := None
1694 let copy_selection () =
1696 math_view_clipboard :=
1697 Some ((find_selection_owner ())#strings_of_selection)
1698 with Not_found -> failwith "no selection"
1700 let paste_clipboard paste_kind =
1701 match !math_view_clipboard with
1702 | None -> failwith "empty clipboard"
1704 (try List.assoc paste_kind cb with Not_found -> assert false)