]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaGui.ml
attached auto
[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 console ~(buffer: GText.buffer) () =
35   object (self)
36     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
37     val warning_tag = buffer#create_tag [ `FOREGROUND "yellow" ]
38     val message_tag = buffer#create_tag []
39     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
40     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
41     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
42     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
43     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
44     method clear () =
45       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
46     method log_callback (tag: MatitaLog.log_tag) s =
47       match tag with
48       | `Debug -> self#debug (s ^ "\n")
49       | `Error -> self#error (s ^ "\n")
50       | `Message -> self#message (s ^ "\n")
51       | `Warning -> self#warning (s ^ "\n")
52   end
53
54 class gui () =
55     (* creation order _is_ relevant for windows placement *)
56   let main = new mainWin () in
57   let about = new aboutWin () in
58   let fileSel = new fileSelectionWin () in
59   let keyBindingBoxes = (* event boxes which should receive global key events *)
60     [ main#mainWinEventBox ]
61   in
62   let console = new console ~buffer:main#logTextView#buffer () in
63   object (self)
64     val mutable chosen_file = None
65     val mutable _ok_not_exists = false
66
67     initializer
68         (* glade's check widgets *)
69       List.iter (fun w -> w#check_widgets ())
70         (let c w = (w :> <check_widgets: unit -> unit>) in
71          [ c about; c fileSel; c main ]);
72         (* key bindings *)
73       List.iter (* global key bindings *)
74         (fun (key, callback) -> self#addKeyBinding key callback)
75 (*
76         [ GdkKeysyms._F3,
77             toggle_win ~check:main#showProofMenuItem proof#proofWin;
78           GdkKeysyms._F4,
79             toggle_win ~check:main#showCheckMenuItem check#checkWin;
80 *)
81         [ ];
82         (* about win *)
83       ignore (about#aboutWin#event#connect#delete (fun _ -> true));
84       ignore (main#aboutMenuItem#connect#activate (fun _ ->
85         about#aboutWin#show ()));
86       connect_button about#aboutDismissButton (fun _ ->
87         about#aboutWin#misc#hide ());
88       about#aboutLabel#set_label (Pcre.replace ~pat:"@VERSION@"
89         ~templ:BuildTimeConf.version about#aboutLabel#label);
90         (* file selection win *)
91       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
92       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
93         let return r =
94           chosen_file <- r;
95           fileSel#fileSelectionWin#misc#hide ();
96           GMain.Main.quit ()
97         in
98         match event with
99         | `OK ->
100             let fname = fileSel#fileSelectionWin#filename in
101             if Sys.file_exists fname then
102               (if is_regular fname then return (Some fname))
103             else
104               (if _ok_not_exists then return (Some fname))
105         | `CANCEL -> return None
106         | `HELP -> ()
107         | `DELETE_EVENT -> return None));
108         (* menus *)
109       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
110       main#helpMenu#set_right_justified true;
111         (* console *)
112       let adj = main#logScrolledWin#vadjustment in
113       ignore (adj#connect#changed
114                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
115       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
116         (* toolbar *)
117       let module A = TacticAst in
118       let hole = CicAst.UserInput in
119       let loc = CicAst.dummy_floc in
120       let tac ast _ =
121         if (MatitaScript.instance ())#onGoingProof () then
122           (MatitaScript.instance ())#advance
123             ~statement:("\n" ^ TacticAstPp.pp_tactical (A.Tactic (loc, ast))) ()
124       in
125       let tac_w_term ast _ =
126         if (MatitaScript.instance ())#onGoingProof () then
127           let (buf: GText.buffer) = self#main#scriptTextView#buffer in
128           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
129             ("\n" ^ TacticAstPp.pp_tactic ast)
130       in
131       let tbar = self#main in
132       connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
133       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
134       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
135       connect_button tbar#elimButton (tac_w_term (A.Elim (loc, hole, None)));
136       connect_button tbar#elimTypeButton (tac_w_term (A.ElimType (loc, hole)));
137       connect_button tbar#splitButton (tac (A.Split loc));
138       connect_button tbar#leftButton (tac (A.Left loc));
139       connect_button tbar#rightButton (tac (A.Right loc));
140       connect_button tbar#existsButton (tac (A.Exists loc));
141       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
142       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
143       connect_button tbar#transitivityButton
144         (tac_w_term (A.Transitivity (loc, hole)));
145       connect_button tbar#assumptionButton (tac (A.Assumption loc));
146       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, hole)));
147       connect_button tbar#autoButton (tac (A.Auto (loc,None)));
148         (* quit *)
149       self#setQuitCallback (fun () -> exit 0);
150         (* log *)
151       MatitaLog.set_log_callback self#console#log_callback;
152       GtkSignal.user_handler :=
153         (fun exn ->
154            MatitaLog.error
155              (sprintf "Uncaught exception: %s" (Printexc.to_string exn)));
156         (* script *)
157       let s () = MatitaScript.instance () in
158       let script_fname = ref None in
159       let enable_save_to f =
160         script_fname := Some f;
161         self#main#saveMenuItem#misc#set_sensitive true
162       in
163       let disable_save () =
164         script_fname := None;
165         self#main#saveMenuItem#misc#set_sensitive false
166       in
167       let loadScript () =
168         let script = s () in
169         match self#chooseFile () with
170         | Some f -> script#reset (); script#loadFrom f; enable_save_to f
171         | None -> ()
172       in
173       let saveAsScript () =
174         let script = s () in
175         match self#chooseFile ~ok_not_exists:true () with
176         | Some f -> script#saveTo f; enable_save_to f
177         | None -> ()
178       in
179       let saveScript () =
180         match !script_fname with
181         | None -> saveAsScript ()
182         | Some f -> (s ())#saveTo f
183       in
184       let newScript () = (s ())#reset (); disable_save () in
185       let cursor () =
186         let buf = self#main#scriptTextView#buffer in
187         buf#place_cursor (buf#get_iter_at_mark (`NAME "locked"))
188       in
189       let advance _ = (MatitaScript.instance ())#advance (); cursor () in
190       let retract _ = (MatitaScript.instance ())#retract (); cursor () in
191       let top _ = (MatitaScript.instance ())#goto `Top (); cursor () in
192       let bottom _ = (MatitaScript.instance ())#goto `Bottom (); cursor () in
193       let jump _ = (MatitaScript.instance ())#goto `Cursor (); cursor () in
194       let connect_key sym f =
195         connect_key self#main#mainWinEventBox#event
196           ~modifiers:[`CONTROL] ~stop:true sym f;
197         connect_key self#main#scriptTextView#event
198           ~modifiers:[`CONTROL] ~stop:true sym f
199       in
200       connect_button self#main#scriptAdvanceButton advance;
201       connect_button self#main#scriptRetractButton retract;
202       connect_button self#main#scriptTopButton top;
203       connect_button self#main#scriptBottomButton bottom;
204       connect_key GdkKeysyms._Down advance;
205       connect_key GdkKeysyms._Up retract;
206       connect_key GdkKeysyms._Home top;
207       connect_key GdkKeysyms._End bottom;
208       connect_button self#main#scriptJumpButton jump;
209       connect_menu_item self#main#openMenuItem   loadScript;
210       connect_menu_item self#main#saveMenuItem   saveScript;
211       connect_menu_item self#main#saveAsMenuItem saveAsScript;
212       connect_menu_item self#main#newMenuItem    newScript;
213       connect_key GdkKeysyms._period
214         (fun () ->
215            let buf = self#main#scriptTextView#buffer in
216            buf#insert ~iter:(buf#get_iter_at_mark `INSERT) ".\n";
217            advance ());
218       connect_key GdkKeysyms._Return
219         (fun () ->
220            let buf = self#main#scriptTextView#buffer in
221            buf#insert ~iter:(buf#get_iter_at_mark `INSERT) "\n";
222            advance ());
223         (* debug menu *)
224       self#main#debugMenu#misc#hide ();
225         (* status bar *)
226       self#main#hintLowImage#set_file "icons/matita-bulb-low.png";
227       self#main#hintMediumImage#set_file "icons/matita-bulb-medium.png";
228       self#main#hintHighImage#set_file "icons/matita-bulb-high.png";
229         (* focus *)
230       self#main#scriptTextView#misc#grab_focus ()
231
232     method console = console
233
234     method about = about
235     method fileSel = fileSel
236     method main = main
237
238     method newBrowserWin () =
239       let win = new browserWin () in
240       win#check_widgets ();
241       win
242
243     method newUriDialog () =
244       let dialog = new uriChoiceDialog () in
245       dialog#check_widgets ();
246       dialog
247
248     method newInterpDialog () =
249       let dialog = new interpChoiceDialog () in
250       dialog#check_widgets ();
251       dialog
252
253     method newConfirmationDialog () =
254       let dialog = new confirmationDialog () in
255       dialog#check_widgets ();
256       dialog
257
258     method newEmptyDialog () =
259       let dialog = new emptyDialog () in
260       dialog#check_widgets ();
261       dialog
262
263     method private addKeyBinding key callback =
264       List.iter (fun evbox -> add_key_binding key callback evbox)
265         keyBindingBoxes
266
267     method setQuitCallback callback =
268       ignore (main#toplevel#connect#destroy callback);
269       ignore (main#quitMenuItem#connect#activate callback);
270       self#addKeyBinding GdkKeysyms._q callback
271
272     method chooseFile ?(ok_not_exists = false) () =
273       _ok_not_exists <- ok_not_exists;
274       fileSel#fileSelectionWin#show ();
275       GtkThread.main ();
276       chosen_file
277
278     method askText ?(title = "") ?(msg = "") () =
279       let dialog = new textDialog () in
280       dialog#textDialog#set_title title;
281       dialog#textDialogLabel#set_label msg;
282       let text = ref None in
283       let return v =
284         text := v;
285         dialog#textDialog#destroy ();
286         GMain.Main.quit ()
287       in
288       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
289       connect_button dialog#textDialogCancelButton (fun _ -> return None);
290       connect_button dialog#textDialogOkButton (fun _ ->
291         let text = dialog#textDialogTextView#buffer#get_text () in
292         return (Some text));
293       dialog#textDialog#show ();
294       GtkThread.main ();
295       !text
296
297   end
298
299 let gui () = 
300   let g = new gui () in
301   gui_instance := Some g;
302   g
303   
304 let instance = singleton gui
305
306 let non p x = not (p x)
307
308 let is_var_uri s =
309   try
310     String.sub s (String.length s - 4) 4 = ".var"
311   with Invalid_argument _ -> false
312
313 let interactive_uri_choice
314   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
315   ?(msg = "") ?(nonvars_button = false) ()
316   ~id uris
317 =
318   let gui = instance () in
319   let nonvars_uris = lazy (List.filter (non is_var_uri) uris) in
320   if (selection_mode <> `SINGLE) &&
321     (Helm_registry.get_bool "matita.auto_disambiguation")
322   then
323     Lazy.force nonvars_uris
324   else begin
325     let dialog = gui#newUriDialog () in
326     dialog#uriChoiceTreeView#selection#set_mode
327       (selection_mode :> Gtk.Tags.selection_mode);
328     let model = new stringListModel dialog#uriChoiceTreeView in
329     let choices = ref None in
330     let nonvars = ref false in
331     dialog#uriChoiceDialog#set_title title;
332     dialog#uriChoiceLabel#set_text msg;
333     List.iter model#easy_append uris;
334     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
335     let return v =
336       choices := v;
337       dialog#uriChoiceDialog#destroy ();
338       GMain.Main.quit ()
339     in
340     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
341     connect_button dialog#uriChoiceConstantsButton (fun _ ->
342       return (Some (Lazy.force nonvars_uris)));
343     connect_button dialog#uriChoiceAutoButton (fun _ ->
344       Helm_registry.set_bool "matita.auto_disambiguation" true;
345       return (Some (Lazy.force nonvars_uris)));
346     connect_button dialog#uriChoiceSelectedButton (fun _ ->
347       match model#easy_selection () with
348       | [] -> ()
349       | uris -> return (Some uris));
350     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
351     dialog#uriChoiceDialog#show ();
352     GtkThread.main ();
353     (match !choices with 
354     | None -> raise MatitaTypes.Cancel
355     | Some uris -> uris)
356   end
357
358 class interpModel =
359   let cols = new GTree.column_list in
360   let id_col = cols#add Gobject.Data.string in
361   let dsc_col = cols#add Gobject.Data.string in
362   let interp_no_col = cols#add Gobject.Data.int in
363   let tree_store = GTree.tree_store cols in
364   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
365   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
366   let id_view_col = GTree.view_column ~renderer:id_renderer () in
367   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
368   fun tree_view choices ->
369     object
370       initializer
371         tree_view#set_model (Some (tree_store :> GTree.model));
372         ignore (tree_view#append_column id_view_col);
373         ignore (tree_view#append_column dsc_view_col);
374         let name_of_interp =
375           (* try to find a reasonable name for an interpretation *)
376           let idx = ref 0 in
377           fun interp ->
378             try
379               List.assoc "0" interp
380             with Not_found ->
381               incr idx; string_of_int !idx
382         in
383         tree_store#clear ();
384         let idx = ref ~-1 in
385         List.iter
386           (fun interp ->
387             incr idx;
388             let interp_row = tree_store#append () in
389             tree_store#set ~row:interp_row ~column:id_col
390               (name_of_interp interp);
391             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
392             List.iter
393               (fun (id, dsc) ->
394                 let row = tree_store#append ~parent:interp_row () in
395                 tree_store#set ~row ~column:id_col id;
396                 tree_store#set ~row ~column:dsc_col dsc;
397                 tree_store#set ~row ~column:interp_no_col !idx)
398               interp)
399           choices
400
401       method get_interp_no tree_path =
402         let iter = tree_store#get_iter tree_path in
403         tree_store#get ~row:iter ~column:interp_no_col
404     end
405
406 let interactive_interp_choice () choices =
407   let gui = instance () in
408   assert (choices <> []);
409   let dialog = gui#newInterpDialog () in
410   let model = new interpModel dialog#interpChoiceTreeView choices in
411   let interp_len = List.length (List.hd choices) in
412   dialog#interpChoiceDialog#set_title "Interpretation choice";
413   dialog#interpChoiceDialogLabel#set_label "Choose an interpretation:";
414   let interp_no = ref None in
415   let return _ =
416     dialog#interpChoiceDialog#destroy ();
417     GMain.Main.quit ()
418   in
419   let fail _ = interp_no := None; return () in
420   ignore (dialog#interpChoiceDialog#event#connect#delete (fun _ -> true));
421   connect_button dialog#interpChoiceOkButton (fun _ ->
422     match !interp_no with None -> () | Some _ -> return ());
423   connect_button dialog#interpChoiceCancelButton fail;
424   ignore (dialog#interpChoiceTreeView#connect#row_activated (fun path _ ->
425     interp_no := Some (model#get_interp_no path);
426     return ()));
427   let selection = dialog#interpChoiceTreeView#selection in
428   ignore (selection#connect#changed (fun _ ->
429     match selection#get_selected_rows with
430     | [path] ->
431         MatitaLog.debug (sprintf "selection: %d" (model#get_interp_no path));
432         interp_no := Some (model#get_interp_no path)
433     | _ -> assert false));
434   dialog#interpChoiceDialog#show ();
435   GtkThread.main ();
436   (match !interp_no with Some row -> [row] | _ -> raise MatitaTypes.Cancel)
437