]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaGui.ml
name specifications added for elim_intros, elim_intros_simpl and elim_type
[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 "yellow" ]
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 class gui () =
63     (* creation order _is_ relevant for windows placement *)
64   let main = new mainWin () in
65   let about = new aboutWin () in
66   let fileSel = new fileSelectionWin () in
67   let keyBindingBoxes = (* event boxes which should receive global key events *)
68     [ main#mainWinEventBox ]
69   in
70   let console = new console ~buffer:main#logTextView#buffer () in
71   let (source_view: GSourceView.source_view) =
72     GSourceView.source_view
73       ~auto_indent:true
74       ~insert_spaces_instead_of_tabs:true ~tabs_width:2
75       ~margin:80 ~show_margin:true
76       ~smart_home_end:true
77       ~packing:main#scriptScrolledWin#add
78       ()
79   in
80   let default_font_size =
81     Helm_registry.get_opt_default Helm_registry.int
82       ~default:BuildTimeConf.default_font_size "matita.font_size"
83   in
84   let source_buffer = source_view#source_buffer in
85   object (self)
86     val mutable chosen_file = None
87     val mutable _ok_not_exists = false
88     val mutable script_fname = None
89     val mutable font_size = default_font_size
90    
91     initializer
92         (* glade's check widgets *)
93       List.iter (fun w -> w#check_widgets ())
94         (let c w = (w :> <check_widgets: unit -> unit>) in
95          [ c about; c fileSel; c main ]);
96         (* key bindings *)
97       List.iter (* global key bindings *)
98         (fun (key, callback) -> self#addKeyBinding key callback)
99 (*
100         [ GdkKeysyms._F3,
101             toggle_win ~check:main#showProofMenuItem proof#proofWin;
102           GdkKeysyms._F4,
103             toggle_win ~check:main#showCheckMenuItem check#checkWin;
104 *)
105         [ ];
106         (* about win *)
107       ignore (about#aboutWin#event#connect#delete (fun _ -> true));
108       ignore (main#aboutMenuItem#connect#activate (fun _ ->
109         about#aboutWin#show ()));
110       connect_button about#aboutDismissButton (fun _ ->
111         about#aboutWin#misc#hide ());
112       about#aboutLabel#set_label (Pcre.replace ~pat:"@VERSION@"
113         ~templ:BuildTimeConf.version about#aboutLabel#label);
114         (* file selection win *)
115       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
116       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
117         let return r =
118           chosen_file <- r;
119           fileSel#fileSelectionWin#misc#hide ();
120           GMain.Main.quit ()
121         in
122         match event with
123         | `OK ->
124             let fname = fileSel#fileSelectionWin#filename in
125             if Sys.file_exists fname then
126               (if is_regular fname then return (Some fname))
127             else
128               (if _ok_not_exists then return (Some fname))
129         | `CANCEL -> return None
130         | `HELP -> ()
131         | `DELETE_EVENT -> return None));
132         (* menus *)
133       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
134       main#helpMenu#set_right_justified true;
135         (* console *)
136       let adj = main#logScrolledWin#vadjustment in
137       ignore (adj#connect#changed
138                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
139       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
140         (* toolbar *)
141       let module A = TacticAst in
142       let hole = CicAst.UserInput in
143       let loc = CicAst.dummy_floc in
144       let tac ast _ =
145         if (MatitaScript.instance ())#onGoingProof () then
146           (MatitaScript.instance ())#advance
147             ~statement:("\n" ^ TacticAstPp.pp_tactical (A.Tactic (loc, ast))) ()
148       in
149       let tac_w_term ast _ =
150         if (MatitaScript.instance ())#onGoingProof () then
151           let buf = source_buffer in
152           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
153             ("\n" ^ TacticAstPp.pp_tactic ast)
154       in
155       let tbar = self#main in
156       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
157       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
158       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
159       connect_button tbar#elimButton (tac_w_term (A.Elim (loc, hole, None, None, [])));
160       connect_button tbar#elimTypeButton (tac_w_term (A.ElimType (loc, hole, None, None, [])));
161       connect_button tbar#splitButton (tac (A.Split loc));
162       connect_button tbar#leftButton (tac (A.Left loc));
163       connect_button tbar#rightButton (tac (A.Right loc));
164       connect_button tbar#existsButton (tac (A.Exists loc));
165       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
166       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
167       connect_button tbar#transitivityButton
168         (tac_w_term (A.Transitivity (loc, hole)));
169       connect_button tbar#assumptionButton (tac (A.Assumption loc));
170       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
171       connect_button tbar#autoButton (tac (A.Auto (loc,None,None)));
172       MatitaGtkMisc.toggle_widget_visibility
173        ~widget:(self#main#tacticsButtonsHandlebox :> GObj.widget)
174        ~check:self#main#tacticsBarMenuItem;
175       let module Hr = Helm_registry in
176       if
177         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
178       then 
179         self#main#tacticsBarMenuItem#set_active false;
180       MatitaGtkMisc.toggle_callback 
181         ~callback:(function 
182           | true -> self#main#toplevel#fullscreen () 
183           | false -> self#main#toplevel#unfullscreen ())
184         ~check:self#main#fullscreenMenuItem;
185       self#main#fullscreenMenuItem#set_active false;
186         (* log *)
187       MatitaLog.set_log_callback self#console#log_callback;
188       GtkSignal.user_handler :=
189         (fun exn -> MatitaLog.error (MatitaExcPp.to_string exn));
190         (* script *)
191       let _ =
192         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
193         | None ->
194             MatitaLog.warn (sprintf "can't load language file %s"
195               BuildTimeConf.lang_file)
196         | Some matita_lang ->
197             source_buffer#set_language matita_lang;
198             source_buffer#set_highlight true
199       in
200       let s () = MatitaScript.instance () in
201       let disableSave () =
202         script_fname <- None;
203         self#main#saveMenuItem#misc#set_sensitive false
204       in
205       let loadScript () =
206         let script = s () in
207         match self#chooseFile () with
208         | Some f -> 
209               script#reset (); 
210               script#assignFileName f;
211               script#loadFromFile (); 
212               console#message ("'"^f^"' loaded.\n");
213               self#_enableSaveTo f
214         | None -> ()
215       in
216       let saveAsScript () =
217         let script = s () in
218         match self#chooseFile ~ok_not_exists:true () with
219         | Some f -> 
220               script#assignFileName f;
221               script#saveToFile (); 
222               console#message ("'"^f^"' saved.\n");
223               self#_enableSaveTo f
224         | None -> ()
225       in
226       let saveScript () =
227         match script_fname with
228         | None -> saveAsScript ()
229         | Some f -> 
230               (s ())#assignFileName f;
231               (s ())#saveToFile ();
232               console#message ("'"^f^"' saved.\n");
233       in
234       let newScript () = (s ())#reset (); disableSave () in
235       let cursor () =
236         source_buffer#place_cursor
237           (source_buffer#get_iter_at_mark (`NAME "locked"))
238       in
239       let advance _ = (MatitaScript.instance ())#advance (); cursor () in
240       let retract _ = (MatitaScript.instance ())#retract (); cursor () in
241       let top _ = (MatitaScript.instance ())#goto `Top (); cursor () in
242       let bottom _ = (MatitaScript.instance ())#goto `Bottom (); cursor () in
243       let jump _ = (MatitaScript.instance ())#goto `Cursor (); cursor () in
244       let connect_key sym f =
245         connect_key self#main#mainWinEventBox#event
246           ~modifiers:[`CONTROL] ~stop:true sym f;
247         connect_key self#sourceView#event
248           ~modifiers:[`CONTROL] ~stop:true sym f
249       in
250         (* quit *)
251       self#setQuitCallback (fun () -> 
252         if source_view#buffer#modified then
253           begin
254             let rc =  
255               MatitaGtkMisc.ask_confirmation 
256                 ~parent:main#toplevel
257                 ~title:"Unsaved work!" 
258                 ~message:("Your work is <b>unsaved</b>!\n\n"^
259                      "<i>Do you want to save the script before exiting?</i>")
260                 ()
261             in
262             match rc with
263             | `YES -> saveScript ();
264                       if not source_view#buffer#modified then
265                         GMain.Main.quit ()
266             | `NO -> GMain.Main.quit ()
267             | `CANCEL -> ()
268           end else GMain.Main.quit ());
269       connect_button self#main#scriptAdvanceButton advance;
270       connect_button self#main#scriptRetractButton retract;
271       connect_button self#main#scriptTopButton top;
272       connect_button self#main#scriptBottomButton bottom;
273       connect_key GdkKeysyms._Down advance;
274       connect_key GdkKeysyms._Up retract;
275       connect_key GdkKeysyms._Home top;
276       connect_key GdkKeysyms._End bottom;
277       connect_button self#main#scriptJumpButton jump;
278       connect_menu_item self#main#openMenuItem   loadScript;
279       connect_menu_item self#main#saveMenuItem   saveScript;
280       connect_menu_item self#main#saveAsMenuItem saveAsScript;
281       connect_menu_item self#main#newMenuItem    newScript;
282       connect_key GdkKeysyms._period
283         (fun () ->
284           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
285             ".\n";
286           advance ());
287       connect_key GdkKeysyms._Return
288         (fun () ->
289           source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT)
290             "\n";
291           advance ());
292          (* script monospace font stuff *)  
293       self#updateFontSize ();
294         (* debug menu *)
295       self#main#debugMenu#misc#hide ();
296         (* status bar *)
297       self#main#hintLowImage#set_file (image_path "matita-bulb-low.png");
298       self#main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
299       self#main#hintHighImage#set_file (image_path "matita-bulb-high.png");
300         (* focus *)
301       self#sourceView#misc#grab_focus ();
302         (* main win dimension *)
303       let width = Gdk.Screen.width () in
304       let height = Gdk.Screen.height () in
305       let main_w = width * 90 / 100 in 
306       let main_h = height * 80 / 100 in
307       let script_w = main_w * 6 / 10 in
308       self#main#toplevel#resize ~width:main_w ~height:main_h;
309       self#main#hpaneScriptSequent#set_position script_w  
310     
311     method loadScript file =       
312       let script = MatitaScript.instance () in
313       script#reset (); 
314       script#assignFileName file;
315       script#loadFromFile (); 
316       console#message ("'"^file^"' loaded.");
317       self#_enableSaveTo file
318       
319     method setStar name b =
320       let l = main#scriptLabel in
321       if b then
322         l#set_text (name ^  " *")
323       else
324         l#set_text (name)
325         
326     method private _enableSaveTo file =
327       script_fname <- Some file;
328       self#main#saveMenuItem#misc#set_sensitive true
329         
330
331     method console = console
332     method sourceView: GSourceView.source_view = (source_view: GSourceView.source_view)
333     method about = about
334     method fileSel = fileSel
335     method main = main
336
337     method newBrowserWin () =
338       object (self)
339         inherit browserWin ()
340         val combo = GEdit.combo_box_entry ()
341         initializer
342           self#check_widgets ();
343           let combo_widget = combo#coerce in
344           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
345           combo#entry#misc#grab_focus ()
346         method browserUri = combo
347       end
348
349     method newUriDialog () =
350       let dialog = new uriChoiceDialog () in
351       dialog#check_widgets ();
352       dialog
353
354     method newInterpDialog () =
355       let dialog = new interpChoiceDialog () in
356       dialog#check_widgets ();
357       dialog
358
359     method newConfirmationDialog () =
360       let dialog = new confirmationDialog () in
361       dialog#check_widgets ();
362       dialog
363
364     method newEmptyDialog () =
365       let dialog = new emptyDialog () in
366       dialog#check_widgets ();
367       dialog
368
369     method private addKeyBinding key callback =
370       List.iter (fun evbox -> add_key_binding key callback evbox)
371         keyBindingBoxes
372
373     method setQuitCallback callback =
374       ignore (main#quitMenuItem#connect#activate callback);
375       ignore (main#toplevel#event#connect#delete 
376         (fun _ -> callback ();true));
377       self#addKeyBinding GdkKeysyms._q callback
378
379     method chooseFile ?(ok_not_exists = false) () =
380       _ok_not_exists <- ok_not_exists;
381       fileSel#fileSelectionWin#show ();
382       GtkThread.main ();
383       chosen_file
384
385     method askText ?(title = "") ?(msg = "") () =
386       let dialog = new textDialog () in
387       dialog#textDialog#set_title title;
388       dialog#textDialogLabel#set_label msg;
389       let text = ref None in
390       let return v =
391         text := v;
392         dialog#textDialog#destroy ();
393         GMain.Main.quit ()
394       in
395       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
396       connect_button dialog#textDialogCancelButton (fun _ -> return None);
397       connect_button dialog#textDialogOkButton (fun _ ->
398         let text = dialog#textDialogTextView#buffer#get_text () in
399         return (Some text));
400       dialog#textDialog#show ();
401       GtkThread.main ();
402       !text
403
404     method private updateFontSize () =
405       self#sourceView#misc#modify_font_by_name
406         (sprintf "%s %d" BuildTimeConf.script_font font_size)
407
408     method increaseFontSize () =
409       font_size <- font_size + 1;
410       self#updateFontSize ()
411
412     method decreaseFontSize () =
413       font_size <- font_size - 1;
414       self#updateFontSize ()
415
416     method resetFontSize () =
417       font_size <- default_font_size;
418       self#updateFontSize ()
419
420   end
421
422 let gui () = 
423   let g = new gui () in
424   gui_instance := Some g;
425   g
426   
427 let instance = singleton gui
428
429 let non p x = not (p x)
430
431 (* this is a shit and should be changed :-{ *)
432 let interactive_uri_choice
433   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
434   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
435   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
436   ?copy_cb ()
437   ~id uris
438 =
439   let gui = instance () in
440   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
441   if (selection_mode <> `SINGLE) &&
442     (Helm_registry.get_bool "matita.auto_disambiguation")
443   then
444     Lazy.force nonvars_uris
445   else begin
446     let dialog = gui#newUriDialog () in
447     if hide_uri_entry then
448       dialog#uriEntryHBox#misc#hide ();
449     if hide_try then
450       begin
451       dialog#uriChoiceSelectedButton#misc#hide ();
452       dialog#uriChoiceConstantsButton#misc#hide ();
453       end;
454     dialog#okLabel#set_label ok_label;  
455     dialog#uriChoiceTreeView#selection#set_mode
456       (selection_mode :> Gtk.Tags.selection_mode);
457     let model = new stringListModel dialog#uriChoiceTreeView in
458     let choices = ref None in
459     let nonvars = ref false in
460     (match copy_cb with
461     | None -> ()
462     | Some cb ->
463         dialog#copyButton#misc#show ();
464         connect_button dialog#copyButton 
465         (fun _ ->
466           match model#easy_selection () with
467           | [u] -> (cb u)
468           | _ -> ()));
469     dialog#uriChoiceDialog#set_title title;
470     dialog#uriChoiceLabel#set_text msg;
471     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
472     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
473     let return v =
474       choices := v;
475       dialog#uriChoiceDialog#destroy ();
476       GMain.Main.quit ()
477     in
478     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
479     connect_button dialog#uriChoiceConstantsButton (fun _ ->
480       return (Some (Lazy.force nonvars_uris)));
481     if ok_action = `AUTO then
482       connect_button dialog#uriChoiceAutoButton (fun _ ->
483         Helm_registry.set_bool "matita.auto_disambiguation" true;
484         return (Some (Lazy.force nonvars_uris)))
485     else
486       connect_button dialog#uriChoiceAutoButton (fun _ ->
487         match model#easy_selection () with
488         | [] -> ()
489         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
490     connect_button dialog#uriChoiceSelectedButton (fun _ ->
491       match model#easy_selection () with
492       | [] -> ()
493       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
494     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
495     dialog#uriChoiceDialog#show ();
496     GtkThread.main ();
497     (match !choices with 
498     | None -> raise MatitaTypes.Cancel
499     | Some uris -> uris)
500   end
501
502 class interpModel =
503   let cols = new GTree.column_list in
504   let id_col = cols#add Gobject.Data.string in
505   let dsc_col = cols#add Gobject.Data.string in
506   let interp_no_col = cols#add Gobject.Data.int in
507   let tree_store = GTree.tree_store cols in
508   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
509   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
510   let id_view_col = GTree.view_column ~renderer:id_renderer () in
511   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
512   fun tree_view choices ->
513     object
514       initializer
515         tree_view#set_model (Some (tree_store :> GTree.model));
516         ignore (tree_view#append_column id_view_col);
517         ignore (tree_view#append_column dsc_view_col);
518         let name_of_interp =
519           (* try to find a reasonable name for an interpretation *)
520           let idx = ref 0 in
521           fun interp ->
522             try
523               List.assoc "0" interp
524             with Not_found ->
525               incr idx; string_of_int !idx
526         in
527         tree_store#clear ();
528         let idx = ref ~-1 in
529         List.iter
530           (fun interp ->
531             incr idx;
532             let interp_row = tree_store#append () in
533             tree_store#set ~row:interp_row ~column:id_col
534               (name_of_interp interp);
535             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
536             List.iter
537               (fun (id, dsc) ->
538                 let row = tree_store#append ~parent:interp_row () in
539                 tree_store#set ~row ~column:id_col id;
540                 tree_store#set ~row ~column:dsc_col dsc;
541                 tree_store#set ~row ~column:interp_no_col !idx)
542               interp)
543           choices
544
545       method get_interp_no tree_path =
546         let iter = tree_store#get_iter tree_path in
547         tree_store#get ~row:iter ~column:interp_no_col
548     end
549
550 let interactive_interp_choice () choices =
551   let gui = instance () in
552   assert (choices <> []);
553   let dialog = gui#newInterpDialog () in
554   let model = new interpModel dialog#interpChoiceTreeView choices in
555   let interp_len = List.length (List.hd choices) in
556   dialog#interpChoiceDialog#set_title "Interpretation choice";
557   dialog#interpChoiceDialogLabel#set_label "Choose an interpretation:";
558   let interp_no = ref None in
559   let return _ =
560     dialog#interpChoiceDialog#destroy ();
561     GMain.Main.quit ()
562   in
563   let fail _ = interp_no := None; return () in
564   ignore (dialog#interpChoiceDialog#event#connect#delete (fun _ -> true));
565   connect_button dialog#interpChoiceOkButton (fun _ ->
566     match !interp_no with None -> () | Some _ -> return ());
567   connect_button dialog#interpChoiceCancelButton fail;
568   ignore (dialog#interpChoiceTreeView#connect#row_activated (fun path _ ->
569     interp_no := Some (model#get_interp_no path);
570     return ()));
571   let selection = dialog#interpChoiceTreeView#selection in
572   ignore (selection#connect#changed (fun _ ->
573     match selection#get_selected_rows with
574     | [path] ->
575         MatitaLog.debug (sprintf "selection: %d" (model#get_interp_no path));
576         interp_no := Some (model#get_interp_no path)
577     | _ -> assert false));
578   dialog#interpChoiceDialog#show ();
579   GtkThread.main ();
580   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
581