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/.
35 module Stack = Continuationals.Stack
37 (** inherit from this class if you want to access current script *)
38 class scriptAccessor =
40 method private script = get_matita_script_current ()
43 let cicBrowsers = ref []
45 let tab_label meta_markup =
48 | `Closed m -> sprintf "<s>%s</s>" (aux m)
49 | `Current m -> sprintf "<b>%s</b>" (aux m)
50 | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
51 | `Meta n -> sprintf "?%d" n
53 let markup = aux meta_markup in
54 (GMisc.label ~markup ~show:true ())#coerce
56 let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
58 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
60 inherit scriptAccessor
62 method cicMathView = cicMathView (** clickableMathView accessor *)
65 val mutable switch_page_callback = None
66 val mutable page2goal = [] (* associative list: page no -> goal no *)
67 val mutable goal2page = [] (* the other way round *)
68 val mutable goal2win = [] (* associative list: goal no -> scrolled win *)
69 val mutable _metasenv = `Old []
70 val mutable scrolledWin: GBin.scrolled_window option = None
71 (* scrolled window to which the sequentViewer is currently attached *)
72 val logo = (GMisc.image
73 ~file:(MatitaMisc.image_path "matita_medium.png") ()
76 val logo_with_qed = (GMisc.image
77 ~file:(MatitaMisc.image_path "matita_small.png") ()
81 notebook#set_show_tabs false;
82 ignore(notebook#append_page logo)
84 method load_logo_with_qed =
85 notebook#set_show_tabs false;
86 ignore(notebook#append_page logo_with_qed)
89 cicMathView#remove_selections;
90 (match scrolledWin with
92 (* removing page from the notebook will destroy all contained widget,
93 * we do not want the cicMathView to be destroyed as well *)
94 w#remove cicMathView#coerce;
97 (match switch_page_callback with
99 GtkSignal.disconnect notebook#as_widget id;
100 switch_page_callback <- None
102 for i = 0 to pages do notebook#remove_page 0 done;
103 notebook#set_show_tabs true;
110 method nload_sequents : 'status. #GrafiteTypes.status as 'status -> unit
111 = fun (status : #GrafiteTypes.status) ->
112 let _,_,metasenv,subst,_ = status#obj in
113 _metasenv <- `New (metasenv,subst);
115 let win goal_switch =
117 GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
118 ~shadow_type:`IN ~show:true ()
121 scrolledWin <- Some w;
122 match cicMathView#misc#parent with
123 | None -> w#add cicMathView#coerce
126 match cicMathView#misc#parent with
128 | Some p -> GContainer.cast_container p
130 parent#remove cicMathView#coerce;
131 w#add cicMathView#coerce
133 goal2win <- (goal_switch, reparent) :: goal2win;
137 let stack_goals = Stack.open_goals status#stack in
138 let proof_goals = List.map fst metasenv in
140 HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
141 <> List.sort Pervasives.compare proof_goals
143 prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
144 prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
150 function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
153 let added_goals = ref [] in
154 (* goals can be duplicated on the tack due to focus, but we should avoid
155 * multiple labels in the user interface *)
156 let add_tab markup goal_switch =
157 let goal = Stack.goal_of_switch goal_switch in
158 if not (List.mem goal !added_goals) then begin
159 ignore(notebook#append_page
160 ~tab_label:(tab_label markup) (win goal_switch));
161 page2goal <- (!page, goal_switch) :: page2goal;
162 goal2page <- (goal_switch, !page) :: goal2page;
165 added_goals := goal :: !added_goals
168 let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
169 Stack.iter (** populate notebook with tabs *)
170 ~env:(fun depth tag (pos, sw) ->
172 match depth, pos with
173 | 0, 0 -> `Current (render_switch sw)
174 | 0, _ -> `Shift (pos, `Current (render_switch sw))
175 | 1, pos when Stack.head_tag status#stack = `BranchTag ->
176 `Shift (pos, render_switch sw)
177 | _ -> render_switch sw
180 ~cont:add_switch ~todo:add_switch
182 switch_page_callback <-
183 Some (notebook#connect#switch_page ~callback:(fun page ->
185 try List.assoc page page2goal with Not_found -> assert false
187 self#render_page status ~page ~goal_switch))
189 method private render_page:
190 'status. #ApplyTransformation.status as 'status -> page:int ->
191 goal_switch:Stack.switch -> unit
192 = fun status ~page ~goal_switch ->
193 (match goal_switch with
195 (match _metasenv with
196 `Old menv -> assert false (* MATITA 1.0 *)
197 | `New (menv,subst) ->
198 cicMathView#nload_sequent status menv subst goal)
199 | Stack.Closed goal ->
200 let root = Lazy.force closed_goal_mathml in
201 cicMathView#load_root ~root);
203 cicMathView#set_selection None;
204 List.assoc goal_switch goal2win ()
205 with Not_found -> assert false)
207 method goto_sequent: 'status. #ApplyTransformation.status as 'status -> int -> unit
209 let goal_switch, page =
212 (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
214 with Not_found -> assert false
216 notebook#goto_page page;
217 self#render_page status ~page ~goal_switch
221 let blank_uri = BuildTimeConf.blank_uri
222 let current_proof_uri = BuildTimeConf.current_proof_uri
225 [ `Ast of NotationPt.term
226 | `NCic of NCic.term * NCic.context * NCic.metasenv * NCic.substitution
230 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
235 "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
237 let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
238 let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
239 let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
240 let gui = MatitaMisc.get_gui () in
241 let (win: MatitaGuiTypes.browserWin) = gui#newBrowserWin () in
242 let gviz = LablGraphviz.graphviz ~packing:win#graphScrolledWin#add () in
244 GSourceView2.source_view ~auto_indent:false ~editable:false ()
247 win#scrolledwinContent#add (searchText :> GObj.widget);
249 let text = win#entrySearch#text in
250 let highlight start end_ =
251 searchText#source_buffer#move_mark `INSERT ~where:start;
252 searchText#source_buffer#move_mark `SEL_BOUND ~where:end_;
253 searchText#scroll_mark_onscreen `INSERT
255 let iter = searchText#source_buffer#get_iter `SEL_BOUND in
256 match iter#forward_search text with
258 (match searchText#source_buffer#start_iter#forward_search text with
260 | Some (start,end_) -> highlight start end_)
261 | Some (start,end_) -> highlight start end_
263 ignore(win#entrySearch#connect#activate ~callback);
264 ignore(win#buttonSearch#connect#clicked ~callback);
266 let toplevel = win#toplevel in
267 let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
269 MatitaGtkMisc.report_error ~title:"Cic browser" ~message
273 [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
274 "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
276 let b = (not (Helm_registry.get_bool "matita.debug")) in
282 fail (snd (MatitaExcPp.to_string exn))
285 let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
286 let load_easter_egg = lazy (
287 win#browserImage#set_file (MatitaMisc.image_path "meegg.png"))
290 let module Pp = GraphvizPp.Dot in
291 let filename, oc = Filename.open_temp_file "matita" ".dot" in
292 let fmt = Format.formatter_of_out_channel oc in
293 let status = (get_matita_script_current ())#grafite_status in
297 ~graph_attrs:["overlap", "false"]
298 ~node_attrs:["fontsize", "9"; "width", ".4";
299 "height", ".4"; "shape", "box"]
300 ~edge_attrs:["fontsize", "10"; "len", "2"] fmt;
301 NCicUnifHint.generate_dot_file status fmt;
305 gviz#load_graph_from_file ~gviz_cmd:"neato -Tpng" filename;
306 (*HExtlib.safe_remove filename*)
308 let load_coerchgraph tred () =
309 let module Pp = GraphvizPp.Dot in
310 let filename, oc = Filename.open_temp_file "matita" ".dot" in
311 let fmt = Format.formatter_of_out_channel oc in
314 ~node_attrs:["fontsize", "9"; "width", ".4"; "height", ".4"]
315 ~edge_attrs:["fontsize", "10"] fmt;
316 let status = (get_matita_script_current ())#grafite_status in
317 NCicCoercion.generate_dot_file status fmt;
322 gviz#load_graph_from_file
323 ~gviz_cmd:"dot -Txdot | tred |gvpack -gv | dot" filename
325 gviz#load_graph_from_file
326 ~gviz_cmd:"dot -Txdot | gvpack -gv | dot" filename;
327 HExtlib.safe_remove filename
330 inherit scriptAccessor
332 val mutable gviz_uri = NReference.reference_of_string "cic:/dummy.dec";
334 val dep_contextual_menu = GMenu.menu ()
337 win#mathOrListNotebook#set_show_tabs false;
338 win#browserForwardButton#misc#set_sensitive false;
339 win#browserBackButton#misc#set_sensitive false;
340 ignore (win#browserUri#connect#activate (handle_error' (fun () ->
341 self#loadInput win#browserUri#text)));
342 ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
343 self#load (`About `Current_proof))));
344 ignore (win#browserRefreshButton#connect#clicked
345 (handle_error' (self#refresh ~force:true)));
346 ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
347 ignore (win#browserForwardButton#connect#clicked
348 (handle_error' self#forward));
349 ignore (win#toplevel#event#connect#delete (fun _ ->
350 let my_id = Oo.id self in
351 cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
353 ignore(win#whelpResultTreeview#connect#row_activated
354 ~callback:(fun _ _ ->
355 handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
356 mathView#set_href_callback (Some (fun uri ->
357 handle_error (fun () ->
358 let uri = `NRef (NReference.reference_of_string uri) in
360 gviz#connect_href (fun button_ev attrs ->
361 let time = GdkEvent.Button.time button_ev in
362 let uri = List.assoc "href" attrs in
363 gviz_uri <- NReference.reference_of_string uri;
364 match GdkEvent.Button.button button_ev with
365 | button when button = MatitaMisc.left_button -> self#load (`NRef gviz_uri)
366 | button when button = MatitaMisc.right_button ->
367 dep_contextual_menu#popup ~button ~time
369 connect_menu_item win#browserCloseMenuItem (fun () ->
370 let my_id = Oo.id self in
371 cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
372 win#toplevel#misc#hide(); win#toplevel#destroy ());
373 connect_menu_item win#browserUrlMenuItem (fun () ->
374 win#browserUri#misc#grab_focus ());
376 self#_load (`About `Blank);
379 val mutable current_entry = `About `Blank
381 (** @return None if no object uri can be built from the current entry *)
382 method private currentCicUri =
383 match current_entry with
384 | `NRef uri -> Some uri
388 new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
390 val mutable lastDir = "" (* last loaded "directory" *)
392 method mathView = mathView
394 method private _getSelectedUri () =
395 match model#easy_selection () with
396 | [sel] when is_uri sel -> sel (* absolute URI selected *)
397 (* | [sel] -> win#browserUri#entry#text ^ sel |+ relative URI selected +| *)
398 | [sel] -> lastDir ^ sel
401 (** history RATIONALE
403 * All operations about history are done using _historyFoo.
404 * Only toplevel functions (ATM load and loadInput) call _historyAdd.
407 method private _historyAdd item =
409 win#browserBackButton#misc#set_sensitive true;
410 win#browserForwardButton#misc#set_sensitive false
412 method private _historyPrev () =
413 let item = history#previous in
414 if history#is_begin then win#browserBackButton#misc#set_sensitive false;
415 win#browserForwardButton#misc#set_sensitive true;
418 method private _historyNext () =
419 let item = history#next in
420 if history#is_end then win#browserForwardButton#misc#set_sensitive false;
421 win#browserBackButton#misc#set_sensitive true;
424 (** notebook RATIONALE
426 * Use only these functions to switch between the tabs
428 method private _showMath = win#mathOrListNotebook#goto_page 0
429 method private _showList = win#mathOrListNotebook#goto_page 1
430 method private _showEgg = win#mathOrListNotebook#goto_page 2
431 method private _showGviz = win#mathOrListNotebook#goto_page 3
432 method private _showSearch = win#mathOrListNotebook#goto_page 4
434 method private back () =
436 self#_load (self#_historyPrev ())
437 with MatitaMisc.History_failure -> ()
439 method private forward () =
441 self#_load (self#_historyNext ())
442 with MatitaMisc.History_failure -> ()
444 (* loads a uri which can be a cic uri or an about:* uri
445 * @param uri string *)
446 method private _load ?(force=false) entry =
447 handle_error (fun () ->
448 if entry <> current_entry || entry = `About `Current_proof || entry =
449 `About `Coercions || entry = `About `CoercionsFull || force then
452 | `About `Current_proof -> self#home ()
453 | `About `Blank -> self#blank ()
454 | `About `Us -> self#egg ()
455 | `About `CoercionsFull -> self#coerchgraph false ()
456 | `About `Coercions -> self#coerchgraph true ()
457 | `About `Hints -> self#hints ()
458 | `About `TeX -> self#tex ()
459 | `About `Grammar -> self#grammar ()
460 | `Check term -> self#_loadCheck term
461 | `NCic (term, ctx, metasenv, subst) ->
462 self#_loadTermNCic term metasenv subst ctx
463 | `Dir dir -> self#_loadDir dir
464 | `NRef nref -> self#_loadNReference nref);
468 method private blank () =
470 mathView#load_root (Lazy.force empty_mathml)
472 method private _loadCheck term =
473 failwith "not implemented _loadCheck";
476 method private egg () =
478 Lazy.force load_easter_egg
480 method private redraw_gviz ?center_on () =
481 if Sys.command "which dot" = 0 then
482 let tmpfile, oc = Filename.open_temp_file "matita" ".dot" in
483 let fmt = Format.formatter_of_out_channel oc in
484 (* MATITA 1.0 MetadataDeps.DepGraph.render fmt gviz_graph;*)
486 gviz#load_graph_from_file ~gviz_cmd:"tred | dot" tmpfile;
487 (match center_on with
489 | Some uri -> gviz#center_on_href (NReference.string_of_reference uri));
490 HExtlib.safe_remove tmpfile
492 MatitaGtkMisc.report_error ~title:"graphviz error"
493 ~message:("Graphviz is not installed but is necessary to render "^
494 "the graph of dependencies amoung objects. Please install it.")
495 ~parent:win#toplevel ()
497 method private dependencies direction uri () =
498 assert false (* MATITA 1.0
499 let dbd = LibraryDb.instance () in
502 | `Fwd -> MetadataDeps.DepGraph.direct_deps ~dbd uri
503 | `Back -> MetadataDeps.DepGraph.inverse_deps ~dbd uri in
504 gviz_graph <- graph; (** XXX check this for memory consuption *)
505 self#redraw_gviz ~center_on:uri ();
508 method private coerchgraph tred () =
509 load_coerchgraph tred ();
512 method private hints () =
516 method private tex () =
517 let b = Buffer.create 1000 in
518 Printf.bprintf b "UTF-8 equivalence classes (rotate with ALT-L):\n\n";
521 List.iter (fun sym ->
522 Printf.bprintf b " %s" (Glib.Utf8.from_unichar sym)
524 Printf.bprintf b "\n";
527 (fun l1 l2 -> compare (List.hd l1) (List.hd l2))
528 (Virtuals.get_all_eqclass ()));
529 Printf.bprintf b "\n\nVirtual keys (trigger with ALT-L):\n\n";
532 Printf.bprintf b " %s:\n" tag;
534 (fun names, symbol ->
535 Printf.bprintf b " \t%s\t%s\n"
536 (Glib.Utf8.from_unichar symbol)
537 (String.concat ", " names))
539 (fun (_,a) (_,b) -> compare a b)
541 Printf.bprintf b "\n")
543 (fun (a,_) (b,_) -> compare a b)
544 (Virtuals.get_all_virtuals ()));
545 self#_loadText (Buffer.contents b)
547 method private _loadText text =
548 searchText#source_buffer#set_text text;
549 win#entrySearch#misc#grab_focus ();
552 method private grammar () =
553 self#_loadText (Print_grammar.ebnf_of_term self#script#grafite_status);
555 method private home () =
557 match self#script#grafite_status#ng_mode with
559 self#_loadNObj self#script#grafite_status
560 self#script#grafite_status#obj
563 method private _loadNReference (NReference.Ref (uri,_)) =
564 let obj = NCicEnvironment.get_checked_obj uri in
565 self#_loadNObj self#script#grafite_status obj
567 method private _loadDir dir =
568 let content = Http_getter.ls ~local:false dir in
574 | Http_getter_types.Ls_section s -> "dir", s
575 | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
581 method private setEntry entry =
582 win#browserUri#set_text (MatitaTypes.string_of_entry entry);
583 current_entry <- entry
585 method private _loadNObj status obj =
586 (* showMath must be done _before_ loading the document, since if the
587 * widget is not mapped (hidden by the notebook) the document is not
590 mathView#load_nobject status obj
592 method private _loadTermNCic term m s c =
594 let m = (0,([],c,term))::m in
595 let status = (get_matita_script_current ())#grafite_status in
596 mathView#nload_sequent status m s d;
599 method private _loadList l =
600 model#list_store#clear ();
601 List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
604 (** { public methods, all must call _load!! } *)
607 handle_error (fun () -> self#_load entry; self#_historyAdd entry)
609 (** this is what the browser does when you enter a string an hit enter *)
610 method loadInput txt =
611 let txt = HExtlib.trim_blanks txt in
612 (* (* ZACK: what the heck? *)
614 UriManager.string_of_uri
615 (UriManager.strip_xpointer (UriManager.uri_of_string txt))
620 | txt when is_uri txt ->
621 `NRef (NReference.reference_of_string ((*fix_uri*) txt))
622 | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
625 MatitaTypes.entry_of_string txt
626 with Invalid_argument _ ->
628 (GrafiteTypes.Command_error(sprintf "unsupported uri: %s" txt)))
631 self#_historyAdd entry
633 (** {2 methods used by constructor only} *)
636 method history = history
637 method currentEntry = current_entry
638 method refresh ~force () = self#_load ~force current_entry
642 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
643 MatitaGuiTypes.sequentsViewer
645 (new sequentsViewer ~notebook ~cicMathView ():> MatitaGuiTypes.sequentsViewer)
648 let size = BuildTimeConf.browser_history_size in
649 let rec aux history =
650 let browser = new cicBrowser_impl ~history () in
651 let win = browser#win in
652 ignore (win#browserNewButton#connect#clicked (fun () ->
654 new MatitaMisc.browser_history ~memento:history#save size
657 let newBrowser = aux history in
658 newBrowser#load browser#currentEntry));
660 (* attempt (failed) to close windows on CTRL-W ... *)
661 MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
662 GdkKeysyms._W (fun () -> win#toplevel#destroy ());
664 cicBrowsers := browser :: !cicBrowsers;
665 (browser :> MatitaGuiTypes.cicBrowser)
667 let history = new MatitaMisc.browser_history size (`About `Blank) in
670 let default_cicMathView () =
671 let res = cicMathView ~show:true () in
672 res#set_href_callback
674 let uri = `NRef (NReference.reference_of_string uri) in
675 (cicBrowser ())#load uri));
678 let cicMathView_instance =
679 MatitaMisc.singleton default_cicMathView
681 let default_sequentsViewer notebook =
682 let cicMathView = cicMathView_instance () in
683 sequentsViewer ~notebook ~cicMathView ()
684 let sequentsViewer_instance =
685 let already_used = ref false in
687 if !already_used then assert false
689 (already_used := true;
690 default_sequentsViewer notebook)
692 (** @param reuse if set reused last opened cic browser otherwise
693 * opens a new one. default is false *)
694 let show_entry ?(reuse=false) t =
697 (match !cicBrowsers with
699 | b :: _ -> (b :> MatitaGuiTypes.cicBrowser))
706 let refresh_all_browsers () =
707 List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
709 let get_math_views () =
710 (cicMathView_instance ()) :: (List.map (fun b -> b#mathView) !cicBrowsers)
712 let find_selection_owner () =
715 | [] -> raise Not_found
717 (match mv#get_selections with
721 aux (get_math_views ())
723 let has_selection () =
724 try ignore (find_selection_owner ()); true
725 with Not_found -> false
727 let math_view_clipboard = ref None (* associative list target -> string *)
728 let has_clipboard () = !math_view_clipboard <> None
729 let empty_clipboard () = math_view_clipboard := None
731 let copy_selection () =
733 math_view_clipboard :=
734 Some ((find_selection_owner ())#strings_of_selection)
735 with Not_found -> failwith "no selection"
737 let paste_clipboard paste_kind =
738 match !math_view_clipboard with
739 | None -> failwith "empty clipboard"
741 (try List.assoc paste_kind cb with Not_found -> assert false)