]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaGui.ml
- content/interpretations.ml and ng_cic_content/nTermCicContent.ml where
[helm.git] / matita / matita / matitaGui.ml
1 (* Copyright (C) 2004-2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 open Printf
29
30 open MatitaGeneratedGui
31 open MatitaGtkMisc
32 open MatitaMisc
33
34 exception Found of int
35
36 let all_disambiguation_passes = ref false
37
38 let gui_instance = ref None
39
40 class type browserWin =
41   (* this class exists only because GEdit.combo_box_entry is not supported by
42    * lablgladecc :-(((( *)
43 object
44   inherit MatitaGeneratedGui.browserWin
45   method browserUri: GEdit.entry
46 end
47
48 class console ~(buffer: GText.buffer) () =
49   object (self)
50     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
51     val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
52     val message_tag = buffer#create_tag []
53     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
54     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
55     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
56     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
57     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
58     method clear () =
59       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
60     method log_callback (tag: HLog.log_tag) s =
61       let s = Pcre.replace ~pat:"\e\\[0;3.m([^\e]+)\e\\[0m" ~templ:"$1" s in
62       match tag with
63       | `Debug -> self#debug (s ^ "\n")
64       | `Error -> self#error (s ^ "\n")
65       | `Message -> self#message (s ^ "\n")
66       | `Warning -> self#warning (s ^ "\n")
67   end
68         
69 let clean_current_baseuri grafite_status = 
70   LibraryClean.clean_baseuris [grafite_status#baseuri]
71
72 let save_moo grafite_status = 
73   let script = MatitaScript.current () in
74   let baseuri = grafite_status#baseuri in
75   match script#bos, script#eos with
76   | true, _ -> ()
77   | _, true ->
78      GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
79       grafite_status#dump
80   | _ -> clean_current_baseuri grafite_status 
81 ;;
82     
83 let ask_unsaved parent =
84   MatitaGtkMisc.ask_confirmation 
85     ~parent ~title:"Unsaved work!" 
86     ~message:("Your work is <b>unsaved</b>!\n\n"^
87          "<i>Do you want to save the script before continuing?</i>")
88     ()
89
90 class interpErrorModel =
91   let cols = new GTree.column_list in
92   let id_col = cols#add Gobject.Data.string in
93   let dsc_col = cols#add Gobject.Data.string in
94   let interp_no_col = cols#add Gobject.Data.caml in
95   let tree_store = GTree.tree_store cols in
96   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
97   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
98   let id_view_col = GTree.view_column ~renderer:id_renderer () in
99   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
100   fun (tree_view: GTree.view) choices ->
101     object
102       initializer
103         tree_view#set_model (Some (tree_store :> GTree.model));
104         ignore (tree_view#append_column id_view_col);
105         ignore (tree_view#append_column dsc_view_col);
106         tree_store#clear ();
107         let idx1 = ref ~-1 in
108         List.iter
109           (fun _,lll ->
110             incr idx1;
111             let loc_row =
112              if List.length choices = 1 then
113               None
114              else
115               (let loc_row = tree_store#append () in
116                 begin
117                  match lll with
118                     [passes,envs_and_diffs,_,_] ->
119                       tree_store#set ~row:loc_row ~column:id_col
120                        ("Error location " ^ string_of_int (!idx1+1) ^
121                         ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
122                         " (in passes " ^
123                         String.concat " " (List.map string_of_int passes) ^
124                         ")");
125                       tree_store#set ~row:loc_row ~column:interp_no_col
126                        (!idx1,Some 0,None);
127                   | _ ->
128                     tree_store#set ~row:loc_row ~column:id_col
129                      ("Error location " ^ string_of_int (!idx1+1));
130                     tree_store#set ~row:loc_row ~column:interp_no_col
131                      (!idx1,None,None);
132                 end ;
133                 Some loc_row) in
134             let idx2 = ref ~-1 in
135              List.iter
136               (fun passes,envs_and_diffs,_,_ ->
137                 incr idx2;
138                 let msg_row =
139                  if List.length lll = 1 then
140                   loc_row
141                  else
142                   let msg_row = tree_store#append ?parent:loc_row () in
143                    (tree_store#set ~row:msg_row ~column:id_col
144                      ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
145                       string_of_int (!idx2+1) ^
146                       " (in passes " ^
147                       String.concat " " (List.map string_of_int passes) ^
148                       ")");
149                     tree_store#set ~row:msg_row ~column:interp_no_col
150                      (!idx1,Some !idx2,None);
151                     Some msg_row) in
152                 let idx3 = ref ~-1 in
153                 List.iter
154                  (fun (passes,env,_) ->
155                    incr idx3;
156                    let interp_row =
157                     match envs_and_diffs with
158                        _::_::_ ->
159                         let interp_row = tree_store#append ?parent:msg_row () in
160                         tree_store#set ~row:interp_row ~column:id_col
161                           ("Interpretation " ^ string_of_int (!idx3+1) ^
162                            " (in passes " ^
163                            String.concat " " (List.map string_of_int passes) ^
164                            ")");
165                         tree_store#set ~row:interp_row ~column:interp_no_col
166                          (!idx1,Some !idx2,Some !idx3);
167                         Some interp_row
168                      | [_] -> msg_row
169                      | [] -> assert false
170                    in
171                     List.iter
172                      (fun (_, id, dsc) ->
173                        let row = tree_store#append ?parent:interp_row () in
174                        tree_store#set ~row ~column:id_col id;
175                        tree_store#set ~row ~column:dsc_col dsc;
176                        tree_store#set ~row ~column:interp_no_col
177                         (!idx1,Some !idx2,Some !idx3)
178                      ) env
179                  ) envs_and_diffs
180               ) lll ;
181              if List.length lll > 1 then
182               HExtlib.iter_option
183                (fun p -> tree_view#expand_row (tree_store#get_path p))
184                loc_row
185           ) choices
186
187       method get_interp_no tree_path =
188         let iter = tree_store#get_iter tree_path in
189         tree_store#get ~row:iter ~column:interp_no_col
190     end
191
192 exception UseLibrary;;
193
194 let rec interactive_error_interp ~all_passes
195   (source_buffer:GSourceView2.source_buffer) notify_exn offset errorll filename
196
197   (* hook to save a script for each disambiguation error *)
198   if false then
199    (let text =
200      source_buffer#get_text ~start:source_buffer#start_iter
201       ~stop:source_buffer#end_iter () in
202     let md5 = Digest.to_hex (Digest.string text) in
203     let filename =
204      Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma"  in
205     let ch = open_out filename in
206      output_string ch text;
207     close_out ch
208    );
209   assert (List.flatten errorll <> []);
210   let errorll' =
211    let remove_non_significant =
212      List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
213    let annotated_errorll () =
214     List.rev
215      (snd
216        (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
217          errorll)) in
218    if all_passes then annotated_errorll () else
219      let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
220     (* We remove passes 1,2 and 5,6 *)
221      let res =
222       (1,[])::(2,[])
223       ::(3,remove_non_significant (safe_list_nth errorll 2))
224       ::(4,remove_non_significant (safe_list_nth errorll 3))
225       ::(5,[])::(6,[])::[]
226      in
227       if List.flatten (List.map snd res) <> [] then res
228       else
229        (* all errors (if any) are not significant: we keep them *)
230        let res =
231         (1,[])::(2,[])
232         ::(3,(safe_list_nth errorll 2))
233         ::(4,(safe_list_nth errorll 3))
234         ::(5,[])::(6,[])::[]
235        in
236         if List.flatten (List.map snd res) <> [] then
237          begin
238           HLog.warn
239            "All disambiguation errors are not significant. Showing them anyway." ;
240           res
241          end
242         else
243          begin
244           HLog.warn
245            "No errors in phases 2 and 3. Showing all errors in all phases" ;
246           annotated_errorll ()
247          end
248    in
249   let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
250    match choices with
251       [] -> assert false
252     | [loffset,[_,envs_and_diffs,msg,significant]] ->
253         let _,env,diff = List.hd envs_and_diffs in
254          notify_exn
255           (MultiPassDisambiguator.DisambiguationError
256             (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
257     | _::_ ->
258        let dialog = new disambiguationErrors () in
259        dialog#check_widgets ();
260        if all_passes then
261         dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
262        let model = new interpErrorModel dialog#treeview choices in
263        dialog#disambiguationErrors#set_title "Disambiguation error";
264        dialog#disambiguationErrorsLabel#set_label
265         "Click on an error to see the corresponding message:";
266        ignore (dialog#treeview#connect#cursor_changed
267         (fun _ ->
268           let tree_path =
269            match fst (dialog#treeview#get_cursor ()) with
270               None -> assert false
271            | Some tp -> tp in
272           let idx1,idx2,idx3 = model#get_interp_no tree_path in
273           let loffset,lll = List.nth choices idx1 in
274           let _,envs_and_diffs,msg,significant =
275            match idx2 with
276               Some idx2 -> List.nth lll idx2
277             | None ->
278                 [],[],lazy "Multiple error messages. Please select one.",true
279           in
280           let _,env,diff =
281            match idx3 with
282               Some idx3 -> List.nth envs_and_diffs idx3
283             | None -> [],[],[] (* dymmy value, used *) in
284           let script = MatitaScript.current () in
285           let error_tag = script#error_tag in
286            source_buffer#remove_tag error_tag
287              ~start:source_buffer#start_iter
288              ~stop:source_buffer#end_iter;
289            notify_exn
290             (MultiPassDisambiguator.DisambiguationError
291               (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
292            ));
293        let return _ =
294          dialog#disambiguationErrors#destroy ();
295          GMain.Main.quit ()
296        in
297        let fail _ = return () in
298        ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
299        connect_button dialog#disambiguationErrorsOkButton
300         (fun _ ->
301           let tree_path =
302            match fst (dialog#treeview#get_cursor ()) with
303               None -> assert false
304            | Some tp -> tp in
305           let idx1,idx2,idx3 = model#get_interp_no tree_path in
306           let diff =
307            match idx2,idx3 with
308               Some idx2, Some idx3 ->
309                let _,lll = List.nth choices idx1 in
310                let _,envs_and_diffs,_,_ = List.nth lll idx2 in
311                let _,_,diff = List.nth envs_and_diffs idx3 in
312                 diff
313             | _,_ -> assert false
314           in
315            let newtxt =
316             String.concat "\n"
317              ("" ::
318                List.map
319                 (fun k,desc -> 
320                   let alias =
321                    match k with
322                    | DisambiguateTypes.Id id ->
323                        GrafiteAst.Ident_alias (id, desc)
324                    | DisambiguateTypes.Symbol (symb, i)-> 
325                        GrafiteAst.Symbol_alias (symb, i, desc)
326                    | DisambiguateTypes.Num i ->
327                        GrafiteAst.Number_alias (i, desc)
328                   in
329                    GrafiteAstPp.pp_alias alias)
330                 diff) ^ "\n"
331            in
332             source_buffer#insert
333              ~iter:
334                (source_buffer#get_iter_at_mark
335                 (`NAME "beginning_of_statement")) newtxt ;
336             return ()
337         );
338        connect_button dialog#disambiguationErrorsMoreErrors
339         (fun _ -> return () ; raise UseLibrary);
340        connect_button dialog#disambiguationErrorsCancelButton fail;
341        dialog#disambiguationErrors#show ();
342        GtkThread.main ()
343
344
345 (** Selection handling
346  * Two clipboards are used: "clipboard" and "primary".
347  * "primary" is used by X, when you hit the middle button mouse is content is
348  *    pasted between applications. In Matita this selection always contain the
349  *    textual version of the selected term.
350  * "clipboard" is used inside Matita only and support ATM two different targets:
351  *    "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
352  *    be added
353  *)
354
355 class gui () =
356     (* creation order _is_ relevant for windows placement *)
357   let main = new mainWin () in
358   let fileSel = new fileSelectionWin () in
359   let findRepl = new findReplWin () in
360   let keyBindingBoxes = (* event boxes which should receive global key events *)
361     [ main#mainWinEventBox ]
362   in
363   let console = new console ~buffer:main#logTextView#buffer () in
364   let (source_view: GSourceView2.source_view) =
365     GSourceView2.source_view
366       ~auto_indent:true
367       ~insert_spaces_instead_of_tabs:true ~tab_width:2
368       ~right_margin_position:80 ~show_right_margin:true
369       ~smart_home_end:`AFTER
370       ~packing:main#scriptScrolledWin#add
371       ()
372   in
373   let default_font_size =
374     Helm_registry.get_opt_default Helm_registry.int
375       ~default:BuildTimeConf.default_font_size "matita.font_size"
376   in
377   let similarsymbols_tag_name = "similarsymbolos" in
378   let similarsymbols_tag = `NAME similarsymbols_tag_name in
379   let source_buffer = source_view#source_buffer in
380   object (self)
381     val mutable chosen_file = None
382     val mutable _ok_not_exists = false
383     val mutable _only_directory = false
384     val mutable font_size = default_font_size
385     val mutable similarsymbols = []
386     val mutable similarsymbols_orig = []
387     val clipboard = GData.clipboard Gdk.Atom.clipboard
388     val primary = GData.clipboard Gdk.Atom.primary
389       
390     method private reset_similarsymbols =
391       similarsymbols <- []; 
392       similarsymbols_orig <- []; 
393       try source_buffer#delete_mark similarsymbols_tag
394       with GText.No_such_mark _ -> ()
395    
396     initializer
397       let s () = MatitaScript.current () in
398         (* glade's check widgets *)
399       List.iter (fun w -> w#check_widgets ())
400         (let c w = (w :> <check_widgets: unit -> unit>) in
401         [ c fileSel; c main; c findRepl]);
402         (* key bindings *)
403       List.iter (* global key bindings *)
404         (fun (key, callback) -> self#addKeyBinding key callback)
405 (*
406         [ GdkKeysyms._F3,
407             toggle_win ~check:main#showProofMenuItem proof#proofWin;
408           GdkKeysyms._F4,
409             toggle_win ~check:main#showCheckMenuItem check#checkWin;
410 *)
411         [ ];
412         (* about win *)
413       let parse_txt_file file =
414        let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
415        let l_rev = ref [] in
416        try
417         while true do
418          l_rev := input_line ch :: !l_rev;
419         done;
420         assert false
421        with
422         End_of_file ->
423          close_in ch;
424          List.rev !l_rev in 
425       let about_dialog =
426        GWindow.about_dialog
427         ~authors:(parse_txt_file "AUTHORS")
428         (*~comments:"comments"*)
429         ~copyright:"Copyright (C) 2005, the HELM team"
430         ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
431         ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
432         ~name:"Matita"
433         ~version:BuildTimeConf.version
434         ~website:"http://matita.cs.unibo.it"
435         ()
436       in
437       ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
438       connect_menu_item main#contentsMenuItem (fun () ->
439         if 0 = Sys.command "which gnome-help" then
440           let cmd =
441             sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
442           in
443            ignore (Sys.command cmd)
444         else
445           MatitaGtkMisc.report_error ~title:"help system error"
446            ~message:(
447               "The program gnome-help is not installed\n\n"^
448               "To browse the user manal it is necessary to install "^
449               "the gnome help syste (also known as yelp)") 
450            ~parent:main#toplevel ());
451       connect_menu_item main#aboutMenuItem about_dialog#present;
452         (* findRepl win *)
453       let show_find_Repl () = 
454         findRepl#toplevel#misc#show ();
455         findRepl#toplevel#misc#grab_focus ()
456       in
457       let hide_find_Repl () = findRepl#toplevel#misc#hide () in
458       let find_forward _ = 
459           let highlight start end_ =
460             source_buffer#move_mark `INSERT ~where:start;
461             source_buffer#move_mark `SEL_BOUND ~where:end_;
462             source_view#scroll_mark_onscreen `INSERT
463           in
464           let text = findRepl#findEntry#text in
465           let iter = source_buffer#get_iter `SEL_BOUND in
466           match iter#forward_search text with
467           | None -> 
468               (match source_buffer#start_iter#forward_search text with
469               | None -> ()
470               | Some (start,end_) -> highlight start end_)
471           | Some (start,end_) -> highlight start end_ 
472       in
473       let replace _ =
474         let text = findRepl#replaceEntry#text in
475         let ins = source_buffer#get_iter `INSERT in
476         let sel = source_buffer#get_iter `SEL_BOUND in
477         if ins#compare sel < 0 then 
478           begin
479             ignore(source_buffer#delete_selection ());
480             source_buffer#insert text
481           end
482       in
483       connect_button findRepl#findButton find_forward;
484       connect_button findRepl#findReplButton replace;
485       connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
486       ignore(findRepl#toplevel#event#connect#delete 
487         ~callback:(fun _ -> hide_find_Repl ();true));
488       let safe_undo =
489        fun () ->
490         (* phase 1: we save the actual status of the marks and we undo *)
491         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
492         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
493         let locked_iter_offset = locked_iter#offset in
494         let mark2 =
495          `MARK
496            (source_view#buffer#create_mark ~name:"lock_point"
497              ~left_gravity:true locked_iter) in
498         source_view#source_buffer#undo ();
499         (* phase 2: we save the cursor position and we redo, restoring
500            the previous status of all the marks *)
501         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
502         let mark =
503          `MARK
504            (source_view#buffer#create_mark ~name:"undo_point"
505              ~left_gravity:true cursor_iter)
506         in
507          source_view#source_buffer#redo ();
508          let mark_iter = source_view#buffer#get_iter_at_mark mark in
509          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
510          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
511           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
512           source_view#buffer#delete_mark mark;
513           source_view#buffer#delete_mark mark2;
514           (* phase 3: if after the undo the cursor was in the locked area,
515              then we move it there again and we perform a goto *)
516           if mark_iter#offset < locked_iter_offset then
517            begin
518             source_view#buffer#move_mark `INSERT ~where:mark_iter;
519             (MatitaScript.current ())#goto `Cursor ();
520            end;
521           (* phase 4: we perform again the undo. This time we are sure that
522              the text to undo is not locked *)
523           source_view#source_buffer#undo ();
524           source_view#misc#grab_focus () in
525       let safe_redo =
526        fun () ->
527         (* phase 1: we save the actual status of the marks, we redo and
528            we undo *)
529         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
530         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
531         let locked_iter_offset = locked_iter#offset in
532         let mark2 =
533          `MARK
534            (source_view#buffer#create_mark ~name:"lock_point"
535              ~left_gravity:true locked_iter) in
536         source_view#source_buffer#redo ();
537         source_view#source_buffer#undo ();
538         (* phase 2: we save the cursor position and we restore
539            the previous status of all the marks *)
540         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
541         let mark =
542          `MARK
543            (source_view#buffer#create_mark ~name:"undo_point"
544              ~left_gravity:true cursor_iter)
545         in
546          let mark_iter = source_view#buffer#get_iter_at_mark mark in
547          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
548          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
549           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
550           source_view#buffer#delete_mark mark;
551           source_view#buffer#delete_mark mark2;
552           (* phase 3: if after the undo the cursor is in the locked area,
553              then we move it there again and we perform a goto *)
554           if mark_iter#offset < locked_iter_offset then
555            begin
556             source_view#buffer#move_mark `INSERT ~where:mark_iter;
557             (MatitaScript.current ())#goto `Cursor ();
558            end;
559           (* phase 4: we perform again the redo. This time we are sure that
560              the text to redo is not locked *)
561           source_view#source_buffer#redo ();
562           source_view#misc#grab_focus ()
563       in
564       connect_menu_item main#undoMenuItem safe_undo;
565 (*CSC: XXX
566       ignore(source_view#source_buffer#connect#can_undo
567         ~callback:main#undoMenuItem#misc#set_sensitive);
568 *) main#undoMenuItem#misc#set_sensitive true;
569       connect_menu_item main#redoMenuItem safe_redo;
570 (*CSC: XXX
571       ignore(source_view#source_buffer#connect#can_redo
572         ~callback:main#redoMenuItem#misc#set_sensitive);
573 *) main#redoMenuItem#misc#set_sensitive true;
574       ignore(source_view#connect#after#populate_popup
575        ~callback:(fun pre_menu ->
576          let menu = new GMenu.menu pre_menu in
577          let menuItems = menu#children in
578          let undoMenuItem, redoMenuItem =
579           match menuItems with
580              [undo;redo;sep1;cut;copy;paste;delete;sep2;
581               selectall;sep3;inputmethod;insertunicodecharacter] ->
582                 List.iter menu#remove [ copy; cut; delete; paste ];
583                 undo,redo
584            | _ -> assert false in
585          let add_menu_item =
586            let i = ref 2 in (* last occupied position *)
587            fun ?label ?stock () ->
588              incr i;
589              GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
590               ()
591          in
592          let copy = add_menu_item ~stock:`COPY () in
593          let cut = add_menu_item ~stock:`CUT () in
594          let delete = add_menu_item ~stock:`DELETE () in
595          let paste = add_menu_item ~stock:`PASTE () in
596          let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
597          copy#misc#set_sensitive self#canCopy;
598          cut#misc#set_sensitive self#canCut;
599          delete#misc#set_sensitive self#canDelete;
600          paste#misc#set_sensitive self#canPaste;
601          paste_pattern#misc#set_sensitive self#canPastePattern;
602          connect_menu_item copy self#copy;
603          connect_menu_item cut self#cut;
604          connect_menu_item delete self#delete;
605          connect_menu_item paste self#paste;
606          connect_menu_item paste_pattern self#pastePattern;
607          let new_undoMenuItem =
608           GMenu.image_menu_item
609            ~image:(GMisc.image ~stock:`UNDO ())
610            ~use_mnemonic:true
611            ~label:"_Undo"
612            ~packing:(menu#insert ~pos:0) () in
613          new_undoMenuItem#misc#set_sensitive
614           (undoMenuItem#misc#get_flag `SENSITIVE);
615          menu#remove (undoMenuItem :> GMenu.menu_item);
616          connect_menu_item new_undoMenuItem safe_undo;
617          let new_redoMenuItem =
618           GMenu.image_menu_item
619            ~image:(GMisc.image ~stock:`REDO ())
620            ~use_mnemonic:true
621            ~label:"_Redo"
622            ~packing:(menu#insert ~pos:1) () in
623          new_redoMenuItem#misc#set_sensitive
624           (redoMenuItem#misc#get_flag `SENSITIVE);
625           menu#remove (redoMenuItem :> GMenu.menu_item);
626           connect_menu_item new_redoMenuItem safe_redo));
627
628       connect_menu_item main#editMenu (fun () ->
629         main#copyMenuItem#misc#set_sensitive self#canCopy;
630         main#cutMenuItem#misc#set_sensitive self#canCut;
631         main#deleteMenuItem#misc#set_sensitive self#canDelete;
632         main#pasteMenuItem#misc#set_sensitive self#canPaste;
633         main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
634       connect_menu_item main#copyMenuItem self#copy;
635       connect_menu_item main#cutMenuItem self#cut;
636       connect_menu_item main#deleteMenuItem self#delete;
637       connect_menu_item main#pasteMenuItem self#paste;
638       connect_menu_item main#pastePatternMenuItem self#pastePattern;
639       connect_menu_item main#selectAllMenuItem (fun () ->
640         source_buffer#move_mark `INSERT source_buffer#start_iter;
641         source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
642       connect_menu_item main#findReplMenuItem show_find_Repl;
643       connect_menu_item main#externalEditorMenuItem self#externalEditor;
644       connect_menu_item main#ligatureButton self#nextSimilarSymbol;
645       ignore(source_buffer#connect#after#insert_text 
646        ~callback:(fun iter str -> 
647           if main#menuitemAutoAltL#active && (str = " " || str = "\n") then 
648             ignore(self#expand_virtual_if_any iter str)));
649       ignore (findRepl#findEntry#connect#activate find_forward);
650         (* interface lockers *)
651       let lock_world _ =
652         main#buttonsToolbar#misc#set_sensitive false;
653         main#scriptMenu#misc#set_sensitive false;
654         source_view#set_editable false
655       in
656       let unlock_world _ =
657         main#buttonsToolbar#misc#set_sensitive true;
658         main#scriptMenu#misc#set_sensitive true;
659         source_view#set_editable true;
660         (*The next line seems sufficient to avoid some unknown race condition *)
661         GtkThread.sync (fun () -> ()) ()
662       in
663       let worker_thread = ref None in
664       let notify_exn exn =
665        let floc, msg = MatitaExcPp.to_string exn in
666         begin
667          match floc with
668             None -> ()
669           | Some floc ->
670              let (x, y) = HExtlib.loc_of_floc floc in
671              let script = MatitaScript.current () in
672              let locked_mark = script#locked_mark in
673              let error_tag = script#error_tag in
674              let baseoffset =
675               (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
676              let x' = baseoffset + x in
677              let y' = baseoffset + y in
678              let x_iter = source_buffer#get_iter (`OFFSET x') in
679              let y_iter = source_buffer#get_iter (`OFFSET y') in
680              source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
681              let id = ref None in
682              id := Some (source_buffer#connect#changed ~callback:(fun () ->
683                source_buffer#remove_tag error_tag
684                  ~start:source_buffer#start_iter
685                  ~stop:source_buffer#end_iter;
686                match !id with
687                | None -> assert false (* a race condition occurred *)
688                | Some id ->
689                    (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
690              source_buffer#place_cursor
691               (source_buffer#get_iter (`OFFSET x'));
692         end;
693         HLog.error msg in
694       let locker f () =
695        let thread_main =
696         fun () -> 
697           lock_world ();
698           let saved_use_library= !MultiPassDisambiguator.use_library in
699           try
700            MultiPassDisambiguator.use_library := !all_disambiguation_passes;
701            f ();
702            MultiPassDisambiguator.use_library := saved_use_library;
703            unlock_world ()
704           with
705            | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
706               (try
707                 interactive_error_interp 
708                  ~all_passes:!all_disambiguation_passes source_buffer
709                  notify_exn offset errorll (s())#filename
710                with
711                 | UseLibrary ->
712                    MultiPassDisambiguator.use_library := true;
713                    (try f ()
714                     with
715                     | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
716                        interactive_error_interp ~all_passes:true source_buffer
717                         notify_exn offset errorll (s())#filename
718                     | exc ->
719                        notify_exn exc);
720                 | exc -> notify_exn exc);
721               MultiPassDisambiguator.use_library := saved_use_library;
722               unlock_world ()
723            | exc ->
724               (try notify_exn exc with Sys.Break as e -> notify_exn e);
725               unlock_world ()
726        in
727        (*thread_main ();*)
728        worker_thread := Some (Thread.create thread_main ())
729       in
730       let kill_worker =
731        (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
732        let interrupt = ref None in
733        let old_callback = ref (function _ -> ()) in
734        let force_interrupt n =
735          (* This function is called just before the thread's timeslice ends *)
736          !old_callback n;
737          if Some(Thread.id(Thread.self())) = !interrupt then
738           (interrupt := None; raise Sys.Break) in
739        let _ =
740         match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
741            Sys.Signal_handle f -> old_callback := f
742          | Sys.Signal_ignore
743          | Sys.Signal_default -> assert false
744        in
745         fun () ->
746          match !worker_thread with
747             None -> assert false
748           | Some t -> interrupt := Some (Thread.id t) in
749       let keep_focus f =
750         fun () ->
751          try
752           f (); source_view#misc#grab_focus ()
753          with
754           exc -> source_view#misc#grab_focus (); raise exc in
755       
756         (* file selection win *)
757       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
758       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
759         let return r =
760           chosen_file <- r;
761           fileSel#fileSelectionWin#misc#hide ();
762           GMain.Main.quit ()
763         in
764         match event with
765         | `OK ->
766             let fname = fileSel#fileSelectionWin#filename in
767             if Sys.file_exists fname then
768               begin
769                 if HExtlib.is_regular fname && not (_only_directory) then 
770                   return (Some fname) 
771                 else if _only_directory && HExtlib.is_dir fname then 
772                   return (Some fname)
773               end
774             else
775               begin
776                 if _ok_not_exists then 
777                   return (Some fname)
778               end
779         | `CANCEL -> return None
780         | `HELP -> ()
781         | `DELETE_EVENT -> return None));
782         (* menus *)
783       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
784         (* console *)
785       let adj = main#logScrolledWin#vadjustment in
786         ignore (adj#connect#changed
787                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
788       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
789         (* natural deduction palette *)
790       main#tacticsButtonsHandlebox#misc#hide ();
791       MatitaGtkMisc.toggle_callback
792         ~callback:(fun b -> 
793           if b then main#tacticsButtonsHandlebox#misc#show ()
794           else main#tacticsButtonsHandlebox#misc#hide ())
795         ~check:main#menuitemPalette;
796       connect_button main#butImpl_intro
797         (fun () -> source_buffer#insert "apply rule (⇒#i […] (…));\n");
798       connect_button main#butAnd_intro
799         (fun () -> source_buffer#insert 
800           "apply rule (∧#i (…) (…));\n\t[\n\t|\n\t]\n");
801       connect_button main#butOr_intro_left
802         (fun () -> source_buffer#insert "apply rule (∨#i_l (…));\n");
803       connect_button main#butOr_intro_right
804         (fun () -> source_buffer#insert "apply rule (∨#i_r (…));\n");
805       connect_button main#butNot_intro
806         (fun () -> source_buffer#insert "apply rule (¬#i […] (…));\n");
807       connect_button main#butTop_intro
808         (fun () -> source_buffer#insert "apply rule (⊤#i);\n");
809       connect_button main#butImpl_elim
810         (fun () -> source_buffer#insert 
811           "apply rule (⇒#e (…) (…));\n\t[\n\t|\n\t]\n");
812       connect_button main#butAnd_elim_left
813         (fun () -> source_buffer#insert "apply rule (∧#e_l (…));\n");
814       connect_button main#butAnd_elim_right
815         (fun () -> source_buffer#insert "apply rule (∧#e_r (…));\n");
816       connect_button main#butOr_elim
817         (fun () -> source_buffer#insert 
818           "apply rule (∨#e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
819       connect_button main#butNot_elim
820         (fun () -> source_buffer#insert 
821           "apply rule (¬#e (…) (…));\n\t[\n\t|\n\t]\n");
822       connect_button main#butBot_elim
823         (fun () -> source_buffer#insert "apply rule (⊥#e (…));\n");
824       connect_button main#butRAA
825         (fun () -> source_buffer#insert "apply rule (RAA […] (…));\n");
826       connect_button main#butUseLemma
827         (fun () -> source_buffer#insert "apply rule (lem #premises name â€¦);\n");
828       connect_button main#butDischarge
829         (fun () -> source_buffer#insert "apply rule (discharge […]);\n");
830       
831       connect_button main#butForall_intro
832         (fun () -> source_buffer#insert "apply rule (∀#i {…} (…));\n");
833       connect_button main#butForall_elim
834         (fun () -> source_buffer#insert "apply rule (∀#e {…} (…));\n");
835       connect_button main#butExists_intro
836         (fun () -> source_buffer#insert "apply rule (∃#i {…} (…));\n");
837       connect_button main#butExists_elim
838         (fun () -> source_buffer#insert 
839           "apply rule (∃#e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
840
841     
842       (* TO BE REMOVED *)
843       main#scriptNotebook#remove_page 1;
844       main#scriptNotebook#set_show_tabs false;
845       (* / TO BE REMOVED *)
846       let module Hr = Helm_registry in
847       MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
848         ~callback:(function 
849           | true -> main#toplevel#fullscreen () 
850           | false -> main#toplevel#unfullscreen ());
851       main#fullscreenMenuItem#set_active false;
852       MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
853         ~callback:(function b ->
854           let s = s () in
855           let status =
856            Interpretations.toggle_active_interpretations s#grafite_status b
857           in
858            assert false (* MATITA1.0 ???
859            s#set_grafite_status status*)
860          );
861       MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
862         ~callback:(fun enabled -> Interpretations.hide_coercions := enabled);
863       MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
864         ~callback:(fun enabled ->
865           Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
866       main#unicodeAsTexMenuItem#set_active
867         (Helm_registry.get_bool "matita.paste_unicode_as_tex");
868         (* log *)
869       HLog.set_log_callback self#console#log_callback;
870       GtkSignal.user_handler :=
871         (function 
872         | MatitaScript.ActionCancelled s -> HLog.error s
873         | exn ->
874           if not (Helm_registry.get_bool "matita.debug") then
875            notify_exn exn
876           else raise exn);
877         (* script *)
878       let _ =
879        source_buffer#set_language (Some MatitaGtkMisc.matita_lang);
880        source_buffer#set_highlight_syntax true
881       in
882       let disableSave () =
883         (s())#assignFileName None;
884         main#saveMenuItem#misc#set_sensitive false
885       in
886       let saveAsScript () =
887         let script = s () in
888         match self#chooseFile ~ok_not_exists:true () with
889         | Some f -> 
890               HExtlib.touch f;
891               script#assignFileName (Some f);
892               script#saveToFile (); 
893               console#message ("'"^f^"' saved.\n");
894               self#_enableSaveTo f
895         | None -> ()
896       in
897       let saveScript () =
898         let script = s () in
899         if script#has_name then 
900           (script#saveToFile (); 
901           console#message ("'"^script#filename^"' saved.\n"))
902         else saveAsScript ()
903       in
904       let abandon_script () =
905         let grafite_status = (s ())#grafite_status in
906         if source_view#buffer#modified then
907           (match ask_unsaved main#toplevel with
908           | `YES -> saveScript ()
909           | `NO -> ()
910           | `CANCEL -> raise MatitaTypes.Cancel);
911         save_moo grafite_status
912       in
913       let loadScript () =
914         let script = s () in 
915         try 
916           match self#chooseFile () with
917           | Some f -> 
918               abandon_script ();
919               script#reset (); 
920               script#assignFileName (Some f);
921               source_view#source_buffer#begin_not_undoable_action ();
922               script#loadFromFile f; 
923               source_view#source_buffer#end_not_undoable_action ();
924               source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
925               source_view#buffer#place_cursor source_view#buffer#start_iter;
926               console#message ("'"^f^"' loaded.\n");
927               self#_enableSaveTo f
928           | None -> ()
929         with MatitaTypes.Cancel -> ()
930       in
931       let newScript () = 
932         abandon_script ();
933         source_view#source_buffer#begin_not_undoable_action ();
934         (s ())#reset (); 
935         (s ())#template (); 
936         source_view#source_buffer#end_not_undoable_action ();
937         disableSave ();
938         (s ())#assignFileName None
939       in
940       let cursor () =
941         source_buffer#place_cursor
942           (source_buffer#get_iter_at_mark (`NAME "locked")) in
943       let advance _ = (MatitaScript.current ())#advance (); cursor () in
944       let retract _ = (MatitaScript.current ())#retract (); cursor () in
945       let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
946       let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
947       let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
948       let advance = locker (keep_focus advance) in
949       let retract = locker (keep_focus retract) in
950       let top = locker (keep_focus top) in
951       let bottom = locker (keep_focus bottom) in
952       let jump = locker (keep_focus jump) in
953         (* quit *)
954       self#setQuitCallback (fun () -> 
955         let script = MatitaScript.current () in
956         if source_view#buffer#modified then
957           match ask_unsaved main#toplevel with
958           | `YES -> 
959                saveScript ();
960                save_moo script#grafite_status;
961                GMain.Main.quit ()
962           | `NO -> GMain.Main.quit ()
963           | `CANCEL -> ()
964         else 
965           (save_moo script#grafite_status;
966           GMain.Main.quit ()));
967       connect_button main#scriptAdvanceButton advance;
968       connect_button main#scriptRetractButton retract;
969       connect_button main#scriptTopButton top;
970       connect_button main#scriptBottomButton bottom;
971       connect_button main#scriptJumpButton jump;
972       connect_button main#scriptAbortButton kill_worker;
973       connect_menu_item main#scriptAdvanceMenuItem advance;
974       connect_menu_item main#scriptRetractMenuItem retract;
975       connect_menu_item main#scriptTopMenuItem top;
976       connect_menu_item main#scriptBottomMenuItem bottom;
977       connect_menu_item main#scriptJumpMenuItem jump;
978       connect_menu_item main#openMenuItem   loadScript;
979       connect_menu_item main#saveMenuItem   saveScript;
980       connect_menu_item main#saveAsMenuItem saveAsScript;
981       connect_menu_item main#newMenuItem    newScript;
982       connect_menu_item main#showCoercionsGraphMenuItem 
983         (fun _ -> 
984           let c = MatitaMathView.cicBrowser () in
985           c#load (`About `Coercions));
986       connect_menu_item main#showHintsDbMenuItem 
987         (fun _ -> 
988           let c = MatitaMathView.cicBrowser () in
989           c#load (`About `Hints));
990       connect_menu_item main#showTermGrammarMenuItem 
991         (fun _ -> 
992           let c = MatitaMathView.cicBrowser () in
993           c#load (`About `Grammar));
994       connect_menu_item main#showUnicodeTable
995         (fun _ -> 
996           let c = MatitaMathView.cicBrowser () in
997           c#load (`About `TeX));
998          (* script monospace font stuff *)  
999       self#updateFontSize ();
1000         (* debug menu *)
1001       main#debugMenu#misc#hide ();
1002         (* HBUGS *)
1003       main#hintNotebook#misc#hide ();
1004       (*
1005       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1006       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1007       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1008       *)
1009         (* focus *)
1010       self#sourceView#misc#grab_focus ();
1011         (* main win dimension *)
1012       let width = Gdk.Screen.width ~screen:(Gdk.Screen.default ()) () in
1013       let height = Gdk.Screen.height ~screen:(Gdk.Screen.default ()) () in
1014       (* hack for xinerama, no proper support of monitors from lablgtk *)
1015       let width = if width > 1600 then width / 2 else width in
1016       let height = if height > 1200 then height / 2 else height in
1017       let main_w = width * 90 / 100 in 
1018       let main_h = height * 80 / 100 in
1019       let script_w = main_w * 6 / 10 in
1020       main#toplevel#resize ~width:main_w ~height:main_h;
1021       main#hpaneScriptSequent#set_position script_w;
1022         (* source_view *)
1023       ignore(source_view#connect#after#paste_clipboard 
1024         ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1025       (* clean_locked is set to true only "during" a PRIMARY paste
1026          operation (i.e. by clicking with the second mouse button) *)
1027       let clean_locked = ref false in
1028       ignore(source_view#event#connect#button_press
1029         ~callback:
1030           (fun button ->
1031             if GdkEvent.Button.button button = 2 then
1032              clean_locked := true;
1033             false
1034           ));
1035       ignore(source_view#event#connect#button_release
1036         ~callback:(fun button -> clean_locked := false; false));
1037       ignore(source_view#buffer#connect#after#apply_tag
1038        ~callback:(
1039          fun tag ~start:_ ~stop:_ ->
1040           if !clean_locked &&
1041              tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1042           then
1043            begin
1044             clean_locked := false;
1045             (MatitaScript.current ())#clean_dirty_lock;
1046             clean_locked := true
1047            end));
1048       (* math view handling *)
1049       connect_menu_item main#newCicBrowserMenuItem (fun () ->
1050         ignore(MatitaMathView.cicBrowser ()));
1051       connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1052         self#increaseFontSize ();
1053         MatitaMathView.increase_font_size ();
1054         MatitaMathView.update_font_sizes ());
1055       connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1056         self#decreaseFontSize ();
1057         MatitaMathView.decrease_font_size ();
1058         MatitaMathView.update_font_sizes ());
1059       connect_menu_item main#normalFontSizeMenuItem (fun () ->
1060         self#resetFontSize ();
1061         MatitaMathView.reset_font_size ();
1062         MatitaMathView.update_font_sizes ());
1063       MatitaMathView.reset_font_size ();
1064
1065       (** selections / clipboards handling *)
1066
1067     method markupSelected = MatitaMathView.has_selection ()
1068     method private textSelected =
1069       (source_buffer#get_iter_at_mark `INSERT)#compare
1070         (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1071     method private somethingSelected = self#markupSelected || self#textSelected
1072     method private markupStored = MatitaMathView.has_clipboard ()
1073     method private textStored = clipboard#text <> None
1074     method private somethingStored = self#markupStored || self#textStored
1075
1076     method canCopy = self#somethingSelected
1077     method canCut = self#textSelected
1078     method canDelete = self#textSelected
1079     method canPaste = self#somethingStored
1080     method canPastePattern = self#markupStored
1081
1082     method copy () =
1083       if self#textSelected
1084       then begin
1085         MatitaMathView.empty_clipboard ();
1086         source_view#buffer#copy_clipboard clipboard;
1087       end else
1088         MatitaMathView.copy_selection ()
1089     method cut () =
1090       source_view#buffer#cut_clipboard clipboard;
1091       MatitaMathView.empty_clipboard ()
1092     method delete () = ignore (source_view#buffer#delete_selection ())
1093     method paste () =
1094       if MatitaMathView.has_clipboard ()
1095       then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1096       else source_view#buffer#paste_clipboard clipboard;
1097       (MatitaScript.current ())#clean_dirty_lock
1098     method pastePattern () =
1099       source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1100     
1101     method private expand_virtual_if_any iter tok =
1102       try
1103        let len = MatitaGtkMisc.utf8_string_length tok in
1104        let last_word =
1105         let prev = iter#copy#backward_chars len in
1106          prev#get_slice ~stop:(prev#copy#backward_find_char 
1107           (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
1108        in
1109        let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
1110        self#reset_similarsymbols;
1111        let s = Glib.Utf8.from_unichar symb in
1112        assert(Glib.Utf8.validate s);
1113        source_buffer#delete ~start:iter 
1114          ~stop:(iter#copy#backward_chars
1115            (MatitaGtkMisc.utf8_string_length inplaceof + len));
1116        source_buffer#insert ~iter
1117          (if inplaceof.[0] = '\\' then s else (s ^ tok));
1118        true
1119       with Virtuals.Not_a_virtual -> false
1120          
1121     val similar_memory = Hashtbl.create 97
1122     val mutable old_used_memory = false
1123
1124     method private nextSimilarSymbol () = 
1125       let write_similarsymbol s =
1126         let s = Glib.Utf8.from_unichar s in
1127         let iter = source_buffer#get_iter_at_mark `INSERT in
1128         assert(Glib.Utf8.validate s);
1129         source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
1130         source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s;
1131         (try source_buffer#delete_mark similarsymbols_tag
1132          with GText.No_such_mark _ -> ());
1133         ignore(source_buffer#create_mark ~name:similarsymbols_tag_name
1134           (source_buffer#get_iter_at_mark `INSERT));
1135       in
1136       let new_similarsymbol =
1137         try
1138           let iter_ins = source_buffer#get_iter_at_mark `INSERT in
1139           let iter_lig = source_buffer#get_iter_at_mark similarsymbols_tag in
1140           not (iter_ins#equal iter_lig)
1141         with GText.No_such_mark _ -> true
1142       in
1143       if new_similarsymbol then
1144         (if not(self#expand_virtual_if_any (source_buffer#get_iter_at_mark `INSERT) "")then
1145           let last_symbol = 
1146             let i = source_buffer#get_iter_at_mark `INSERT in
1147             Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
1148           in
1149           (match Virtuals.similar_symbols last_symbol with
1150           | [] ->  ()
1151           | eqclass ->
1152               similarsymbols_orig <- eqclass;
1153               let is_used = 
1154                 try Hashtbl.find similar_memory similarsymbols_orig  
1155                 with Not_found -> 
1156                   let is_used = List.map (fun x -> x,false) eqclass in
1157                   Hashtbl.add similar_memory eqclass is_used; 
1158                   is_used
1159               in
1160               let hd, next, tl = 
1161                 let used, unused = 
1162                   List.partition (fun s -> List.assoc s is_used) eqclass 
1163                 in
1164                 match used @ unused with a::b::c -> a,b,c | _ -> assert false
1165               in
1166               let hd, tl = 
1167                 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
1168               in
1169               old_used_memory <- List.assoc hd is_used;
1170               let is_used = 
1171                 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
1172               in
1173               Hashtbl.replace similar_memory similarsymbols_orig is_used;
1174               write_similarsymbol hd;
1175               similarsymbols <- tl @ [ hd ]))
1176       else 
1177         match similarsymbols with
1178         | [] -> ()
1179         | hd :: tl ->
1180             let is_used = Hashtbl.find similar_memory similarsymbols_orig in
1181             let last = HExtlib.list_last tl in
1182             let old_used_for_last = old_used_memory in
1183             old_used_memory <- List.assoc hd is_used;
1184             let is_used = 
1185               (hd, true) :: (last,old_used_for_last) ::
1186                 List.filter (fun (x,_) -> x <> last && x <> hd) is_used 
1187             in
1188             Hashtbl.replace similar_memory similarsymbols_orig is_used;
1189             similarsymbols <- tl @ [ hd ];
1190             write_similarsymbol hd
1191
1192     method private externalEditor () =
1193       let cmd = Helm_registry.get "matita.external_editor" in
1194 (* ZACK uncomment to enable interactive ask of external editor command *)
1195 (*      let cmd =
1196          let msg =
1197           "External editor command:
1198 %f  will be substitute for the script name,
1199 %p  for the cursor position in bytes,
1200 %l  for the execution point in bytes."
1201         in
1202         ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1203           ~default:(Helm_registry.get "matita.external_editor") ()
1204       in *)
1205       let script = MatitaScript.current () in
1206       let fname = script#filename in
1207       let slice mark =
1208         source_buffer#start_iter#get_slice
1209           ~stop:(source_buffer#get_iter_at_mark mark)
1210       in
1211       let locked = `MARK script#locked_mark in
1212       let string_pos mark = string_of_int (String.length (slice mark)) in
1213       let cursor_pos = string_pos `INSERT in
1214       let locked_pos = string_pos locked in
1215       let cmd =
1216         Pcre.replace ~pat:"%f" ~templ:fname
1217           (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1218             (Pcre.replace ~pat:"%l" ~templ:locked_pos
1219               cmd))
1220       in
1221       let locked_before = slice locked in
1222       let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1223       ignore (Unix.system cmd);
1224       source_buffer#set_text (HExtlib.input_file fname);
1225       let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1226       source_buffer#move_mark locked locked_iter;
1227       source_buffer#apply_tag script#locked_tag
1228         ~start:source_buffer#start_iter ~stop:locked_iter;
1229       let locked_after = slice locked in
1230       let line = ref 0 in
1231       let col = ref 0 in
1232       try
1233         for i = 0 to String.length locked_before - 1 do
1234           if locked_before.[i] <> locked_after.[i] then begin
1235             source_buffer#place_cursor
1236               ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1237             script#goto `Cursor ();
1238             raise Exit
1239           end else if locked_before.[i] = '\n' then begin
1240             incr line;
1241             col := 0
1242           end
1243         done
1244       with
1245       | Exit -> ()
1246       | Invalid_argument _ -> script#goto `Bottom ()
1247
1248     method loadScript file =       
1249       let script = MatitaScript.current () in
1250       script#reset (); 
1251       script#assignFileName (Some file);
1252       let file = script#filename in
1253       let content =
1254        if Sys.file_exists file then file
1255        else BuildTimeConf.script_template
1256       in
1257       source_view#source_buffer#begin_not_undoable_action ();
1258       script#loadFromFile content;
1259       source_view#source_buffer#end_not_undoable_action ();
1260       source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1261       source_view#buffer#place_cursor source_view#buffer#start_iter;
1262       console#message ("'"^file^"' loaded.");
1263       self#_enableSaveTo file
1264       
1265     method setStar b =
1266       let s = MatitaScript.current () in
1267       let w = main#toplevel in
1268       let set x = w#set_title x in
1269       let name = 
1270         "Matita - " ^ Filename.basename s#filename ^ 
1271         (if b then "*" else "") ^
1272         " in " ^ s#buri_of_current_file 
1273       in
1274         set name
1275         
1276     method private _enableSaveTo file =
1277       self#main#saveMenuItem#misc#set_sensitive true
1278         
1279     method console = console
1280     method sourceView: GSourceView2.source_view =
1281       (source_view: GSourceView2.source_view)
1282     method fileSel = fileSel
1283     method findRepl = findRepl
1284     method main = main
1285
1286     method newBrowserWin () =
1287       object (self)
1288         inherit browserWin ()
1289         val combo = GEdit.entry ()
1290         initializer
1291           self#check_widgets ();
1292           let combo_widget = combo#coerce in
1293           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1294           combo#misc#grab_focus ()
1295         method browserUri = combo
1296       end
1297
1298     method newUriDialog () =
1299       let dialog = new uriChoiceDialog () in
1300       dialog#check_widgets ();
1301       dialog
1302
1303     method newConfirmationDialog () =
1304       let dialog = new confirmationDialog () in
1305       dialog#check_widgets ();
1306       dialog
1307
1308     method newEmptyDialog () =
1309       let dialog = new emptyDialog () in
1310       dialog#check_widgets ();
1311       dialog
1312
1313     method private addKeyBinding key callback =
1314       List.iter (fun evbox -> add_key_binding key callback evbox)
1315         keyBindingBoxes
1316
1317     method setQuitCallback callback =
1318       connect_menu_item main#quitMenuItem callback;
1319       ignore (main#toplevel#event#connect#delete 
1320         (fun _ -> callback ();true));
1321       self#addKeyBinding GdkKeysyms._q callback
1322
1323     method chooseFile ?(ok_not_exists = false) () =
1324       _ok_not_exists <- ok_not_exists;
1325       _only_directory <- false;
1326       fileSel#fileSelectionWin#show ();
1327       GtkThread.main ();
1328       chosen_file
1329
1330     method private chooseDir ?(ok_not_exists = false) () =
1331       _ok_not_exists <- ok_not_exists;
1332       _only_directory <- true;
1333       fileSel#fileSelectionWin#show ();
1334       GtkThread.main ();
1335       (* we should check that this is a directory *)
1336       chosen_file
1337   
1338     method askText ?(title = "") ?(msg = "") () =
1339       let dialog = new textDialog () in
1340       dialog#textDialog#set_title title;
1341       dialog#textDialogLabel#set_label msg;
1342       let text = ref None in
1343       let return v =
1344         text := v;
1345         dialog#textDialog#destroy ();
1346         GMain.Main.quit ()
1347       in
1348       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1349       connect_button dialog#textDialogCancelButton (fun _ -> return None);
1350       connect_button dialog#textDialogOkButton (fun _ ->
1351         let text = dialog#textDialogTextView#buffer#get_text () in
1352         return (Some text));
1353       dialog#textDialog#show ();
1354       GtkThread.main ();
1355       !text
1356
1357     method private updateFontSize () =
1358       self#sourceView#misc#modify_font_by_name
1359         (sprintf "%s %d" BuildTimeConf.script_font font_size)
1360
1361     method increaseFontSize () =
1362       font_size <- font_size + 1;
1363       self#updateFontSize ()
1364
1365     method decreaseFontSize () =
1366       font_size <- font_size - 1;
1367       self#updateFontSize ()
1368
1369     method resetFontSize () =
1370       font_size <- default_font_size;
1371       self#updateFontSize ()
1372
1373   end
1374
1375 let gui () = 
1376   let g = new gui () in
1377   gui_instance := Some g;
1378   MatitaMathView.set_gui g;
1379   g
1380   
1381 let instance = singleton gui
1382
1383 let non p x = not (p x)
1384
1385 (* this is a shit and should be changed :-{ *)
1386 let interactive_uri_choice
1387   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1388   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
1389   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
1390   ?copy_cb ()
1391   ~id uris
1392 =
1393   let gui = instance () in
1394   if (selection_mode <> `SINGLE) &&
1395     (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1396   then
1397     uris
1398   else begin
1399     let dialog = gui#newUriDialog () in
1400     if hide_uri_entry then
1401       dialog#uriEntryHBox#misc#hide ();
1402     if hide_try then
1403       begin
1404       dialog#uriChoiceSelectedButton#misc#hide ();
1405       dialog#uriChoiceConstantsButton#misc#hide ();
1406       end;
1407     dialog#okLabel#set_label ok_label;  
1408     dialog#uriChoiceTreeView#selection#set_mode
1409       (selection_mode :> Gtk.Tags.selection_mode);
1410     let model = new stringListModel dialog#uriChoiceTreeView in
1411     let choices = ref None in
1412     (match copy_cb with
1413     | None -> ()
1414     | Some cb ->
1415         dialog#copyButton#misc#show ();
1416         connect_button dialog#copyButton 
1417         (fun _ ->
1418           match model#easy_selection () with
1419           | [u] -> (cb u)
1420           | _ -> ()));
1421     dialog#uriChoiceDialog#set_title title;
1422     dialog#uriChoiceLabel#set_text msg;
1423     List.iter model#easy_append (List.map NReference.string_of_reference uris);
1424     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1425     let return v =
1426       choices := v;
1427       dialog#uriChoiceDialog#destroy ();
1428       GMain.Main.quit ()
1429     in
1430     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1431     connect_button dialog#uriChoiceConstantsButton (fun _ ->
1432       return (Some uris));
1433     if ok_action = `AUTO then
1434       connect_button dialog#uriChoiceAutoButton (fun _ ->
1435         Helm_registry.set_bool "matita.auto_disambiguation" true;
1436         return (Some uris))
1437     else
1438       connect_button dialog#uriChoiceAutoButton (fun _ ->
1439         match model#easy_selection () with
1440         | [] -> ()
1441         | uris -> return (Some (List.map NReference.reference_of_string uris)));
1442     connect_button dialog#uriChoiceSelectedButton (fun _ ->
1443       match model#easy_selection () with
1444       | [] -> ()
1445       | uris -> return (Some (List.map NReference.reference_of_string uris)));
1446     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1447     dialog#uriChoiceDialog#show ();
1448     GtkThread.main ();
1449     (match !choices with 
1450     | None -> raise MatitaTypes.Cancel
1451     | Some uris -> uris)
1452   end
1453
1454 class interpModel =
1455   let cols = new GTree.column_list in
1456   let id_col = cols#add Gobject.Data.string in
1457   let dsc_col = cols#add Gobject.Data.string in
1458   let interp_no_col = cols#add Gobject.Data.int in
1459   let tree_store = GTree.tree_store cols in
1460   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1461   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1462   let id_view_col = GTree.view_column ~renderer:id_renderer () in
1463   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1464   fun tree_view choices ->
1465     object
1466       initializer
1467         tree_view#set_model (Some (tree_store :> GTree.model));
1468         ignore (tree_view#append_column id_view_col);
1469         ignore (tree_view#append_column dsc_view_col);
1470         let name_of_interp =
1471           (* try to find a reasonable name for an interpretation *)
1472           let idx = ref 0 in
1473           fun interp ->
1474             try
1475               List.assoc "0" interp
1476             with Not_found ->
1477               incr idx; string_of_int !idx
1478         in
1479         tree_store#clear ();
1480         let idx = ref ~-1 in
1481         List.iter
1482           (fun interp ->
1483             incr idx;
1484             let interp_row = tree_store#append () in
1485             tree_store#set ~row:interp_row ~column:id_col
1486               (name_of_interp interp);
1487             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1488             List.iter
1489               (fun (id, dsc) ->
1490                 let row = tree_store#append ~parent:interp_row () in
1491                 tree_store#set ~row ~column:id_col id;
1492                 tree_store#set ~row ~column:dsc_col dsc;
1493                 tree_store#set ~row ~column:interp_no_col !idx)
1494               interp)
1495           choices
1496
1497       method get_interp_no tree_path =
1498         let iter = tree_store#get_iter tree_path in
1499         tree_store#get ~row:iter ~column:interp_no_col
1500     end
1501
1502
1503 let interactive_string_choice 
1504   text prefix_len ?(title = "") ?(msg = "") () ~id locs uris 
1505
1506   let gui = instance () in
1507     let dialog = gui#newUriDialog () in
1508     dialog#uriEntryHBox#misc#hide ();
1509     dialog#uriChoiceSelectedButton#misc#hide ();
1510     dialog#uriChoiceAutoButton#misc#hide ();
1511     dialog#uriChoiceConstantsButton#misc#hide ();
1512     dialog#uriChoiceTreeView#selection#set_mode
1513       (`SINGLE :> Gtk.Tags.selection_mode);
1514     let model = new stringListModel dialog#uriChoiceTreeView in
1515     let choices = ref None in
1516     dialog#uriChoiceDialog#set_title title; 
1517     let hack_len = MatitaGtkMisc.utf8_string_length text in
1518     let rec colorize acc_len = function
1519       | [] -> 
1520           let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1521           escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1522       | he::tl -> 
1523           let start, stop =  HExtlib.loc_of_floc he in
1524           let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1525           let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1526           let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1527           escape_pango_markup str1 ^ "<b>" ^ 
1528           escape_pango_markup str2 ^ "</b>" ^ 
1529           colorize stop tl
1530     in
1531 (*     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1532                 Printf.eprintf "(%d,%d)" start stop) locs; *)
1533     let locs = 
1534       List.sort 
1535         (fun loc1 loc2 -> 
1536           fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2)) 
1537         locs 
1538     in
1539 (*     prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1540     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1541                 Printf.eprintf "(%d,%d)" start stop) locs;
1542     prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1543     dialog#uriChoiceLabel#set_use_markup true;
1544     let txt = colorize 0 locs in
1545     let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1546       (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1547     in
1548     dialog#uriChoiceLabel#set_label txt;
1549     List.iter model#easy_append uris;
1550     let return v =
1551       choices := v;
1552       dialog#uriChoiceDialog#destroy ();
1553       GMain.Main.quit ()
1554     in
1555     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1556     connect_button dialog#uriChoiceForwardButton (fun _ ->
1557       match model#easy_selection () with
1558       | [] -> ()
1559       | uris -> return (Some uris));
1560     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1561     dialog#uriChoiceDialog#show ();
1562     GtkThread.main ();
1563     (match !choices with 
1564     | None -> raise MatitaTypes.Cancel
1565     | Some uris -> uris)
1566
1567 let interactive_interp_choice () text prefix_len choices =
1568 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1569  let filter_choices filter =
1570   let rec is_compatible filter =
1571    function
1572       [] -> true
1573     | ([],_,_)::tl -> is_compatible filter tl
1574     | (loc::tlloc,id,dsc)::tl ->
1575        try
1576         if List.assoc (loc,id) filter = dsc then
1577          is_compatible filter ((tlloc,id,dsc)::tl)
1578         else
1579          false
1580        with
1581         Not_found -> true
1582   in
1583    List.filter (fun (_,interp) -> is_compatible filter interp)
1584  in
1585  let rec get_choices loc id =
1586   function
1587      [] -> []
1588    | (_,he)::tl ->
1589       let _,_,dsc =
1590        List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1591       in
1592        dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1593  in
1594  let example_interp =
1595   match choices with
1596      [] -> assert false
1597    | he::_ -> he in
1598  let ask_user id locs choices =
1599   interactive_string_choice
1600    text prefix_len
1601    ~title:"Ambiguous input"
1602    ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1603  in
1604  let rec classify ids filter partial_interpretations =
1605   match ids with
1606      [] -> List.map fst partial_interpretations
1607    | ([],_,_)::tl -> classify tl filter partial_interpretations
1608    | (loc::tlloc,id,dsc)::tl ->
1609       let choices = get_choices loc id partial_interpretations in
1610       let chosen_dsc =
1611        match choices with
1612           [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1613         | [dsc] -> dsc
1614         | _ ->
1615           match ask_user id [loc] choices with
1616              [x] -> x
1617            | _ -> assert false
1618       in
1619        let filter = ((loc,id),chosen_dsc)::filter in
1620        let compatible_interps = filter_choices filter partial_interpretations in
1621         classify ((tlloc,id,dsc)::tl) filter compatible_interps
1622  in
1623  let enumerated_choices =
1624   let idx = ref ~-1 in
1625   List.map (fun interp -> incr idx; !idx,interp) choices
1626  in
1627   classify example_interp [] enumerated_choices
1628
1629 let _ =
1630   (* disambiguator callbacks *)
1631   Disambiguate.set_choose_uris_callback
1632    (fun ~selection_mode ?ok ?(enable_button_for_non_vars=false) ~title ~msg ->
1633      interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1634   Disambiguate.set_choose_interp_callback (interactive_interp_choice ());
1635   (* gtk initialization *)
1636   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1637   ignore (GMain.Main.init ())
1638