]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitaMathView.ml
ground_2 released and permanently renamed as ground
[helm.git] / matitaB / matita / matitaMathView.ml
1 (* Copyright (C) 2004-2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (* $Id$ *)
27
28 open Printf
29
30 open GrafiteTypes
31 open MatitaGtkMisc
32 open MatitaGuiTypes
33 open CicMathView
34
35 module Stack = Continuationals.Stack
36
37 let cicBrowsers = ref []
38
39 let tab_label meta_markup =
40   let rec aux =
41     function
42     | `Closed m -> sprintf "<s>%s</s>" (aux m)
43     | `Current m -> sprintf "<b>%s</b>" (aux m)
44     | `Shift (pos, m) -> sprintf "|<sub>%d</sub>: %s" pos (aux m)
45     | `Meta n -> sprintf "?%d" n
46   in
47   let markup = aux meta_markup in
48   (GMisc.label ~markup ~show:true ())#coerce
49
50 let goal_of_switch = function Stack.Open g | Stack.Closed g -> g
51
52 class sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) () =
53   object (self)
54     method cicMathView = cicMathView  (** clickableMathView accessor *)
55
56     val mutable pages = 0
57     val mutable switch_page_callback = None
58     val mutable page2goal = []  (* associative list: page no -> goal no *)
59     val mutable goal2page = []  (* the other way round *)
60     val mutable goal2win = []   (* associative list: goal no -> scrolled win *)
61     val mutable _metasenv = [],[]
62     val mutable scrolledWin: GBin.scrolled_window option = None
63       (* scrolled window to which the sequentViewer is currently attached *)
64     val logo = (GMisc.image
65       ~file:(MatitaMisc.image_path "matita_medium.png") ()
66       :> GObj.widget)
67             
68     val logo_with_qed = (GMisc.image
69       ~file:(MatitaMisc.image_path "matita_small.png") ()
70       :> GObj.widget)
71
72     method load_logo =
73      notebook#set_show_tabs false;
74      ignore(notebook#append_page logo)
75
76     method load_logo_with_qed =
77      notebook#set_show_tabs false;
78      ignore(notebook#append_page logo_with_qed)
79
80     method reset =
81       cicMathView#remove_selections;
82       (match scrolledWin with
83       | Some w ->
84           (* removing page from the notebook will destroy all contained widget,
85           * we do not want the cicMathView to be destroyed as well *)
86           w#remove cicMathView#coerce;
87           scrolledWin <- None
88       | None -> ());
89       (match switch_page_callback with
90       | Some id ->
91           GtkSignal.disconnect notebook#as_widget id;
92           switch_page_callback <- None
93       | None -> ());
94       for i = 0 to pages do notebook#remove_page 0 done; 
95       notebook#set_show_tabs true;
96       pages <- 0;
97       page2goal <- [];
98       goal2page <- [];
99       goal2win <- [];
100       _metasenv <- [],[]
101
102     method nload_sequents : 'status. #GrafiteTypes.status as 'status -> unit
103     = fun (status : #GrafiteTypes.status) ->
104      let _,_,metasenv,subst,_ = status#obj in
105       _metasenv <- metasenv,subst;
106       pages <- 0;
107       let win goal_switch =
108         let w =
109           GBin.scrolled_window ~hpolicy:`AUTOMATIC ~vpolicy:`ALWAYS
110             ~shadow_type:`IN ~show:true ()
111         in
112         let reparent () =
113           scrolledWin <- Some w;
114           (match cicMathView#misc#parent with
115             | None -> ()
116             | Some parent ->
117                let parent =
118                 match cicMathView#misc#parent with
119                    None -> assert false
120                  | Some p -> GContainer.cast_container p
121                in
122                 parent#remove cicMathView#coerce);
123           w#add cicMathView#coerce;
124           ignore (w#vadjustment#set_value
125            (w#vadjustment#upper -. w#vadjustment#page_size));
126           ignore (w#vadjustment#connect#changed (fun _ ->
127             w#vadjustment#set_value
128              (w#vadjustment#upper -. w#vadjustment#page_size)))
129         in
130         goal2win <- (goal_switch, reparent) :: goal2win;
131         w#coerce
132       in
133       assert (
134         let stack_goals = Stack.open_goals status#stack in
135         let proof_goals = List.map fst metasenv in
136         if
137           HExtlib.list_uniq (List.sort Pervasives.compare stack_goals)
138           <> List.sort Pervasives.compare proof_goals
139         then begin
140           prerr_endline ("STACK GOALS = " ^ String.concat " " (List.map string_of_int stack_goals));
141           prerr_endline ("PROOF GOALS = " ^ String.concat " " (List.map string_of_int proof_goals));
142           false
143         end
144         else true
145       );
146       let render_switch =
147         function Stack.Open i ->`Meta i | Stack.Closed i ->`Closed (`Meta i)
148       in
149       let page = ref 0 in
150       let added_goals = ref [] in
151         (* goals can be duplicated on the tack due to focus, but we should avoid
152          * multiple labels in the user interface *)
153       let add_tab markup goal_switch =
154         let goal = Stack.goal_of_switch goal_switch in
155         if not (List.mem goal !added_goals) then begin
156           ignore(notebook#append_page 
157             ~tab_label:(tab_label markup) (win goal_switch));
158           page2goal <- (!page, goal_switch) :: page2goal;
159           goal2page <- (goal_switch, !page) :: goal2page;
160           incr page;
161           pages <- pages + 1;
162           added_goals := goal :: !added_goals
163         end
164       in
165       let add_switch _ _ (_, sw) = add_tab (render_switch sw) sw in
166       Stack.iter  (** populate notebook with tabs *)
167         ~env:(fun depth tag (pos, sw) ->
168           let markup =
169             match depth, pos with
170             | 0, 0 -> `Current (render_switch sw)
171             | 0, _ -> `Shift (pos, `Current (render_switch sw))
172             | 1, pos when Stack.head_tag status#stack = `BranchTag ->
173                 `Shift (pos, render_switch sw)
174             | _ -> render_switch sw
175           in
176           add_tab markup sw)
177         ~cont:add_switch ~todo:add_switch
178         status#stack;
179       switch_page_callback <-
180         Some (notebook#connect#switch_page ~callback:(fun page ->
181           let goal_switch =
182             try List.assoc page page2goal with Not_found -> assert false
183           in
184           self#render_page status ~page ~goal_switch))
185
186     method private render_page:
187      'status. #ApplyTransformation.status as 'status -> page:int ->
188        goal_switch:Stack.switch -> unit
189      = fun status ~page ~goal_switch ->
190       (match goal_switch with
191       | Stack.Open goal ->
192          let menv,subst = _metasenv in
193           cicMathView#nload_sequent status menv subst goal
194       | Stack.Closed goal ->
195           let root = Lazy.force closed_goal_mathml in
196           cicMathView#load_root ~root);
197       (try
198         cicMathView#set_selection None;
199         List.assoc goal_switch goal2win ()
200       with Not_found -> assert false)
201
202     method goto_sequent: 'status. #ApplyTransformation.status as 'status -> int -> unit
203      = fun status goal ->
204       let goal_switch, page =
205         try
206           List.find
207             (function Stack.Open g, _ | Stack.Closed g, _ -> g = goal)
208             goal2page
209         with Not_found -> assert false
210       in
211       notebook#goto_page page;
212       self#render_page status ~page ~goal_switch
213
214   end
215
216 let blank_uri = BuildTimeConf.blank_uri
217 let current_proof_uri = BuildTimeConf.current_proof_uri
218
219 type term_source =
220   [ `Ast of NotationPt.term
221   | `NCic of NCic.term * NCic.context * NCic.metasenv * NCic.substitution
222   | `String of string
223   ]
224
225 class cicBrowser_impl ~(history:MatitaTypes.mathViewer_entry MatitaMisc.history)
226   ()
227 =
228   let uri_RE =
229     Pcre.regexp
230       "^cic:/([^/]+/)*[^/]+\\.(con|ind|var)(#xpointer\\(\\d+(/\\d+)+\\))?$"
231   in
232   let dir_RE = Pcre.regexp "^cic:((/([^/]+/)*[^/]+(/)?)|/|)$" in
233   let is_uri txt = Pcre.pmatch ~rex:uri_RE txt in
234   let is_dir txt = Pcre.pmatch ~rex:dir_RE txt in
235   let gui = MatitaMisc.get_gui () in
236   let win = new MatitaGeneratedGui.browserWin () in
237   let _ = win#browserUri#misc#grab_focus () in
238   let gviz = LablGraphviz.graphviz ~packing:win#graphScrolledWin#add () in
239   let searchText = 
240     GSourceView2.source_view ~auto_indent:false ~editable:false ()
241   in
242   let _ =
243      win#scrolledwinContent#add (searchText :> GObj.widget);
244      let callback () = 
245        let text = win#entrySearch#text in
246        let highlight start end_ =
247          searchText#source_buffer#move_mark `INSERT ~where:start;
248          searchText#source_buffer#move_mark `SEL_BOUND ~where:end_;
249          searchText#scroll_mark_onscreen `INSERT
250        in
251        let iter = searchText#source_buffer#get_iter `SEL_BOUND in
252        match iter#forward_search text with
253        | None -> 
254            (match searchText#source_buffer#start_iter#forward_search text with
255            | None -> ()
256            | Some (start,end_) -> highlight start end_)
257        | Some (start,end_) -> highlight start end_
258      in
259      ignore(win#entrySearch#connect#activate ~callback);
260      ignore(win#buttonSearch#connect#clicked ~callback);
261   in
262   let toplevel = win#toplevel in
263   let mathView = cicMathView ~packing:win#scrolledBrowser#add () in
264   let fail message = 
265     MatitaGtkMisc.report_error ~title:"Cic browser" ~message 
266       ~parent:toplevel ()  
267   in
268   let tags =
269     [ "dir", GdkPixbuf.from_file (MatitaMisc.image_path "matita-folder.png");
270       "obj", GdkPixbuf.from_file (MatitaMisc.image_path "matita-object.png") ]
271   in
272   let b = (not (Helm_registry.get_bool "matita.debug")) in
273   let handle_error f =
274     try
275       f ()
276     with exn ->
277       if b then
278         fail (snd (MatitaExcPp.to_string exn))
279       else raise exn
280   in
281   let handle_error' f = (fun () -> handle_error (fun () -> f ())) in
282   let load_easter_egg = lazy (
283     win#browserImage#set_file (MatitaMisc.image_path "meegg.png"))
284   in
285   let load_hints () =
286       let module Pp = GraphvizPp.Dot in
287       let filename, oc = Filename.open_temp_file "matita" ".dot" in
288       let fmt = Format.formatter_of_out_channel oc in
289       let status = (get_matita_script_current ())#status in
290       Pp.header 
291         ~name:"Hints"
292         ~graph_type:"graph"
293         ~graph_attrs:["overlap", "false"]
294         ~node_attrs:["fontsize", "9"; "width", ".4"; 
295             "height", ".4"; "shape", "box"]
296         ~edge_attrs:["fontsize", "10"; "len", "2"] fmt;
297       NCicUnifHint.generate_dot_file status fmt;
298       Pp.trailer fmt;
299       Pp.raw "@." fmt;
300       close_out oc;
301       gviz#load_graph_from_file ~gviz_cmd:"neato -Tpng" filename;
302       (*HExtlib.safe_remove filename*)
303   in
304   let load_coerchgraph tred () = 
305       let module Pp = GraphvizPp.Dot in
306       let filename, oc = Filename.open_temp_file "matita" ".dot" in
307       let fmt = Format.formatter_of_out_channel oc in
308       Pp.header 
309         ~name:"Coercions"
310         ~node_attrs:["fontsize", "9"; "width", ".4"; "height", ".4"]
311         ~edge_attrs:["fontsize", "10"] fmt;
312       let status = (get_matita_script_current ())#status in
313       NCicCoercion.generate_dot_file status fmt;
314       Pp.trailer fmt;
315       Pp.raw "@." fmt;
316       close_out oc;
317       if tred then
318         gviz#load_graph_from_file 
319           ~gviz_cmd:"dot -Txdot | tred |gvpack -gv | dot" filename
320       else
321         gviz#load_graph_from_file 
322           ~gviz_cmd:"dot -Txdot | gvpack -gv | dot" filename;
323       HExtlib.safe_remove filename
324   in
325   object (self)
326     val mutable gviz_uri = NReference.reference_of_string "cic:/dummy.dec";
327
328     val dep_contextual_menu = GMenu.menu ()
329
330     initializer
331       win#mathOrListNotebook#set_show_tabs false;
332       win#browserForwardButton#misc#set_sensitive false;
333       win#browserBackButton#misc#set_sensitive false;
334       ignore (win#browserUri#connect#activate (handle_error' (fun () ->
335         self#loadInput win#browserUri#text)));
336       ignore (win#browserHomeButton#connect#clicked (handle_error' (fun () ->
337         self#load (`About `Current_proof))));
338       ignore (win#browserRefreshButton#connect#clicked
339         (handle_error' (self#refresh ~force:true)));
340       ignore (win#browserBackButton#connect#clicked (handle_error' self#back));
341       ignore (win#browserForwardButton#connect#clicked
342         (handle_error' self#forward));
343       ignore (win#toplevel#event#connect#delete (fun _ ->
344         let my_id = Oo.id self in
345         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
346         false));
347       ignore(win#whelpResultTreeview#connect#row_activated 
348         ~callback:(fun _ _ ->
349           handle_error (fun () -> self#loadInput (self#_getSelectedUri ()))));
350       mathView#set_href_callback (Some (fun uri ->
351         handle_error (fun () ->
352          let uri = `NRef (NReference.reference_of_string uri) in
353           self#load uri)));
354       gviz#connect_href (fun button_ev attrs ->
355         let time = GdkEvent.Button.time button_ev in
356         let uri = List.assoc "href" attrs in
357         gviz_uri <- NReference.reference_of_string uri;
358         match GdkEvent.Button.button button_ev with
359         | button when button = MatitaMisc.left_button -> self#load (`NRef gviz_uri)
360         | button when button = MatitaMisc.right_button ->
361             dep_contextual_menu#popup ~button ~time
362         | _ -> ());
363       connect_menu_item win#browserCloseMenuItem (fun () ->
364         let my_id = Oo.id self in
365         cicBrowsers := List.filter (fun b -> Oo.id b <> my_id) !cicBrowsers;
366         win#toplevel#misc#hide(); win#toplevel#destroy ());
367       connect_menu_item win#browserUrlMenuItem (fun () ->
368         win#browserUri#misc#grab_focus ());
369
370       self#_load (`About `Blank);
371       toplevel#show ()
372
373     val mutable current_entry = `About `Blank 
374
375       (** @return None if no object uri can be built from the current entry *)
376     method private currentCicUri =
377       match current_entry with
378       | `NRef uri -> Some uri
379       | _ -> None
380
381     val model =
382       new MatitaGtkMisc.taggedStringListModel tags win#whelpResultTreeview
383
384     val mutable lastDir = ""  (* last loaded "directory" *)
385
386     method mathView = mathView
387
388     method private _getSelectedUri () =
389       match model#easy_selection () with
390       | [sel] when is_uri sel -> sel  (* absolute URI selected *)
391 (*       | [sel] -> win#browserUri#entry#text ^ sel  |+ relative URI selected +| *)
392       | [sel] -> lastDir ^ sel
393       | _ -> assert false
394
395     (** history RATIONALE 
396      *
397      * All operations about history are done using _historyFoo.
398      * Only toplevel functions (ATM load and loadInput) call _historyAdd.
399      *)
400           
401     method private _historyAdd item = 
402       history#add item;
403       win#browserBackButton#misc#set_sensitive true;
404       win#browserForwardButton#misc#set_sensitive false
405
406     method private _historyPrev () =
407       let item = history#previous in
408       if history#is_begin then win#browserBackButton#misc#set_sensitive false;
409       win#browserForwardButton#misc#set_sensitive true;
410       item
411     
412     method private _historyNext () =
413       let item = history#next in
414       if history#is_end then win#browserForwardButton#misc#set_sensitive false;
415       win#browserBackButton#misc#set_sensitive true;
416       item
417
418     (** notebook RATIONALE 
419      * 
420      * Use only these functions to switch between the tabs
421      *)
422     method private _showMath = win#mathOrListNotebook#goto_page   0
423     method private _showList = win#mathOrListNotebook#goto_page   1
424     method private _showEgg  = win#mathOrListNotebook#goto_page   2
425     method private _showGviz = win#mathOrListNotebook#goto_page   3
426     method private _showSearch = win#mathOrListNotebook#goto_page 4
427
428     method private back () =
429       try
430         self#_load (self#_historyPrev ())
431       with MatitaMisc.History_failure -> ()
432
433     method private forward () =
434       try
435         self#_load (self#_historyNext ())
436       with MatitaMisc.History_failure -> ()
437
438       (* loads a uri which can be a cic uri or an about:* uri
439       * @param uri string *)
440     method private _load ?(force=false) entry =
441       handle_error (fun () ->
442        if entry <> current_entry || entry = `About `Current_proof || entry =
443          `About `Coercions || entry = `About `CoercionsFull || force then
444         begin
445           (match entry with
446           | `About `Current_proof -> self#home ()
447           | `About `Blank -> self#blank ()
448           | `About `Us -> self#egg ()
449           | `About `CoercionsFull -> self#coerchgraph false ()
450           | `About `Coercions -> self#coerchgraph true ()
451           | `About `Hints -> self#hints ()
452           | `About `TeX -> self#tex ()
453           | `About `Grammar -> self#grammar () 
454           | `Check term -> self#_loadCheck term
455           | `NCic (term, ctx, metasenv, subst) -> 
456                self#_loadTermNCic term metasenv subst ctx
457           | `Dir dir -> self#_loadDir dir
458           | `NRef nref -> self#_loadNReference nref);
459           self#setEntry entry
460         end)
461
462     method private blank () =
463       self#_showMath;
464       mathView#load_root (Lazy.force empty_mathml)
465
466     method private _loadCheck term =
467       failwith "not implemented _loadCheck";
468 (*       self#_showMath *)
469
470     method private egg () =
471       self#_showEgg;
472       Lazy.force load_easter_egg
473
474     method private redraw_gviz ?center_on () =
475       if Sys.command "which dot" = 0 then
476        let tmpfile, oc = Filename.open_temp_file "matita" ".dot" in
477        let fmt = Format.formatter_of_out_channel oc in
478        (* MATITA 1.0 MetadataDeps.DepGraph.render fmt gviz_graph;*)
479        close_out oc;
480        gviz#load_graph_from_file ~gviz_cmd:"tred | dot" tmpfile;
481        (match center_on with
482        | None -> ()
483        | Some uri -> gviz#center_on_href (NReference.string_of_reference uri));
484        HExtlib.safe_remove tmpfile
485       else
486        MatitaGtkMisc.report_error ~title:"graphviz error"
487         ~message:("Graphviz is not installed but is necessary to render "^
488          "the graph of dependencies amoung objects. Please install it.")
489         ~parent:win#toplevel ()
490
491     method private dependencies direction uri () =
492       assert false (* MATITA 1.0
493       let dbd = LibraryDb.instance () in
494       let graph =
495         match direction with
496         | `Fwd -> MetadataDeps.DepGraph.direct_deps ~dbd uri
497         | `Back -> MetadataDeps.DepGraph.inverse_deps ~dbd uri in
498       gviz_graph <- graph;  (** XXX check this for memory consuption *)
499       self#redraw_gviz ~center_on:uri ();
500       self#_showGviz *)
501
502     method private coerchgraph tred () =
503       load_coerchgraph tred ();
504       self#_showGviz
505
506     method private hints () =
507       load_hints ();
508       self#_showGviz
509
510     method private tex () =
511       let b = Buffer.create 1000 in
512       Printf.bprintf b "UTF-8 equivalence classes (rotate with ALT-L):\n\n";
513       List.iter 
514         (fun l ->
515            List.iter (fun sym ->
516              Printf.bprintf b "  %s" (Glib.Utf8.from_unichar sym) 
517            ) l;
518            Printf.bprintf b "\n";
519         )
520         (List.sort 
521           (fun l1 l2 -> compare (List.hd l1) (List.hd l2))
522           (Virtuals.get_all_eqclass ()));
523       Printf.bprintf b "\n\nVirtual keys (trigger with ALT-L):\n\n";
524       List.iter 
525         (fun tag, items -> 
526            Printf.bprintf b "  %s:\n" tag;
527            List.iter 
528              (fun names, symbol ->
529                 Printf.bprintf b "  \t%s\t%s\n" 
530                   (Glib.Utf8.from_unichar symbol)
531                   (String.concat ", " names))
532              (List.sort 
533                (fun (_,a) (_,b) -> compare a b)
534                items);
535            Printf.bprintf b "\n")
536         (List.sort 
537           (fun (a,_) (b,_) -> compare a b)
538           (Virtuals.get_all_virtuals ()));
539       self#_loadText (Buffer.contents b)
540
541     method private _loadText text =
542       searchText#source_buffer#set_text text;
543       win#entrySearch#misc#grab_focus ();
544       self#_showSearch
545
546     method private grammar () =
547       self#_loadText
548        (Print_grammar.ebnf_of_term (get_matita_script_current ())#status);
549
550     method private home () =
551       self#_showMath;
552       let status = (get_matita_script_current ())#status in
553        match status#ng_mode with
554           `ProofMode -> self#_loadNObj status status#obj
555         | _ -> self#blank ()
556
557     method private _loadNReference (NReference.Ref (uri,_)) =
558       let status = (get_matita_script_current ())#status in
559       let obj = NCicEnvironment.get_checked_obj status uri in
560       self#_loadNObj status obj
561
562     method private _loadDir dir = 
563       let content = Http_getter.ls ~local:false dir in
564       let l =
565         List.fast_sort
566           Pervasives.compare
567           (List.map
568             (function 
569               | Http_getter_types.Ls_section s -> "dir", s
570               | Http_getter_types.Ls_object o -> "obj", o.Http_getter_types.uri)
571             content)
572       in
573       lastDir <- dir;
574       self#_loadList l
575
576     method private setEntry entry =
577       win#browserUri#set_text (MatitaTypes.string_of_entry entry);
578       current_entry <- entry
579
580     method private _loadNObj status obj =
581       (* showMath must be done _before_ loading the document, since if the
582        * widget is not mapped (hidden by the notebook) the document is not
583        * rendered *)
584       self#_showMath;
585       mathView#load_nobject status obj
586
587     method private _loadTermNCic term m s c =
588       let d = 0 in
589       let m = (0,([],c,term))::m in
590       let status = (get_matita_script_current ())#status in
591       mathView#nload_sequent status m s d;
592       self#_showMath
593
594     method private _loadList l =
595       model#list_store#clear ();
596       List.iter (fun (tag, s) -> model#easy_append ~tag s) l;
597       self#_showList
598
599     (** { public methods, all must call _load!! } *)
600       
601     method load entry =
602       handle_error (fun () -> self#_load entry; self#_historyAdd entry)
603
604     (**  this is what the browser does when you enter a string an hit enter *)
605     method loadInput txt =
606       let txt = HExtlib.trim_blanks txt in
607       (* (* ZACK: what the heck? *)
608       let fix_uri txt =
609         UriManager.string_of_uri
610           (UriManager.strip_xpointer (UriManager.uri_of_string txt))
611       in
612       *)
613         let entry =
614           match txt with
615           | txt when is_uri txt ->
616               `NRef (NReference.reference_of_string ((*fix_uri*) txt))
617           | txt when is_dir txt -> `Dir (MatitaMisc.normalize_dir txt)
618           | txt ->
619              (try
620                MatitaTypes.entry_of_string txt
621               with Invalid_argument _ ->
622                raise
623                 (GrafiteTypes.Command_error(sprintf "unsupported uri: %s" txt)))
624         in
625         self#_load entry;
626         self#_historyAdd entry
627
628       (** {2 methods used by constructor only} *)
629
630     method win = win
631     method history = history
632     method currentEntry = current_entry
633     method refresh ~force () = self#_load ~force current_entry
634
635   end
636   
637 let sequentsViewer ~(notebook:GPack.notebook) ~(cicMathView:cicMathView) ():
638   MatitaGuiTypes.sequentsViewer
639 =
640   (new sequentsViewer ~notebook ~cicMathView ():> MatitaGuiTypes.sequentsViewer)
641
642 let new_cicBrowser () =
643   let size = BuildTimeConf.browser_history_size in
644   let rec aux history =
645     let browser = new cicBrowser_impl ~history () in
646     let win = browser#win in
647     ignore (win#browserNewButton#connect#clicked (fun () ->
648       let history =
649         new MatitaMisc.browser_history ~memento:history#save size
650           (`About `Blank)
651       in
652       let newBrowser = aux history in
653       newBrowser#load browser#currentEntry));
654 (*
655       (* attempt (failed) to close windows on CTRL-W ... *)
656     MatitaGtkMisc.connect_key win#browserWinEventBox#event ~modifiers:[`CONTROL]
657       GdkKeysyms._W (fun () -> win#toplevel#destroy ());
658 *)
659     cicBrowsers := browser :: !cicBrowsers;
660     browser
661   in
662   let history = new MatitaMisc.browser_history size (`About `Blank) in
663   aux history
664
665 (** @param reuse if set reused last opened cic browser otherwise 
666 *  opens a new one. default is false *)
667 let cicBrowser ?(reuse=false) t =
668  let browser =
669   if reuse then
670    (match !cicBrowsers with [] -> new_cicBrowser () | b :: _ -> b)
671   else
672    new_cicBrowser ()
673  in
674   match t with
675      None -> ()
676    | Some t -> browser#load t
677 ;;
678
679 let default_cicMathView () =
680  let res = cicMathView ~show:true () in
681   res#set_href_callback
682     (Some (fun uri ->
683       let uri = `NRef (NReference.reference_of_string uri) in
684        cicBrowser (Some uri)));
685   res
686
687 let cicMathView_instance =
688  MatitaMisc.singleton default_cicMathView
689
690 let default_sequentsViewer notebook =
691   let cicMathView = cicMathView_instance () in
692   sequentsViewer ~notebook ~cicMathView ()
693
694 let sequentsViewer_instance =
695  let already_used = ref false in
696   fun notebook ->
697    if !already_used then assert false
698    else
699     (already_used := true;
700      default_sequentsViewer notebook)
701
702 let refresh_all_browsers () =
703   List.iter (fun b -> b#refresh ~force:false ()) !cicBrowsers
704
705 let get_math_views () =
706   (cicMathView_instance ()) :: (List.map (fun b -> b#mathView) !cicBrowsers)
707
708 let find_selection_owner () =
709   let rec aux =
710     function
711     | [] -> raise Not_found
712     | mv :: tl ->
713         (match mv#get_selections with
714         | [] -> aux tl
715         | sel :: _ -> mv)
716   in
717   aux (get_math_views ())
718
719 let has_selection () =
720   try ignore (find_selection_owner ()); true
721   with Not_found -> false
722
723 let math_view_clipboard = ref None (* associative list target -> string *)
724 let has_clipboard () = !math_view_clipboard <> None
725 let empty_clipboard () = math_view_clipboard := None
726
727 let copy_selection () =
728   try
729     math_view_clipboard :=
730       Some ((find_selection_owner ())#strings_of_selection)
731   with Not_found -> failwith "no selection"
732
733 let paste_clipboard paste_kind =
734   match !math_view_clipboard with
735   | None -> failwith "empty clipboard"
736   | Some cb ->
737       (try List.assoc paste_kind cb with Not_found -> assert false)
738