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