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