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