]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaGui.ml
Highlighting of parse errors implemented.
[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           mooname 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 newDevelopmentWin () 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:GdkPixbuf.pixbuf*)
175         (*?logo_icon_name:string*)
176         ~name:"Matita"
177         ~version:BuildTimeConf.version
178         ~website:"http://helm.cs.unibo.it"
179         ()
180       in
181       ignore (main#aboutMenuItem#connect#activate
182        (fun _ -> 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       ignore(self#main#undoMenuItem#connect#activate ~callback:safe_undo);
296       ignore(source_view#source_buffer#connect#can_undo
297         ~callback:self#main#undoMenuItem#misc#set_sensitive);
298       ignore(self#main#redoMenuItem#connect#activate ~callback:safe_redo);
299       ignore(source_view#source_buffer#connect#can_redo
300         ~callback:self#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          ignore(new_undoMenuItem#connect#activate ~callback: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           ignore(new_redoMenuItem#connect#activate ~callback:safe_redo);
330          ));
331       let clipboard =
332        let atom = Gdk.Atom.clipboard in
333         GData.clipboard atom in
334       ignore(self#main#editMenu#connect#activate
335         ~callback:
336           (fun () ->
337             let something_selected =
338               (source_buffer#get_iter_at_mark `INSERT)#compare
339               (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
340             in
341              self#main#cutMenuItem#misc#set_sensitive something_selected;
342              self#main#copyMenuItem#misc#set_sensitive something_selected;
343              self#main#deleteMenuItem#misc#set_sensitive something_selected;
344              self#main#pasteMenuItem#misc#set_sensitive (clipboard#text <> None)
345           ));
346       ignore(self#main#cutMenuItem#connect#activate
347         ~callback:(fun () -> source_view#buffer#cut_clipboard clipboard));
348       ignore(self#main#copyMenuItem#connect#activate
349         ~callback:(fun () -> source_view#buffer#copy_clipboard clipboard));
350       ignore(self#main#pasteMenuItem#connect#activate
351         ~callback:(fun () ->
352           source_view#buffer#paste_clipboard clipboard;
353           (MatitaScript.instance ())#clean_dirty_lock));
354       ignore(self#main#deleteMenuItem#connect#activate
355         ~callback:(fun () -> ignore (source_view#buffer#delete_selection ())));
356       ignore(self#main#selectAllMenuItem#connect#activate
357         ~callback:(fun () ->
358           source_buffer#move_mark `INSERT source_buffer#start_iter;
359           source_buffer#move_mark `SEL_BOUND source_buffer#end_iter));
360       ignore(self#main#findReplMenuItem#connect#activate
361         ~callback:show_find_Repl);
362       ignore (findRepl#findEntry#connect#activate ~callback:find_forward);
363         (* interface lockers *)
364       let lock_world _ =
365         main#buttonsToolbar#misc#set_sensitive false;
366         develList#buttonsHbox#misc#set_sensitive false;
367         source_view#set_editable false
368       in
369       let unlock_world _ =
370         main#buttonsToolbar#misc#set_sensitive true;
371         develList#buttonsHbox#misc#set_sensitive true;
372         source_view#set_editable true
373       in
374       let locker f = 
375         fun () -> 
376           lock_world ();
377           try f ();unlock_world () with exc -> unlock_world (); raise exc in
378       let keep_focus f =
379         fun () ->
380          try
381           f (); source_view#misc#grab_focus ()
382          with
383           exc -> source_view#misc#grab_focus (); raise exc in
384         (* developments win *)
385       let model = 
386         new MatitaGtkMisc.multiStringListModel 
387           ~cols:2 develList#developmentsTreeview
388       in
389       let refresh_devels_win () =
390         model#list_store#clear ();
391         List.iter 
392           (fun (name, root) -> model#easy_mappend [name;root]) 
393           (MatitamakeLib.list_known_developments ())
394       in
395       let get_devel_selected () = 
396         match model#easy_mselection () with
397         | [[name;_]] -> MatitamakeLib.development_for_name name
398         | _ -> assert false 
399       in
400       let refresh () = 
401         while Glib.Main.pending () do 
402           ignore(Glib.Main.iteration false); 
403         done
404       in
405       connect_button develList#newButton
406         (fun () -> 
407           next_devel_must_contain <- None;
408           newDevel#toplevel#misc#show());
409       connect_button develList#deleteButton
410         (locker (fun () -> 
411           (match get_devel_selected () with
412           | None -> ()
413           | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
414           refresh_devels_win ()));
415       connect_button develList#buildButton 
416         (locker (fun () -> 
417           match get_devel_selected () with
418           | None -> ()
419           | Some d -> 
420               let build = locker 
421                 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
422               in
423               ignore(build ())));
424       connect_button develList#cleanButton 
425         (locker (fun () -> 
426           match get_devel_selected () with
427           | None -> ()
428           | Some d -> 
429               let clean = locker 
430                 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
431               in
432               ignore(clean ())));
433       connect_button develList#closeButton 
434         (fun () -> develList#toplevel#misc#hide());
435       ignore(develList#toplevel#event#connect#delete 
436         (fun _ -> develList#toplevel#misc#hide();true));
437       let selected_devel = ref None in
438       connect_menu_item self#main#developmentsMenuItem
439         (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
440       
441         (* add development win *)
442       let check_if_root_contains root =
443         match next_devel_must_contain with
444         | None -> true
445         | Some path -> 
446             let is_prefix_of d1 d2 =
447               let len1 = String.length d1 in
448               let len2 = String.length d2 in
449               if len2 < len1 then 
450                 false
451               else
452                 let pref = String.sub d2 0 len1 in
453                 pref = d1
454             in
455             is_prefix_of root path
456       in
457       connect_button newDevel#addButton 
458        (fun () -> 
459           let name = newDevel#nameEntry#text in
460           let root = newDevel#rootEntry#text in
461           if check_if_root_contains root then
462             begin
463               ignore (MatitamakeLib.initialize_development name root);
464               refresh_devels_win ();
465               newDevel#nameEntry#set_text "";
466               newDevel#rootEntry#set_text "";
467               newDevel#toplevel#misc#hide()
468             end
469           else
470             MatitaLog.error ("The selected root does not contain " ^ 
471               match next_devel_must_contain with 
472               | Some x -> x 
473               | _ -> assert false));
474       connect_button newDevel#chooseRootButton 
475        (fun () ->
476          let path = self#chooseDir () in
477          match path with
478          | Some path -> newDevel#rootEntry#set_text path
479          | None -> ());
480       connect_button newDevel#cancelButton 
481        (fun () -> newDevel#toplevel#misc#hide ());
482       ignore(newDevel#toplevel#event#connect#delete 
483         (fun _ -> newDevel#toplevel#misc#hide();true));
484       
485         (* file selection win *)
486       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
487       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
488         let return r =
489           chosen_file <- r;
490           fileSel#fileSelectionWin#misc#hide ();
491           GMain.Main.quit ()
492         in
493         match event with
494         | `OK ->
495             let fname = fileSel#fileSelectionWin#filename in
496             if Sys.file_exists fname then
497               begin
498                 if is_regular fname && not(_only_directory) then 
499                   return (Some fname) 
500                 else if _only_directory && is_dir fname then 
501                   return (Some fname)
502               end
503             else
504               begin
505                 if _ok_not_exists then 
506                   return (Some fname)
507               end
508         | `CANCEL -> return None
509         | `HELP -> ()
510         | `DELETE_EVENT -> return None));
511         (* menus *)
512       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
513         (* console *)
514       let adj = main#logScrolledWin#vadjustment in
515         ignore (adj#connect#changed
516                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
517       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
518         (* toolbar *)
519       let module A = GrafiteAst in
520       let hole = CicNotationPt.UserInput in
521       let loc = Disambiguate.dummy_floc in
522       let tac ast _ =
523         if (MatitaScript.instance ())#onGoingProof () then
524           (MatitaScript.instance ())#advance
525             ~statement:("\n" ^ GrafiteAstPp.pp_tactical (A.Tactic (loc, ast)))
526             ()
527       in
528       let tac_w_term ast _ =
529         if (MatitaScript.instance ())#onGoingProof () then
530           let buf = source_buffer in
531           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
532             ("\n" ^ GrafiteAstPp.pp_tactic ast)
533       in
534       let tbar = self#main in
535       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
536       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
537       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
538       connect_button tbar#elimButton (tac_w_term (A.Elim (loc, hole, None, None, [])));
539       connect_button tbar#elimTypeButton (tac_w_term (A.ElimType (loc, hole, None, None, [])));
540       connect_button tbar#splitButton (tac (A.Split loc));
541       connect_button tbar#leftButton (tac (A.Left loc));
542       connect_button tbar#rightButton (tac (A.Right loc));
543       connect_button tbar#existsButton (tac (A.Exists loc));
544       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
545       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
546       connect_button tbar#transitivityButton
547         (tac_w_term (A.Transitivity (loc, hole)));
548       connect_button tbar#assumptionButton (tac (A.Assumption loc));
549       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
550       connect_button tbar#autoButton (tac (A.Auto (loc,None,None,None))); (* ALB *)
551       MatitaGtkMisc.toggle_widget_visibility
552        ~widget:(self#main#tacticsButtonsHandlebox :> GObj.widget)
553        ~check:self#main#tacticsBarMenuItem;
554       let module Hr = Helm_registry in
555       if
556         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
557       then 
558         self#main#tacticsBarMenuItem#set_active false;
559       MatitaGtkMisc.toggle_callback 
560         ~callback:(function 
561           | true -> self#main#toplevel#fullscreen () 
562           | false -> self#main#toplevel#unfullscreen ())
563         ~check:self#main#fullscreenMenuItem;
564       self#main#fullscreenMenuItem#set_active false;
565         (* log *)
566       MatitaLog.set_log_callback self#console#log_callback;
567       GtkSignal.user_handler :=
568         (fun exn -> MatitaLog.error (MatitaExcPp.to_string exn));
569         (* script *)
570       let _ =
571         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
572         | None ->
573             MatitaLog.warn (sprintf "can't load language file %s"
574               BuildTimeConf.lang_file)
575         | Some matita_lang ->
576             source_buffer#set_language matita_lang;
577             source_buffer#set_highlight true
578       in
579       let s () = MatitaScript.instance () in
580       let disableSave () =
581         script_fname <- None;
582         self#main#saveMenuItem#misc#set_sensitive false
583       in
584       let saveAsScript () =
585         let script = s () in
586         match self#chooseFile ~ok_not_exists:true () with
587         | Some f -> 
588               script#assignFileName f;
589               script#saveToFile (); 
590               console#message ("'"^f^"' saved.\n");
591               self#_enableSaveTo f
592         | None -> ()
593       in
594       let saveScript () =
595         match script_fname with
596         | None -> saveAsScript ()
597         | Some f -> 
598               (s ())#assignFileName f;
599               (s ())#saveToFile ();
600               console#message ("'"^f^"' saved.\n");
601       in
602       let loadScript () =
603         let script = s () in 
604         let status = script#status in
605         try 
606           if source_view#buffer#modified then
607             begin
608               match ask_unsaved main#toplevel with
609               | `YES -> saveScript ()
610               | `NO -> ()
611               | `CANCEL -> raise MatitaTypes.Cancel
612             end;
613           (match script_fname with
614           | None -> ()
615           | Some fname -> 
616               ask_and_save_moo_if_needed main#toplevel fname status);
617           match self#chooseFile () with
618           | Some f -> 
619                 script#reset (); 
620                 script#assignFileName f;
621                 source_view#source_buffer#begin_not_undoable_action ();
622                 script#loadFromFile f; 
623                 source_view#source_buffer#end_not_undoable_action ();
624                 console#message ("'"^f^"' loaded.\n");
625                 self#_enableSaveTo f
626           | None -> ()
627         with MatitaTypes.Cancel -> ()
628       in
629       let newScript () = 
630         source_view#source_buffer#begin_not_undoable_action ();
631         (s ())#reset (); 
632         (s ())#template (); 
633         source_view#source_buffer#end_not_undoable_action ();
634         disableSave ();
635         script_fname <- None
636       in
637       let cursor () =
638         source_buffer#place_cursor
639           (source_buffer#get_iter_at_mark (`NAME "locked")) in
640       let advance _ = (MatitaScript.instance ())#advance (); cursor () in
641       let retract _ = (MatitaScript.instance ())#retract (); cursor () in
642       let top _ = (MatitaScript.instance ())#goto `Top (); cursor () in
643       let bottom _ = (MatitaScript.instance ())#goto `Bottom (); cursor () in
644       let jump _ = (MatitaScript.instance ())#goto `Cursor (); cursor () in
645       let advance = locker (keep_focus advance) in
646       let retract = locker (keep_focus retract) in
647       let top = locker (keep_focus top) in
648       let bottom = locker (keep_focus bottom) in
649       let jump = locker (keep_focus jump) in
650       let connect_key sym f =
651         connect_key self#main#mainWinEventBox#event
652           ~modifiers:[`CONTROL] ~stop:true sym f;
653         connect_key self#sourceView#event
654           ~modifiers:[`CONTROL] ~stop:true sym f
655       in
656         (* quit *)
657       self#setQuitCallback (fun () -> 
658         let status = (MatitaScript.instance ())#status in
659         if source_view#buffer#modified then
660           begin
661             let rc = ask_unsaved main#toplevel in 
662             try
663               match rc with
664               | `YES -> saveScript ();
665                         if not source_view#buffer#modified then
666                           begin
667                             (match script_fname with
668                             | None -> ()
669                             | Some fname -> 
670                                ask_and_save_moo_if_needed 
671                                  main#toplevel fname status);
672                           GMain.Main.quit ()
673                           end
674               | `NO -> GMain.Main.quit ()
675               | `CANCEL -> raise MatitaTypes.Cancel
676             with MatitaTypes.Cancel -> ()
677           end 
678         else 
679           begin  
680             (match script_fname with
681             | None -> clean_current_baseuri status; GMain.Main.quit ()
682             | Some fname ->
683                 try
684                   ask_and_save_moo_if_needed main#toplevel fname status;
685                   GMain.Main.quit ()
686                 with MatitaTypes.Cancel -> ())
687           end);
688       connect_button self#main#scriptAdvanceButton advance;
689       connect_button self#main#scriptRetractButton retract;
690       connect_button self#main#scriptTopButton top;
691       connect_button self#main#scriptBottomButton bottom;
692       connect_key GdkKeysyms._Down advance;
693       connect_key GdkKeysyms._Up retract;
694       connect_key GdkKeysyms._Home top;
695       connect_key GdkKeysyms._End bottom;
696       connect_button self#main#scriptJumpButton jump;
697       connect_menu_item self#main#openMenuItem   loadScript;
698       connect_menu_item self#main#saveMenuItem   saveScript;
699       connect_menu_item self#main#saveAsMenuItem saveAsScript;
700       connect_menu_item self#main#newMenuItem    newScript;
701       connect_key GdkKeysyms._period
702         (fun () ->
703           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
704             ".\n";
705           advance ());
706       connect_key GdkKeysyms._Return
707         (fun () ->
708           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
709             "\n";
710           advance ());
711          (* script monospace font stuff *)  
712       self#updateFontSize ();
713         (* debug menu *)
714       self#main#debugMenu#misc#hide ();
715         (* status bar *)
716       self#main#hintLowImage#set_file (image_path "matita-bulb-low.png");
717       self#main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
718       self#main#hintHighImage#set_file (image_path "matita-bulb-high.png");
719         (* focus *)
720       self#sourceView#misc#grab_focus ();
721         (* main win dimension *)
722       let width = Gdk.Screen.width () in
723       let height = Gdk.Screen.height () in
724       let main_w = width * 90 / 100 in 
725       let main_h = height * 80 / 100 in
726       let script_w = main_w * 6 / 10 in
727       self#main#toplevel#resize ~width:main_w ~height:main_h;
728       self#main#hpaneScriptSequent#set_position script_w;
729         (* source_view *)
730       ignore(source_view#connect#after#paste_clipboard 
731         ~callback:(fun () -> (MatitaScript.instance ())#clean_dirty_lock))
732     
733     method loadScript file =       
734       let script = MatitaScript.instance () in
735       script#reset (); 
736       script#assignFileName file;
737       let content =
738        if Sys.file_exists file then file
739        else BuildTimeConf.script_template
740       in
741        source_view#source_buffer#begin_not_undoable_action ();
742        script#loadFromFile content;
743        source_view#source_buffer#end_not_undoable_action ();
744        console#message ("'"^file^"' loaded.");
745        self#_enableSaveTo file
746       
747     method setStar name b =
748       let l = main#scriptLabel in
749       if b then
750         l#set_text (name ^  " *")
751       else
752         l#set_text (name)
753         
754     method private _enableSaveTo file =
755       script_fname <- Some file;
756       self#main#saveMenuItem#misc#set_sensitive true
757         
758
759     method console = console
760     method sourceView: GSourceView.source_view = (source_view: GSourceView.source_view)
761     method fileSel = fileSel
762     method findRepl = findRepl
763     method main = main
764     method develList = develList
765     method newDevel = newDevel
766
767     method newBrowserWin () =
768       object (self)
769         inherit browserWin ()
770         val combo = GEdit.combo_box_entry ()
771         initializer
772           self#check_widgets ();
773           let combo_widget = combo#coerce in
774           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
775           combo#entry#misc#grab_focus ()
776         method browserUri = combo
777       end
778
779     method newUriDialog () =
780       let dialog = new uriChoiceDialog () in
781       dialog#check_widgets ();
782       dialog
783
784     method newInterpDialog () =
785       let dialog = new interpChoiceDialog () in
786       dialog#check_widgets ();
787       dialog
788
789     method newConfirmationDialog () =
790       let dialog = new confirmationDialog () in
791       dialog#check_widgets ();
792       dialog
793
794     method newEmptyDialog () =
795       let dialog = new emptyDialog () in
796       dialog#check_widgets ();
797       dialog
798
799     method private addKeyBinding key callback =
800       List.iter (fun evbox -> add_key_binding key callback evbox)
801         keyBindingBoxes
802
803     method setQuitCallback callback =
804       ignore (main#quitMenuItem#connect#activate callback);
805       ignore (main#toplevel#event#connect#delete 
806         (fun _ -> callback ();true));
807       self#addKeyBinding GdkKeysyms._q callback
808
809     method chooseFile ?(ok_not_exists = false) () =
810       _ok_not_exists <- ok_not_exists;
811       _only_directory <- false;
812       fileSel#fileSelectionWin#show ();
813       GtkThread.main ();
814       chosen_file
815
816     method private chooseDir ?(ok_not_exists = false) () =
817       _ok_not_exists <- ok_not_exists;
818       _only_directory <- true;
819       fileSel#fileSelectionWin#show ();
820       GtkThread.main ();
821       (* we should check that this is a directory *)
822       chosen_file
823   
824     method createDevelopment ~containing =
825       next_devel_must_contain <- containing;
826       newDevel#toplevel#misc#show()
827
828     method askText ?(title = "") ?(msg = "") () =
829       let dialog = new textDialog () in
830       dialog#textDialog#set_title title;
831       dialog#textDialogLabel#set_label msg;
832       let text = ref None in
833       let return v =
834         text := v;
835         dialog#textDialog#destroy ();
836         GMain.Main.quit ()
837       in
838       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
839       connect_button dialog#textDialogCancelButton (fun _ -> return None);
840       connect_button dialog#textDialogOkButton (fun _ ->
841         let text = dialog#textDialogTextView#buffer#get_text () in
842         return (Some text));
843       dialog#textDialog#show ();
844       GtkThread.main ();
845       !text
846
847     method private updateFontSize () =
848       self#sourceView#misc#modify_font_by_name
849         (sprintf "%s %d" BuildTimeConf.script_font font_size)
850
851     method increaseFontSize () =
852       font_size <- font_size + 1;
853       self#updateFontSize ()
854
855     method decreaseFontSize () =
856       font_size <- font_size - 1;
857       self#updateFontSize ()
858
859     method resetFontSize () =
860       font_size <- default_font_size;
861       self#updateFontSize ()
862
863   end
864
865 let gui () = 
866   let g = new gui () in
867   gui_instance := Some g;
868   g
869   
870 let instance = singleton gui
871
872 let non p x = not (p x)
873
874 (* this is a shit and should be changed :-{ *)
875 let interactive_uri_choice
876   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
877   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
878   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
879   ?copy_cb ()
880   ~id uris
881 =
882   let gui = instance () in
883   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
884   if (selection_mode <> `SINGLE) &&
885     (Helm_registry.get_bool "matita.auto_disambiguation")
886   then
887     Lazy.force nonvars_uris
888   else begin
889     let dialog = gui#newUriDialog () in
890     if hide_uri_entry then
891       dialog#uriEntryHBox#misc#hide ();
892     if hide_try then
893       begin
894       dialog#uriChoiceSelectedButton#misc#hide ();
895       dialog#uriChoiceConstantsButton#misc#hide ();
896       end;
897     dialog#okLabel#set_label ok_label;  
898     dialog#uriChoiceTreeView#selection#set_mode
899       (selection_mode :> Gtk.Tags.selection_mode);
900     let model = new stringListModel dialog#uriChoiceTreeView in
901     let choices = ref None in
902     let nonvars = ref false in
903     (match copy_cb with
904     | None -> ()
905     | Some cb ->
906         dialog#copyButton#misc#show ();
907         connect_button dialog#copyButton 
908         (fun _ ->
909           match model#easy_selection () with
910           | [u] -> (cb u)
911           | _ -> ()));
912     dialog#uriChoiceDialog#set_title title;
913     dialog#uriChoiceLabel#set_text msg;
914     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
915     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
916     let return v =
917       choices := v;
918       dialog#uriChoiceDialog#destroy ();
919       GMain.Main.quit ()
920     in
921     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
922     connect_button dialog#uriChoiceConstantsButton (fun _ ->
923       return (Some (Lazy.force nonvars_uris)));
924     if ok_action = `AUTO then
925       connect_button dialog#uriChoiceAutoButton (fun _ ->
926         Helm_registry.set_bool "matita.auto_disambiguation" true;
927         return (Some (Lazy.force nonvars_uris)))
928     else
929       connect_button dialog#uriChoiceAutoButton (fun _ ->
930         match model#easy_selection () with
931         | [] -> ()
932         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
933     connect_button dialog#uriChoiceSelectedButton (fun _ ->
934       match model#easy_selection () with
935       | [] -> ()
936       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
937     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
938     dialog#uriChoiceDialog#show ();
939     GtkThread.main ();
940     (match !choices with 
941     | None -> raise MatitaTypes.Cancel
942     | Some uris -> uris)
943   end
944
945 class interpModel =
946   let cols = new GTree.column_list in
947   let id_col = cols#add Gobject.Data.string in
948   let dsc_col = cols#add Gobject.Data.string in
949   let interp_no_col = cols#add Gobject.Data.int in
950   let tree_store = GTree.tree_store cols in
951   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
952   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
953   let id_view_col = GTree.view_column ~renderer:id_renderer () in
954   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
955   fun tree_view choices ->
956     object
957       initializer
958         tree_view#set_model (Some (tree_store :> GTree.model));
959         ignore (tree_view#append_column id_view_col);
960         ignore (tree_view#append_column dsc_view_col);
961         let name_of_interp =
962           (* try to find a reasonable name for an interpretation *)
963           let idx = ref 0 in
964           fun interp ->
965             try
966               List.assoc "0" interp
967             with Not_found ->
968               incr idx; string_of_int !idx
969         in
970         tree_store#clear ();
971         let idx = ref ~-1 in
972         List.iter
973           (fun interp ->
974             incr idx;
975             let interp_row = tree_store#append () in
976             tree_store#set ~row:interp_row ~column:id_col
977               (name_of_interp interp);
978             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
979             List.iter
980               (fun (id, dsc) ->
981                 let row = tree_store#append ~parent:interp_row () in
982                 tree_store#set ~row ~column:id_col id;
983                 tree_store#set ~row ~column:dsc_col dsc;
984                 tree_store#set ~row ~column:interp_no_col !idx)
985               interp)
986           choices
987
988       method get_interp_no tree_path =
989         let iter = tree_store#get_iter tree_path in
990         tree_store#get ~row:iter ~column:interp_no_col
991     end
992
993 let interactive_interp_choice () choices =
994   let gui = instance () in
995   assert (choices <> []);
996   let dialog = gui#newInterpDialog () in
997   let model = new interpModel dialog#interpChoiceTreeView choices in
998   let interp_len = List.length (List.hd choices) in
999   dialog#interpChoiceDialog#set_title "Interpretation choice";
1000   dialog#interpChoiceDialogLabel#set_label "Choose an interpretation:";
1001   let interp_no = ref None in
1002   let return _ =
1003     dialog#interpChoiceDialog#destroy ();
1004     GMain.Main.quit ()
1005   in
1006   let fail _ = interp_no := None; return () in
1007   ignore (dialog#interpChoiceDialog#event#connect#delete (fun _ -> true));
1008   connect_button dialog#interpChoiceOkButton (fun _ ->
1009     match !interp_no with None -> () | Some _ -> return ());
1010   connect_button dialog#interpChoiceCancelButton fail;
1011   ignore (dialog#interpChoiceTreeView#connect#row_activated (fun path _ ->
1012     interp_no := Some (model#get_interp_no path);
1013     return ()));
1014   let selection = dialog#interpChoiceTreeView#selection in
1015   ignore (selection#connect#changed (fun _ ->
1016     match selection#get_selected_rows with
1017     | [path] ->
1018         MatitaLog.debug (sprintf "selection: %d" (model#get_interp_no path));
1019         interp_no := Some (model#get_interp_no path)
1020     | _ -> assert false));
1021   dialog#interpChoiceDialog#show ();
1022   GtkThread.main ();
1023   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
1024