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