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.metadata_file_of_baseuri
89 ~must_exist:false ~baseuri ~writable:true in
91 LibraryMisc.lexicon_file_of_baseuri
92 ~must_exist:false ~baseuri ~writable:true
94 GrafiteMarshal.save_moo moo_fname
95 grafite_status.GrafiteTypes.moo_content_rev;
96 LibraryNoDb.save_metadata metadata_fname
97 lexicon_status.LexiconEngine.metadata;
98 LexiconMarshal.save_lexicon lexicon_fname
99 lexicon_status.LexiconEngine.lexicon_content_rev
103 MatitaGtkMisc.ask_confirmation
104 ~title:"A .moo can be generated"
105 ~message:(Printf.sprintf
106 "%s can be generated for %s.\n<i>Should I generate it?</i>"
107 (Filename.basename moo_fname) (Filename.basename fname))
114 | `CANCEL -> raise MatitaTypes.Cancel
119 clean_current_baseuri grafite_status
123 clean_current_baseuri grafite_status
125 let ask_unsaved parent =
126 MatitaGtkMisc.ask_confirmation
127 ~parent ~title:"Unsaved work!"
128 ~message:("Your work is <b>unsaved</b>!\n\n"^
129 "<i>Do you want to save the script before continuing?</i>")
132 class interpErrorModel =
133 let cols = new GTree.column_list in
134 let id_col = cols#add Gobject.Data.string in
135 let dsc_col = cols#add Gobject.Data.string in
136 let interp_no_col = cols#add Gobject.Data.caml in
137 let tree_store = GTree.tree_store cols in
138 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
139 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
140 let id_view_col = GTree.view_column ~renderer:id_renderer () in
141 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
142 fun (tree_view: GTree.view) choices ->
145 tree_view#set_model (Some (tree_store :> GTree.model));
146 ignore (tree_view#append_column id_view_col);
147 ignore (tree_view#append_column dsc_view_col);
149 let idx1 = ref ~-1 in
154 if List.length choices = 1 then
157 (let loc_row = tree_store#append () in
160 [passes,envs_and_diffs,_] ->
161 tree_store#set ~row:loc_row ~column:id_col
162 ("Error location " ^ string_of_int (!idx1+1) ^
163 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
165 String.concat " " (List.map string_of_int passes) ^
167 tree_store#set ~row:loc_row ~column:interp_no_col
170 tree_store#set ~row:loc_row ~column:id_col
171 ("Error location " ^ string_of_int (!idx1+1));
172 tree_store#set ~row:loc_row ~column:interp_no_col
176 let idx2 = ref ~-1 in
178 (fun passes,envs_and_diffs,_ ->
181 if List.length lll = 1 then
184 let msg_row = tree_store#append ?parent:loc_row () in
185 (tree_store#set ~row:msg_row ~column:id_col
186 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
187 string_of_int (!idx2+1) ^
189 String.concat " " (List.map string_of_int passes) ^
191 tree_store#set ~row:msg_row ~column:interp_no_col
192 (!idx1,Some !idx2,None);
194 let idx3 = ref ~-1 in
196 (fun (passes,env,_) ->
199 match envs_and_diffs with
201 let interp_row = tree_store#append ?parent:msg_row () in
202 tree_store#set ~row:interp_row ~column:id_col
203 ("Interpretation " ^ string_of_int (!idx3+1) ^
205 String.concat " " (List.map string_of_int passes) ^
207 tree_store#set ~row:interp_row ~column:interp_no_col
208 (!idx1,Some !idx2,Some !idx3);
215 let row = tree_store#append ?parent:interp_row () in
216 tree_store#set ~row ~column:id_col id;
217 tree_store#set ~row ~column:dsc_col dsc;
218 tree_store#set ~row ~column:interp_no_col
219 (!idx1,Some !idx2,Some !idx3)
223 if List.length lll > 1 then
225 (fun p -> tree_view#expand_row (tree_store#get_path p))
229 method get_interp_no tree_path =
230 let iter = tree_store#get_iter tree_path in
231 tree_store#get ~row:iter ~column:interp_no_col
235 let rec interactive_error_interp ?(all_passes=false) source_buffer notify_exn
239 if all_passes then errorll else List.rev (List.tl (List.tl (List.rev errorll))) in
247 (fun (env,diff,offset,msg) ->
248 offset, [[!pass], [[!pass], env, diff], msg]) l
250 (* Here we are doing a stable sort and list_uniq returns the latter
251 "equal" element. I.e. we are showing the error corresponding to the
252 most advanced disambiguation pass *)
254 let choices_compare (o1,_) (o2,_) = compare o1 o2 in
255 let choices_compare_by_passes (p1,_,_) (p2,_,_) =
261 | (o1,res1)::(o2,res2)::tl when o1 = o2 ->
262 let merge_by_name errors =
263 let merge_by_env errors =
264 let choices_compare_by_env (_,e1,_) (_,e2,_) = compare e1 e2 in
265 let choices_compare_by_passes (p1,_,_) (p2,_,_) =
267 let rec uniq_by_env =
271 | (p1,e1,_)::(p2,e2,d2)::tl when e1 = e2 ->
272 uniq_by_env ((p1@p2,e2,d2) :: tl)
273 | h1::tl -> h1 :: uniq_by_env tl
275 List.sort choices_compare_by_passes
276 (uniq_by_env (List.stable_sort choices_compare_by_env errors))
278 let choices_compare_by_msg (_,_,m1) (_,_,m2) =
279 compare (Lazy.force m1) (Lazy.force m2) in
280 let rec uniq_by_msg =
284 | (p1,i1,m1)::(p2,i2,m2)::tl when Lazy.force m1 = Lazy.force m2 ->
285 uniq_by_msg ((p1@p2,merge_by_env (i1@i2),m2) :: tl)
286 | h1::tl -> h1 :: uniq_by_msg tl
288 List.sort choices_compare_by_msg
289 (uniq_by_msg (List.stable_sort choices_compare_by_msg errors))
291 let res = merge_by_name (res1@res2) in
292 uniq ((o1,res) :: tl)
293 | h1::tl -> h1 :: uniq tl
295 List.map (fun o,l -> o,List.sort choices_compare_by_passes l)
296 (uniq (List.stable_sort choices_compare choices))
300 | [loffset,[_,envs_and_diffs,msg]] ->
301 let _,env,diff = List.hd envs_and_diffs in
303 (GrafiteDisambiguator.DisambiguationError
304 (offset,[[env,diff,loffset,msg]]));
306 let dialog = new disambiguationErrors () in
307 dialog#check_widgets ();
309 dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
310 let model = new interpErrorModel dialog#treeview choices in
311 dialog#disambiguationErrors#set_title "Disambiguation error";
312 dialog#disambiguationErrorsLabel#set_label
313 "Click on an interpretation to see the corresponding error message:";
314 ignore (dialog#treeview#connect#cursor_changed (fun _ ->
316 match fst (dialog#treeview#get_cursor ()) with
319 let idx1,idx2,idx3 = model#get_interp_no tree_path in
320 let loffset,lll = List.nth choices idx1 in
321 let _,envs_and_diffs,msg =
323 Some idx2 -> List.nth lll idx2
324 | None -> [],[],lazy "Multiple error messages. Please select one." in
327 Some idx3 -> List.nth envs_and_diffs idx3
328 | None -> [],[],[] (* dymmy value, used *) in
329 let script = MatitaScript.current () in
330 let error_tag = script#error_tag in
331 source_buffer#remove_tag error_tag
332 ~start:source_buffer#start_iter
333 ~stop:source_buffer#end_iter;
335 (GrafiteDisambiguator.DisambiguationError
336 (offset,[[env,diff,loffset,msg]]))
339 dialog#disambiguationErrors#destroy ();
342 let fail _ = return () in
343 ignore (dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
344 connect_button dialog#disambiguationErrorsOkButton (fun _ -> return ());
345 connect_button dialog#disambiguationErrorsMoreErrors
346 (fun _ -> return () ;
347 interactive_error_interp ~all_passes:true source_buffer notify_exn offset
349 connect_button dialog#disambiguationErrorsCancelButton fail;
350 dialog#disambiguationErrors#show ();
354 (** Selection handling
355 * Two clipboards are used: "clipboard" and "primary".
356 * "primary" is used by X, when you hit the middle button mouse is content is
357 * pasted between applications. In Matita this selection always contain the
358 * textual version of the selected term.
359 * "clipboard" is used inside Matita only and support ATM two different targets:
360 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
365 (* creation order _is_ relevant for windows placement *)
366 let main = new mainWin () in
367 let fileSel = new fileSelectionWin () in
368 let findRepl = new findReplWin () in
369 let develList = new develListWin () in
370 let newDevel = new newDevelWin () in
371 let keyBindingBoxes = (* event boxes which should receive global key events *)
372 [ main#mainWinEventBox ]
374 let console = new console ~buffer:main#logTextView#buffer () in
375 let (source_view: GSourceView.source_view) =
376 GSourceView.source_view
378 ~insert_spaces_instead_of_tabs:true ~tabs_width:2
379 ~margin:80 ~show_margin:true
381 ~packing:main#scriptScrolledWin#add
384 let default_font_size =
385 Helm_registry.get_opt_default Helm_registry.int
386 ~default:BuildTimeConf.default_font_size "matita.font_size"
388 let source_buffer = source_view#source_buffer in
390 val mutable chosen_file = None
391 val mutable _ok_not_exists = false
392 val mutable _only_directory = false
393 val mutable script_fname = None
394 val mutable font_size = default_font_size
395 val mutable next_devel_must_contain = None
396 val mutable next_ligatures = []
397 val clipboard = GData.clipboard Gdk.Atom.clipboard
398 val primary = GData.clipboard Gdk.Atom.primary
401 (* glade's check widgets *)
402 List.iter (fun w -> w#check_widgets ())
403 (let c w = (w :> <check_widgets: unit -> unit>) in
404 [ c fileSel; c main; c findRepl]);
406 List.iter (* global key bindings *)
407 (fun (key, callback) -> self#addKeyBinding key callback)
410 toggle_win ~check:main#showProofMenuItem proof#proofWin;
412 toggle_win ~check:main#showCheckMenuItem check#checkWin;
416 let parse_txt_file file =
417 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
418 let l_rev = ref [] in
421 l_rev := input_line ch :: !l_rev;
430 ~authors:(parse_txt_file "AUTHORS")
431 (*~comments:"comments"*)
432 ~copyright:"Copyright (C) 2005, the HELM team"
433 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
434 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
436 ~version:BuildTimeConf.version
437 ~website:"http://helm.cs.unibo.it"
440 connect_menu_item main#contentsMenuItem (fun () ->
442 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
444 ignore (Sys.command cmd));
445 connect_menu_item main#aboutMenuItem about_dialog#present;
447 let show_find_Repl () =
448 findRepl#toplevel#misc#show ();
449 findRepl#toplevel#misc#grab_focus ()
451 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
453 let highlight start end_ =
454 source_buffer#move_mark `INSERT ~where:start;
455 source_buffer#move_mark `SEL_BOUND ~where:end_;
456 source_view#scroll_mark_onscreen `INSERT
458 let text = findRepl#findEntry#text in
459 let iter = source_buffer#get_iter `SEL_BOUND in
460 match iter#forward_search text with
462 (match source_buffer#start_iter#forward_search text with
464 | Some (start,end_) -> highlight start end_)
465 | Some (start,end_) -> highlight start end_
468 let text = findRepl#replaceEntry#text in
469 let ins = source_buffer#get_iter `INSERT in
470 let sel = source_buffer#get_iter `SEL_BOUND in
471 if ins#compare sel < 0 then
473 ignore(source_buffer#delete_selection ());
474 source_buffer#insert text
477 connect_button findRepl#findButton find_forward;
478 connect_button findRepl#findReplButton replace;
479 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
480 ignore(findRepl#toplevel#event#connect#delete
481 ~callback:(fun _ -> hide_find_Repl ();true));
484 (* phase 1: we save the actual status of the marks and we undo *)
485 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
486 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
487 let locked_iter_offset = locked_iter#offset in
490 (source_view#buffer#create_mark ~name:"lock_point"
491 ~left_gravity:true locked_iter) in
492 source_view#source_buffer#undo ();
493 (* phase 2: we save the cursor position and we redo, restoring
494 the previous status of all the marks *)
495 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
498 (source_view#buffer#create_mark ~name:"undo_point"
499 ~left_gravity:true cursor_iter)
501 source_view#source_buffer#redo ();
502 let mark_iter = source_view#buffer#get_iter_at_mark mark in
503 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
504 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
505 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
506 source_view#buffer#delete_mark mark;
507 source_view#buffer#delete_mark mark2;
508 (* phase 3: if after the undo the cursor was in the locked area,
509 then we move it there again and we perform a goto *)
510 if mark_iter#offset < locked_iter_offset then
512 source_view#buffer#move_mark `INSERT ~where:mark_iter;
513 (MatitaScript.current ())#goto `Cursor ();
515 (* phase 4: we perform again the undo. This time we are sure that
516 the text to undo is not locked *)
517 source_view#source_buffer#undo ();
518 source_view#misc#grab_focus () in
521 (* phase 1: we save the actual status of the marks, we redo and
523 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
524 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
525 let locked_iter_offset = locked_iter#offset in
528 (source_view#buffer#create_mark ~name:"lock_point"
529 ~left_gravity:true locked_iter) in
530 source_view#source_buffer#redo ();
531 source_view#source_buffer#undo ();
532 (* phase 2: we save the cursor position and we restore
533 the previous status of all the marks *)
534 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
537 (source_view#buffer#create_mark ~name:"undo_point"
538 ~left_gravity:true cursor_iter)
540 let mark_iter = source_view#buffer#get_iter_at_mark mark in
541 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
542 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
543 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
544 source_view#buffer#delete_mark mark;
545 source_view#buffer#delete_mark mark2;
546 (* phase 3: if after the undo the cursor is in the locked area,
547 then we move it there again and we perform a goto *)
548 if mark_iter#offset < locked_iter_offset then
550 source_view#buffer#move_mark `INSERT ~where:mark_iter;
551 (MatitaScript.current ())#goto `Cursor ();
553 (* phase 4: we perform again the redo. This time we are sure that
554 the text to redo is not locked *)
555 source_view#source_buffer#redo ();
556 source_view#misc#grab_focus ()
558 connect_menu_item main#undoMenuItem safe_undo;
559 ignore(source_view#source_buffer#connect#can_undo
560 ~callback:main#undoMenuItem#misc#set_sensitive);
561 connect_menu_item main#redoMenuItem safe_redo;
562 ignore(source_view#source_buffer#connect#can_redo
563 ~callback:main#redoMenuItem#misc#set_sensitive);
564 ignore(source_view#connect#after#populate_popup
565 ~callback:(fun pre_menu ->
566 let menu = new GMenu.menu pre_menu in
567 let menuItems = menu#children in
568 let undoMenuItem, redoMenuItem =
570 [undo;redo;sep1;cut;copy;paste;delete;sep2;
571 selectall;sep3;inputmethod;insertunicodecharacter] ->
572 List.iter menu#remove [ copy; cut; delete; paste ];
574 | _ -> assert false in
576 let i = ref 2 in (* last occupied position *)
577 fun ?label ?stock () ->
579 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
582 let copy = add_menu_item ~stock:`COPY () in
583 let cut = add_menu_item ~stock:`CUT () in
584 let delete = add_menu_item ~stock:`DELETE () in
585 let paste = add_menu_item ~stock:`PASTE () in
586 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
587 copy#misc#set_sensitive self#canCopy;
588 cut#misc#set_sensitive self#canCut;
589 delete#misc#set_sensitive self#canDelete;
590 paste#misc#set_sensitive self#canPaste;
591 paste_pattern#misc#set_sensitive self#canPastePattern;
592 connect_menu_item copy self#copy;
593 connect_menu_item cut self#cut;
594 connect_menu_item delete self#delete;
595 connect_menu_item paste self#paste;
596 connect_menu_item paste_pattern self#pastePattern;
597 let new_undoMenuItem =
598 GMenu.image_menu_item
599 ~image:(GMisc.image ~stock:`UNDO ())
602 ~packing:(menu#insert ~pos:0) () in
603 new_undoMenuItem#misc#set_sensitive
604 (undoMenuItem#misc#get_flag `SENSITIVE);
605 menu#remove (undoMenuItem :> GMenu.menu_item);
606 connect_menu_item new_undoMenuItem safe_undo;
607 let new_redoMenuItem =
608 GMenu.image_menu_item
609 ~image:(GMisc.image ~stock:`REDO ())
612 ~packing:(menu#insert ~pos:1) () in
613 new_redoMenuItem#misc#set_sensitive
614 (redoMenuItem#misc#get_flag `SENSITIVE);
615 menu#remove (redoMenuItem :> GMenu.menu_item);
616 connect_menu_item new_redoMenuItem safe_redo));
618 connect_menu_item main#editMenu (fun () ->
619 main#copyMenuItem#misc#set_sensitive self#canCopy;
620 main#cutMenuItem#misc#set_sensitive self#canCut;
621 main#deleteMenuItem#misc#set_sensitive self#canDelete;
622 main#pasteMenuItem#misc#set_sensitive self#canPaste;
623 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
624 connect_menu_item main#copyMenuItem self#copy;
625 connect_menu_item main#cutMenuItem self#cut;
626 connect_menu_item main#deleteMenuItem self#delete;
627 connect_menu_item main#pasteMenuItem self#paste;
628 connect_menu_item main#pastePatternMenuItem self#pastePattern;
629 connect_menu_item main#selectAllMenuItem (fun () ->
630 source_buffer#move_mark `INSERT source_buffer#start_iter;
631 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
632 connect_menu_item main#findReplMenuItem show_find_Repl;
633 connect_menu_item main#externalEditorMenuItem self#externalEditor;
634 connect_menu_item main#ligatureButton self#nextLigature;
635 ignore (findRepl#findEntry#connect#activate find_forward);
636 (* interface lockers *)
638 main#buttonsToolbar#misc#set_sensitive false;
639 develList#buttonsHbox#misc#set_sensitive false;
640 main#scriptMenu#misc#set_sensitive false;
641 source_view#set_editable false
644 main#buttonsToolbar#misc#set_sensitive true;
645 develList#buttonsHbox#misc#set_sensitive true;
646 main#scriptMenu#misc#set_sensitive true;
647 source_view#set_editable true;
648 (*The next line seems sufficient to avoid some unknown race condition *)
649 GtkThread.sync (fun () -> ()) ()
651 let worker_thread = ref None in
653 let floc, msg = MatitaExcPp.to_string exn in
658 let (x, y) = HExtlib.loc_of_floc floc in
659 let script = MatitaScript.current () in
660 let locked_mark = script#locked_mark in
661 let error_tag = script#error_tag in
663 (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
664 let x' = baseoffset + x in
665 let y' = baseoffset + y in
666 let x_iter = source_buffer#get_iter (`OFFSET x') in
667 let y_iter = source_buffer#get_iter (`OFFSET y') in
668 source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
670 id := Some (source_buffer#connect#changed ~callback:(fun () ->
671 source_buffer#remove_tag error_tag
672 ~start:source_buffer#start_iter
673 ~stop:source_buffer#end_iter;
675 | None -> assert false (* a race condition occurred *)
677 (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
678 source_buffer#place_cursor
679 (source_buffer#get_iter (`OFFSET x'));
690 | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
691 interactive_error_interp source_buffer notify_exn offset errorll ;
697 worker_thread := Some (Thread.create thread_main ()) in
699 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
700 let interrupt = ref None in
701 let old_callback = ref (function _ -> ()) in
702 let force_interrupt n =
703 (* This function is called just before the thread's timeslice ends *)
705 if Some(Thread.id(Thread.self())) = !interrupt then
706 (interrupt := None; raise Sys.Break) in
708 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
709 Sys.Signal_handle f -> old_callback := f
711 | Sys.Signal_default -> assert false
714 match !worker_thread with
716 | Some t -> interrupt := Some (Thread.id t) in
720 f (); source_view#misc#grab_focus ()
722 exc -> source_view#misc#grab_focus (); raise exc in
723 (* developments win *)
725 new MatitaGtkMisc.multiStringListModel
726 ~cols:2 develList#developmentsTreeview
728 let refresh_devels_win () =
729 model#list_store#clear ();
731 (fun (name, root) -> model#easy_mappend [name;root])
732 (MatitamakeLib.list_known_developments ())
734 let get_devel_selected () =
735 match model#easy_mselection () with
736 | [[name;_]] -> MatitamakeLib.development_for_name name
740 while Glib.Main.pending () do
741 ignore(Glib.Main.iteration false);
744 connect_button develList#newButton
746 next_devel_must_contain <- None;
747 newDevel#toplevel#misc#show());
748 connect_button develList#deleteButton
750 (match get_devel_selected () with
752 | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
753 refresh_devels_win ()));
754 connect_button develList#buildButton
756 match get_devel_selected () with
760 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
763 connect_button develList#cleanButton
765 match get_devel_selected () with
769 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
772 connect_button develList#publishButton
774 match get_devel_selected () with
777 let publish = locker (fun () ->
778 MatitamakeLib.publish_development_in_bg refresh d) in
779 ignore(publish ())));
780 connect_button develList#graphButton (fun () ->
781 match get_devel_selected () with
784 (match MatitamakeLib.dot_for_development d with
787 let browser = MatitaMathView.cicBrowser () in
788 browser#load (`Development
789 (MatitamakeLib.name_for_development d))));
790 connect_button develList#closeButton
791 (fun () -> develList#toplevel#misc#hide());
792 ignore(develList#toplevel#event#connect#delete
793 (fun _ -> develList#toplevel#misc#hide();true));
794 connect_menu_item main#developmentsMenuItem
795 (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
797 (* add development win *)
798 let check_if_root_contains root =
799 match next_devel_must_contain with
802 let is_prefix_of d1 d2 =
803 let len1 = String.length d1 in
804 let len2 = String.length d2 in
808 let pref = String.sub d2 0 len1 in
811 is_prefix_of root path
813 connect_button newDevel#addButton
815 let name = newDevel#nameEntry#text in
816 let root = newDevel#rootEntry#text in
817 if check_if_root_contains root then
819 ignore (MatitamakeLib.initialize_development name root);
820 refresh_devels_win ();
821 newDevel#nameEntry#set_text "";
822 newDevel#rootEntry#set_text "";
823 newDevel#toplevel#misc#hide()
826 HLog.error ("The selected root does not contain " ^
827 match next_devel_must_contain with
829 | _ -> assert false));
830 connect_button newDevel#chooseRootButton
832 let path = self#chooseDir () in
834 | Some path -> newDevel#rootEntry#set_text path
836 connect_button newDevel#cancelButton
837 (fun () -> newDevel#toplevel#misc#hide ());
838 ignore(newDevel#toplevel#event#connect#delete
839 (fun _ -> newDevel#toplevel#misc#hide();true));
841 (* file selection win *)
842 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
843 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
846 fileSel#fileSelectionWin#misc#hide ();
851 let fname = fileSel#fileSelectionWin#filename in
852 if Sys.file_exists fname then
854 if HExtlib.is_regular fname && not (_only_directory) then
856 else if _only_directory && HExtlib.is_dir fname then
861 if _ok_not_exists then
864 | `CANCEL -> return None
866 | `DELETE_EVENT -> return None));
868 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
870 let adj = main#logScrolledWin#vadjustment in
871 ignore (adj#connect#changed
872 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
873 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
875 let module A = GrafiteAst in
876 let hole = CicNotationPt.UserInput in
877 let loc = HExtlib.dummy_floc in
879 if (MatitaScript.current ())#onGoingProof () then
880 (MatitaScript.current ())#advance
882 ^ GrafiteAstPp.pp_tactical ~term_pp:CicNotationPp.pp_term
883 ~lazy_term_pp:CicNotationPp.pp_term (A.Tactic (loc, ast)))
886 let tac_w_term ast _ =
887 if (MatitaScript.current ())#onGoingProof () then
888 let buf = source_buffer in
889 buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
891 ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
892 ~lazy_term_pp:CicNotationPp.pp_term ast)
895 connect_button tbar#introsButton (tac (A.Intros (loc, None, [])));
896 connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
897 connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
898 connect_button tbar#elimButton (tac_w_term
899 (A.Elim (loc, hole, None, None, [])));
900 connect_button tbar#elimTypeButton (tac_w_term
901 (A.ElimType (loc, hole, None, None, [])));
902 connect_button tbar#splitButton (tac (A.Split loc));
903 connect_button tbar#leftButton (tac (A.Left loc));
904 connect_button tbar#rightButton (tac (A.Right loc));
905 connect_button tbar#existsButton (tac (A.Exists loc));
906 connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
907 connect_button tbar#symmetryButton (tac (A.Symmetry loc));
908 connect_button tbar#transitivityButton
909 (tac_w_term (A.Transitivity (loc, hole)));
910 connect_button tbar#assumptionButton (tac (A.Assumption loc));
911 connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
912 connect_button tbar#autoButton (tac (A.Auto (loc,[])));
913 MatitaGtkMisc.toggle_widget_visibility
914 ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
915 ~check:main#tacticsBarMenuItem;
916 let module Hr = Helm_registry in
918 not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
920 main#tacticsBarMenuItem#set_active false;
921 MatitaGtkMisc.toggle_callback
923 | true -> main#toplevel#fullscreen ()
924 | false -> main#toplevel#unfullscreen ())
925 ~check:main#fullscreenMenuItem;
926 main#fullscreenMenuItem#set_active false;
928 HLog.set_log_callback self#console#log_callback;
929 GtkSignal.user_handler :=
931 | MatitaScript.ActionCancelled s -> HLog.error s
933 if not (Helm_registry.get_bool "matita.debug") then
937 ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
939 match GSourceView.source_language_from_file BuildTimeConf.lang_file with
941 HLog.warn (sprintf "can't load language file %s"
942 BuildTimeConf.lang_file)
943 | Some matita_lang ->
944 source_buffer#set_language matita_lang;
945 source_buffer#set_highlight true
947 let s () = MatitaScript.current () in
949 script_fname <- None;
950 main#saveMenuItem#misc#set_sensitive false
952 let saveAsScript () =
954 match self#chooseFile ~ok_not_exists:true () with
956 script#assignFileName f;
957 script#saveToFile ();
958 console#message ("'"^f^"' saved.\n");
963 match script_fname with
964 | None -> saveAsScript ()
966 (s ())#assignFileName f;
967 (s ())#saveToFile ();
968 console#message ("'"^f^"' saved.\n");
970 let abandon_script () =
971 let lexicon_status = (s ())#lexicon_status in
972 let grafite_status = (s ())#grafite_status in
973 if source_view#buffer#modified then
974 (match ask_unsaved main#toplevel with
975 | `YES -> saveScript ()
977 | `CANCEL -> raise MatitaTypes.Cancel);
978 (match script_fname with
981 ask_and_save_moo_if_needed main#toplevel fname
982 lexicon_status grafite_status);
987 match self#chooseFile () with
991 script#assignFileName f;
992 source_view#source_buffer#begin_not_undoable_action ();
993 script#loadFromFile f;
994 source_view#source_buffer#end_not_undoable_action ();
995 console#message ("'"^f^"' loaded.\n");
998 with MatitaTypes.Cancel -> ()
1002 source_view#source_buffer#begin_not_undoable_action ();
1005 source_view#source_buffer#end_not_undoable_action ();
1007 script_fname <- None
1010 source_buffer#place_cursor
1011 (source_buffer#get_iter_at_mark (`NAME "locked")) in
1012 let advance _ = (MatitaScript.current ())#advance (); cursor () in
1013 let retract _ = (MatitaScript.current ())#retract (); cursor () in
1014 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
1015 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
1016 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
1017 let advance = locker (keep_focus advance) in
1018 let retract = locker (keep_focus retract) in
1019 let top = locker (keep_focus top) in
1020 let bottom = locker (keep_focus bottom) in
1021 let jump = locker (keep_focus jump) in
1023 self#setQuitCallback (fun () ->
1024 let lexicon_status = (MatitaScript.current ())#lexicon_status in
1025 let grafite_status = (MatitaScript.current ())#grafite_status in
1026 if source_view#buffer#modified then
1028 let rc = ask_unsaved main#toplevel in
1031 | `YES -> saveScript ();
1032 if not source_view#buffer#modified then
1034 (match script_fname with
1037 ask_and_save_moo_if_needed main#toplevel
1038 fname lexicon_status grafite_status);
1041 | `NO -> GMain.Main.quit ()
1042 | `CANCEL -> raise MatitaTypes.Cancel
1043 with MatitaTypes.Cancel -> ()
1047 (match script_fname with
1048 | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
1051 ask_and_save_moo_if_needed main#toplevel fname lexicon_status
1054 with MatitaTypes.Cancel -> ())
1056 connect_button main#scriptAdvanceButton advance;
1057 connect_button main#scriptRetractButton retract;
1058 connect_button main#scriptTopButton top;
1059 connect_button main#scriptBottomButton bottom;
1060 connect_button main#scriptJumpButton jump;
1061 connect_button main#scriptAbortButton kill_worker;
1062 connect_menu_item main#scriptAdvanceMenuItem advance;
1063 connect_menu_item main#scriptRetractMenuItem retract;
1064 connect_menu_item main#scriptTopMenuItem top;
1065 connect_menu_item main#scriptBottomMenuItem bottom;
1066 connect_menu_item main#scriptJumpMenuItem jump;
1067 connect_menu_item main#openMenuItem loadScript;
1068 connect_menu_item main#saveMenuItem saveScript;
1069 connect_menu_item main#saveAsMenuItem saveAsScript;
1070 connect_menu_item main#newMenuItem newScript;
1071 (* script monospace font stuff *)
1072 self#updateFontSize ();
1074 main#debugMenu#misc#hide ();
1076 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1077 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1078 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1080 self#sourceView#misc#grab_focus ();
1081 (* main win dimension *)
1082 let width = Gdk.Screen.width () in
1083 let height = Gdk.Screen.height () in
1084 let main_w = width * 90 / 100 in
1085 let main_h = height * 80 / 100 in
1086 let script_w = main_w * 6 / 10 in
1087 main#toplevel#resize ~width:main_w ~height:main_h;
1088 main#hpaneScriptSequent#set_position script_w;
1090 ignore(source_view#connect#after#paste_clipboard
1091 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1092 (* clean_locked is set to true only "during" a PRIMARY paste
1093 operation (i.e. by clicking with the second mouse button) *)
1094 let clean_locked = ref false in
1095 ignore(source_view#event#connect#button_press
1098 if GdkEvent.Button.button button = 2 then
1099 clean_locked := true;
1102 ignore(source_view#event#connect#button_release
1103 ~callback:(fun button -> clean_locked := false; false));
1104 ignore(source_view#buffer#connect#after#apply_tag
1106 fun tag ~start:_ ~stop:_ ->
1108 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1111 clean_locked := false;
1112 (MatitaScript.current ())#clean_dirty_lock;
1113 clean_locked := true
1115 (* math view handling *)
1116 connect_menu_item main#newCicBrowserMenuItem (fun () ->
1117 ignore (MatitaMathView.cicBrowser ()));
1118 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1119 self#increaseFontSize ();
1120 MatitaMathView.increase_font_size ();
1121 MatitaMathView.update_font_sizes ());
1122 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1123 self#decreaseFontSize ();
1124 MatitaMathView.decrease_font_size ();
1125 MatitaMathView.update_font_sizes ());
1126 connect_menu_item main#normalFontSizeMenuItem (fun () ->
1127 self#resetFontSize ();
1128 MatitaMathView.reset_font_size ();
1129 MatitaMathView.update_font_sizes ());
1130 MatitaMathView.reset_font_size ();
1132 (** selections / clipboards handling *)
1134 method markupSelected = MatitaMathView.has_selection ()
1135 method private textSelected =
1136 (source_buffer#get_iter_at_mark `INSERT)#compare
1137 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1138 method private somethingSelected = self#markupSelected || self#textSelected
1139 method private markupStored = MatitaMathView.has_clipboard ()
1140 method private textStored = clipboard#text <> None
1141 method private somethingStored = self#markupStored || self#textStored
1143 method canCopy = self#somethingSelected
1144 method canCut = self#textSelected
1145 method canDelete = self#textSelected
1146 method canPaste = self#somethingStored
1147 method canPastePattern = self#markupStored
1150 if self#textSelected
1152 MatitaMathView.empty_clipboard ();
1153 source_view#buffer#copy_clipboard clipboard;
1155 MatitaMathView.copy_selection ()
1157 source_view#buffer#cut_clipboard clipboard;
1158 MatitaMathView.empty_clipboard ()
1159 method delete () = ignore (source_view#buffer#delete_selection ())
1161 if MatitaMathView.has_clipboard ()
1162 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1163 else source_view#buffer#paste_clipboard clipboard;
1164 (MatitaScript.current ())#clean_dirty_lock
1165 method pastePattern () =
1166 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1168 method private nextLigature () =
1169 let iter = source_buffer#get_iter_at_mark `INSERT in
1170 let write_ligature len s =
1171 assert(Glib.Utf8.validate s);
1172 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
1173 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
1175 let get_ligature word =
1176 let len = String.length word in
1179 for i = len - 1 downto 0 do
1180 if HExtlib.is_alpha word.[i] then ()
1182 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
1186 if i = ~-1 then None else Some (String.sub word i (len - i))
1188 let aux_ligature () =
1190 for i = len - 1 downto 0 do
1191 if CicNotationLexer.is_ligature_char word.[i] then ()
1192 else raise (Found (i+1))
1198 Some (String.sub word i (len - i))
1199 with Invalid_argument _ -> None)
1201 match aux_tex () with
1202 | Some macro -> macro
1203 | None -> (match aux_ligature () with Some l -> l | None -> word)
1205 (match next_ligatures with
1206 | [] -> (* find ligatures and fill next_ligatures, then try again *)
1209 ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
1211 let ligature = get_ligature last_word in
1212 (match CicNotationLexer.lookup_ligatures ligature with
1215 write_ligature (MatitaGtkMisc.utf8_string_length ligature) hd;
1216 next_ligatures <- tl @ [ hd ])
1218 write_ligature 1 hd;
1219 next_ligatures <- tl @ [ hd ])
1221 method private externalEditor () =
1222 let cmd = Helm_registry.get "matita.external_editor" in
1223 (* ZACK uncomment to enable interactive ask of external editor command *)
1226 "External editor command:
1227 %f will be substitute for the script name,
1228 %p for the cursor position in bytes,
1229 %l for the execution point in bytes."
1231 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1232 ~default:(Helm_registry.get "matita.external_editor") ()
1234 let fname = (MatitaScript.current ())#filename in
1236 source_buffer#start_iter#get_slice
1237 ~stop:(source_buffer#get_iter_at_mark mark)
1239 let script = MatitaScript.current () in
1240 let locked = `MARK script#locked_mark in
1241 let string_pos mark = string_of_int (String.length (slice mark)) in
1242 let cursor_pos = string_pos `INSERT in
1243 let locked_pos = string_pos locked in
1245 Pcre.replace ~pat:"%f" ~templ:fname
1246 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1247 (Pcre.replace ~pat:"%l" ~templ:locked_pos
1250 let locked_before = slice locked in
1251 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1252 ignore (Unix.system cmd);
1253 source_buffer#set_text (HExtlib.input_file fname);
1254 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1255 source_buffer#move_mark locked locked_iter;
1256 source_buffer#apply_tag script#locked_tag
1257 ~start:source_buffer#start_iter ~stop:locked_iter;
1258 let locked_after = slice locked in
1262 for i = 0 to String.length locked_before - 1 do
1263 if locked_before.[i] <> locked_after.[i] then begin
1264 source_buffer#place_cursor
1265 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1266 script#goto `Cursor ();
1268 end else if locked_before.[i] = '\n' then begin
1275 | Invalid_argument _ -> script#goto `Bottom ()
1277 method loadScript file =
1278 let script = MatitaScript.current () in
1280 if Pcre.pmatch ~pat:"\\.p$" file then
1283 Helm_registry.get_opt_default Helm_registry.string ~default:"./"
1286 let data = Matitaprover.p_to_ma ~filename:file ~tptppath () in
1287 let filename = Pcre.replace ~pat:"\\.p$" ~templ:".ma" file in
1288 script#assignFileName filename;
1289 source_view#source_buffer#begin_not_undoable_action ();
1290 script#loadFromString data;
1291 source_view#source_buffer#end_not_undoable_action ();
1292 console#message ("'"^filename^"' loaded.");
1293 self#_enableSaveTo filename
1297 script#assignFileName file;
1299 if Sys.file_exists file then file
1300 else BuildTimeConf.script_template
1302 source_view#source_buffer#begin_not_undoable_action ();
1303 script#loadFromFile content;
1304 source_view#source_buffer#end_not_undoable_action ();
1305 console#message ("'"^file^"' loaded.");
1306 self#_enableSaveTo file
1309 method setStar name b =
1310 let l = main#scriptLabel in
1312 l#set_text (name ^ " *")
1316 method private _enableSaveTo file =
1317 script_fname <- Some file;
1318 self#main#saveMenuItem#misc#set_sensitive true
1320 method console = console
1321 method sourceView: GSourceView.source_view =
1322 (source_view: GSourceView.source_view)
1323 method fileSel = fileSel
1324 method findRepl = findRepl
1326 method develList = develList
1327 method newDevel = newDevel
1329 method newBrowserWin () =
1331 inherit browserWin ()
1332 val combo = GEdit.combo_box_entry ()
1334 self#check_widgets ();
1335 let combo_widget = combo#coerce in
1336 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1337 combo#entry#misc#grab_focus ()
1338 method browserUri = combo
1341 method newUriDialog () =
1342 let dialog = new uriChoiceDialog () in
1343 dialog#check_widgets ();
1346 method newConfirmationDialog () =
1347 let dialog = new confirmationDialog () in
1348 dialog#check_widgets ();
1351 method newEmptyDialog () =
1352 let dialog = new emptyDialog () in
1353 dialog#check_widgets ();
1356 method private addKeyBinding key callback =
1357 List.iter (fun evbox -> add_key_binding key callback evbox)
1360 method setQuitCallback callback =
1361 connect_menu_item main#quitMenuItem callback;
1362 ignore (main#toplevel#event#connect#delete
1363 (fun _ -> callback ();true));
1364 self#addKeyBinding GdkKeysyms._q callback
1366 method chooseFile ?(ok_not_exists = false) () =
1367 _ok_not_exists <- ok_not_exists;
1368 _only_directory <- false;
1369 fileSel#fileSelectionWin#show ();
1373 method private chooseDir ?(ok_not_exists = false) () =
1374 _ok_not_exists <- ok_not_exists;
1375 _only_directory <- true;
1376 fileSel#fileSelectionWin#show ();
1378 (* we should check that this is a directory *)
1381 method createDevelopment ~containing =
1382 next_devel_must_contain <- containing;
1383 newDevel#toplevel#misc#show()
1385 method askText ?(title = "") ?(msg = "") () =
1386 let dialog = new textDialog () in
1387 dialog#textDialog#set_title title;
1388 dialog#textDialogLabel#set_label msg;
1389 let text = ref None in
1392 dialog#textDialog#destroy ();
1395 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1396 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1397 connect_button dialog#textDialogOkButton (fun _ ->
1398 let text = dialog#textDialogTextView#buffer#get_text () in
1399 return (Some text));
1400 dialog#textDialog#show ();
1404 method private updateFontSize () =
1405 self#sourceView#misc#modify_font_by_name
1406 (sprintf "%s %d" BuildTimeConf.script_font font_size)
1408 method increaseFontSize () =
1409 font_size <- font_size + 1;
1410 self#updateFontSize ()
1412 method decreaseFontSize () =
1413 font_size <- font_size - 1;
1414 self#updateFontSize ()
1416 method resetFontSize () =
1417 font_size <- default_font_size;
1418 self#updateFontSize ()
1423 let g = new gui () in
1424 gui_instance := Some g;
1425 MatitaMathView.set_gui g;
1428 let instance = singleton gui
1430 let non p x = not (p x)
1432 (* this is a shit and should be changed :-{ *)
1433 let interactive_uri_choice
1434 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1435 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1436 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1440 let gui = instance () in
1441 let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1442 if (selection_mode <> `SINGLE) &&
1443 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1445 Lazy.force nonvars_uris
1447 let dialog = gui#newUriDialog () in
1448 if hide_uri_entry then
1449 dialog#uriEntryHBox#misc#hide ();
1452 dialog#uriChoiceSelectedButton#misc#hide ();
1453 dialog#uriChoiceConstantsButton#misc#hide ();
1455 dialog#okLabel#set_label ok_label;
1456 dialog#uriChoiceTreeView#selection#set_mode
1457 (selection_mode :> Gtk.Tags.selection_mode);
1458 let model = new stringListModel dialog#uriChoiceTreeView in
1459 let choices = ref None in
1463 dialog#copyButton#misc#show ();
1464 connect_button dialog#copyButton
1466 match model#easy_selection () with
1469 dialog#uriChoiceDialog#set_title title;
1470 dialog#uriChoiceLabel#set_text msg;
1471 List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1472 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1475 dialog#uriChoiceDialog#destroy ();
1478 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1479 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1480 return (Some (Lazy.force nonvars_uris)));
1481 if ok_action = `AUTO then
1482 connect_button dialog#uriChoiceAutoButton (fun _ ->
1483 Helm_registry.set_bool "matita.auto_disambiguation" true;
1484 return (Some (Lazy.force nonvars_uris)))
1486 connect_button dialog#uriChoiceAutoButton (fun _ ->
1487 match model#easy_selection () with
1489 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1490 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1491 match model#easy_selection () with
1493 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1494 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1495 dialog#uriChoiceDialog#show ();
1497 (match !choices with
1498 | None -> raise MatitaTypes.Cancel
1499 | Some uris -> uris)
1503 let cols = new GTree.column_list in
1504 let id_col = cols#add Gobject.Data.string in
1505 let dsc_col = cols#add Gobject.Data.string in
1506 let interp_no_col = cols#add Gobject.Data.int in
1507 let tree_store = GTree.tree_store cols in
1508 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1509 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1510 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1511 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1512 fun tree_view choices ->
1515 tree_view#set_model (Some (tree_store :> GTree.model));
1516 ignore (tree_view#append_column id_view_col);
1517 ignore (tree_view#append_column dsc_view_col);
1518 let name_of_interp =
1519 (* try to find a reasonable name for an interpretation *)
1523 List.assoc "0" interp
1525 incr idx; string_of_int !idx
1527 tree_store#clear ();
1528 let idx = ref ~-1 in
1532 let interp_row = tree_store#append () in
1533 tree_store#set ~row:interp_row ~column:id_col
1534 (name_of_interp interp);
1535 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1538 let row = tree_store#append ~parent:interp_row () in
1539 tree_store#set ~row ~column:id_col id;
1540 tree_store#set ~row ~column:dsc_col dsc;
1541 tree_store#set ~row ~column:interp_no_col !idx)
1545 method get_interp_no tree_path =
1546 let iter = tree_store#get_iter tree_path in
1547 tree_store#get ~row:iter ~column:interp_no_col
1550 let interactive_string_choice
1551 text prefix_len ?(title = "") ?(msg = "") () ~id locs uris
1553 let gui = instance () in
1554 let dialog = gui#newUriDialog () in
1555 dialog#uriEntryHBox#misc#hide ();
1556 dialog#uriChoiceSelectedButton#misc#hide ();
1557 dialog#uriChoiceAutoButton#misc#hide ();
1558 dialog#uriChoiceConstantsButton#misc#hide ();
1559 dialog#uriChoiceTreeView#selection#set_mode
1560 (`SINGLE :> Gtk.Tags.selection_mode);
1561 let model = new stringListModel dialog#uriChoiceTreeView in
1562 let choices = ref None in
1563 dialog#uriChoiceDialog#set_title title;
1564 let hack_len = MatitaGtkMisc.utf8_string_length text in
1565 let rec colorize acc_len = function
1567 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1568 fst(MatitaGtkMisc.utf8_parsed_text text floc)
1570 let start, stop = HExtlib.loc_of_floc he in
1571 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1572 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1573 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1574 str1 ^ "<b>" ^ str2 ^ "</b>" ^ colorize stop tl
1576 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1577 Printf.eprintf "(%d,%d)" start stop) locs; *)
1581 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1584 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1585 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1586 Printf.eprintf "(%d,%d)" start stop) locs;
1587 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1588 dialog#uriChoiceLabel#set_use_markup true;
1589 let txt = colorize 0 locs in
1590 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1591 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1593 dialog#uriChoiceLabel#set_label txt;
1594 List.iter model#easy_append uris;
1597 dialog#uriChoiceDialog#destroy ();
1600 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1601 connect_button dialog#uriChoiceForwardButton (fun _ ->
1602 match model#easy_selection () with
1604 | uris -> return (Some uris));
1605 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1606 dialog#uriChoiceDialog#show ();
1608 (match !choices with
1609 | None -> raise MatitaTypes.Cancel
1610 | Some uris -> uris)
1612 let interactive_interp_choice () text prefix_len choices =
1613 (* List.iter (fun (l,_,_) ->
1614 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1615 Printf.eprintf "(%d,%d)" start stop) l; prerr_endline "")
1616 ((List.hd choices)); *)
1617 let filter_choices filter =
1618 let rec is_compatible filter =
1623 if List.assoc id filter = dsc then
1624 is_compatible filter tl
1630 List.filter (fun (_,interp) -> is_compatible filter interp)
1632 let rec get_choices id =
1636 let _,_,dsc = List.find (fun (_,id',_) -> id = id') he in
1637 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices id tl))
1639 let example_interp =
1643 let ask_user id locs choices =
1644 interactive_string_choice
1646 ~title:"Ambiguous input"
1647 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1649 let rec classify ids filter partial_interpretations =
1651 [] -> List.map fst partial_interpretations
1652 | (locs,id,_)::tl ->
1653 let choices = get_choices id partial_interpretations in
1658 match ask_user id locs choices with
1662 let filter = (id,chosen_dsc)::filter in
1663 let compatible_interps = filter_choices filter partial_interpretations in
1664 classify tl filter compatible_interps in
1665 let enumerated_choices =
1666 let idx = ref ~-1 in
1667 List.map (fun interp -> incr idx; !idx,interp) choices
1669 classify example_interp [] enumerated_choices
1672 (* disambiguator callbacks *)
1673 GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1674 GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1675 (* gtk initialization *)
1676 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1677 GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1678 ignore (GMain.Main.init ())