1 (* Copyright (C) 2004-2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
30 open MatitaGeneratedGui
34 let all_disambiguation_passes = ref false
36 (* this is a shit and should be changed :-{ *)
37 let interactive_uri_choice
38 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
39 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
40 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
44 if (selection_mode <> `SINGLE) &&
45 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
49 let dialog = new uriChoiceDialog () in
50 if hide_uri_entry then
51 dialog#uriEntryHBox#misc#hide ();
54 dialog#uriChoiceSelectedButton#misc#hide ();
55 dialog#uriChoiceConstantsButton#misc#hide ();
57 dialog#okLabel#set_label ok_label;
58 dialog#uriChoiceTreeView#selection#set_mode
59 (selection_mode :> Gtk.Tags.selection_mode);
60 let model = new stringListModel dialog#uriChoiceTreeView in
61 let choices = ref None in
65 dialog#copyButton#misc#show ();
66 connect_button dialog#copyButton
68 match model#easy_selection () with
71 dialog#uriChoiceDialog#set_title title;
72 dialog#uriChoiceLabel#set_text msg;
73 List.iter model#easy_append (List.map NReference.string_of_reference uris);
74 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
77 dialog#uriChoiceDialog#destroy ();
80 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
81 connect_button dialog#uriChoiceConstantsButton (fun _ ->
83 if ok_action = `AUTO then
84 connect_button dialog#uriChoiceAutoButton (fun _ ->
85 Helm_registry.set_bool "matita.auto_disambiguation" true;
88 connect_button dialog#uriChoiceAutoButton (fun _ ->
89 match model#easy_selection () with
91 | uris -> return (Some (List.map NReference.reference_of_string uris)));
92 connect_button dialog#uriChoiceSelectedButton (fun _ ->
93 match model#easy_selection () with
95 | uris -> return (Some (List.map NReference.reference_of_string uris)));
96 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
97 dialog#uriChoiceDialog#show ();
98 (* CSC: old Gtk2 code. Use #run instead. Look for similar code handling
102 | None -> raise MatitaTypes.Cancel
107 class console ~(buffer: GText.buffer) () =
109 val error_tag = buffer#create_tag [ `FOREGROUND "red" ]
110 val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
111 val message_tag = buffer#create_tag []
112 val debug_tag = buffer#create_tag [ `FOREGROUND "#888888" ]
113 method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
114 method error s = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
115 method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
116 method debug s = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
118 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
119 method log_callback (tag: HLog.log_tag) s =
120 let s = Pcre.replace ~pat:"
\e\\[0;3.m([^
\e]+)
\e\\[0m" ~templ:"$1" s in
122 | `Debug -> self#debug (s ^ "\n")
123 | `Error -> self#error (s ^ "\n")
124 | `Message -> self#message (s ^ "\n")
125 | `Warning -> self#warning (s ^ "\n")
128 let clean_current_baseuri status =
129 LibraryClean.clean_baseuris [status#baseuri]
131 let save_moo0 ~do_clean script status =
132 let baseuri = status#baseuri in
133 match script#bos, script#eos with
136 GrafiteTypes.Serializer.serialize ~baseuri:(NUri.uri_of_string baseuri)
138 | _ -> if do_clean then clean_current_baseuri status
141 let save_moo status =
142 let script = MatitaScript.current () in
143 save_moo0 ~do_clean:true script status
146 let ask_unsaved parent filename =
147 MatitaGtkMisc.ask_confirmation
148 ~parent ~title:"Unsaved work!"
149 ~message:("Script <b>" ^ filename ^ "</b> is modified.!\n\n"^
150 "<i>Do you want to save the script before continuing?</i>")
153 class interpErrorModel =
154 let cols = new GTree.column_list in
155 let id_col = cols#add Gobject.Data.string in
156 let dsc_col = cols#add Gobject.Data.string in
157 let interp_no_col = cols#add Gobject.Data.caml in
158 let tree_store = GTree.tree_store cols in
159 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
160 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
161 let id_view_col = GTree.view_column ~renderer:id_renderer () in
162 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
163 fun (tree_view: GTree.view) choices ->
166 tree_view#set_model (Some (tree_store :> GTree.model));
167 ignore (tree_view#append_column id_view_col);
168 ignore (tree_view#append_column dsc_view_col);
170 let idx1 = ref ~-1 in
175 if List.length choices = 1 then
178 (let loc_row = tree_store#append () in
181 [passes,_envs_and_diffs,_,_] ->
182 tree_store#set ~row:loc_row ~column:id_col
183 ("Error location " ^ string_of_int (!idx1+1) ^
184 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
186 String.concat " " (List.map string_of_int passes) ^
188 tree_store#set ~row:loc_row ~column:interp_no_col
191 tree_store#set ~row:loc_row ~column:id_col
192 ("Error location " ^ string_of_int (!idx1+1));
193 tree_store#set ~row:loc_row ~column:interp_no_col
197 let idx2 = ref ~-1 in
199 (fun (passes,envs_and_diffs,_,_) ->
202 if List.length lll = 1 then
205 let msg_row = tree_store#append ?parent:loc_row () in
206 (tree_store#set ~row:msg_row ~column:id_col
207 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
208 string_of_int (!idx2+1) ^
210 String.concat " " (List.map string_of_int passes) ^
212 tree_store#set ~row:msg_row ~column:interp_no_col
213 (!idx1,Some !idx2,None);
215 let idx3 = ref ~-1 in
217 (fun (passes,env,_) ->
220 match envs_and_diffs with
222 let interp_row = tree_store#append ?parent:msg_row () in
223 tree_store#set ~row:interp_row ~column:id_col
224 ("Interpretation " ^ string_of_int (!idx3+1) ^
226 String.concat " " (List.map string_of_int passes) ^
228 tree_store#set ~row:interp_row ~column:interp_no_col
229 (!idx1,Some !idx2,Some !idx3);
236 let row = tree_store#append ?parent:interp_row () in
237 tree_store#set ~row ~column:id_col id;
238 tree_store#set ~row ~column:dsc_col dsc;
239 tree_store#set ~row ~column:interp_no_col
240 (!idx1,Some !idx2,Some !idx3)
244 if List.length lll > 1 then
246 (fun p -> tree_view#expand_row (tree_store#get_path p))
250 method get_interp_no tree_path =
251 let iter = tree_store#get_iter tree_path in
252 tree_store#get ~row:iter ~column:interp_no_col
255 exception UseLibrary;;
257 let interactive_error_interp ~all_passes
258 (source_buffer:GSourceView3.source_buffer) notify_exn offset errorll filename
260 (* hook to save a script for each disambiguation error *)
263 source_buffer#get_text ~start:source_buffer#start_iter
264 ~stop:source_buffer#end_iter () in
265 let md5 = Digest.to_hex (Digest.string text) in
267 Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma" in
268 let ch = open_out filename in
269 output_string ch text;
272 assert (List.flatten errorll <> []);
274 let remove_non_significant =
275 List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
276 let annotated_errorll () =
279 (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
281 if all_passes then annotated_errorll () else
282 let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
283 (* We remove passes 1,2 and 5,6 *)
286 ::(3,remove_non_significant (safe_list_nth errorll 2))
287 ::(4,remove_non_significant (safe_list_nth errorll 3))
290 if List.flatten (List.map snd res) <> [] then res
292 (* all errors (if any) are not significant: we keep them *)
295 ::(3,(safe_list_nth errorll 2))
296 ::(4,(safe_list_nth errorll 3))
299 if List.flatten (List.map snd res) <> [] then
302 "All disambiguation errors are not significant. Showing them anyway." ;
308 "No errors in phases 2 and 3. Showing all errors in all phases" ;
312 let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
315 | [loffset,[_,envs_and_diffs,msg,significant]] ->
316 let _,env,diff = List.hd envs_and_diffs in
318 (MultiPassDisambiguator.DisambiguationError
319 (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
321 GtkThread.sync (fun _ ->
322 let dialog = new disambiguationErrors () in
323 dialog#toplevel#add_button "Fix this interpretation" `OK;
324 dialog#toplevel#add_button "Close" `DELETE_EVENT;
325 if not all_passes then
326 dialog#toplevel#add_button "More errors" `HELP; (* HELP means MORE *)
327 let model = new interpErrorModel dialog#treeview choices in
328 dialog#disambiguationErrors#set_title "Disambiguation error";
329 dialog#disambiguationErrorsLabel#set_label
330 "Click on an error to see the corresponding message:";
331 ignore (dialog#treeview#connect#cursor_changed
334 match fst (dialog#treeview#get_cursor ()) with
337 let idx1,idx2,idx3 = model#get_interp_no tree_path in
338 let loffset,lll = List.nth choices idx1 in
339 let _,envs_and_diffs,msg,significant =
341 Some idx2 -> List.nth lll idx2
343 [],[],lazy "Multiple error messages. Please select one.",true
347 Some idx3 -> List.nth envs_and_diffs idx3
348 | None -> [],[],[] (* dymmy value, used *) in
349 let script = MatitaScript.current () in
350 let error_tag = script#error_tag in
351 source_buffer#remove_tag error_tag
352 ~start:source_buffer#start_iter
353 ~stop:source_buffer#end_iter;
355 (MultiPassDisambiguator.DisambiguationError
356 (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
358 (match GtkThread.sync dialog#toplevel#run () with
361 match fst (dialog#treeview#get_cursor ()) with
364 let idx1,idx2,idx3 = model#get_interp_no tree_path in
367 Some idx2, Some idx3 ->
368 let _,lll = List.nth choices idx1 in
369 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
370 let _,_,diff = List.nth envs_and_diffs idx3 in
372 | _,_ -> assert false
381 | DisambiguateTypes.Id id ->
382 GrafiteAst.Ident_alias (id, desc)
383 | DisambiguateTypes.Symbol (symb, i)->
384 GrafiteAst.Symbol_alias (symb, i, desc)
385 | DisambiguateTypes.Num i ->
386 GrafiteAst.Number_alias (i, desc)
388 GrafiteAstPp.pp_alias alias)
393 (source_buffer#get_iter_at_mark
394 (`NAME "beginning_of_statement")) newtxt
395 | `HELP (* HELP MEANS MORE *) ->
396 dialog#toplevel#destroy () ;
398 | `DELETE_EVENT -> ()
399 | _ -> assert false) ;
400 dialog#toplevel#destroy ()
403 let ref_kill_worker = ref (fun _ -> assert false)
406 (* creation order _is_ relevant for windows placement *)
407 let main = new mainWin () in
408 let sequents_viewer =
409 MatitaMathView.sequentsViewer_instance main#sequentsNotebook in
410 let findRepl = new findReplWin () in
411 let keyBindingBoxes = (* event boxes which should receive global key events *)
412 [ main#mainWinEventBox ]
414 let console = new console ~buffer:main#logTextView#buffer () in
416 val mutable chosen_file = None
417 val mutable _ok_not_exists = false
418 val mutable _only_directory = false
419 val mutable current_page = -1
422 let s () = MatitaScript.current () in
424 List.iter (* global key bindings *)
425 (fun (key, modifiers, callback) ->
426 self#addKeyBinding key ~modifiers callback)
429 toggle_win ~check:main#showProofMenuItem proof#proofWin;
431 toggle_win ~check:main#showCheckMenuItem check#checkWin;
434 GdkKeysyms._Page_Down, [`CONTROL], main#scriptNotebook#next_page;
435 GdkKeysyms._Page_Up, [`CONTROL], main#scriptNotebook#previous_page
438 let parse_txt_file file =
439 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
440 let l_rev = ref [] in
443 l_rev := input_line ch :: !l_rev;
452 ~authors:(parse_txt_file "AUTHORS")
453 (*~comments:"comments"*)
454 ~copyright:"Copyright (C) 2005, the HELM team"
455 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
456 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
458 ~version:BuildTimeConf.version
459 ~website:"http://matita.cs.unibo.it"
462 ignore(about_dialog#event#connect#delete (fun _ -> true));
463 ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
464 connect_menu_item main#contentsMenuItem (fun () ->
465 if 0 = Sys.command "which gnome-help" then
467 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
469 ignore (Sys.command cmd)
471 MatitaGtkMisc.report_error ~title:"help system error"
473 "The program gnome-help is not installed\n\n"^
474 "To browse the user manal it is necessary to install "^
475 "the gnome help syste (also known as yelp)")
476 ~parent:main#toplevel ());
477 connect_menu_item main#aboutMenuItem about_dialog#present;
479 let show_find_Repl () =
480 findRepl#toplevel#misc#show ();
481 findRepl#toplevel#misc#grab_focus ()
483 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
485 let source_view = (s ())#source_view in
486 let highlight start end_ =
487 source_view#source_buffer#move_mark `INSERT ~where:start;
488 source_view#source_buffer#move_mark `SEL_BOUND ~where:end_;
489 source_view#scroll_mark_onscreen `INSERT
491 let text = findRepl#findEntry#text in
492 let iter = source_view#source_buffer#get_iter `SEL_BOUND in
493 match iter#forward_search text with
495 (match source_view#source_buffer#start_iter#forward_search text with
497 | Some (start,end_) -> highlight start end_)
498 | Some (start,end_) -> highlight start end_
501 let source_view = (s ())#source_view in
502 let text = findRepl#replaceEntry#text in
503 let ins = source_view#source_buffer#get_iter `INSERT in
504 let sel = source_view#source_buffer#get_iter `SEL_BOUND in
505 if ins#compare sel < 0 then
507 ignore(source_view#source_buffer#delete_selection ());
508 source_view#source_buffer#insert text
511 connect_button findRepl#findButton find_forward;
512 connect_button findRepl#findReplButton replace;
513 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
514 ignore(findRepl#toplevel#event#connect#delete
515 ~callback:(fun _ -> hide_find_Repl ();true));
516 connect_menu_item main#undoMenuItem
517 (fun () -> (MatitaScript.current ())#safe_undo);
518 main#undoMenuItem#misc#set_sensitive false;
519 connect_menu_item main#redoMenuItem
520 (fun () -> (MatitaScript.current ())#safe_redo);
521 main#redoMenuItem#misc#set_sensitive false;
522 connect_menu_item main#editMenu (fun () ->
523 main#copyMenuItem#misc#set_sensitive
524 (MatitaScript.current ())#canCopy;
525 main#cutMenuItem#misc#set_sensitive
526 (MatitaScript.current ())#canCut;
527 main#deleteMenuItem#misc#set_sensitive
528 (MatitaScript.current ())#canDelete;
529 main#pasteMenuItem#misc#set_sensitive
530 (MatitaScript.current ())#canPaste;
531 main#pastePatternMenuItem#misc#set_sensitive
532 (MatitaScript.current ())#canPastePattern);
533 connect_menu_item main#copyMenuItem
534 (fun () -> (MatitaScript.current ())#copy ());
535 connect_menu_item main#cutMenuItem
536 (fun () -> (MatitaScript.current ())#cut ());
537 connect_menu_item main#deleteMenuItem
538 (fun () -> (MatitaScript.current ())#delete ());
539 connect_menu_item main#pasteMenuItem
540 (fun () -> (MatitaScript.current ())#paste ());
541 connect_menu_item main#pastePatternMenuItem
542 (fun () -> (MatitaScript.current ())#pastePattern ());
543 connect_menu_item main#selectAllMenuItem (fun () ->
544 let source_view = (s ())#source_view in
545 source_view#source_buffer#move_mark `INSERT source_view#source_buffer#start_iter;
546 source_view#source_buffer#move_mark `SEL_BOUND source_view#source_buffer#end_iter);
547 connect_menu_item main#findReplMenuItem show_find_Repl;
548 connect_menu_item main#externalEditorMenuItem self#externalEditor;
549 connect_menu_item main#ligatureButton
550 (fun () -> (MatitaScript.current ())#nextSimilarSymbol);
551 ignore (findRepl#findEntry#connect#activate find_forward);
552 (* interface lockers *)
554 let source_view = (s ())#source_view in
555 main#buttonsToolbar#misc#set_sensitive false;
556 main#scriptMenu#misc#set_sensitive false;
557 source_view#set_editable false;
558 main#scriptAbortButton#set_sensitive true
561 let source_view = (s ())#source_view in
562 main#buttonsToolbar#misc#set_sensitive true;
563 main#scriptMenu#misc#set_sensitive true;
564 source_view#set_editable true;
565 main#scriptAbortButton#set_sensitive false
567 let worker_thread = ref None in
568 let notify_exn (source_view : GSourceView3.source_view) exn =
569 let floc, msg = MatitaExcPp.to_string exn in
574 let (x, y) = HExtlib.loc_of_floc floc in
575 let script = MatitaScript.current () in
576 let locked_mark = script#locked_mark in
577 let error_tag = script#error_tag in
579 (source_view#source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
580 let x' = baseoffset + x in
581 let y' = baseoffset + y in
582 let x_iter = source_view#source_buffer#get_iter (`OFFSET x') in
583 let y_iter = source_view#source_buffer#get_iter (`OFFSET y') in
584 source_view#source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
586 id := Some (source_view#source_buffer#connect#changed ~callback:(fun () ->
587 source_view#source_buffer#remove_tag error_tag
588 ~start:source_view#source_buffer#start_iter
589 ~stop:source_view#source_buffer#end_iter;
591 | None -> assert false (* a race condition occurred *)
593 source_view#source_buffer#misc#disconnect id));
594 source_view#source_buffer#place_cursor
595 (source_view#source_buffer#get_iter (`OFFSET x'));
598 let locker f script =
599 let source_view = script#source_view in
602 ignore (Thread.sigmask Unix.SIG_UNBLOCK [Sys.sigvtalrm]);
604 let saved_use_library= !MultiPassDisambiguator.use_library in
606 MultiPassDisambiguator.use_library := !all_disambiguation_passes;
608 MultiPassDisambiguator.use_library := saved_use_library;
611 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
613 interactive_error_interp
614 ~all_passes:!all_disambiguation_passes source_view#source_buffer
615 (notify_exn source_view) offset errorll (s())#filename
618 MultiPassDisambiguator.use_library := true;
621 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
622 interactive_error_interp ~all_passes:true source_view#source_buffer
623 (notify_exn source_view) offset errorll (s())#filename
625 notify_exn source_view exc);
626 | exc -> notify_exn source_view exc);
627 MultiPassDisambiguator.use_library := saved_use_library;
630 (try notify_exn source_view exc
631 with Sys.Break as e -> notify_exn source_view e);
634 worker_thread := Some (Thread.create thread_main ())
637 let interrupt = ref None in
638 let old_callback = ref (function _ -> ()) in
639 let force_interrupt n =
640 (* This function is called every 1s (see Unix.setitimer call above) *)
642 (* it may be a masked interrupt for the previous thread that arrives
644 if Some(Thread.id(Thread.self())) = !interrupt then
645 (interrupt := None; raise Sys.Break)
647 ignore (Thread.sigmask Unix.SIG_BLOCK [Sys.sigvtalrm]);
648 ignore (Unix.setitimer Unix.ITIMER_VIRTUAL {Unix.it_interval = 1.; it_value = 1.});
650 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
651 Sys.Signal_handle f -> old_callback := f
653 | Sys.Signal_default -> assert false
656 match !worker_thread with
658 | Some t -> interrupt := Some (Thread.id t) in
659 ref_kill_worker := kill_worker ;
660 let keep_focus f (script: MatitaScript.script) =
662 f script; script#source_view#misc#grab_focus ()
664 exc -> script#source_view#misc#grab_focus (); raise exc in
667 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
669 let adj = main#logScrolledWin#vadjustment in
670 ignore (adj#connect#changed
671 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
672 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
673 console#message (sprintf "\tStandard library location:\n\t %s\n" BuildTimeConf.new_stdlib_dir_devel);
674 (* natural deduction palette *)
675 main#tacticsButtonsHandlebox#misc#hide ();
676 MatitaGtkMisc.toggle_callback
678 if b then main#tacticsButtonsHandlebox#misc#show ()
679 else main#tacticsButtonsHandlebox#misc#hide ())
680 ~check:main#menuitemPalette;
681 connect_button main#butImpl_intro
682 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⇒#i […] (…));\n");
683 connect_button main#butAnd_intro
684 (fun () -> (s ())#source_view#source_buffer#insert
685 "apply rule (∧#i (…) (…));\n\t[\n\t|\n\t]\n");
686 connect_button main#butOr_intro_left
687 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∨#i_l (…));\n");
688 connect_button main#butOr_intro_right
689 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∨#i_r (…));\n");
690 connect_button main#butNot_intro
691 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (¬#i […] (…));\n");
692 connect_button main#butTop_intro
693 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⊤#i);\n");
694 connect_button main#butImpl_elim
695 (fun () -> (s ())#source_view#source_buffer#insert
696 "apply rule (⇒#e (…) (…));\n\t[\n\t|\n\t]\n");
697 connect_button main#butAnd_elim_left
698 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∧#e_l (…));\n");
699 connect_button main#butAnd_elim_right
700 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∧#e_r (…));\n");
701 connect_button main#butOr_elim
702 (fun () -> (s ())#source_view#source_buffer#insert
703 "apply rule (∨#e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
704 connect_button main#butNot_elim
705 (fun () -> (s ())#source_view#source_buffer#insert
706 "apply rule (¬#e (…) (…));\n\t[\n\t|\n\t]\n");
707 connect_button main#butBot_elim
708 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (⊥#e (…));\n");
709 connect_button main#butRAA
710 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (RAA […] (…));\n");
711 connect_button main#butUseLemma
712 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (lem #premises name …);\n");
713 connect_button main#butDischarge
714 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (discharge […]);\n");
716 connect_button main#butForall_intro
717 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∀#i {…} (…));\n");
718 connect_button main#butForall_elim
719 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∀#e {…} (…));\n");
720 connect_button main#butExists_intro
721 (fun () -> (s ())#source_view#source_buffer#insert "apply rule (∃#i {…} (…));\n");
722 connect_button main#butExists_elim
723 (fun () -> (s ())#source_view#source_buffer#insert
724 "apply rule (∃#e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
727 MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
729 | true -> main#toplevel#fullscreen ()
730 | false -> main#toplevel#unfullscreen ());
731 main#fullscreenMenuItem#set_active false;
732 MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
733 ~callback:(function b ->
735 let _status = Interpretations.toggle_active_interpretations s#status b
737 assert false (* MATITA 1.0 ???
738 s#set_grafite_status status*)
740 MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
741 ~callback:(fun enabled -> Interpretations.hide_coercions := enabled);
742 MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
743 ~callback:(fun enabled ->
744 Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
745 main#unicodeAsTexMenuItem#set_active
746 (Helm_registry.get_bool "matita.paste_unicode_as_tex");
748 HLog.set_log_callback (fun tag msg -> GtkThread.async (self#console#log_callback tag) msg);
749 GtkSignal.user_handler :=
751 | MatitaScript.ActionCancelled s -> HLog.error s
753 if not (Helm_registry.get_bool "matita.debug") then
754 (* MatitaScript.current is problably wrong, but what else
756 notify_exn (MatitaScript.current ())#source_view exn
760 match self#chooseFile () with
761 | Some f -> self#loadScript f
763 with MatitaTypes.Cancel -> ()
766 let source_view = (s ())#source_view in
767 source_view#source_buffer#place_cursor
768 (source_view#source_buffer#get_iter_at_mark (`NAME "locked")) in
769 let advance (script: MatitaScript.script) = script#advance (); cursor () in
770 let retract (script: MatitaScript.script) = script#retract (); cursor () in
771 let top (script: MatitaScript.script) = script#goto `Top (); cursor () in
772 let bottom (script: MatitaScript.script) = script#goto `Bottom (); cursor () in
773 let jump (script: MatitaScript.script) = script#goto `Cursor (); cursor () in
774 let advance () = locker (keep_focus advance) (MatitaScript.current ()) in
775 let retract () = locker (keep_focus retract) (MatitaScript.current ()) in
776 let top () = locker (keep_focus top) (MatitaScript.current ()) in
777 let bottom () = locker (keep_focus bottom) (MatitaScript.current ()) in
778 let jump () = locker (keep_focus jump) (MatitaScript.current ()) in
780 self#setQuitCallback (fun () ->
781 let cancel = ref false in
782 MatitaScript.iter_scripts
785 if not (self#closeScript0 script) then
789 connect_button main#scriptAdvanceButton advance;
790 connect_button main#scriptRetractButton retract;
791 connect_button main#scriptTopButton top;
792 connect_button main#scriptBottomButton bottom;
793 connect_button main#scriptJumpButton jump;
794 connect_button main#scriptAbortButton kill_worker;
795 main#scriptAbortButton#set_sensitive false;
796 connect_menu_item main#scriptAdvanceMenuItem advance;
797 connect_menu_item main#scriptRetractMenuItem retract;
798 connect_menu_item main#scriptTopMenuItem top;
799 connect_menu_item main#scriptBottomMenuItem bottom;
800 connect_menu_item main#scriptJumpMenuItem jump;
801 connect_menu_item main#openMenuItem loadScript;
802 connect_menu_item main#saveMenuItem
803 (fun () -> self#saveScript (MatitaScript.current ()));
804 connect_menu_item main#saveAsMenuItem
805 (fun () -> self#saveAsScript (MatitaScript.current ()));
806 connect_menu_item main#newMenuItem self#newScript;
807 connect_menu_item main#closeMenuItem self#closeCurrentScript;
808 connect_menu_item main#showCoercionsGraphMenuItem
809 (fun _ -> MatitaMathView.cicBrowser (Some (`About `Coercions)));
810 connect_menu_item main#showHintsDbMenuItem
811 (fun _ -> MatitaMathView.cicBrowser (Some (`About `Hints)));
812 connect_menu_item main#showTermGrammarMenuItem
813 (fun _ -> MatitaMathView.cicBrowser (Some (`About `Grammar)));
814 connect_menu_item main#showUnicodeTable
815 (fun _ -> MatitaMathView.cicBrowser (Some (`About `TeX)));
817 main#debugMenu#misc#hide ();
819 main#hintNotebook#misc#hide ();
821 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
822 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
823 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
825 (* main win dimension *)
826 let width = Gdk.Screen.width ~screen:(Gdk.Screen.default ()) () in
827 let height = Gdk.Screen.height ~screen:(Gdk.Screen.default ()) () in
828 (* hack for xinerama, no proper support of monitors from lablgtk *)
829 let width = if width > 1600 then width / 2 else width in
830 let height = if height > 1200 then height / 2 else height in
831 let main_w = width * 90 / 100 in
832 let main_h = height * 80 / 100 in
833 let script_w = main_w * 6 / 10 in
834 main#toplevel#resize ~width:main_w ~height:main_h;
835 main#hpaneScriptSequent#set_position script_w;
836 (* math view handling *)
837 connect_menu_item main#newCicBrowserMenuItem (fun () ->
838 ignore(MatitaMathView.cicBrowser None));
839 connect_menu_item main#increaseFontSizeMenuItem
840 MatitaMisc.increase_font_size;
841 connect_menu_item main#decreaseFontSizeMenuItem
842 MatitaMisc.decrease_font_size;
843 connect_menu_item main#normalFontSizeMenuItem
844 MatitaMisc.reset_font_size;
845 ignore (main#scriptNotebook#connect#switch_page (fun page ->
847 current_page <- page;
848 let script = MatitaScript.at_page page in
850 main#undoMenuItem#misc#set_sensitive
851 script#source_view#source_buffer#can_undo ;
852 main#redoMenuItem#misc#set_sensitive
853 script#source_view#source_buffer#can_redo ;
854 main#saveMenuItem#misc#set_sensitive script#has_name))
856 method private externalEditor () =
857 let script = MatitaScript.current () in
858 let source_view = script#source_view in
859 let cmd = Helm_registry.get "matita.external_editor" in
860 (* ZACK uncomment to enable interactive ask of external editor command *)
863 "External editor command:
864 %f will be substitute for the script name,
865 %p for the cursor position in bytes,
866 %l for the execution point in bytes."
868 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
869 ~default:(Helm_registry.get "matita.external_editor") ()
871 let fname = script#filename in
873 source_view#source_buffer#start_iter#get_slice
874 ~stop:(source_view#source_buffer#get_iter_at_mark mark)
876 let locked = `MARK script#locked_mark in
877 let string_pos mark = string_of_int (String.length (slice mark)) in
878 let cursor_pos = string_pos `INSERT in
879 let locked_pos = string_pos locked in
881 Pcre.replace ~pat:"%f" ~templ:fname
882 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
883 (Pcre.replace ~pat:"%l" ~templ:locked_pos
886 let locked_before = slice locked in
887 let locked_offset = (source_view#source_buffer#get_iter_at_mark locked)#offset in
888 ignore (Unix.system cmd);
889 source_view#source_buffer#set_text (HExtlib.input_file fname);
890 let locked_iter = source_view#source_buffer#get_iter (`OFFSET locked_offset) in
891 source_view#source_buffer#move_mark locked locked_iter;
892 source_view#source_buffer#apply_tag script#locked_tag
893 ~start:source_view#source_buffer#start_iter ~stop:locked_iter;
894 let locked_after = slice locked in
898 for i = 0 to String.length locked_before - 1 do
899 if locked_before.[i] <> locked_after.[i] then begin
900 source_view#source_buffer#place_cursor
901 ~where:(source_view#source_buffer#get_iter (`LINEBYTE (!line, !col)));
902 script#goto `Cursor ();
904 end else if locked_before.[i] = '\n' then begin
911 | Invalid_argument _ -> script#goto `Bottom ()
913 method private saveAsScript script =
914 match self#chooseFile ~ok_not_exists:true () with
917 script#assignFileName (Some f);
918 script#saveToFile ();
919 console#message ("'"^f^"' saved.\n");
923 method private saveScript script =
924 if script#has_name then
925 (script#saveToFile ();
926 console#message ("'"^script#filename^"' saved.\n"))
927 else self#saveAsScript script
929 (* returns false if closure is aborted by the user *)
930 method private closeScript0 script =
931 if script#source_view#buffer#modified then
933 ask_unsaved main#toplevel (Filename.basename script#filename)
936 self#saveScript script;
937 save_moo script#status;
940 | `DELETE_EVENT -> false
942 (save_moo script#status; true)
944 method private closeScript page script =
945 if self#closeScript0 script then
947 MatitaScript.destroy page;
948 ignore (main#scriptNotebook#remove_page page)
951 method private closeCurrentScript () =
952 let page = main#scriptNotebook#current_page in
953 let script = MatitaScript.at_page page in
954 self#closeScript page script
956 method private save_page () =
957 if current_page >= 0 then
958 let old_script = MatitaScript.at_page current_page in
959 save_moo0 ~do_clean:false old_script old_script#status
961 method newScript () =
963 let scrolledWindow = GBin.scrolled_window () in
964 let hbox = GPack.hbox () in
965 let tab_label = GMisc.label ~text:"foo" ~packing:hbox#pack () in
967 GMisc.label ~text:"" ~packing:(hbox#pack ~expand:true ~fill:true) () in
969 GButton.button ~relief:`NONE ~packing:hbox#pack () in
970 let image = GMisc.image ~stock:`CLOSE ~icon_size:`MENU () in
971 closebutton#set_image image#coerce;
972 let script = MatitaScript.script ~parent:scrolledWindow ~tab_label () in
973 ignore (main#scriptNotebook#prepend_page ~tab_label:hbox#coerce
974 scrolledWindow#coerce);
975 ignore (closebutton#connect#clicked (fun () ->
977 (main#scriptNotebook#page_num scrolledWindow#coerce) script));
978 main#scriptNotebook#goto_page 0;
979 sequents_viewer#reset;
980 sequents_viewer#load_logo;
981 let browser_observer _ = MatitaMathView.refresh_all_browsers () in
982 let sequents_observer status =
983 sequents_viewer#reset;
984 match status#ng_mode with
986 sequents_viewer#nload_sequents status;
989 Continuationals.Stack.find_goal status#stack
991 sequents_viewer#goto_sequent status goal
992 with Failure _ -> ());
993 | `CommandMode -> sequents_viewer#load_logo
995 script#addObserver sequents_observer;
996 script#addObserver browser_observer
998 method kill_worker () = !ref_kill_worker ()
1000 method loadScript file =
1001 let page = main#scriptNotebook#current_page in
1002 let script = MatitaScript.at_page page in
1003 if script#source_view#buffer#modified || script#has_name then
1005 let script = MatitaScript.current () in
1006 let source_view = script#source_view in
1008 script#assignFileName (Some file);
1009 let file = script#filename in
1011 if Sys.file_exists file then file
1012 else BuildTimeConf.script_template
1014 source_view#source_buffer#begin_not_undoable_action ();
1015 script#loadFromFile content;
1016 source_view#source_buffer#end_not_undoable_action ();
1017 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1018 source_view#buffer#place_cursor source_view#buffer#start_iter;
1019 console#message ("'"^file^"' loaded.");
1020 self#_enableSaveTo file
1022 method private _enableSaveTo _file =
1023 self#main#saveMenuItem#misc#set_sensitive true
1025 method private console = console
1026 method private findRepl = findRepl
1029 method private addKeyBinding key ?modifiers callback =
1030 (* List.iter (fun evbox -> add_key_binding key callback evbox) *)
1031 List.iter (fun evbox -> connect_key evbox#event key ?modifiers callback)
1034 method private setQuitCallback callback =
1035 connect_menu_item main#quitMenuItem callback;
1036 ignore (main#toplevel#event#connect#delete
1037 (fun _ -> callback ();true));
1038 self#addKeyBinding GdkKeysyms._q callback
1040 method private chooseFileOrDir ok_not_exists only_directory =
1041 let fileSel = GWindow.file_chooser_dialog
1043 ~title:"Select file"
1048 fileSel#add_select_button_stock `OPEN `OK;
1049 fileSel#add_button_stock `CANCEL `CANCEL;
1050 ignore (fileSel#set_current_folder(Sys.getcwd ())) ;
1053 match fileSel#run () with
1055 (match fileSel#filename with
1058 if Sys.file_exists fname then
1060 if HExtlib.is_regular fname && not (only_directory) then
1062 else if only_directory && HExtlib.is_dir fname then
1067 else if ok_not_exists then Some fname else aux ())
1069 | `DELETE_EVENT -> None in
1071 fileSel#destroy () ;
1074 method private chooseFile ?(ok_not_exists = false) () =
1075 self#chooseFileOrDir ok_not_exists false
1077 method private chooseDir ?(ok_not_exists = false) () =
1078 (* we should check that this is a directory *)
1079 self#chooseFileOrDir ok_not_exists true
1084 let g = new gui () in
1085 let rg = (g :> MatitaGuiTypes.gui) in
1086 MatitaMisc.set_gui rg;
1090 let instance = singleton gui
1092 let non p x = not (p x)
1095 let cols = new GTree.column_list in
1096 let id_col = cols#add Gobject.Data.string in
1097 let dsc_col = cols#add Gobject.Data.string in
1098 let interp_no_col = cols#add Gobject.Data.int in
1099 let tree_store = GTree.tree_store cols in
1100 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1101 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1102 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1103 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1104 fun tree_view choices ->
1107 tree_view#set_model (Some (tree_store :> GTree.model));
1108 ignore (tree_view#append_column id_view_col);
1109 ignore (tree_view#append_column dsc_view_col);
1110 let name_of_interp =
1111 (* try to find a reasonable name for an interpretation *)
1115 List.assoc "0" interp
1117 incr idx; string_of_int !idx
1119 tree_store#clear ();
1120 let idx = ref ~-1 in
1124 let interp_row = tree_store#append () in
1125 tree_store#set ~row:interp_row ~column:id_col
1126 (name_of_interp interp);
1127 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1130 let row = tree_store#append ~parent:interp_row () in
1131 tree_store#set ~row ~column:id_col id;
1132 tree_store#set ~row ~column:dsc_col dsc;
1133 tree_store#set ~row ~column:interp_no_col !idx)
1137 method get_interp_no tree_path =
1138 let iter = tree_store#get_iter tree_path in
1139 tree_store#get ~row:iter ~column:interp_no_col
1143 let interactive_string_choice
1144 text prefix_len ?(title = "") ?msg:(_ = "") () ~id:_ locs uris
1146 GtkThread.sync (fun _ ->
1147 let dialog = new uriChoiceDialog () in
1148 dialog#uriEntryHBox#misc#hide ();
1149 dialog#uriChoiceSelectedButton#misc#hide ();
1150 dialog#uriChoiceAutoButton#misc#hide ();
1151 dialog#uriChoiceConstantsButton#misc#hide ();
1152 dialog#uriChoiceTreeView#selection#set_mode
1153 (`SINGLE :> Gtk.Tags.selection_mode);
1154 let model = new stringListModel dialog#uriChoiceTreeView in
1155 let choices = ref [] in
1156 dialog#uriChoiceDialog#set_title title;
1157 let hack_len = MatitaGtkMisc.utf8_string_length text in
1158 let rec colorize acc_len = function
1160 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1161 escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1163 let start, stop = HExtlib.loc_of_floc he in
1164 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1165 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1166 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1167 escape_pango_markup str1 ^ "<b>" ^
1168 escape_pango_markup str2 ^ "</b>" ^
1171 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1172 Printf.eprintf "(%d,%d)" start stop) locs; *)
1176 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1179 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1180 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1181 Printf.eprintf "(%d,%d)" start stop) locs;
1182 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1183 dialog#uriChoiceLabel#set_use_markup true;
1184 let txt = colorize 0 locs in
1185 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1186 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1188 dialog#uriChoiceLabel#set_label txt;
1189 List.iter model#easy_append uris;
1190 connect_button dialog#uriChoiceForwardButton (fun _ ->
1191 match model#easy_selection () with
1193 | uris -> choices := uris; dialog#toplevel#response `OK);
1194 connect_button dialog#uriChoiceAbortButton (fun _ -> dialog#toplevel#response `DELETE_EVENT);
1195 dialog#uriChoiceDialog#show ();
1197 match dialog#toplevel#run () with
1198 | `DELETE_EVENT -> dialog#toplevel#destroy() ; raise MatitaTypes.Cancel
1200 | _ -> assert false in
1201 dialog#toplevel#destroy () ;
1204 let interactive_interp_choice () text prefix_len choices =
1205 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1206 let filter_choices filter =
1207 let rec is_compatible filter =
1210 | ([],_,_)::tl -> is_compatible filter tl
1211 | (loc::tlloc,id,dsc)::tl ->
1213 if List.assoc (loc,id) filter = dsc then
1214 is_compatible filter ((tlloc,id,dsc)::tl)
1220 List.filter (fun (_,interp) -> is_compatible filter interp)
1222 let rec get_choices loc id =
1227 List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1229 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1231 let example_interp =
1235 let ask_user id locs choices =
1236 interactive_string_choice
1238 ~title:"Ambiguous input"
1239 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1241 let rec classify ids filter partial_interpretations =
1243 [] -> List.map fst partial_interpretations
1244 | ([],_,_)::tl -> classify tl filter partial_interpretations
1245 | (loc::tlloc,id,dsc)::tl ->
1246 let choices = get_choices loc id partial_interpretations in
1249 [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1252 match ask_user id [loc] choices with
1256 let filter = ((loc,id),chosen_dsc)::filter in
1257 let compatible_interps = filter_choices filter partial_interpretations in
1258 classify ((tlloc,id,dsc)::tl) filter compatible_interps
1260 let enumerated_choices =
1261 let idx = ref ~-1 in
1262 List.map (fun interp -> incr idx; !idx,interp) choices
1264 classify example_interp [] enumerated_choices
1267 (* disambiguator callbacks *)
1268 Disambiguate.set_choose_uris_callback
1269 (fun ~selection_mode ?ok ?enable_button_for_non_vars:(_=false) ~title ~msg ->
1270 interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1271 Disambiguate.set_choose_interp_callback (interactive_interp_choice ());
1272 (* gtk initialization *)
1273 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file (* loads gtk rc *)