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 exception Found of int
36 let gui_instance = ref None
38 class type browserWin =
39 (* this class exists only because GEdit.combo_box_entry is not supported by
40 * lablgladecc :-(((( *)
42 inherit MatitaGeneratedGui.browserWin
43 method browserUri: GEdit.combo_box_entry
46 class console ~(buffer: GText.buffer) () =
48 val error_tag = buffer#create_tag [ `FOREGROUND "red" ]
49 val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
50 val message_tag = buffer#create_tag []
51 val debug_tag = buffer#create_tag [ `FOREGROUND "#888888" ]
52 method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
53 method error s = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
54 method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
55 method debug s = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
57 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
58 method log_callback (tag: HLog.log_tag) s =
60 | `Debug -> self#debug (s ^ "\n")
61 | `Error -> self#error (s ^ "\n")
62 | `Message -> self#message (s ^ "\n")
63 | `Warning -> self#warning (s ^ "\n")
66 let clean_current_baseuri grafite_status =
68 let baseuri = GrafiteTypes.get_string_option grafite_status "baseuri" in
69 LibraryClean.clean_baseuris [baseuri]
70 with GrafiteTypes.Option_error _ -> ()
72 let ask_and_save_moo_if_needed parent fname lexicon_status grafite_status =
74 try Some (GrafiteTypes.get_string_option grafite_status "baseuri")
75 with GrafiteTypes.Option_error _ -> None
77 if (MatitaScript.current ())#eos &&
78 grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof &&
82 let baseuri = match baseuri with Some b -> b | None -> assert false in
84 LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri
88 LibraryMisc.lexicon_file_of_baseuri
89 ~must_exist:false ~baseuri ~writable:true
91 GrafiteMarshal.save_moo moo_fname
92 grafite_status.GrafiteTypes.moo_content_rev;
93 LexiconMarshal.save_lexicon lexicon_fname
94 lexicon_status.LexiconEngine.lexicon_content_rev
98 MatitaGtkMisc.ask_confirmation
99 ~title:"A .moo can be generated"
100 ~message:(Printf.sprintf
101 "%s can be generated for %s.\n<i>Should I generate it?</i>"
102 (Filename.basename moo_fname) (Filename.basename fname))
109 | `CANCEL -> raise MatitaTypes.Cancel
114 clean_current_baseuri grafite_status
118 clean_current_baseuri grafite_status
120 let ask_unsaved parent =
121 MatitaGtkMisc.ask_confirmation
122 ~parent ~title:"Unsaved work!"
123 ~message:("Your work is <b>unsaved</b>!\n\n"^
124 "<i>Do you want to save the script before continuing?</i>")
127 class interpErrorModel =
128 let cols = new GTree.column_list in
129 let id_col = cols#add Gobject.Data.string in
130 let dsc_col = cols#add Gobject.Data.string in
131 let interp_no_col = cols#add Gobject.Data.caml in
132 let tree_store = GTree.tree_store cols in
133 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
134 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
135 let id_view_col = GTree.view_column ~renderer:id_renderer () in
136 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
137 fun (tree_view: GTree.view) choices ->
140 tree_view#set_model (Some (tree_store :> GTree.model));
141 ignore (tree_view#append_column id_view_col);
142 ignore (tree_view#append_column dsc_view_col);
144 let idx1 = ref ~-1 in
149 if List.length choices = 1 then
152 (let loc_row = tree_store#append () in
155 [passes,envs_and_diffs,_,_] ->
156 tree_store#set ~row:loc_row ~column:id_col
157 ("Error location " ^ string_of_int (!idx1+1) ^
158 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
160 String.concat " " (List.map string_of_int passes) ^
162 tree_store#set ~row:loc_row ~column:interp_no_col
165 tree_store#set ~row:loc_row ~column:id_col
166 ("Error location " ^ string_of_int (!idx1+1));
167 tree_store#set ~row:loc_row ~column:interp_no_col
171 let idx2 = ref ~-1 in
173 (fun passes,envs_and_diffs,_,_ ->
176 if List.length lll = 1 then
179 let msg_row = tree_store#append ?parent:loc_row () in
180 (tree_store#set ~row:msg_row ~column:id_col
181 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
182 string_of_int (!idx2+1) ^
184 String.concat " " (List.map string_of_int passes) ^
186 tree_store#set ~row:msg_row ~column:interp_no_col
187 (!idx1,Some !idx2,None);
189 let idx3 = ref ~-1 in
191 (fun (passes,env,_) ->
194 match envs_and_diffs with
196 let interp_row = tree_store#append ?parent:msg_row () in
197 tree_store#set ~row:interp_row ~column:id_col
198 ("Interpretation " ^ string_of_int (!idx3+1) ^
200 String.concat " " (List.map string_of_int passes) ^
202 tree_store#set ~row:interp_row ~column:interp_no_col
203 (!idx1,Some !idx2,Some !idx3);
210 let row = tree_store#append ?parent:interp_row () in
211 tree_store#set ~row ~column:id_col id;
212 tree_store#set ~row ~column:dsc_col dsc;
213 tree_store#set ~row ~column:interp_no_col
214 (!idx1,Some !idx2,Some !idx3)
218 if List.length lll > 1 then
220 (fun p -> tree_view#expand_row (tree_store#get_path p))
224 method get_interp_no tree_path =
225 let iter = tree_store#get_iter tree_path in
226 tree_store#get ~row:iter ~column:interp_no_col
230 let rec interactive_error_interp ?(all_passes=false) (source_buffer:GSourceView.source_buffer) notify_exn offset errorll
232 assert (List.flatten errorll <> []);
234 let remove_non_significant =
235 List.filter (fun (_env,_diff,_loc,_msg,significant) -> significant) in
236 if all_passes then errorll else
237 let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
238 (* We remove passes 1,2 and 5,6 *)
241 ::(remove_non_significant (safe_list_nth errorll 2))
242 ::(remove_non_significant (safe_list_nth errorll 3))
245 if List.flatten res <> [] then res
247 (* all errors (if any) are not significant: we keep them *)
250 ::(safe_list_nth errorll 2)
251 ::(safe_list_nth errorll 3)
254 if List.flatten res <> [] then
257 "All disambiguation errors are not significant. Showing them anyway." ;
263 "No errors in phases 2 and 3. Showing all errors in all phases" ;
274 (fun (env,diff,offset,msg,significant) ->
275 offset, [[!pass], [[!pass], env, diff], msg, significant]) l
277 (* Here we are doing a stable sort and list_uniq returns the latter
278 "equal" element. I.e. we are showing the error corresponding to the
279 most advanced disambiguation pass *)
281 let choices_compare (o1,_) (o2,_) = compare o1 o2 in
282 let choices_compare_by_passes (p1,_,_,_) (p2,_,_,_) =
288 | (o1,res1)::(o2,res2)::tl when o1 = o2 ->
289 let merge_by_name errors =
290 let merge_by_env errors =
291 let choices_compare_by_env (_,e1,_) (_,e2,_) = compare e1 e2 in
292 let choices_compare_by_passes (p1,_,_) (p2,_,_) =
294 let rec uniq_by_env =
298 | (p1,e1,_)::(p2,e2,d2)::tl when e1 = e2 ->
299 uniq_by_env ((p1@p2,e2,d2) :: tl)
300 | h1::tl -> h1 :: uniq_by_env tl
302 List.sort choices_compare_by_passes
303 (uniq_by_env (List.stable_sort choices_compare_by_env errors))
305 let choices_compare_by_msg (_,_,m1,_) (_,_,m2,_) =
306 compare (Lazy.force m1) (Lazy.force m2) in
307 let rec uniq_by_msg =
311 | (p1,i1,m1,s1)::(p2,i2,m2,s2)::tl
312 when Lazy.force m1 = Lazy.force m2 && s1 = s2 ->
313 uniq_by_msg ((p1@p2,merge_by_env (i1@i2),m2,s2) :: tl)
314 | h1::tl -> h1 :: uniq_by_msg tl
316 List.sort choices_compare_by_msg
317 (uniq_by_msg (List.stable_sort choices_compare_by_msg errors))
319 let res = merge_by_name (res1@res2) in
320 uniq ((o1,res) :: tl)
321 | h1::tl -> h1 :: uniq tl
323 (* Errors in phase 3 that are not also in phase 4 are filtered out *)
324 let filter_phase_3 choices =
325 if all_passes then choices
330 (loffset,messages) ->
331 let filtered_messages =
338 if filtered_messages = [] then
341 Some (loffset,filtered_messages))
346 (List.map (fun o,l -> o,List.sort choices_compare_by_passes l)
347 (uniq (List.stable_sort choices_compare choices)))
351 | [loffset,[_,envs_and_diffs,msg,significant]] ->
352 let _,env,diff = List.hd envs_and_diffs in
354 (GrafiteDisambiguator.DisambiguationError
355 (offset,[[env,diff,loffset,msg,significant]]));
357 let dialog = new disambiguationErrors () in
358 dialog#check_widgets ();
360 dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
361 let model = new interpErrorModel dialog#treeview choices in
362 dialog#disambiguationErrors#set_title "Disambiguation error";
363 dialog#disambiguationErrorsLabel#set_label
364 "Click on an error to see the corresponding message:";
365 ignore (dialog#treeview#connect#cursor_changed
368 match fst (dialog#treeview#get_cursor ()) with
371 let idx1,idx2,idx3 = model#get_interp_no tree_path in
372 let loffset,lll = List.nth choices idx1 in
373 let _,envs_and_diffs,msg,significant =
375 Some idx2 -> List.nth lll idx2
377 [],[],lazy "Multiple error messages. Please select one.",true
381 Some idx3 -> List.nth envs_and_diffs idx3
382 | None -> [],[],[] (* dymmy value, used *) in
383 let script = MatitaScript.current () in
384 let error_tag = script#error_tag in
385 source_buffer#remove_tag error_tag
386 ~start:source_buffer#start_iter
387 ~stop:source_buffer#end_iter;
389 (GrafiteDisambiguator.DisambiguationError
390 (offset,[[env,diff,loffset,msg,significant]]))
393 dialog#disambiguationErrors#destroy ();
396 let fail _ = return () in
397 ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
398 connect_button dialog#disambiguationErrorsOkButton
401 match fst (dialog#treeview#get_cursor ()) with
404 let idx1,idx2,idx3 = model#get_interp_no tree_path in
407 Some idx2, Some idx3 ->
408 let _,lll = List.nth choices idx1 in
409 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
410 let _,_,diff = List.nth envs_and_diffs idx3 in
412 | _,_ -> assert false
419 DisambiguatePp.pp_environment
420 (DisambiguateTypes.Environment.add k value
421 DisambiguateTypes.Environment.empty))
426 (source_buffer#get_iter_at_mark
427 (`NAME "beginning_of_statement")) newtxt ;
430 connect_button dialog#disambiguationErrorsMoreErrors
431 (fun _ -> return () ;
432 interactive_error_interp ~all_passes:true source_buffer notify_exn offset
434 connect_button dialog#disambiguationErrorsCancelButton fail;
435 dialog#disambiguationErrors#show ();
439 (** Selection handling
440 * Two clipboards are used: "clipboard" and "primary".
441 * "primary" is used by X, when you hit the middle button mouse is content is
442 * pasted between applications. In Matita this selection always contain the
443 * textual version of the selected term.
444 * "clipboard" is used inside Matita only and support ATM two different targets:
445 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
450 (* creation order _is_ relevant for windows placement *)
451 let main = new mainWin () in
452 let fileSel = new fileSelectionWin () in
453 let findRepl = new findReplWin () in
454 let develList = new develListWin () in
455 let newDevel = new newDevelWin () in
456 let keyBindingBoxes = (* event boxes which should receive global key events *)
457 [ main#mainWinEventBox ]
459 let console = new console ~buffer:main#logTextView#buffer () in
460 let (source_view: GSourceView.source_view) =
461 GSourceView.source_view
463 ~insert_spaces_instead_of_tabs:true ~tabs_width:2
464 ~margin:80 ~show_margin:true
466 ~packing:main#scriptScrolledWin#add
469 let default_font_size =
470 Helm_registry.get_opt_default Helm_registry.int
471 ~default:BuildTimeConf.default_font_size "matita.font_size"
473 let source_buffer = source_view#source_buffer in
475 val mutable chosen_file = None
476 val mutable _ok_not_exists = false
477 val mutable _only_directory = false
478 val mutable script_fname = None
479 val mutable font_size = default_font_size
480 val mutable next_devel_must_contain = None
481 val mutable next_ligatures = []
482 val clipboard = GData.clipboard Gdk.Atom.clipboard
483 val primary = GData.clipboard Gdk.Atom.primary
486 (* glade's check widgets *)
487 List.iter (fun w -> w#check_widgets ())
488 (let c w = (w :> <check_widgets: unit -> unit>) in
489 [ c fileSel; c main; c findRepl]);
491 List.iter (* global key bindings *)
492 (fun (key, callback) -> self#addKeyBinding key callback)
495 toggle_win ~check:main#showProofMenuItem proof#proofWin;
497 toggle_win ~check:main#showCheckMenuItem check#checkWin;
501 let parse_txt_file file =
502 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
503 let l_rev = ref [] in
506 l_rev := input_line ch :: !l_rev;
515 ~authors:(parse_txt_file "AUTHORS")
516 (*~comments:"comments"*)
517 ~copyright:"Copyright (C) 2005, the HELM team"
518 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
519 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
521 ~version:BuildTimeConf.version
522 ~website:"http://helm.cs.unibo.it"
525 connect_menu_item main#contentsMenuItem (fun () ->
527 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
529 ignore (Sys.command cmd));
530 connect_menu_item main#aboutMenuItem about_dialog#present;
532 let show_find_Repl () =
533 findRepl#toplevel#misc#show ();
534 findRepl#toplevel#misc#grab_focus ()
536 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
538 let highlight start end_ =
539 source_buffer#move_mark `INSERT ~where:start;
540 source_buffer#move_mark `SEL_BOUND ~where:end_;
541 source_view#scroll_mark_onscreen `INSERT
543 let text = findRepl#findEntry#text in
544 let iter = source_buffer#get_iter `SEL_BOUND in
545 match iter#forward_search text with
547 (match source_buffer#start_iter#forward_search text with
549 | Some (start,end_) -> highlight start end_)
550 | Some (start,end_) -> highlight start end_
553 let text = findRepl#replaceEntry#text in
554 let ins = source_buffer#get_iter `INSERT in
555 let sel = source_buffer#get_iter `SEL_BOUND in
556 if ins#compare sel < 0 then
558 ignore(source_buffer#delete_selection ());
559 source_buffer#insert text
562 connect_button findRepl#findButton find_forward;
563 connect_button findRepl#findReplButton replace;
564 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
565 ignore(findRepl#toplevel#event#connect#delete
566 ~callback:(fun _ -> hide_find_Repl ();true));
569 (* phase 1: we save the actual status of the marks and we undo *)
570 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
571 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
572 let locked_iter_offset = locked_iter#offset in
575 (source_view#buffer#create_mark ~name:"lock_point"
576 ~left_gravity:true locked_iter) in
577 source_view#source_buffer#undo ();
578 (* phase 2: we save the cursor position and we redo, restoring
579 the previous status of all the marks *)
580 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
583 (source_view#buffer#create_mark ~name:"undo_point"
584 ~left_gravity:true cursor_iter)
586 source_view#source_buffer#redo ();
587 let mark_iter = source_view#buffer#get_iter_at_mark mark in
588 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
589 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
590 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
591 source_view#buffer#delete_mark mark;
592 source_view#buffer#delete_mark mark2;
593 (* phase 3: if after the undo the cursor was in the locked area,
594 then we move it there again and we perform a goto *)
595 if mark_iter#offset < locked_iter_offset then
597 source_view#buffer#move_mark `INSERT ~where:mark_iter;
598 (MatitaScript.current ())#goto `Cursor ();
600 (* phase 4: we perform again the undo. This time we are sure that
601 the text to undo is not locked *)
602 source_view#source_buffer#undo ();
603 source_view#misc#grab_focus () in
606 (* phase 1: we save the actual status of the marks, we redo and
608 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
609 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
610 let locked_iter_offset = locked_iter#offset in
613 (source_view#buffer#create_mark ~name:"lock_point"
614 ~left_gravity:true locked_iter) in
615 source_view#source_buffer#redo ();
616 source_view#source_buffer#undo ();
617 (* phase 2: we save the cursor position and we restore
618 the previous status of all the marks *)
619 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
622 (source_view#buffer#create_mark ~name:"undo_point"
623 ~left_gravity:true cursor_iter)
625 let mark_iter = source_view#buffer#get_iter_at_mark mark in
626 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
627 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
628 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
629 source_view#buffer#delete_mark mark;
630 source_view#buffer#delete_mark mark2;
631 (* phase 3: if after the undo the cursor is in the locked area,
632 then we move it there again and we perform a goto *)
633 if mark_iter#offset < locked_iter_offset then
635 source_view#buffer#move_mark `INSERT ~where:mark_iter;
636 (MatitaScript.current ())#goto `Cursor ();
638 (* phase 4: we perform again the redo. This time we are sure that
639 the text to redo is not locked *)
640 source_view#source_buffer#redo ();
641 source_view#misc#grab_focus ()
643 connect_menu_item main#undoMenuItem safe_undo;
644 ignore(source_view#source_buffer#connect#can_undo
645 ~callback:main#undoMenuItem#misc#set_sensitive);
646 connect_menu_item main#redoMenuItem safe_redo;
647 ignore(source_view#source_buffer#connect#can_redo
648 ~callback:main#redoMenuItem#misc#set_sensitive);
649 ignore(source_view#connect#after#populate_popup
650 ~callback:(fun pre_menu ->
651 let menu = new GMenu.menu pre_menu in
652 let menuItems = menu#children in
653 let undoMenuItem, redoMenuItem =
655 [undo;redo;sep1;cut;copy;paste;delete;sep2;
656 selectall;sep3;inputmethod;insertunicodecharacter] ->
657 List.iter menu#remove [ copy; cut; delete; paste ];
659 | _ -> assert false in
661 let i = ref 2 in (* last occupied position *)
662 fun ?label ?stock () ->
664 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
667 let copy = add_menu_item ~stock:`COPY () in
668 let cut = add_menu_item ~stock:`CUT () in
669 let delete = add_menu_item ~stock:`DELETE () in
670 let paste = add_menu_item ~stock:`PASTE () in
671 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
672 copy#misc#set_sensitive self#canCopy;
673 cut#misc#set_sensitive self#canCut;
674 delete#misc#set_sensitive self#canDelete;
675 paste#misc#set_sensitive self#canPaste;
676 paste_pattern#misc#set_sensitive self#canPastePattern;
677 connect_menu_item copy self#copy;
678 connect_menu_item cut self#cut;
679 connect_menu_item delete self#delete;
680 connect_menu_item paste self#paste;
681 connect_menu_item paste_pattern self#pastePattern;
682 let new_undoMenuItem =
683 GMenu.image_menu_item
684 ~image:(GMisc.image ~stock:`UNDO ())
687 ~packing:(menu#insert ~pos:0) () in
688 new_undoMenuItem#misc#set_sensitive
689 (undoMenuItem#misc#get_flag `SENSITIVE);
690 menu#remove (undoMenuItem :> GMenu.menu_item);
691 connect_menu_item new_undoMenuItem safe_undo;
692 let new_redoMenuItem =
693 GMenu.image_menu_item
694 ~image:(GMisc.image ~stock:`REDO ())
697 ~packing:(menu#insert ~pos:1) () in
698 new_redoMenuItem#misc#set_sensitive
699 (redoMenuItem#misc#get_flag `SENSITIVE);
700 menu#remove (redoMenuItem :> GMenu.menu_item);
701 connect_menu_item new_redoMenuItem safe_redo));
703 connect_menu_item main#editMenu (fun () ->
704 main#copyMenuItem#misc#set_sensitive self#canCopy;
705 main#cutMenuItem#misc#set_sensitive self#canCut;
706 main#deleteMenuItem#misc#set_sensitive self#canDelete;
707 main#pasteMenuItem#misc#set_sensitive self#canPaste;
708 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
709 connect_menu_item main#copyMenuItem self#copy;
710 connect_menu_item main#cutMenuItem self#cut;
711 connect_menu_item main#deleteMenuItem self#delete;
712 connect_menu_item main#pasteMenuItem self#paste;
713 connect_menu_item main#pastePatternMenuItem self#pastePattern;
714 connect_menu_item main#selectAllMenuItem (fun () ->
715 source_buffer#move_mark `INSERT source_buffer#start_iter;
716 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
717 connect_menu_item main#findReplMenuItem show_find_Repl;
718 connect_menu_item main#externalEditorMenuItem self#externalEditor;
719 connect_menu_item main#ligatureButton self#nextLigature;
720 ignore (findRepl#findEntry#connect#activate find_forward);
721 (* interface lockers *)
723 main#buttonsToolbar#misc#set_sensitive false;
724 develList#buttonsHbox#misc#set_sensitive false;
725 main#scriptMenu#misc#set_sensitive false;
726 source_view#set_editable false
729 main#buttonsToolbar#misc#set_sensitive true;
730 develList#buttonsHbox#misc#set_sensitive true;
731 main#scriptMenu#misc#set_sensitive true;
732 source_view#set_editable true;
733 (*The next line seems sufficient to avoid some unknown race condition *)
734 GtkThread.sync (fun () -> ()) ()
736 let worker_thread = ref None in
738 let floc, msg = MatitaExcPp.to_string exn in
743 let (x, y) = HExtlib.loc_of_floc floc in
744 let script = MatitaScript.current () in
745 let locked_mark = script#locked_mark in
746 let error_tag = script#error_tag in
748 (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
749 let x' = baseoffset + x in
750 let y' = baseoffset + y in
751 let x_iter = source_buffer#get_iter (`OFFSET x') in
752 let y_iter = source_buffer#get_iter (`OFFSET y') in
753 source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
755 id := Some (source_buffer#connect#changed ~callback:(fun () ->
756 source_buffer#remove_tag error_tag
757 ~start:source_buffer#start_iter
758 ~stop:source_buffer#end_iter;
760 | None -> assert false (* a race condition occurred *)
762 (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
763 source_buffer#place_cursor
764 (source_buffer#get_iter (`OFFSET x'));
775 | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
777 interactive_error_interp source_buffer notify_exn offset
780 exc -> notify_exn exc);
786 worker_thread := Some (Thread.create thread_main ()) in
788 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
789 let interrupt = ref None in
790 let old_callback = ref (function _ -> ()) in
791 let force_interrupt n =
792 (* This function is called just before the thread's timeslice ends *)
794 if Some(Thread.id(Thread.self())) = !interrupt then
795 (interrupt := None; raise Sys.Break) in
797 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
798 Sys.Signal_handle f -> old_callback := f
800 | Sys.Signal_default -> assert false
803 match !worker_thread with
805 | Some t -> interrupt := Some (Thread.id t) in
809 f (); source_view#misc#grab_focus ()
811 exc -> source_view#misc#grab_focus (); raise exc in
812 (* developments win *)
814 new MatitaGtkMisc.multiStringListModel
815 ~cols:2 develList#developmentsTreeview
817 let refresh_devels_win () =
818 model#list_store#clear ();
820 (fun (name, root) -> model#easy_mappend [name;root])
821 (MatitamakeLib.list_known_developments ())
823 let get_devel_selected () =
824 match model#easy_mselection () with
825 | [[name;_]] -> MatitamakeLib.development_for_name name
829 while Glib.Main.pending () do
830 ignore(Glib.Main.iteration false);
833 connect_button develList#newButton
835 next_devel_must_contain <- None;
836 newDevel#toplevel#misc#show());
837 connect_button develList#deleteButton
839 (match get_devel_selected () with
841 | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
842 refresh_devels_win ()));
843 connect_button develList#buildButton
845 match get_devel_selected () with
849 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
852 connect_button develList#cleanButton
854 match get_devel_selected () with
858 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
861 connect_button develList#publishButton
863 match get_devel_selected () with
866 let publish = locker (fun () ->
867 MatitamakeLib.publish_development_in_bg refresh d) in
868 ignore(publish ())));
869 connect_button develList#graphButton (fun () ->
870 match get_devel_selected () with
873 (match MatitamakeLib.dot_for_development d with
876 let browser = MatitaMathView.cicBrowser () in
877 browser#load (`Development
878 (MatitamakeLib.name_for_development d))));
879 connect_button develList#closeButton
880 (fun () -> develList#toplevel#misc#hide());
881 ignore(develList#toplevel#event#connect#delete
882 (fun _ -> develList#toplevel#misc#hide();true));
883 connect_menu_item main#developmentsMenuItem
884 (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
886 (* add development win *)
887 let check_if_root_contains root =
888 match next_devel_must_contain with
891 let is_prefix_of d1 d2 =
892 let len1 = String.length d1 in
893 let len2 = String.length d2 in
897 let pref = String.sub d2 0 len1 in
900 is_prefix_of root path
902 connect_button newDevel#addButton
904 let name = newDevel#nameEntry#text in
905 let root = newDevel#rootEntry#text in
906 if check_if_root_contains root then
908 ignore (MatitamakeLib.initialize_development name root);
909 refresh_devels_win ();
910 newDevel#nameEntry#set_text "";
911 newDevel#rootEntry#set_text "";
912 newDevel#toplevel#misc#hide()
915 HLog.error ("The selected root does not contain " ^
916 match next_devel_must_contain with
918 | _ -> assert false));
919 connect_button newDevel#chooseRootButton
921 let path = self#chooseDir () in
923 | Some path -> newDevel#rootEntry#set_text path
925 connect_button newDevel#cancelButton
926 (fun () -> newDevel#toplevel#misc#hide ());
927 ignore(newDevel#toplevel#event#connect#delete
928 (fun _ -> newDevel#toplevel#misc#hide();true));
930 (* file selection win *)
931 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
932 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
935 fileSel#fileSelectionWin#misc#hide ();
940 let fname = fileSel#fileSelectionWin#filename in
941 if Sys.file_exists fname then
943 if HExtlib.is_regular fname && not (_only_directory) then
945 else if _only_directory && HExtlib.is_dir fname then
950 if _ok_not_exists then
953 | `CANCEL -> return None
955 | `DELETE_EVENT -> return None));
957 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
959 let adj = main#logScrolledWin#vadjustment in
960 ignore (adj#connect#changed
961 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
962 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
964 let module A = GrafiteAst in
965 let hole = CicNotationPt.UserInput in
966 let loc = HExtlib.dummy_floc in
968 if (MatitaScript.current ())#onGoingProof () then
969 (MatitaScript.current ())#advance
971 ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
972 ~lazy_term_pp:CicNotationPp.pp_term ast)
975 let tac_w_term ast _ =
976 if (MatitaScript.current ())#onGoingProof () then
977 let buf = source_buffer in
978 buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
980 ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
981 ~lazy_term_pp:CicNotationPp.pp_term ast)
984 connect_button tbar#introsButton (tac (A.Intros (loc, (None, []))));
985 connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
986 connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
987 connect_button tbar#elimButton (tac_w_term
988 (let pattern = None, [], Some CicNotationPt.UserInput in
989 A.Elim (loc, hole, None, pattern, (None, []))));
990 connect_button tbar#elimTypeButton (tac_w_term
991 (A.ElimType (loc, hole, None, (None, []))));
992 connect_button tbar#splitButton (tac (A.Split loc));
993 connect_button tbar#leftButton (tac (A.Left loc));
994 connect_button tbar#rightButton (tac (A.Right loc));
995 connect_button tbar#existsButton (tac (A.Exists loc));
996 connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
997 connect_button tbar#symmetryButton (tac (A.Symmetry loc));
998 connect_button tbar#transitivityButton
999 (tac_w_term (A.Transitivity (loc, hole)));
1000 connect_button tbar#assumptionButton (tac (A.Assumption loc));
1001 connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
1002 connect_button tbar#autoButton (tac (A.AutoBatch (loc,[])));
1003 MatitaGtkMisc.toggle_widget_visibility
1004 ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
1005 ~check:main#tacticsBarMenuItem;
1006 let module Hr = Helm_registry in
1008 not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
1010 main#tacticsBarMenuItem#set_active false;
1011 MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
1013 | true -> main#toplevel#fullscreen ()
1014 | false -> main#toplevel#unfullscreen ());
1015 main#fullscreenMenuItem#set_active false;
1016 MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
1019 CicNotation.set_active_notations
1020 (List.map fst (CicNotation.get_all_notations ()))
1022 CicNotation.set_active_notations []);
1023 MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
1024 ~callback:(fun enabled -> Acic2content.hide_coercions := enabled);
1025 MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
1026 ~callback:(fun enabled ->
1027 Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
1028 if not (Helm_registry.has "matita.paste_unicode_as_tex") then
1029 Helm_registry.set_bool "matita.paste_unicode_as_tex" true;
1030 main#unicodeAsTexMenuItem#set_active
1031 (Helm_registry.get_bool "matita.paste_unicode_as_tex");
1033 HLog.set_log_callback self#console#log_callback;
1034 GtkSignal.user_handler :=
1036 | MatitaScript.ActionCancelled s -> HLog.error s
1038 if not (Helm_registry.get_bool "matita.debug") then
1042 ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
1044 match GSourceView.source_language_from_file BuildTimeConf.lang_file with
1046 HLog.warn (sprintf "can't load language file %s"
1047 BuildTimeConf.lang_file)
1048 | Some matita_lang ->
1049 source_buffer#set_language matita_lang;
1050 source_buffer#set_highlight true
1052 let s () = MatitaScript.current () in
1053 let disableSave () =
1054 script_fname <- None;
1055 main#saveMenuItem#misc#set_sensitive false
1057 let saveAsScript () =
1058 let script = s () in
1059 match self#chooseFile ~ok_not_exists:true () with
1061 script#assignFileName f;
1062 script#saveToFile ();
1063 console#message ("'"^f^"' saved.\n");
1064 self#_enableSaveTo f
1068 match script_fname with
1069 | None -> saveAsScript ()
1071 (s ())#assignFileName f;
1072 (s ())#saveToFile ();
1073 console#message ("'"^f^"' saved.\n");
1075 let abandon_script () =
1076 let lexicon_status = (s ())#lexicon_status in
1077 let grafite_status = (s ())#grafite_status in
1078 if source_view#buffer#modified then
1079 (match ask_unsaved main#toplevel with
1080 | `YES -> saveScript ()
1082 | `CANCEL -> raise MatitaTypes.Cancel);
1083 (match script_fname with
1086 ask_and_save_moo_if_needed main#toplevel fname
1087 lexicon_status grafite_status);
1090 let script = s () in
1092 match self#chooseFile () with
1096 script#assignFileName f;
1097 source_view#source_buffer#begin_not_undoable_action ();
1098 script#loadFromFile f;
1099 source_view#source_buffer#end_not_undoable_action ();
1100 console#message ("'"^f^"' loaded.\n");
1101 self#_enableSaveTo f
1103 with MatitaTypes.Cancel -> ()
1107 source_view#source_buffer#begin_not_undoable_action ();
1110 source_view#source_buffer#end_not_undoable_action ();
1112 script_fname <- None
1115 source_buffer#place_cursor
1116 (source_buffer#get_iter_at_mark (`NAME "locked")) in
1117 let advance _ = (MatitaScript.current ())#advance (); cursor () in
1118 let retract _ = (MatitaScript.current ())#retract (); cursor () in
1119 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
1120 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
1121 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
1122 let advance = locker (keep_focus advance) in
1123 let retract = locker (keep_focus retract) in
1124 let top = locker (keep_focus top) in
1125 let bottom = locker (keep_focus bottom) in
1126 let jump = locker (keep_focus jump) in
1128 self#setQuitCallback (fun () ->
1129 let lexicon_status = (MatitaScript.current ())#lexicon_status in
1130 let grafite_status = (MatitaScript.current ())#grafite_status in
1131 if source_view#buffer#modified then
1133 let rc = ask_unsaved main#toplevel in
1136 | `YES -> saveScript ();
1137 if not source_view#buffer#modified then
1139 (match script_fname with
1142 ask_and_save_moo_if_needed main#toplevel
1143 fname lexicon_status grafite_status);
1146 | `NO -> GMain.Main.quit ()
1147 | `CANCEL -> raise MatitaTypes.Cancel
1148 with MatitaTypes.Cancel -> ()
1152 (match script_fname with
1153 | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
1156 ask_and_save_moo_if_needed main#toplevel fname lexicon_status
1159 with MatitaTypes.Cancel -> ())
1161 connect_button main#scriptAdvanceButton advance;
1162 connect_button main#scriptRetractButton retract;
1163 connect_button main#scriptTopButton top;
1164 connect_button main#scriptBottomButton bottom;
1165 connect_button main#scriptJumpButton jump;
1166 connect_button main#scriptAbortButton kill_worker;
1167 connect_menu_item main#scriptAdvanceMenuItem advance;
1168 connect_menu_item main#scriptRetractMenuItem retract;
1169 connect_menu_item main#scriptTopMenuItem top;
1170 connect_menu_item main#scriptBottomMenuItem bottom;
1171 connect_menu_item main#scriptJumpMenuItem jump;
1172 connect_menu_item main#openMenuItem loadScript;
1173 connect_menu_item main#saveMenuItem saveScript;
1174 connect_menu_item main#saveAsMenuItem saveAsScript;
1175 connect_menu_item main#newMenuItem newScript;
1176 (* script monospace font stuff *)
1177 self#updateFontSize ();
1179 main#debugMenu#misc#hide ();
1181 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1182 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1183 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1185 self#sourceView#misc#grab_focus ();
1186 (* main win dimension *)
1187 let width = Gdk.Screen.width () in
1188 let height = Gdk.Screen.height () in
1189 let main_w = width * 90 / 100 in
1190 let main_h = height * 80 / 100 in
1191 let script_w = main_w * 6 / 10 in
1192 main#toplevel#resize ~width:main_w ~height:main_h;
1193 main#hpaneScriptSequent#set_position script_w;
1195 ignore(source_view#connect#after#paste_clipboard
1196 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1197 (* clean_locked is set to true only "during" a PRIMARY paste
1198 operation (i.e. by clicking with the second mouse button) *)
1199 let clean_locked = ref false in
1200 ignore(source_view#event#connect#button_press
1203 if GdkEvent.Button.button button = 2 then
1204 clean_locked := true;
1207 ignore(source_view#event#connect#button_release
1208 ~callback:(fun button -> clean_locked := false; false));
1209 ignore(source_view#buffer#connect#after#apply_tag
1211 fun tag ~start:_ ~stop:_ ->
1213 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1216 clean_locked := false;
1217 (MatitaScript.current ())#clean_dirty_lock;
1218 clean_locked := true
1220 (* math view handling *)
1221 connect_menu_item main#newCicBrowserMenuItem (fun () ->
1222 ignore (MatitaMathView.cicBrowser ()));
1223 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1224 self#increaseFontSize ();
1225 MatitaMathView.increase_font_size ();
1226 MatitaMathView.update_font_sizes ());
1227 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1228 self#decreaseFontSize ();
1229 MatitaMathView.decrease_font_size ();
1230 MatitaMathView.update_font_sizes ());
1231 connect_menu_item main#normalFontSizeMenuItem (fun () ->
1232 self#resetFontSize ();
1233 MatitaMathView.reset_font_size ();
1234 MatitaMathView.update_font_sizes ());
1235 MatitaMathView.reset_font_size ();
1237 (** selections / clipboards handling *)
1239 method markupSelected = MatitaMathView.has_selection ()
1240 method private textSelected =
1241 (source_buffer#get_iter_at_mark `INSERT)#compare
1242 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1243 method private somethingSelected = self#markupSelected || self#textSelected
1244 method private markupStored = MatitaMathView.has_clipboard ()
1245 method private textStored = clipboard#text <> None
1246 method private somethingStored = self#markupStored || self#textStored
1248 method canCopy = self#somethingSelected
1249 method canCut = self#textSelected
1250 method canDelete = self#textSelected
1251 method canPaste = self#somethingStored
1252 method canPastePattern = self#markupStored
1255 if self#textSelected
1257 MatitaMathView.empty_clipboard ();
1258 source_view#buffer#copy_clipboard clipboard;
1260 MatitaMathView.copy_selection ()
1262 source_view#buffer#cut_clipboard clipboard;
1263 MatitaMathView.empty_clipboard ()
1264 method delete () = ignore (source_view#buffer#delete_selection ())
1266 if MatitaMathView.has_clipboard ()
1267 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1268 else source_view#buffer#paste_clipboard clipboard;
1269 (MatitaScript.current ())#clean_dirty_lock
1270 method pastePattern () =
1271 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1273 method private nextLigature () =
1274 let iter = source_buffer#get_iter_at_mark `INSERT in
1275 let write_ligature len s =
1276 assert(Glib.Utf8.validate s);
1277 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
1278 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
1280 let get_ligature word =
1281 let len = String.length word in
1284 for i = len - 1 downto 0 do
1285 if HExtlib.is_alpha word.[i] then ()
1287 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
1291 if i = ~-1 then None else Some (String.sub word i (len - i))
1293 let aux_ligature () =
1295 for i = len - 1 downto 0 do
1296 if CicNotationLexer.is_ligature_char word.[i] then ()
1297 else raise (Found (i+1))
1303 Some (String.sub word i (len - i))
1304 with Invalid_argument _ -> None)
1306 match aux_tex () with
1307 | Some macro -> macro
1308 | None -> (match aux_ligature () with Some l -> l | None -> word)
1310 (match next_ligatures with
1311 | [] -> (* find ligatures and fill next_ligatures, then try again *)
1314 ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
1316 let ligature = get_ligature last_word in
1317 (match CicNotationLexer.lookup_ligatures ligature with
1320 write_ligature (MatitaGtkMisc.utf8_string_length ligature) hd;
1321 next_ligatures <- tl @ [ hd ])
1323 write_ligature 1 hd;
1324 next_ligatures <- tl @ [ hd ])
1326 method private externalEditor () =
1327 let cmd = Helm_registry.get "matita.external_editor" in
1328 (* ZACK uncomment to enable interactive ask of external editor command *)
1331 "External editor command:
1332 %f will be substitute for the script name,
1333 %p for the cursor position in bytes,
1334 %l for the execution point in bytes."
1336 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1337 ~default:(Helm_registry.get "matita.external_editor") ()
1339 let fname = (MatitaScript.current ())#filename in
1341 source_buffer#start_iter#get_slice
1342 ~stop:(source_buffer#get_iter_at_mark mark)
1344 let script = MatitaScript.current () in
1345 let locked = `MARK script#locked_mark in
1346 let string_pos mark = string_of_int (String.length (slice mark)) in
1347 let cursor_pos = string_pos `INSERT in
1348 let locked_pos = string_pos locked in
1350 Pcre.replace ~pat:"%f" ~templ:fname
1351 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1352 (Pcre.replace ~pat:"%l" ~templ:locked_pos
1355 let locked_before = slice locked in
1356 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1357 ignore (Unix.system cmd);
1358 source_buffer#set_text (HExtlib.input_file fname);
1359 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1360 source_buffer#move_mark locked locked_iter;
1361 source_buffer#apply_tag script#locked_tag
1362 ~start:source_buffer#start_iter ~stop:locked_iter;
1363 let locked_after = slice locked in
1367 for i = 0 to String.length locked_before - 1 do
1368 if locked_before.[i] <> locked_after.[i] then begin
1369 source_buffer#place_cursor
1370 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1371 script#goto `Cursor ();
1373 end else if locked_before.[i] = '\n' then begin
1380 | Invalid_argument _ -> script#goto `Bottom ()
1382 method loadScript file =
1383 let script = MatitaScript.current () in
1385 if Pcre.pmatch ~pat:"\\.p$" file then
1388 Helm_registry.get_opt_default Helm_registry.string ~default:"./"
1391 let data = Matitaprover.p_to_ma ~filename:file ~tptppath () in
1392 let filename = Pcre.replace ~pat:"\\.p$" ~templ:".ma" file in
1393 script#assignFileName filename;
1394 source_view#source_buffer#begin_not_undoable_action ();
1395 script#loadFromString data;
1396 source_view#source_buffer#end_not_undoable_action ();
1397 console#message ("'"^filename^"' loaded.");
1398 self#_enableSaveTo filename
1402 script#assignFileName file;
1404 if Sys.file_exists file then file
1405 else BuildTimeConf.script_template
1407 source_view#source_buffer#begin_not_undoable_action ();
1408 script#loadFromFile content;
1409 source_view#source_buffer#end_not_undoable_action ();
1410 console#message ("'"^file^"' loaded.");
1411 self#_enableSaveTo file
1414 method setStar name b =
1415 let l = main#scriptLabel in
1417 l#set_text (name ^ " *")
1421 method private _enableSaveTo file =
1422 script_fname <- Some file;
1423 self#main#saveMenuItem#misc#set_sensitive true
1425 method console = console
1426 method sourceView: GSourceView.source_view =
1427 (source_view: GSourceView.source_view)
1428 method fileSel = fileSel
1429 method findRepl = findRepl
1431 method develList = develList
1432 method newDevel = newDevel
1434 method newBrowserWin () =
1436 inherit browserWin ()
1437 val combo = GEdit.combo_box_entry ()
1439 self#check_widgets ();
1440 let combo_widget = combo#coerce in
1441 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1442 combo#entry#misc#grab_focus ()
1443 method browserUri = combo
1446 method newUriDialog () =
1447 let dialog = new uriChoiceDialog () in
1448 dialog#check_widgets ();
1451 method newConfirmationDialog () =
1452 let dialog = new confirmationDialog () in
1453 dialog#check_widgets ();
1456 method newEmptyDialog () =
1457 let dialog = new emptyDialog () in
1458 dialog#check_widgets ();
1461 method private addKeyBinding key callback =
1462 List.iter (fun evbox -> add_key_binding key callback evbox)
1465 method setQuitCallback callback =
1466 connect_menu_item main#quitMenuItem callback;
1467 ignore (main#toplevel#event#connect#delete
1468 (fun _ -> callback ();true));
1469 self#addKeyBinding GdkKeysyms._q callback
1471 method chooseFile ?(ok_not_exists = false) () =
1472 _ok_not_exists <- ok_not_exists;
1473 _only_directory <- false;
1474 fileSel#fileSelectionWin#show ();
1478 method private chooseDir ?(ok_not_exists = false) () =
1479 _ok_not_exists <- ok_not_exists;
1480 _only_directory <- true;
1481 fileSel#fileSelectionWin#show ();
1483 (* we should check that this is a directory *)
1486 method createDevelopment ~containing =
1487 next_devel_must_contain <- containing;
1488 newDevel#toplevel#misc#show()
1490 method askText ?(title = "") ?(msg = "") () =
1491 let dialog = new textDialog () in
1492 dialog#textDialog#set_title title;
1493 dialog#textDialogLabel#set_label msg;
1494 let text = ref None in
1497 dialog#textDialog#destroy ();
1500 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1501 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1502 connect_button dialog#textDialogOkButton (fun _ ->
1503 let text = dialog#textDialogTextView#buffer#get_text () in
1504 return (Some text));
1505 dialog#textDialog#show ();
1509 method private updateFontSize () =
1510 self#sourceView#misc#modify_font_by_name
1511 (sprintf "%s %d" BuildTimeConf.script_font font_size)
1513 method increaseFontSize () =
1514 font_size <- font_size + 1;
1515 self#updateFontSize ()
1517 method decreaseFontSize () =
1518 font_size <- font_size - 1;
1519 self#updateFontSize ()
1521 method resetFontSize () =
1522 font_size <- default_font_size;
1523 self#updateFontSize ()
1528 let g = new gui () in
1529 gui_instance := Some g;
1530 MatitaMathView.set_gui g;
1533 let instance = singleton gui
1535 let non p x = not (p x)
1537 (* this is a shit and should be changed :-{ *)
1538 let interactive_uri_choice
1539 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1540 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1541 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1545 let gui = instance () in
1546 let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1547 if (selection_mode <> `SINGLE) &&
1548 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1550 Lazy.force nonvars_uris
1552 let dialog = gui#newUriDialog () in
1553 if hide_uri_entry then
1554 dialog#uriEntryHBox#misc#hide ();
1557 dialog#uriChoiceSelectedButton#misc#hide ();
1558 dialog#uriChoiceConstantsButton#misc#hide ();
1560 dialog#okLabel#set_label ok_label;
1561 dialog#uriChoiceTreeView#selection#set_mode
1562 (selection_mode :> Gtk.Tags.selection_mode);
1563 let model = new stringListModel dialog#uriChoiceTreeView in
1564 let choices = ref None in
1568 dialog#copyButton#misc#show ();
1569 connect_button dialog#copyButton
1571 match model#easy_selection () with
1574 dialog#uriChoiceDialog#set_title title;
1575 dialog#uriChoiceLabel#set_text msg;
1576 List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1577 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1580 dialog#uriChoiceDialog#destroy ();
1583 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1584 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1585 return (Some (Lazy.force nonvars_uris)));
1586 if ok_action = `AUTO then
1587 connect_button dialog#uriChoiceAutoButton (fun _ ->
1588 Helm_registry.set_bool "matita.auto_disambiguation" true;
1589 return (Some (Lazy.force nonvars_uris)))
1591 connect_button dialog#uriChoiceAutoButton (fun _ ->
1592 match model#easy_selection () with
1594 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1595 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1596 match model#easy_selection () with
1598 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1599 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1600 dialog#uriChoiceDialog#show ();
1602 (match !choices with
1603 | None -> raise MatitaTypes.Cancel
1604 | Some uris -> uris)
1608 let cols = new GTree.column_list in
1609 let id_col = cols#add Gobject.Data.string in
1610 let dsc_col = cols#add Gobject.Data.string in
1611 let interp_no_col = cols#add Gobject.Data.int in
1612 let tree_store = GTree.tree_store cols in
1613 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1614 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1615 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1616 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1617 fun tree_view choices ->
1620 tree_view#set_model (Some (tree_store :> GTree.model));
1621 ignore (tree_view#append_column id_view_col);
1622 ignore (tree_view#append_column dsc_view_col);
1623 let name_of_interp =
1624 (* try to find a reasonable name for an interpretation *)
1628 List.assoc "0" interp
1630 incr idx; string_of_int !idx
1632 tree_store#clear ();
1633 let idx = ref ~-1 in
1637 let interp_row = tree_store#append () in
1638 tree_store#set ~row:interp_row ~column:id_col
1639 (name_of_interp interp);
1640 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1643 let row = tree_store#append ~parent:interp_row () in
1644 tree_store#set ~row ~column:id_col id;
1645 tree_store#set ~row ~column:dsc_col dsc;
1646 tree_store#set ~row ~column:interp_no_col !idx)
1650 method get_interp_no tree_path =
1651 let iter = tree_store#get_iter tree_path in
1652 tree_store#get ~row:iter ~column:interp_no_col
1655 let interactive_string_choice
1656 text prefix_len ?(title = "") ?(msg = "") () ~id locs uris
1658 let gui = instance () in
1659 let dialog = gui#newUriDialog () in
1660 dialog#uriEntryHBox#misc#hide ();
1661 dialog#uriChoiceSelectedButton#misc#hide ();
1662 dialog#uriChoiceAutoButton#misc#hide ();
1663 dialog#uriChoiceConstantsButton#misc#hide ();
1664 dialog#uriChoiceTreeView#selection#set_mode
1665 (`SINGLE :> Gtk.Tags.selection_mode);
1666 let model = new stringListModel dialog#uriChoiceTreeView in
1667 let choices = ref None in
1668 dialog#uriChoiceDialog#set_title title;
1669 let hack_len = MatitaGtkMisc.utf8_string_length text in
1670 let rec colorize acc_len = function
1672 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1673 fst(MatitaGtkMisc.utf8_parsed_text text floc)
1675 let start, stop = HExtlib.loc_of_floc he in
1676 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1677 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1678 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1679 str1 ^ "<b>" ^ str2 ^ "</b>" ^ colorize stop tl
1681 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1682 Printf.eprintf "(%d,%d)" start stop) locs; *)
1686 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1689 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1690 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1691 Printf.eprintf "(%d,%d)" start stop) locs;
1692 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1693 dialog#uriChoiceLabel#set_use_markup true;
1694 let txt = colorize 0 locs in
1695 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1696 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1698 dialog#uriChoiceLabel#set_label txt;
1699 List.iter model#easy_append uris;
1702 dialog#uriChoiceDialog#destroy ();
1705 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1706 connect_button dialog#uriChoiceForwardButton (fun _ ->
1707 match model#easy_selection () with
1709 | uris -> return (Some uris));
1710 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1711 dialog#uriChoiceDialog#show ();
1713 (match !choices with
1714 | None -> raise MatitaTypes.Cancel
1715 | Some uris -> uris)
1717 let interactive_interp_choice () text prefix_len choices =
1718 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1719 let filter_choices filter =
1720 let rec is_compatible filter =
1723 | ([],_,_)::tl -> is_compatible filter tl
1724 | (loc::tlloc,id,dsc)::tl ->
1726 if List.assoc (loc,id) filter = dsc then
1727 is_compatible filter ((tlloc,id,dsc)::tl)
1733 List.filter (fun (_,interp) -> is_compatible filter interp)
1735 let rec get_choices loc id =
1740 List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1742 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1744 let example_interp =
1748 let ask_user id locs choices =
1749 interactive_string_choice
1751 ~title:"Ambiguous input"
1752 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1754 let rec classify ids filter partial_interpretations =
1756 [] -> List.map fst partial_interpretations
1757 | ([],_,_)::tl -> classify tl filter partial_interpretations
1758 | (loc::tlloc,id,dsc)::tl ->
1759 let choices = get_choices loc id partial_interpretations in
1762 [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1765 match ask_user id [loc] choices with
1769 let filter = ((loc,id),chosen_dsc)::filter in
1770 let compatible_interps = filter_choices filter partial_interpretations in
1771 classify ((tlloc,id,dsc)::tl) filter compatible_interps
1773 let enumerated_choices =
1774 let idx = ref ~-1 in
1775 List.map (fun interp -> incr idx; !idx,interp) choices
1777 classify example_interp [] enumerated_choices
1780 (* disambiguator callbacks *)
1781 GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1782 GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1783 (* gtk initialization *)
1784 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1785 GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1786 ignore (GMain.Main.init ())