]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaGui.ml
- fixed dummy_floc (now in DisambiguateTypes)
[helm.git] / helm / 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 open Printf
27
28 open MatitaGeneratedGui
29 open MatitaGtkMisc
30 open MatitaMisc
31
32 let gui_instance = ref None
33
34 class type browserWin =
35   (* this class exists only because GEdit.combo_box_entry is not supported by
36    * lablgladecc :-(((( *)
37 object
38   inherit MatitaGeneratedGui.browserWin
39   method browserUri: GEdit.combo_box_entry
40 end
41
42 class console ~(buffer: GText.buffer) () =
43   object (self)
44     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
45     val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
46     val message_tag = buffer#create_tag []
47     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
48     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
49     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
50     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
51     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
52     method clear () =
53       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
54     method log_callback (tag: MatitaLog.log_tag) s =
55       match tag with
56       | `Debug -> self#debug (s ^ "\n")
57       | `Error -> self#error (s ^ "\n")
58       | `Message -> self#message (s ^ "\n")
59       | `Warning -> self#warning (s ^ "\n")
60   end
61         
62 let clean_current_baseuri status = 
63     try  
64       let baseuri = MatitaTypes.get_string_option status "baseuri" in
65       MatitacleanLib.clean_baseuris [baseuri]
66     with MatitaTypes.Option_error _ -> ()
67
68 let ask_and_save_moo_if_needed parent fname status = 
69   let save () =
70     MatitacLib.dump_moo_to_file fname status.MatitaTypes.moo_content_rev in
71   if (MatitaScript.instance ())#eos &&
72      status.MatitaTypes.proof_status = MatitaTypes.No_proof
73   then
74     begin
75       let mooname = 
76         MatitaMisc.obj_file_of_script fname
77       in
78       let rc = 
79         MatitaGtkMisc.ask_confirmation
80         ~title:"A .moo can be generated"
81         ~message:(Printf.sprintf 
82           "%s can be generated for %s.\n<i>Should I generate it?</i>"
83           (Filename.basename mooname) (Filename.basename fname))
84         ~parent ()
85       in
86       let b = 
87         match rc with 
88         | `YES -> true 
89         | `NO -> false 
90         | `CANCEL -> raise MatitaTypes.Cancel 
91       in
92       if b then
93         save ()
94       else
95         clean_current_baseuri status
96     end
97   else
98     clean_current_baseuri status 
99     
100 let ask_unsaved parent =
101   MatitaGtkMisc.ask_confirmation 
102     ~parent ~title:"Unsaved work!" 
103     ~message:("Your work is <b>unsaved</b>!\n\n"^
104          "<i>Do you want to save the script before exiting?</i>")
105     ()
106
107 class gui () =
108     (* creation order _is_ relevant for windows placement *)
109   let main = new mainWin () in
110   let fileSel = new fileSelectionWin () in
111   let findRepl = new findReplWin () in
112   let develList = new develListWin () in
113   let newDevel = new newDevelWin () in
114   let keyBindingBoxes = (* event boxes which should receive global key events *)
115     [ main#mainWinEventBox ]
116   in
117   let console = new console ~buffer:main#logTextView#buffer () in
118   let (source_view: GSourceView.source_view) =
119     GSourceView.source_view
120       ~auto_indent:true
121       ~insert_spaces_instead_of_tabs:true ~tabs_width:2
122       ~margin:80 ~show_margin:true
123       ~smart_home_end:true
124       ~packing:main#scriptScrolledWin#add
125       ()
126   in
127   let default_font_size =
128     Helm_registry.get_opt_default Helm_registry.int
129       ~default:BuildTimeConf.default_font_size "matita.font_size"
130   in
131   let source_buffer = source_view#source_buffer in
132   object (self)
133     val mutable chosen_file = None
134     val mutable _ok_not_exists = false
135     val mutable _only_directory = false
136     val mutable script_fname = None
137     val mutable font_size = default_font_size
138     val mutable next_devel_must_contain = None
139    
140     initializer
141         (* glade's check widgets *)
142       List.iter (fun w -> w#check_widgets ())
143         (let c w = (w :> <check_widgets: unit -> unit>) in
144         [ c fileSel; c main; c findRepl]);
145         (* key bindings *)
146       List.iter (* global key bindings *)
147         (fun (key, callback) -> self#addKeyBinding key callback)
148 (*
149         [ GdkKeysyms._F3,
150             toggle_win ~check:main#showProofMenuItem proof#proofWin;
151           GdkKeysyms._F4,
152             toggle_win ~check:main#showCheckMenuItem check#checkWin;
153 *)
154         [ ];
155         (* about win *)
156       let parse_txt_file file =
157        let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
158        let l_rev = ref [] in
159        try
160         while true do
161          l_rev := input_line ch :: !l_rev;
162         done;
163         assert false
164        with
165         End_of_file ->
166          close_in ch;
167          List.rev !l_rev in 
168       let about_dialog =
169        GWindow.about_dialog
170         ~authors:(parse_txt_file "AUTHORS")
171         (*~comments:"comments"*)
172         ~copyright:"Copyright (C) 2005, the HELM team"
173         ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
174         ~logo:
175           (GdkPixbuf.from_file
176             (BuildTimeConf.runtime_base_dir ^ "/logo/matita_medium.png"))
177         ~name:"Matita"
178         ~version:BuildTimeConf.version
179         ~website:"http://helm.cs.unibo.it"
180         ()
181       in
182       connect_menu_item main#aboutMenuItem about_dialog#present;
183         (* findRepl win *)
184       let show_find_Repl () = 
185         findRepl#toplevel#misc#show ();
186         findRepl#toplevel#misc#grab_focus ()
187       in
188       let hide_find_Repl () = findRepl#toplevel#misc#hide () in
189       let find_forward _ = 
190           let highlight start end_ =
191             source_buffer#move_mark `INSERT ~where:start;
192             source_buffer#move_mark `SEL_BOUND ~where:end_;
193             source_view#scroll_mark_onscreen `INSERT
194           in
195           let text = findRepl#findEntry#text in
196           let iter = source_buffer#get_iter `SEL_BOUND in
197           match iter#forward_search text with
198           | None -> 
199               (match source_buffer#start_iter#forward_search text with
200               | None -> ()
201               | Some (start,end_) -> highlight start end_)
202           | Some (start,end_) -> highlight start end_ 
203       in
204       let replace _ =
205         let text = findRepl#replaceEntry#text in
206         let ins = source_buffer#get_iter `INSERT in
207         let sel = source_buffer#get_iter `SEL_BOUND in
208         if ins#compare sel < 0 then 
209           begin
210             ignore(source_buffer#delete_selection ());
211             source_buffer#insert text
212           end
213       in
214       connect_button findRepl#findButton find_forward;
215       connect_button findRepl#findReplButton replace;
216       connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
217       ignore(findRepl#toplevel#event#connect#delete 
218         ~callback:(fun _ -> hide_find_Repl ();true));
219       let safe_undo =
220        fun () ->
221         (* phase 1: we save the actual status of the marks and we undo *)
222         let locked_mark = `MARK ((MatitaScript.instance ())#locked_mark) in
223         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
224         let locked_iter_offset = locked_iter#offset in
225         let mark2 =
226          `MARK
227            (source_view#buffer#create_mark ~name:"lock_point"
228              ~left_gravity:true locked_iter) in
229         source_view#source_buffer#undo ();
230         (* phase 2: we save the cursor position and we redo, restoring
231            the previous status of all the marks *)
232         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
233         let mark =
234          `MARK
235            (source_view#buffer#create_mark ~name:"undo_point"
236              ~left_gravity:true cursor_iter)
237         in
238          source_view#source_buffer#redo ();
239          let mark_iter = source_view#buffer#get_iter_at_mark mark in
240          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
241          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
242           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
243           source_view#buffer#delete_mark mark;
244           source_view#buffer#delete_mark mark2;
245           (* phase 3: if after the undo the cursor was in the locked area,
246              then we move it there again and we perform a goto *)
247           if mark_iter#offset < locked_iter_offset then
248            begin
249             source_view#buffer#move_mark `INSERT ~where:mark_iter;
250             (MatitaScript.instance ())#goto `Cursor ();
251            end;
252           (* phase 4: we perform again the undo. This time we are sure that
253              the text to undo is not locked *)
254           source_view#source_buffer#undo ();
255           source_view#misc#grab_focus () in
256       let safe_redo =
257        fun () ->
258         (* phase 1: we save the actual status of the marks, we redo and
259            we undo *)
260         let locked_mark = `MARK ((MatitaScript.instance ())#locked_mark) in
261         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
262         let locked_iter_offset = locked_iter#offset in
263         let mark2 =
264          `MARK
265            (source_view#buffer#create_mark ~name:"lock_point"
266              ~left_gravity:true locked_iter) in
267         source_view#source_buffer#redo ();
268         source_view#source_buffer#undo ();
269         (* phase 2: we save the cursor position and we restore
270            the previous status of all the marks *)
271         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
272         let mark =
273          `MARK
274            (source_view#buffer#create_mark ~name:"undo_point"
275              ~left_gravity:true cursor_iter)
276         in
277          let mark_iter = source_view#buffer#get_iter_at_mark mark in
278          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
279          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
280           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
281           source_view#buffer#delete_mark mark;
282           source_view#buffer#delete_mark mark2;
283           (* phase 3: if after the undo the cursor is in the locked area,
284              then we move it there again and we perform a goto *)
285           if mark_iter#offset < locked_iter_offset then
286            begin
287             source_view#buffer#move_mark `INSERT ~where:mark_iter;
288             (MatitaScript.instance ())#goto `Cursor ();
289            end;
290           (* phase 4: we perform again the redo. This time we are sure that
291              the text to redo is not locked *)
292           source_view#source_buffer#redo ();
293           source_view#misc#grab_focus ()
294       in
295       connect_menu_item main#undoMenuItem safe_undo;
296       ignore(source_view#source_buffer#connect#can_undo
297         ~callback:main#undoMenuItem#misc#set_sensitive);
298       connect_menu_item main#redoMenuItem safe_redo;
299       ignore(source_view#source_buffer#connect#can_redo
300         ~callback:main#redoMenuItem#misc#set_sensitive);
301       ignore(source_view#connect#after#populate_popup
302        ~callback:(fun pre_menu ->
303          let menu = new GMenu.menu pre_menu in
304          let menuItems = menu#children in
305          let undoMenuItem, redoMenuItem =
306           match menuItems with
307              [undo;redo;sep1;cut;copy;paste;delete;sep2;
308               selectall;sep3;inputmethod;insertunicodecharacter] -> undo,redo
309            | _ -> assert false in
310          let new_undoMenuItem =
311           GMenu.image_menu_item
312            ~image:(GMisc.image ~stock:`UNDO ())
313            ~use_mnemonic:true
314            ~label:"_Undo"
315            ~packing:(menu#insert ~pos:0) () in
316          new_undoMenuItem#misc#set_sensitive
317           (undoMenuItem#misc#get_flag `SENSITIVE);
318          menu#remove (undoMenuItem :> GMenu.menu_item);
319          connect_menu_item new_undoMenuItem safe_undo;
320          let new_redoMenuItem =
321           GMenu.image_menu_item
322            ~image:(GMisc.image ~stock:`REDO ())
323            ~use_mnemonic:true
324            ~label:"_Redo"
325            ~packing:(menu#insert ~pos:1) () in
326          new_redoMenuItem#misc#set_sensitive
327           (redoMenuItem#misc#get_flag `SENSITIVE);
328           menu#remove (redoMenuItem :> GMenu.menu_item);
329           connect_menu_item new_redoMenuItem safe_redo));
330       let clipboard = GData.clipboard Gdk.Atom.clipboard in
331       let text_selected () =
332         (source_buffer#get_iter_at_mark `INSERT)#compare
333           (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
334       in
335       let markup_selected () = MatitaMathView.get_selections () <> None in
336       connect_menu_item main#editMenu (fun () ->
337         let text_selected = text_selected () in
338         let markup_selected = markup_selected () in
339         let something_selected = text_selected || markup_selected in
340         main#cutMenuItem#misc#set_sensitive text_selected;
341         main#copyMenuItem#misc#set_sensitive something_selected;
342         main#deleteMenuItem#misc#set_sensitive text_selected;
343         main#pasteMenuItem#misc#set_sensitive (clipboard#text <> None));
344       connect_menu_item main#cutMenuItem (fun () ->
345         source_view#buffer#cut_clipboard clipboard);
346       connect_menu_item main#copyMenuItem (fun () ->
347         if text_selected () then
348           source_view#buffer#copy_clipboard clipboard
349         else if markup_selected () then
350           match MatitaMathView.get_selections () with
351           | None
352           | Some [] -> ()
353           | Some (s :: _) -> clipboard#set_text s);
354       connect_menu_item main#pasteMenuItem (fun () ->
355         source_view#buffer#paste_clipboard clipboard;
356         (MatitaScript.instance ())#clean_dirty_lock);
357       connect_menu_item main#deleteMenuItem (fun () ->
358         ignore (source_view#buffer#delete_selection ()));
359       connect_menu_item main#selectAllMenuItem (fun () ->
360         source_buffer#move_mark `INSERT source_buffer#start_iter;
361         source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
362       connect_menu_item main#findReplMenuItem show_find_Repl;
363       ignore (findRepl#findEntry#connect#activate find_forward);
364         (* interface lockers *)
365       let lock_world _ =
366         main#buttonsToolbar#misc#set_sensitive false;
367         develList#buttonsHbox#misc#set_sensitive false;
368         source_view#set_editable false
369       in
370       let unlock_world _ =
371         main#buttonsToolbar#misc#set_sensitive true;
372         develList#buttonsHbox#misc#set_sensitive true;
373         source_view#set_editable true
374       in
375       let locker f = 
376         fun () -> 
377           lock_world ();
378           try f ();unlock_world () with exc -> unlock_world (); raise exc in
379       let keep_focus f =
380         fun () ->
381          try
382           f (); source_view#misc#grab_focus ()
383          with
384           exc -> source_view#misc#grab_focus (); raise exc in
385         (* developments win *)
386       let model = 
387         new MatitaGtkMisc.multiStringListModel 
388           ~cols:2 develList#developmentsTreeview
389       in
390       let refresh_devels_win () =
391         model#list_store#clear ();
392         List.iter 
393           (fun (name, root) -> model#easy_mappend [name;root]) 
394           (MatitamakeLib.list_known_developments ())
395       in
396       let get_devel_selected () = 
397         match model#easy_mselection () with
398         | [[name;_]] -> MatitamakeLib.development_for_name name
399         | _ -> assert false 
400       in
401       let refresh () = 
402         while Glib.Main.pending () do 
403           ignore(Glib.Main.iteration false); 
404         done
405       in
406       connect_button develList#newButton
407         (fun () -> 
408           next_devel_must_contain <- None;
409           newDevel#toplevel#misc#show());
410       connect_button develList#deleteButton
411         (locker (fun () -> 
412           (match get_devel_selected () with
413           | None -> ()
414           | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
415           refresh_devels_win ()));
416       connect_button develList#buildButton 
417         (locker (fun () -> 
418           match get_devel_selected () with
419           | None -> ()
420           | Some d -> 
421               let build = locker 
422                 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
423               in
424               ignore(build ())));
425       connect_button develList#cleanButton 
426         (locker (fun () -> 
427           match get_devel_selected () with
428           | None -> ()
429           | Some d -> 
430               let clean = locker 
431                 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
432               in
433               ignore(clean ())));
434       connect_button develList#closeButton 
435         (fun () -> develList#toplevel#misc#hide());
436       ignore(develList#toplevel#event#connect#delete 
437         (fun _ -> develList#toplevel#misc#hide();true));
438       let selected_devel = ref None in
439       connect_menu_item main#developmentsMenuItem
440         (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
441       
442         (* add development win *)
443       let check_if_root_contains root =
444         match next_devel_must_contain with
445         | None -> true
446         | Some path -> 
447             let is_prefix_of d1 d2 =
448               let len1 = String.length d1 in
449               let len2 = String.length d2 in
450               if len2 < len1 then 
451                 false
452               else
453                 let pref = String.sub d2 0 len1 in
454                 pref = d1
455             in
456             is_prefix_of root path
457       in
458       connect_button newDevel#addButton 
459        (fun () -> 
460           let name = newDevel#nameEntry#text in
461           let root = newDevel#rootEntry#text in
462           if check_if_root_contains root then
463             begin
464               ignore (MatitamakeLib.initialize_development name root);
465               refresh_devels_win ();
466               newDevel#nameEntry#set_text "";
467               newDevel#rootEntry#set_text "";
468               newDevel#toplevel#misc#hide()
469             end
470           else
471             MatitaLog.error ("The selected root does not contain " ^ 
472               match next_devel_must_contain with 
473               | Some x -> x 
474               | _ -> assert false));
475       connect_button newDevel#chooseRootButton 
476        (fun () ->
477          let path = self#chooseDir () in
478          match path with
479          | Some path -> newDevel#rootEntry#set_text path
480          | None -> ());
481       connect_button newDevel#cancelButton 
482        (fun () -> newDevel#toplevel#misc#hide ());
483       ignore(newDevel#toplevel#event#connect#delete 
484         (fun _ -> newDevel#toplevel#misc#hide();true));
485       
486         (* file selection win *)
487       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
488       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
489         let return r =
490           chosen_file <- r;
491           fileSel#fileSelectionWin#misc#hide ();
492           GMain.Main.quit ()
493         in
494         match event with
495         | `OK ->
496             let fname = fileSel#fileSelectionWin#filename in
497             if Sys.file_exists fname then
498               begin
499                 if is_regular fname && not(_only_directory) then 
500                   return (Some fname) 
501                 else if _only_directory && is_dir fname then 
502                   return (Some fname)
503               end
504             else
505               begin
506                 if _ok_not_exists then 
507                   return (Some fname)
508               end
509         | `CANCEL -> return None
510         | `HELP -> ()
511         | `DELETE_EVENT -> return None));
512         (* menus *)
513       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
514         (* console *)
515       let adj = main#logScrolledWin#vadjustment in
516         ignore (adj#connect#changed
517                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
518       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
519         (* toolbar *)
520       let module A = GrafiteAst in
521       let hole = CicNotationPt.UserInput in
522       let loc = DisambiguateTypes.dummy_floc in
523       let tac ast _ =
524         if (MatitaScript.instance ())#onGoingProof () then
525           (MatitaScript.instance ())#advance
526             ~statement:("\n" ^ GrafiteAstPp.pp_tactical (A.Tactic (loc, ast)))
527             ()
528       in
529       let tac_w_term ast _ =
530         if (MatitaScript.instance ())#onGoingProof () then
531           let buf = source_buffer in
532           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
533             ("\n" ^ GrafiteAstPp.pp_tactic ast)
534       in
535       let tbar = main in
536       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
537       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
538       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
539       connect_button tbar#elimButton (tac_w_term
540         (A.Elim (loc, hole, None, None, [])));
541       connect_button tbar#elimTypeButton (tac_w_term
542         (A.ElimType (loc, hole, None, None, [])));
543       connect_button tbar#splitButton (tac (A.Split loc));
544       connect_button tbar#leftButton (tac (A.Left loc));
545       connect_button tbar#rightButton (tac (A.Right loc));
546       connect_button tbar#existsButton (tac (A.Exists loc));
547       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
548       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
549       connect_button tbar#transitivityButton
550         (tac_w_term (A.Transitivity (loc, hole)));
551       connect_button tbar#assumptionButton (tac (A.Assumption loc));
552       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
553       connect_button tbar#autoButton (tac (A.Auto (loc,None,None,None)));
554       MatitaGtkMisc.toggle_widget_visibility
555        ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
556        ~check:main#tacticsBarMenuItem;
557       let module Hr = Helm_registry in
558       if
559         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
560       then 
561         main#tacticsBarMenuItem#set_active false;
562       MatitaGtkMisc.toggle_callback 
563         ~callback:(function 
564           | true -> main#toplevel#fullscreen () 
565           | false -> main#toplevel#unfullscreen ())
566         ~check:main#fullscreenMenuItem;
567       main#fullscreenMenuItem#set_active false;
568         (* log *)
569       MatitaLog.set_log_callback self#console#log_callback;
570       GtkSignal.user_handler :=
571         (fun exn -> MatitaLog.error (MatitaExcPp.to_string exn));
572         (* script *)
573       let _ =
574         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
575         | None ->
576             MatitaLog.warn (sprintf "can't load language file %s"
577               BuildTimeConf.lang_file)
578         | Some matita_lang ->
579             source_buffer#set_language matita_lang;
580             source_buffer#set_highlight true
581       in
582       let s () = MatitaScript.instance () in
583       let disableSave () =
584         script_fname <- None;
585         main#saveMenuItem#misc#set_sensitive false
586       in
587       let saveAsScript () =
588         let script = s () in
589         match self#chooseFile ~ok_not_exists:true () with
590         | Some f -> 
591               script#assignFileName f;
592               script#saveToFile (); 
593               console#message ("'"^f^"' saved.\n");
594               self#_enableSaveTo f
595         | None -> ()
596       in
597       let saveScript () =
598         match script_fname with
599         | None -> saveAsScript ()
600         | Some f -> 
601               (s ())#assignFileName f;
602               (s ())#saveToFile ();
603               console#message ("'"^f^"' saved.\n");
604       in
605       let loadScript () =
606         let script = s () in 
607         let status = script#status in
608         try 
609           if source_view#buffer#modified then
610             begin
611               match ask_unsaved main#toplevel with
612               | `YES -> saveScript ()
613               | `NO -> ()
614               | `CANCEL -> raise MatitaTypes.Cancel
615             end;
616           (match script_fname with
617           | None -> ()
618           | Some fname -> 
619               ask_and_save_moo_if_needed main#toplevel fname status);
620           match self#chooseFile () with
621           | Some f -> 
622                 script#reset (); 
623                 script#assignFileName f;
624                 source_view#source_buffer#begin_not_undoable_action ();
625                 script#loadFromFile f; 
626                 source_view#source_buffer#end_not_undoable_action ();
627                 console#message ("'"^f^"' loaded.\n");
628                 self#_enableSaveTo f
629           | None -> ()
630         with MatitaTypes.Cancel -> ()
631       in
632       let newScript () = 
633         source_view#source_buffer#begin_not_undoable_action ();
634         (s ())#reset (); 
635         (s ())#template (); 
636         source_view#source_buffer#end_not_undoable_action ();
637         disableSave ();
638         script_fname <- None
639       in
640       let cursor () =
641         source_buffer#place_cursor
642           (source_buffer#get_iter_at_mark (`NAME "locked")) in
643       let advance _ = (MatitaScript.instance ())#advance (); cursor () in
644       let retract _ = (MatitaScript.instance ())#retract (); cursor () in
645       let top _ = (MatitaScript.instance ())#goto `Top (); cursor () in
646       let bottom _ = (MatitaScript.instance ())#goto `Bottom (); cursor () in
647       let jump _ = (MatitaScript.instance ())#goto `Cursor (); cursor () in
648       let advance = locker (keep_focus advance) in
649       let retract = locker (keep_focus retract) in
650       let top = locker (keep_focus top) in
651       let bottom = locker (keep_focus bottom) in
652       let jump = locker (keep_focus jump) in
653       let connect_key sym f =
654         connect_key main#mainWinEventBox#event
655           ~modifiers:[`CONTROL] ~stop:true sym f;
656         connect_key self#sourceView#event
657           ~modifiers:[`CONTROL] ~stop:true sym f
658       in
659         (* quit *)
660       self#setQuitCallback (fun () -> 
661         let status = (MatitaScript.instance ())#status in
662         if source_view#buffer#modified then
663           begin
664             let rc = ask_unsaved main#toplevel in 
665             try
666               match rc with
667               | `YES -> saveScript ();
668                         if not source_view#buffer#modified then
669                           begin
670                             (match script_fname with
671                             | None -> ()
672                             | Some fname -> 
673                                ask_and_save_moo_if_needed 
674                                  main#toplevel fname status);
675                           GMain.Main.quit ()
676                           end
677               | `NO -> GMain.Main.quit ()
678               | `CANCEL -> raise MatitaTypes.Cancel
679             with MatitaTypes.Cancel -> ()
680           end 
681         else 
682           begin  
683             (match script_fname with
684             | None -> clean_current_baseuri status; GMain.Main.quit ()
685             | Some fname ->
686                 try
687                   ask_and_save_moo_if_needed main#toplevel fname status;
688                   GMain.Main.quit ()
689                 with MatitaTypes.Cancel -> ())
690           end);
691       connect_button main#scriptAdvanceButton advance;
692       connect_button main#scriptRetractButton retract;
693       connect_button main#scriptTopButton top;
694       connect_button main#scriptBottomButton bottom;
695       connect_key GdkKeysyms._Down advance;
696       connect_key GdkKeysyms._Up retract;
697       connect_key GdkKeysyms._Home top;
698       connect_key GdkKeysyms._End bottom;
699       connect_button main#scriptJumpButton jump;
700       connect_menu_item main#openMenuItem   loadScript;
701       connect_menu_item main#saveMenuItem   saveScript;
702       connect_menu_item main#saveAsMenuItem saveAsScript;
703       connect_menu_item main#newMenuItem    newScript;
704       connect_key GdkKeysyms._period
705         (fun () ->
706           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
707             ".\n";
708           advance ());
709       connect_key GdkKeysyms._Return
710         (fun () ->
711           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
712             "\n";
713           advance ());
714          (* script monospace font stuff *)  
715       self#updateFontSize ();
716         (* debug menu *)
717       main#debugMenu#misc#hide ();
718         (* status bar *)
719       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
720       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
721       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
722         (* focus *)
723       self#sourceView#misc#grab_focus ();
724         (* main win dimension *)
725       let width = Gdk.Screen.width () in
726       let height = Gdk.Screen.height () in
727       let main_w = width * 90 / 100 in 
728       let main_h = height * 80 / 100 in
729       let script_w = main_w * 6 / 10 in
730       main#toplevel#resize ~width:main_w ~height:main_h;
731       main#hpaneScriptSequent#set_position script_w;
732         (* source_view *)
733       ignore(source_view#connect#after#paste_clipboard 
734         ~callback:(fun () -> (MatitaScript.instance ())#clean_dirty_lock));
735       (* clean_locked is set to true only "during" a PRIMARY paste
736          operation (i.e. by clicking with the second mouse button) *)
737       let clean_locked = ref false in
738       ignore(source_view#event#connect#button_press
739         ~callback:
740           (fun button ->
741             if GdkEvent.Button.button button = 2 then
742              clean_locked := true;
743             false
744           ));
745       ignore(source_view#event#connect#button_release
746         ~callback:(fun button -> clean_locked := false; false));
747       ignore(source_view#buffer#connect#after#apply_tag
748        ~callback:(
749          fun tag ~start:_ ~stop:_ ->
750           if !clean_locked &&
751              tag#get_oid = (MatitaScript.instance ())#locked_tag#get_oid
752           then
753            begin
754             clean_locked := false;
755             (MatitaScript.instance ())#clean_dirty_lock;
756             clean_locked := true
757            end));
758       (* math view handling *)
759       connect_menu_item main#newCicBrowserMenuItem (fun () ->
760         ignore (MatitaMathView.cicBrowser ()));
761       connect_menu_item main#increaseFontSizeMenuItem (fun () ->
762         self#increaseFontSize ();
763         MatitaMathView.increase_font_size ();
764         MatitaMathView.update_font_sizes ());
765       connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
766         self#decreaseFontSize ();
767         MatitaMathView.decrease_font_size ();
768         MatitaMathView.update_font_sizes ());
769       connect_menu_item main#normalFontSizeMenuItem (fun () ->
770         self#resetFontSize ();
771         MatitaMathView.reset_font_size ();
772         MatitaMathView.update_font_sizes ());
773       MatitaMathView.reset_font_size ();
774     
775     method loadScript file =       
776       let script = MatitaScript.instance () in
777       script#reset (); 
778       script#assignFileName file;
779       let content =
780        if Sys.file_exists file then file
781        else BuildTimeConf.script_template
782       in
783        source_view#source_buffer#begin_not_undoable_action ();
784        script#loadFromFile content;
785        source_view#source_buffer#end_not_undoable_action ();
786        console#message ("'"^file^"' loaded.");
787        self#_enableSaveTo file
788       
789     method setStar name b =
790       let l = main#scriptLabel in
791       if b then
792         l#set_text (name ^  " *")
793       else
794         l#set_text (name)
795         
796     method private _enableSaveTo file =
797       script_fname <- Some file;
798       self#main#saveMenuItem#misc#set_sensitive true
799         
800     method console = console
801     method sourceView: GSourceView.source_view =
802       (source_view: GSourceView.source_view)
803     method fileSel = fileSel
804     method findRepl = findRepl
805     method main = main
806     method develList = develList
807     method newDevel = newDevel
808
809     method newBrowserWin () =
810       object (self)
811         inherit browserWin ()
812         val combo = GEdit.combo_box_entry ()
813         initializer
814           self#check_widgets ();
815           let combo_widget = combo#coerce in
816           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
817           combo#entry#misc#grab_focus ()
818         method browserUri = combo
819       end
820
821     method newUriDialog () =
822       let dialog = new uriChoiceDialog () in
823       dialog#check_widgets ();
824       dialog
825
826     method newInterpDialog () =
827       let dialog = new interpChoiceDialog () in
828       dialog#check_widgets ();
829       dialog
830
831     method newConfirmationDialog () =
832       let dialog = new confirmationDialog () in
833       dialog#check_widgets ();
834       dialog
835
836     method newEmptyDialog () =
837       let dialog = new emptyDialog () in
838       dialog#check_widgets ();
839       dialog
840
841     method private addKeyBinding key callback =
842       List.iter (fun evbox -> add_key_binding key callback evbox)
843         keyBindingBoxes
844
845     method setQuitCallback callback =
846       connect_menu_item main#quitMenuItem callback;
847       ignore (main#toplevel#event#connect#delete 
848         (fun _ -> callback ();true));
849       self#addKeyBinding GdkKeysyms._q callback
850
851     method chooseFile ?(ok_not_exists = false) () =
852       _ok_not_exists <- ok_not_exists;
853       _only_directory <- false;
854       fileSel#fileSelectionWin#show ();
855       GtkThread.main ();
856       chosen_file
857
858     method private chooseDir ?(ok_not_exists = false) () =
859       _ok_not_exists <- ok_not_exists;
860       _only_directory <- true;
861       fileSel#fileSelectionWin#show ();
862       GtkThread.main ();
863       (* we should check that this is a directory *)
864       chosen_file
865   
866     method createDevelopment ~containing =
867       next_devel_must_contain <- containing;
868       newDevel#toplevel#misc#show()
869
870     method askText ?(title = "") ?(msg = "") () =
871       let dialog = new textDialog () in
872       dialog#textDialog#set_title title;
873       dialog#textDialogLabel#set_label msg;
874       let text = ref None in
875       let return v =
876         text := v;
877         dialog#textDialog#destroy ();
878         GMain.Main.quit ()
879       in
880       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
881       connect_button dialog#textDialogCancelButton (fun _ -> return None);
882       connect_button dialog#textDialogOkButton (fun _ ->
883         let text = dialog#textDialogTextView#buffer#get_text () in
884         return (Some text));
885       dialog#textDialog#show ();
886       GtkThread.main ();
887       !text
888
889     method private updateFontSize () =
890       self#sourceView#misc#modify_font_by_name
891         (sprintf "%s %d" BuildTimeConf.script_font font_size)
892
893     method increaseFontSize () =
894       font_size <- font_size + 1;
895       self#updateFontSize ()
896
897     method decreaseFontSize () =
898       font_size <- font_size - 1;
899       self#updateFontSize ()
900
901     method resetFontSize () =
902       font_size <- default_font_size;
903       self#updateFontSize ()
904
905   end
906
907 let gui () = 
908   let g = new gui () in
909   gui_instance := Some g;
910   MatitaMathView.set_gui g;
911   g
912   
913 let instance = singleton gui
914
915 let non p x = not (p x)
916
917 (* this is a shit and should be changed :-{ *)
918 let interactive_uri_choice
919   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
920   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
921   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
922   ?copy_cb ()
923   ~id uris
924 =
925   let gui = instance () in
926   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
927   if (selection_mode <> `SINGLE) &&
928     (Helm_registry.get_bool "matita.auto_disambiguation")
929   then
930     Lazy.force nonvars_uris
931   else begin
932     let dialog = gui#newUriDialog () in
933     if hide_uri_entry then
934       dialog#uriEntryHBox#misc#hide ();
935     if hide_try then
936       begin
937       dialog#uriChoiceSelectedButton#misc#hide ();
938       dialog#uriChoiceConstantsButton#misc#hide ();
939       end;
940     dialog#okLabel#set_label ok_label;  
941     dialog#uriChoiceTreeView#selection#set_mode
942       (selection_mode :> Gtk.Tags.selection_mode);
943     let model = new stringListModel dialog#uriChoiceTreeView in
944     let choices = ref None in
945     let nonvars = ref false in
946     (match copy_cb with
947     | None -> ()
948     | Some cb ->
949         dialog#copyButton#misc#show ();
950         connect_button dialog#copyButton 
951         (fun _ ->
952           match model#easy_selection () with
953           | [u] -> (cb u)
954           | _ -> ()));
955     dialog#uriChoiceDialog#set_title title;
956     dialog#uriChoiceLabel#set_text msg;
957     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
958     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
959     let return v =
960       choices := v;
961       dialog#uriChoiceDialog#destroy ();
962       GMain.Main.quit ()
963     in
964     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
965     connect_button dialog#uriChoiceConstantsButton (fun _ ->
966       return (Some (Lazy.force nonvars_uris)));
967     if ok_action = `AUTO then
968       connect_button dialog#uriChoiceAutoButton (fun _ ->
969         Helm_registry.set_bool "matita.auto_disambiguation" true;
970         return (Some (Lazy.force nonvars_uris)))
971     else
972       connect_button dialog#uriChoiceAutoButton (fun _ ->
973         match model#easy_selection () with
974         | [] -> ()
975         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
976     connect_button dialog#uriChoiceSelectedButton (fun _ ->
977       match model#easy_selection () with
978       | [] -> ()
979       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
980     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
981     dialog#uriChoiceDialog#show ();
982     GtkThread.main ();
983     (match !choices with 
984     | None -> raise MatitaTypes.Cancel
985     | Some uris -> uris)
986   end
987
988 class interpModel =
989   let cols = new GTree.column_list in
990   let id_col = cols#add Gobject.Data.string in
991   let dsc_col = cols#add Gobject.Data.string in
992   let interp_no_col = cols#add Gobject.Data.int in
993   let tree_store = GTree.tree_store cols in
994   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
995   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
996   let id_view_col = GTree.view_column ~renderer:id_renderer () in
997   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
998   fun tree_view choices ->
999     object
1000       initializer
1001         tree_view#set_model (Some (tree_store :> GTree.model));
1002         ignore (tree_view#append_column id_view_col);
1003         ignore (tree_view#append_column dsc_view_col);
1004         let name_of_interp =
1005           (* try to find a reasonable name for an interpretation *)
1006           let idx = ref 0 in
1007           fun interp ->
1008             try
1009               List.assoc "0" interp
1010             with Not_found ->
1011               incr idx; string_of_int !idx
1012         in
1013         tree_store#clear ();
1014         let idx = ref ~-1 in
1015         List.iter
1016           (fun interp ->
1017             incr idx;
1018             let interp_row = tree_store#append () in
1019             tree_store#set ~row:interp_row ~column:id_col
1020               (name_of_interp interp);
1021             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1022             List.iter
1023               (fun (id, dsc) ->
1024                 let row = tree_store#append ~parent:interp_row () in
1025                 tree_store#set ~row ~column:id_col id;
1026                 tree_store#set ~row ~column:dsc_col dsc;
1027                 tree_store#set ~row ~column:interp_no_col !idx)
1028               interp)
1029           choices
1030
1031       method get_interp_no tree_path =
1032         let iter = tree_store#get_iter tree_path in
1033         tree_store#get ~row:iter ~column:interp_no_col
1034     end
1035
1036 let interactive_interp_choice () choices =
1037   let gui = instance () in
1038   assert (choices <> []);
1039   let dialog = gui#newInterpDialog () in
1040   let model = new interpModel dialog#interpChoiceTreeView choices in
1041   let interp_len = List.length (List.hd choices) in
1042   dialog#interpChoiceDialog#set_title "Interpretation choice";
1043   dialog#interpChoiceDialogLabel#set_label "Choose an interpretation:";
1044   let interp_no = ref None in
1045   let return _ =
1046     dialog#interpChoiceDialog#destroy ();
1047     GMain.Main.quit ()
1048   in
1049   let fail _ = interp_no := None; return () in
1050   ignore (dialog#interpChoiceDialog#event#connect#delete (fun _ -> true));
1051   connect_button dialog#interpChoiceOkButton (fun _ ->
1052     match !interp_no with None -> () | Some _ -> return ());
1053   connect_button dialog#interpChoiceCancelButton fail;
1054   ignore (dialog#interpChoiceTreeView#connect#row_activated (fun path _ ->
1055     interp_no := Some (model#get_interp_no path);
1056     return ()));
1057   let selection = dialog#interpChoiceTreeView#selection in
1058   ignore (selection#connect#changed (fun _ ->
1059     match selection#get_selected_rows with
1060     | [path] ->
1061         MatitaLog.debug (sprintf "selection: %d" (model#get_interp_no path));
1062         interp_no := Some (model#get_interp_no path)
1063     | _ -> assert false));
1064   dialog#interpChoiceDialog#show ();
1065   GtkThread.main ();
1066   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
1067
1068 let _ =
1069   (* disambiguator callbacks *)
1070   MatitaDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1071   MatitaDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1072   (* gtk initialization *)
1073   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1074   GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1075   ignore (GMain.Main.init ())
1076