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