]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaGui.ml
WARNING: partial commit.
[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      GrafiteTypes.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:(
860           let s = s () in
861           let status =
862            Interpretations.toggle_active_interpretations s#grafite_status
863           in
864            assert false (* MATITA1.0 ???
865            s#set_grafite_status status*)
866          );
867       MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
868         ~callback:(fun enabled -> NTermCicContent.hide_coercions := enabled);
869       MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
870         ~callback:(fun enabled ->
871           Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
872       main#unicodeAsTexMenuItem#set_active
873         (Helm_registry.get_bool "matita.paste_unicode_as_tex");
874         (* log *)
875       HLog.set_log_callback self#console#log_callback;
876       GtkSignal.user_handler :=
877         (function 
878         | MatitaScript.ActionCancelled s -> HLog.error s
879         | exn ->
880           if not (Helm_registry.get_bool "matita.debug") then
881            notify_exn exn
882           else raise exn);
883         (* script *)
884       let _ =
885        source_buffer#set_language (Some MatitaGtkMisc.matita_lang);
886        source_buffer#set_highlight_syntax true
887       in
888       let disableSave () =
889         (s())#assignFileName None;
890         main#saveMenuItem#misc#set_sensitive false
891       in
892       let saveAsScript () =
893         let script = s () in
894         match self#chooseFile ~ok_not_exists:true () with
895         | Some f -> 
896               HExtlib.touch f;
897               script#assignFileName (Some f);
898               script#saveToFile (); 
899               console#message ("'"^f^"' saved.\n");
900               self#_enableSaveTo f
901         | None -> ()
902       in
903       let saveScript () =
904         let script = s () in
905         if script#has_name then 
906           (script#saveToFile (); 
907           console#message ("'"^script#filename^"' saved.\n"))
908         else saveAsScript ()
909       in
910       let abandon_script () =
911         let grafite_status = (s ())#grafite_status in
912         if source_view#buffer#modified then
913           (match ask_unsaved main#toplevel with
914           | `YES -> saveScript ()
915           | `NO -> ()
916           | `CANCEL -> raise MatitaTypes.Cancel);
917         save_moo grafite_status
918       in
919       let loadScript () =
920         let script = s () in 
921         try 
922           match self#chooseFile () with
923           | Some f -> 
924               abandon_script ();
925               script#reset (); 
926               script#assignFileName (Some f);
927               source_view#source_buffer#begin_not_undoable_action ();
928               script#loadFromFile f; 
929               source_view#source_buffer#end_not_undoable_action ();
930               source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
931               source_view#buffer#place_cursor source_view#buffer#start_iter;
932               console#message ("'"^f^"' loaded.\n");
933               self#_enableSaveTo f
934           | None -> ()
935         with MatitaTypes.Cancel -> ()
936       in
937       let newScript () = 
938         abandon_script ();
939         source_view#source_buffer#begin_not_undoable_action ();
940         (s ())#reset (); 
941         (s ())#template (); 
942         source_view#source_buffer#end_not_undoable_action ();
943         disableSave ();
944         (s ())#assignFileName None
945       in
946       let cursor () =
947         source_buffer#place_cursor
948           (source_buffer#get_iter_at_mark (`NAME "locked")) in
949       let advance _ = (MatitaScript.current ())#advance (); cursor () in
950       let retract _ = (MatitaScript.current ())#retract (); cursor () in
951       let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
952       let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
953       let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
954       let advance = locker (keep_focus advance) in
955       let retract = locker (keep_focus retract) in
956       let top = locker (keep_focus top) in
957       let bottom = locker (keep_focus bottom) in
958       let jump = locker (keep_focus jump) in
959         (* quit *)
960       self#setQuitCallback (fun () -> 
961         let script = MatitaScript.current () in
962         if source_view#buffer#modified then
963           match ask_unsaved main#toplevel with
964           | `YES -> 
965                saveScript ();
966                save_moo script#grafite_status;
967                GMain.Main.quit ()
968           | `NO -> GMain.Main.quit ()
969           | `CANCEL -> ()
970         else 
971           (save_moo script#grafite_status;
972           GMain.Main.quit ()));
973       connect_button main#scriptAdvanceButton advance;
974       connect_button main#scriptRetractButton retract;
975       connect_button main#scriptTopButton top;
976       connect_button main#scriptBottomButton bottom;
977       connect_button main#scriptJumpButton jump;
978       connect_button main#scriptAbortButton kill_worker;
979       connect_menu_item main#scriptAdvanceMenuItem advance;
980       connect_menu_item main#scriptRetractMenuItem retract;
981       connect_menu_item main#scriptTopMenuItem top;
982       connect_menu_item main#scriptBottomMenuItem bottom;
983       connect_menu_item main#scriptJumpMenuItem jump;
984       connect_menu_item main#openMenuItem   loadScript;
985       connect_menu_item main#saveMenuItem   saveScript;
986       connect_menu_item main#saveAsMenuItem saveAsScript;
987       connect_menu_item main#newMenuItem    newScript;
988       connect_menu_item main#showCoercionsGraphMenuItem 
989         (fun _ -> 
990           let c = MatitaMathView.cicBrowser () in
991           c#load (`About `Coercions));
992       connect_menu_item main#showHintsDbMenuItem 
993         (fun _ -> 
994           let c = MatitaMathView.cicBrowser () in
995           c#load (`About `Hints));
996       connect_menu_item main#showTermGrammarMenuItem 
997         (fun _ -> 
998           let c = MatitaMathView.cicBrowser () in
999           c#load (`About `Grammar));
1000       connect_menu_item main#showUnicodeTable
1001         (fun _ -> 
1002           let c = MatitaMathView.cicBrowser () in
1003           c#load (`About `TeX));
1004          (* script monospace font stuff *)  
1005       self#updateFontSize ();
1006         (* debug menu *)
1007       main#debugMenu#misc#hide ();
1008         (* HBUGS *)
1009       main#hintNotebook#misc#hide ();
1010       (*
1011       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1012       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1013       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1014       *)
1015         (* focus *)
1016       self#sourceView#misc#grab_focus ();
1017         (* main win dimension *)
1018       let width = Gdk.Screen.width ~screen:(Gdk.Screen.default ()) () in
1019       let height = Gdk.Screen.height ~screen:(Gdk.Screen.default ()) () in
1020       (* hack for xinerama, no proper support of monitors from lablgtk *)
1021       let width = if width > 1600 then width / 2 else width in
1022       let height = if height > 1200 then height / 2 else height in
1023       let main_w = width * 90 / 100 in 
1024       let main_h = height * 80 / 100 in
1025       let script_w = main_w * 6 / 10 in
1026       main#toplevel#resize ~width:main_w ~height:main_h;
1027       main#hpaneScriptSequent#set_position script_w;
1028         (* source_view *)
1029       ignore(source_view#connect#after#paste_clipboard 
1030         ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1031       (* clean_locked is set to true only "during" a PRIMARY paste
1032          operation (i.e. by clicking with the second mouse button) *)
1033       let clean_locked = ref false in
1034       ignore(source_view#event#connect#button_press
1035         ~callback:
1036           (fun button ->
1037             if GdkEvent.Button.button button = 2 then
1038              clean_locked := true;
1039             false
1040           ));
1041       ignore(source_view#event#connect#button_release
1042         ~callback:(fun button -> clean_locked := false; false));
1043       ignore(source_view#buffer#connect#after#apply_tag
1044        ~callback:(
1045          fun tag ~start:_ ~stop:_ ->
1046           if !clean_locked &&
1047              tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1048           then
1049            begin
1050             clean_locked := false;
1051             (MatitaScript.current ())#clean_dirty_lock;
1052             clean_locked := true
1053            end));
1054       (* math view handling *)
1055       connect_menu_item main#newCicBrowserMenuItem (fun () ->
1056         ignore(MatitaMathView.cicBrowser ()));
1057       connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1058         self#increaseFontSize ();
1059         MatitaMathView.increase_font_size ();
1060         MatitaMathView.update_font_sizes ());
1061       connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1062         self#decreaseFontSize ();
1063         MatitaMathView.decrease_font_size ();
1064         MatitaMathView.update_font_sizes ());
1065       connect_menu_item main#normalFontSizeMenuItem (fun () ->
1066         self#resetFontSize ();
1067         MatitaMathView.reset_font_size ();
1068         MatitaMathView.update_font_sizes ());
1069       MatitaMathView.reset_font_size ();
1070
1071       (** selections / clipboards handling *)
1072
1073     method markupSelected = MatitaMathView.has_selection ()
1074     method private textSelected =
1075       (source_buffer#get_iter_at_mark `INSERT)#compare
1076         (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1077     method private somethingSelected = self#markupSelected || self#textSelected
1078     method private markupStored = MatitaMathView.has_clipboard ()
1079     method private textStored = clipboard#text <> None
1080     method private somethingStored = self#markupStored || self#textStored
1081
1082     method canCopy = self#somethingSelected
1083     method canCut = self#textSelected
1084     method canDelete = self#textSelected
1085     method canPaste = self#somethingStored
1086     method canPastePattern = self#markupStored
1087
1088     method copy () =
1089       if self#textSelected
1090       then begin
1091         MatitaMathView.empty_clipboard ();
1092         source_view#buffer#copy_clipboard clipboard;
1093       end else
1094         MatitaMathView.copy_selection ()
1095     method cut () =
1096       source_view#buffer#cut_clipboard clipboard;
1097       MatitaMathView.empty_clipboard ()
1098     method delete () = ignore (source_view#buffer#delete_selection ())
1099     method paste () =
1100       if MatitaMathView.has_clipboard ()
1101       then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1102       else source_view#buffer#paste_clipboard clipboard;
1103       (MatitaScript.current ())#clean_dirty_lock
1104     method pastePattern () =
1105       source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1106     
1107     method private expand_virtual_if_any iter tok =
1108       try
1109        let len = MatitaGtkMisc.utf8_string_length tok in
1110        let last_word =
1111         let prev = iter#copy#backward_chars len in
1112          prev#get_slice ~stop:(prev#copy#backward_find_char 
1113           (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
1114        in
1115        let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
1116        self#reset_similarsymbols;
1117        let s = Glib.Utf8.from_unichar symb in
1118        assert(Glib.Utf8.validate s);
1119        source_buffer#delete ~start:iter 
1120          ~stop:(iter#copy#backward_chars
1121            (MatitaGtkMisc.utf8_string_length inplaceof + len));
1122        source_buffer#insert ~iter
1123          (if inplaceof.[0] = '\\' then s else (s ^ tok));
1124        true
1125       with Virtuals.Not_a_virtual -> false
1126          
1127     val similar_memory = Hashtbl.create 97
1128     val mutable old_used_memory = false
1129
1130     method private nextSimilarSymbol () = 
1131       let write_similarsymbol s =
1132         let s = Glib.Utf8.from_unichar s in
1133         let iter = source_buffer#get_iter_at_mark `INSERT in
1134         assert(Glib.Utf8.validate s);
1135         source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
1136         source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s;
1137         (try source_buffer#delete_mark similarsymbols_tag
1138          with GText.No_such_mark _ -> ());
1139         ignore(source_buffer#create_mark ~name:similarsymbols_tag_name
1140           (source_buffer#get_iter_at_mark `INSERT));
1141       in
1142       let new_similarsymbol =
1143         try
1144           let iter_ins = source_buffer#get_iter_at_mark `INSERT in
1145           let iter_lig = source_buffer#get_iter_at_mark similarsymbols_tag in
1146           not (iter_ins#equal iter_lig)
1147         with GText.No_such_mark _ -> true
1148       in
1149       if new_similarsymbol then
1150         (if not(self#expand_virtual_if_any (source_buffer#get_iter_at_mark `INSERT) "")then
1151           let last_symbol = 
1152             let i = source_buffer#get_iter_at_mark `INSERT in
1153             Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
1154           in
1155           (match Virtuals.similar_symbols last_symbol with
1156           | [] ->  ()
1157           | eqclass ->
1158               similarsymbols_orig <- eqclass;
1159               let is_used = 
1160                 try Hashtbl.find similar_memory similarsymbols_orig  
1161                 with Not_found -> 
1162                   let is_used = List.map (fun x -> x,false) eqclass in
1163                   Hashtbl.add similar_memory eqclass is_used; 
1164                   is_used
1165               in
1166               let hd, next, tl = 
1167                 let used, unused = 
1168                   List.partition (fun s -> List.assoc s is_used) eqclass 
1169                 in
1170                 match used @ unused with a::b::c -> a,b,c | _ -> assert false
1171               in
1172               let hd, tl = 
1173                 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
1174               in
1175               old_used_memory <- List.assoc hd is_used;
1176               let is_used = 
1177                 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
1178               in
1179               Hashtbl.replace similar_memory similarsymbols_orig is_used;
1180               write_similarsymbol hd;
1181               similarsymbols <- tl @ [ hd ]))
1182       else 
1183         match similarsymbols with
1184         | [] -> ()
1185         | hd :: tl ->
1186             let is_used = Hashtbl.find similar_memory similarsymbols_orig in
1187             let last = HExtlib.list_last tl in
1188             let old_used_for_last = old_used_memory in
1189             old_used_memory <- List.assoc hd is_used;
1190             let is_used = 
1191               (hd, true) :: (last,old_used_for_last) ::
1192                 List.filter (fun (x,_) -> x <> last && x <> hd) is_used 
1193             in
1194             Hashtbl.replace similar_memory similarsymbols_orig is_used;
1195             similarsymbols <- tl @ [ hd ];
1196             write_similarsymbol hd
1197
1198     method private externalEditor () =
1199       let cmd = Helm_registry.get "matita.external_editor" in
1200 (* ZACK uncomment to enable interactive ask of external editor command *)
1201 (*      let cmd =
1202          let msg =
1203           "External editor command:
1204 %f  will be substitute for the script name,
1205 %p  for the cursor position in bytes,
1206 %l  for the execution point in bytes."
1207         in
1208         ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1209           ~default:(Helm_registry.get "matita.external_editor") ()
1210       in *)
1211       let script = MatitaScript.current () in
1212       let fname = script#filename in
1213       let slice mark =
1214         source_buffer#start_iter#get_slice
1215           ~stop:(source_buffer#get_iter_at_mark mark)
1216       in
1217       let locked = `MARK script#locked_mark in
1218       let string_pos mark = string_of_int (String.length (slice mark)) in
1219       let cursor_pos = string_pos `INSERT in
1220       let locked_pos = string_pos locked in
1221       let cmd =
1222         Pcre.replace ~pat:"%f" ~templ:fname
1223           (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1224             (Pcre.replace ~pat:"%l" ~templ:locked_pos
1225               cmd))
1226       in
1227       let locked_before = slice locked in
1228       let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1229       ignore (Unix.system cmd);
1230       source_buffer#set_text (HExtlib.input_file fname);
1231       let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1232       source_buffer#move_mark locked locked_iter;
1233       source_buffer#apply_tag script#locked_tag
1234         ~start:source_buffer#start_iter ~stop:locked_iter;
1235       let locked_after = slice locked in
1236       let line = ref 0 in
1237       let col = ref 0 in
1238       try
1239         for i = 0 to String.length locked_before - 1 do
1240           if locked_before.[i] <> locked_after.[i] then begin
1241             source_buffer#place_cursor
1242               ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1243             script#goto `Cursor ();
1244             raise Exit
1245           end else if locked_before.[i] = '\n' then begin
1246             incr line;
1247             col := 0
1248           end
1249         done
1250       with
1251       | Exit -> ()
1252       | Invalid_argument _ -> script#goto `Bottom ()
1253
1254     method loadScript file =       
1255       let script = MatitaScript.current () in
1256       script#reset (); 
1257       script#assignFileName (Some file);
1258       let file = script#filename in
1259       let content =
1260        if Sys.file_exists file then file
1261        else BuildTimeConf.script_template
1262       in
1263       source_view#source_buffer#begin_not_undoable_action ();
1264       script#loadFromFile content;
1265       source_view#source_buffer#end_not_undoable_action ();
1266       source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1267       source_view#buffer#place_cursor source_view#buffer#start_iter;
1268       console#message ("'"^file^"' loaded.");
1269       self#_enableSaveTo file
1270       
1271     method setStar b =
1272       let s = MatitaScript.current () in
1273       let w = main#toplevel in
1274       let set x = w#set_title x in
1275       let name = 
1276         "Matita - " ^ Filename.basename s#filename ^ 
1277         (if b then "*" else "") ^
1278         " in " ^ s#buri_of_current_file 
1279       in
1280         set name
1281         
1282     method private _enableSaveTo file =
1283       self#main#saveMenuItem#misc#set_sensitive true
1284         
1285     method console = console
1286     method sourceView: GSourceView2.source_view =
1287       (source_view: GSourceView2.source_view)
1288     method fileSel = fileSel
1289     method findRepl = findRepl
1290     method main = main
1291
1292     method newBrowserWin () =
1293       object (self)
1294         inherit browserWin ()
1295         val combo = GEdit.entry ()
1296         initializer
1297           self#check_widgets ();
1298           let combo_widget = combo#coerce in
1299           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1300           combo#misc#grab_focus ()
1301         method browserUri = combo
1302       end
1303
1304     method newUriDialog () =
1305       let dialog = new uriChoiceDialog () in
1306       dialog#check_widgets ();
1307       dialog
1308
1309     method newConfirmationDialog () =
1310       let dialog = new confirmationDialog () in
1311       dialog#check_widgets ();
1312       dialog
1313
1314     method newEmptyDialog () =
1315       let dialog = new emptyDialog () in
1316       dialog#check_widgets ();
1317       dialog
1318
1319     method private addKeyBinding key callback =
1320       List.iter (fun evbox -> add_key_binding key callback evbox)
1321         keyBindingBoxes
1322
1323     method setQuitCallback callback =
1324       connect_menu_item main#quitMenuItem callback;
1325       ignore (main#toplevel#event#connect#delete 
1326         (fun _ -> callback ();true));
1327       self#addKeyBinding GdkKeysyms._q callback
1328
1329     method chooseFile ?(ok_not_exists = false) () =
1330       _ok_not_exists <- ok_not_exists;
1331       _only_directory <- false;
1332       fileSel#fileSelectionWin#show ();
1333       GtkThread.main ();
1334       chosen_file
1335
1336     method private chooseDir ?(ok_not_exists = false) () =
1337       _ok_not_exists <- ok_not_exists;
1338       _only_directory <- true;
1339       fileSel#fileSelectionWin#show ();
1340       GtkThread.main ();
1341       (* we should check that this is a directory *)
1342       chosen_file
1343   
1344     method askText ?(title = "") ?(msg = "") () =
1345       let dialog = new textDialog () in
1346       dialog#textDialog#set_title title;
1347       dialog#textDialogLabel#set_label msg;
1348       let text = ref None in
1349       let return v =
1350         text := v;
1351         dialog#textDialog#destroy ();
1352         GMain.Main.quit ()
1353       in
1354       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1355       connect_button dialog#textDialogCancelButton (fun _ -> return None);
1356       connect_button dialog#textDialogOkButton (fun _ ->
1357         let text = dialog#textDialogTextView#buffer#get_text () in
1358         return (Some text));
1359       dialog#textDialog#show ();
1360       GtkThread.main ();
1361       !text
1362
1363     method private updateFontSize () =
1364       self#sourceView#misc#modify_font_by_name
1365         (sprintf "%s %d" BuildTimeConf.script_font font_size)
1366
1367     method increaseFontSize () =
1368       font_size <- font_size + 1;
1369       self#updateFontSize ()
1370
1371     method decreaseFontSize () =
1372       font_size <- font_size - 1;
1373       self#updateFontSize ()
1374
1375     method resetFontSize () =
1376       font_size <- default_font_size;
1377       self#updateFontSize ()
1378
1379   end
1380
1381 let gui () = 
1382   let g = new gui () in
1383   gui_instance := Some g;
1384   MatitaMathView.set_gui g;
1385   g
1386   
1387 let instance = singleton gui
1388
1389 let non p x = not (p x)
1390
1391 (* this is a shit and should be changed :-{ *)
1392 let interactive_uri_choice
1393   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1394   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
1395   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
1396   ?copy_cb ()
1397   ~id uris
1398 =
1399   let gui = instance () in
1400   if (selection_mode <> `SINGLE) &&
1401     (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1402   then
1403     uris
1404   else begin
1405     let dialog = gui#newUriDialog () in
1406     if hide_uri_entry then
1407       dialog#uriEntryHBox#misc#hide ();
1408     if hide_try then
1409       begin
1410       dialog#uriChoiceSelectedButton#misc#hide ();
1411       dialog#uriChoiceConstantsButton#misc#hide ();
1412       end;
1413     dialog#okLabel#set_label ok_label;  
1414     dialog#uriChoiceTreeView#selection#set_mode
1415       (selection_mode :> Gtk.Tags.selection_mode);
1416     let model = new stringListModel dialog#uriChoiceTreeView in
1417     let choices = ref None in
1418     (match copy_cb with
1419     | None -> ()
1420     | Some cb ->
1421         dialog#copyButton#misc#show ();
1422         connect_button dialog#copyButton 
1423         (fun _ ->
1424           match model#easy_selection () with
1425           | [u] -> (cb u)
1426           | _ -> ()));
1427     dialog#uriChoiceDialog#set_title title;
1428     dialog#uriChoiceLabel#set_text msg;
1429     List.iter model#easy_append (List.map NReference.string_of_reference uris);
1430     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1431     let return v =
1432       choices := v;
1433       dialog#uriChoiceDialog#destroy ();
1434       GMain.Main.quit ()
1435     in
1436     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1437     connect_button dialog#uriChoiceConstantsButton (fun _ ->
1438       return (Some uris));
1439     if ok_action = `AUTO then
1440       connect_button dialog#uriChoiceAutoButton (fun _ ->
1441         Helm_registry.set_bool "matita.auto_disambiguation" true;
1442         return (Some uris))
1443     else
1444       connect_button dialog#uriChoiceAutoButton (fun _ ->
1445         match model#easy_selection () with
1446         | [] -> ()
1447         | uris -> return (Some (List.map NReference.reference_of_string uris)));
1448     connect_button dialog#uriChoiceSelectedButton (fun _ ->
1449       match model#easy_selection () with
1450       | [] -> ()
1451       | uris -> return (Some (List.map NReference.reference_of_string uris)));
1452     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1453     dialog#uriChoiceDialog#show ();
1454     GtkThread.main ();
1455     (match !choices with 
1456     | None -> raise MatitaTypes.Cancel
1457     | Some uris -> uris)
1458   end
1459
1460 class interpModel =
1461   let cols = new GTree.column_list in
1462   let id_col = cols#add Gobject.Data.string in
1463   let dsc_col = cols#add Gobject.Data.string in
1464   let interp_no_col = cols#add Gobject.Data.int in
1465   let tree_store = GTree.tree_store cols in
1466   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1467   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1468   let id_view_col = GTree.view_column ~renderer:id_renderer () in
1469   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1470   fun tree_view choices ->
1471     object
1472       initializer
1473         tree_view#set_model (Some (tree_store :> GTree.model));
1474         ignore (tree_view#append_column id_view_col);
1475         ignore (tree_view#append_column dsc_view_col);
1476         let name_of_interp =
1477           (* try to find a reasonable name for an interpretation *)
1478           let idx = ref 0 in
1479           fun interp ->
1480             try
1481               List.assoc "0" interp
1482             with Not_found ->
1483               incr idx; string_of_int !idx
1484         in
1485         tree_store#clear ();
1486         let idx = ref ~-1 in
1487         List.iter
1488           (fun interp ->
1489             incr idx;
1490             let interp_row = tree_store#append () in
1491             tree_store#set ~row:interp_row ~column:id_col
1492               (name_of_interp interp);
1493             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1494             List.iter
1495               (fun (id, dsc) ->
1496                 let row = tree_store#append ~parent:interp_row () in
1497                 tree_store#set ~row ~column:id_col id;
1498                 tree_store#set ~row ~column:dsc_col dsc;
1499                 tree_store#set ~row ~column:interp_no_col !idx)
1500               interp)
1501           choices
1502
1503       method get_interp_no tree_path =
1504         let iter = tree_store#get_iter tree_path in
1505         tree_store#get ~row:iter ~column:interp_no_col
1506     end
1507
1508
1509 let interactive_string_choice 
1510   text prefix_len ?(title = "") ?(msg = "") () ~id locs uris 
1511
1512   let gui = instance () in
1513     let dialog = gui#newUriDialog () in
1514     dialog#uriEntryHBox#misc#hide ();
1515     dialog#uriChoiceSelectedButton#misc#hide ();
1516     dialog#uriChoiceAutoButton#misc#hide ();
1517     dialog#uriChoiceConstantsButton#misc#hide ();
1518     dialog#uriChoiceTreeView#selection#set_mode
1519       (`SINGLE :> Gtk.Tags.selection_mode);
1520     let model = new stringListModel dialog#uriChoiceTreeView in
1521     let choices = ref None in
1522     dialog#uriChoiceDialog#set_title title; 
1523     let hack_len = MatitaGtkMisc.utf8_string_length text in
1524     let rec colorize acc_len = function
1525       | [] -> 
1526           let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1527           escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1528       | he::tl -> 
1529           let start, stop =  HExtlib.loc_of_floc he in
1530           let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1531           let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1532           let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1533           escape_pango_markup str1 ^ "<b>" ^ 
1534           escape_pango_markup str2 ^ "</b>" ^ 
1535           colorize stop tl
1536     in
1537 (*     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1538                 Printf.eprintf "(%d,%d)" start stop) locs; *)
1539     let locs = 
1540       List.sort 
1541         (fun loc1 loc2 -> 
1542           fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2)) 
1543         locs 
1544     in
1545 (*     prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1546     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1547                 Printf.eprintf "(%d,%d)" start stop) locs;
1548     prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1549     dialog#uriChoiceLabel#set_use_markup true;
1550     let txt = colorize 0 locs in
1551     let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1552       (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1553     in
1554     dialog#uriChoiceLabel#set_label txt;
1555     List.iter model#easy_append uris;
1556     let return v =
1557       choices := v;
1558       dialog#uriChoiceDialog#destroy ();
1559       GMain.Main.quit ()
1560     in
1561     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1562     connect_button dialog#uriChoiceForwardButton (fun _ ->
1563       match model#easy_selection () with
1564       | [] -> ()
1565       | uris -> return (Some uris));
1566     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1567     dialog#uriChoiceDialog#show ();
1568     GtkThread.main ();
1569     (match !choices with 
1570     | None -> raise MatitaTypes.Cancel
1571     | Some uris -> uris)
1572
1573 let interactive_interp_choice () text prefix_len choices =
1574 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1575  let filter_choices filter =
1576   let rec is_compatible filter =
1577    function
1578       [] -> true
1579     | ([],_,_)::tl -> is_compatible filter tl
1580     | (loc::tlloc,id,dsc)::tl ->
1581        try
1582         if List.assoc (loc,id) filter = dsc then
1583          is_compatible filter ((tlloc,id,dsc)::tl)
1584         else
1585          false
1586        with
1587         Not_found -> true
1588   in
1589    List.filter (fun (_,interp) -> is_compatible filter interp)
1590  in
1591  let rec get_choices loc id =
1592   function
1593      [] -> []
1594    | (_,he)::tl ->
1595       let _,_,dsc =
1596        List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1597       in
1598        dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1599  in
1600  let example_interp =
1601   match choices with
1602      [] -> assert false
1603    | he::_ -> he in
1604  let ask_user id locs choices =
1605   interactive_string_choice
1606    text prefix_len
1607    ~title:"Ambiguous input"
1608    ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1609  in
1610  let rec classify ids filter partial_interpretations =
1611   match ids with
1612      [] -> List.map fst partial_interpretations
1613    | ([],_,_)::tl -> classify tl filter partial_interpretations
1614    | (loc::tlloc,id,dsc)::tl ->
1615       let choices = get_choices loc id partial_interpretations in
1616       let chosen_dsc =
1617        match choices with
1618           [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1619         | [dsc] -> dsc
1620         | _ ->
1621           match ask_user id [loc] choices with
1622              [x] -> x
1623            | _ -> assert false
1624       in
1625        let filter = ((loc,id),chosen_dsc)::filter in
1626        let compatible_interps = filter_choices filter partial_interpretations in
1627         classify ((tlloc,id,dsc)::tl) filter compatible_interps
1628  in
1629  let enumerated_choices =
1630   let idx = ref ~-1 in
1631   List.map (fun interp -> incr idx; !idx,interp) choices
1632  in
1633   classify example_interp [] enumerated_choices
1634
1635 let _ =
1636   (* disambiguator callbacks *)
1637   Disambiguate.set_choose_uris_callback
1638    (fun ~selection_mode ?ok ?(enable_button_for_non_vars=false) ~title ~msg ->
1639      interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1640   Disambiguate.set_choose_interp_callback (interactive_interp_choice ());
1641   (* gtk initialization *)
1642   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1643   ignore (GMain.Main.init ())
1644