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 all_disambiguation_passes = ref false
38 let gui_instance = ref None
40 class type browserWin =
41 (* this class exists only because GEdit.combo_box_entry is not supported by
42 * lablgladecc :-(((( *)
44 inherit MatitaGeneratedGui.browserWin
45 method browserUri: GEdit.entry
48 class console ~(buffer: GText.buffer) () =
50 val error_tag = buffer#create_tag [ `FOREGROUND "red" ]
51 val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
52 val message_tag = buffer#create_tag []
53 val debug_tag = buffer#create_tag [ `FOREGROUND "#888888" ]
54 method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
55 method error s = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
56 method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
57 method debug s = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
59 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
60 method log_callback (tag: HLog.log_tag) s =
61 let s = Pcre.replace ~pat:"
\e\\[0;3.m([^
\e]+)
\e\\[0m" ~templ:"$1" s in
63 | `Debug -> self#debug (s ^ "\n")
64 | `Error -> self#error (s ^ "\n")
65 | `Message -> self#message (s ^ "\n")
66 | `Warning -> self#warning (s ^ "\n")
69 let clean_current_baseuri grafite_status =
70 LibraryClean.clean_baseuris [GrafiteTypes.get_baseuri grafite_status]
72 let save_moo lexicon_status grafite_status =
73 let script = MatitaScript.current () in
74 let baseuri = GrafiteTypes.get_baseuri grafite_status in
76 grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof
78 match script#bos, script#eos, no_pstatus with
82 LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri
85 LibraryMisc.lexicon_file_of_baseuri
86 ~must_exist:false ~baseuri ~writable:true
88 GrafiteMarshal.save_moo moo_fname
89 grafite_status.GrafiteTypes.moo_content_rev;
90 LexiconMarshal.save_lexicon lexicon_fname
91 lexicon_status.LexiconEngine.lexicon_content_rev
92 | _ -> clean_current_baseuri grafite_status
95 let ask_unsaved parent =
96 MatitaGtkMisc.ask_confirmation
97 ~parent ~title:"Unsaved work!"
98 ~message:("Your work is <b>unsaved</b>!\n\n"^
99 "<i>Do you want to save the script before continuing?</i>")
102 class interpErrorModel =
103 let cols = new GTree.column_list in
104 let id_col = cols#add Gobject.Data.string in
105 let dsc_col = cols#add Gobject.Data.string in
106 let interp_no_col = cols#add Gobject.Data.caml in
107 let tree_store = GTree.tree_store cols in
108 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
109 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
110 let id_view_col = GTree.view_column ~renderer:id_renderer () in
111 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
112 fun (tree_view: GTree.view) choices ->
115 tree_view#set_model (Some (tree_store :> GTree.model));
116 ignore (tree_view#append_column id_view_col);
117 ignore (tree_view#append_column dsc_view_col);
119 let idx1 = ref ~-1 in
124 if List.length choices = 1 then
127 (let loc_row = tree_store#append () in
130 [passes,envs_and_diffs,_,_] ->
131 tree_store#set ~row:loc_row ~column:id_col
132 ("Error location " ^ string_of_int (!idx1+1) ^
133 ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
135 String.concat " " (List.map string_of_int passes) ^
137 tree_store#set ~row:loc_row ~column:interp_no_col
140 tree_store#set ~row:loc_row ~column:id_col
141 ("Error location " ^ string_of_int (!idx1+1));
142 tree_store#set ~row:loc_row ~column:interp_no_col
146 let idx2 = ref ~-1 in
148 (fun passes,envs_and_diffs,_,_ ->
151 if List.length lll = 1 then
154 let msg_row = tree_store#append ?parent:loc_row () in
155 (tree_store#set ~row:msg_row ~column:id_col
156 ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
157 string_of_int (!idx2+1) ^
159 String.concat " " (List.map string_of_int passes) ^
161 tree_store#set ~row:msg_row ~column:interp_no_col
162 (!idx1,Some !idx2,None);
164 let idx3 = ref ~-1 in
166 (fun (passes,env,_) ->
169 match envs_and_diffs with
171 let interp_row = tree_store#append ?parent:msg_row () in
172 tree_store#set ~row:interp_row ~column:id_col
173 ("Interpretation " ^ string_of_int (!idx3+1) ^
175 String.concat " " (List.map string_of_int passes) ^
177 tree_store#set ~row:interp_row ~column:interp_no_col
178 (!idx1,Some !idx2,Some !idx3);
185 let row = tree_store#append ?parent:interp_row () in
186 tree_store#set ~row ~column:id_col id;
187 tree_store#set ~row ~column:dsc_col dsc;
188 tree_store#set ~row ~column:interp_no_col
189 (!idx1,Some !idx2,Some !idx3)
193 if List.length lll > 1 then
195 (fun p -> tree_view#expand_row (tree_store#get_path p))
199 method get_interp_no tree_path =
200 let iter = tree_store#get_iter tree_path in
201 tree_store#get ~row:iter ~column:interp_no_col
205 let rec interactive_error_interp ~all_passes
206 (source_buffer:GSourceView.source_buffer) notify_exn offset errorll filename
208 (* hook to save a script for each disambiguation error *)
211 source_buffer#get_text ~start:source_buffer#start_iter
212 ~stop:source_buffer#end_iter () in
213 let md5 = Digest.to_hex (Digest.string text) in
215 Filename.chop_extension filename ^ ".error." ^ md5 ^ ".ma" in
216 let ch = open_out filename in
217 output_string ch text;
220 assert (List.flatten errorll <> []);
222 let remove_non_significant =
223 List.filter (fun (_env,_diff,_loc_msg,significant) -> significant) in
224 let annotated_errorll () =
227 (List.fold_left (fun (pass,res) item -> pass+1,(pass+1,item)::res) (0,[])
229 if all_passes then annotated_errorll () else
230 let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
231 (* We remove passes 1,2 and 5,6 *)
234 ::(3,remove_non_significant (safe_list_nth errorll 2))
235 ::(4,remove_non_significant (safe_list_nth errorll 3))
238 if List.flatten (List.map snd res) <> [] then res
240 (* all errors (if any) are not significant: we keep them *)
243 ::(3,(safe_list_nth errorll 2))
244 ::(4,(safe_list_nth errorll 3))
247 if List.flatten (List.map snd res) <> [] then
250 "All disambiguation errors are not significant. Showing them anyway." ;
256 "No errors in phases 2 and 3. Showing all errors in all phases" ;
260 let choices = MatitaExcPp.compact_disambiguation_errors all_passes errorll' in
263 | [loffset,[_,envs_and_diffs,msg,significant]] ->
264 let _,env,diff = List.hd envs_and_diffs in
266 (MultiPassDisambiguator.DisambiguationError
267 (offset,[[env,diff,lazy (loffset,Lazy.force msg),significant]]));
269 let dialog = new disambiguationErrors () in
270 dialog#check_widgets ();
272 dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
273 let model = new interpErrorModel dialog#treeview choices in
274 dialog#disambiguationErrors#set_title "Disambiguation error";
275 dialog#disambiguationErrorsLabel#set_label
276 "Click on an error to see the corresponding message:";
277 ignore (dialog#treeview#connect#cursor_changed
280 match fst (dialog#treeview#get_cursor ()) with
283 let idx1,idx2,idx3 = model#get_interp_no tree_path in
284 let loffset,lll = List.nth choices idx1 in
285 let _,envs_and_diffs,msg,significant =
287 Some idx2 -> List.nth lll idx2
289 [],[],lazy "Multiple error messages. Please select one.",true
293 Some idx3 -> List.nth envs_and_diffs idx3
294 | None -> [],[],[] (* dymmy value, used *) in
295 let script = MatitaScript.current () in
296 let error_tag = script#error_tag in
297 source_buffer#remove_tag error_tag
298 ~start:source_buffer#start_iter
299 ~stop:source_buffer#end_iter;
301 (MultiPassDisambiguator.DisambiguationError
302 (offset,[[env,diff,lazy(loffset,Lazy.force msg),significant]]))
305 dialog#disambiguationErrors#destroy ();
308 let fail _ = return () in
309 ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
310 connect_button dialog#disambiguationErrorsOkButton
313 match fst (dialog#treeview#get_cursor ()) with
316 let idx1,idx2,idx3 = model#get_interp_no tree_path in
319 Some idx2, Some idx3 ->
320 let _,lll = List.nth choices idx1 in
321 let _,envs_and_diffs,_,_ = List.nth lll idx2 in
322 let _,_,diff = List.nth envs_and_diffs idx3 in
324 | _,_ -> assert false
331 let alias = DisambiguatePp.alias_of_domain_and_desc k desc in
332 LexiconAstPp.pp_alias alias)
337 (source_buffer#get_iter_at_mark
338 (`NAME "beginning_of_statement")) newtxt ;
341 connect_button dialog#disambiguationErrorsMoreErrors
342 (fun _ -> return () ;
343 interactive_error_interp ~all_passes:true source_buffer
344 notify_exn offset errorll filename);
345 connect_button dialog#disambiguationErrorsCancelButton fail;
346 dialog#disambiguationErrors#show ();
350 (** Selection handling
351 * Two clipboards are used: "clipboard" and "primary".
352 * "primary" is used by X, when you hit the middle button mouse is content is
353 * pasted between applications. In Matita this selection always contain the
354 * textual version of the selected term.
355 * "clipboard" is used inside Matita only and support ATM two different targets:
356 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
361 (* creation order _is_ relevant for windows placement *)
362 let main = new mainWin () in
363 let fileSel = new fileSelectionWin () in
364 let findRepl = new findReplWin () in
365 let keyBindingBoxes = (* event boxes which should receive global key events *)
366 [ main#mainWinEventBox ]
368 let console = new console ~buffer:main#logTextView#buffer () in
369 let (source_view: GSourceView.source_view) =
370 GSourceView.source_view
372 ~insert_spaces_instead_of_tabs:true ~tabs_width:2
373 ~margin:80 ~show_margin:true
375 ~packing:main#scriptScrolledWin#add
378 let default_font_size =
379 Helm_registry.get_opt_default Helm_registry.int
380 ~default:BuildTimeConf.default_font_size "matita.font_size"
382 let source_buffer = source_view#source_buffer in
384 val mutable chosen_file = None
385 val mutable _ok_not_exists = false
386 val mutable _only_directory = false
387 val mutable font_size = default_font_size
388 val mutable next_ligatures = []
389 val clipboard = GData.clipboard Gdk.Atom.clipboard
390 val primary = GData.clipboard Gdk.Atom.primary
393 let s () = MatitaScript.current () in
394 (* glade's check widgets *)
395 List.iter (fun w -> w#check_widgets ())
396 (let c w = (w :> <check_widgets: unit -> unit>) in
397 [ c fileSel; c main; c findRepl]);
399 List.iter (* global key bindings *)
400 (fun (key, callback) -> self#addKeyBinding key callback)
403 toggle_win ~check:main#showProofMenuItem proof#proofWin;
405 toggle_win ~check:main#showCheckMenuItem check#checkWin;
409 let parse_txt_file file =
410 let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
411 let l_rev = ref [] in
414 l_rev := input_line ch :: !l_rev;
423 ~authors:(parse_txt_file "AUTHORS")
424 (*~comments:"comments"*)
425 ~copyright:"Copyright (C) 2005, the HELM team"
426 ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
427 ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
429 ~version:BuildTimeConf.version
430 ~website:"http://matita.cs.unibo.it"
433 ignore(about_dialog#connect#response (fun _ ->about_dialog#misc#hide ()));
434 connect_menu_item main#contentsMenuItem (fun () ->
435 if 0 = Sys.command "which gnome-help" then
437 sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
439 ignore (Sys.command cmd)
441 MatitaGtkMisc.report_error ~title:"help system error"
443 "The program gnome-help is not installed\n\n"^
444 "To browse the user manal it is necessary to install "^
445 "the gnome help syste (also known as yelp)")
446 ~parent:main#toplevel ());
447 connect_menu_item main#aboutMenuItem about_dialog#present;
449 let show_find_Repl () =
450 findRepl#toplevel#misc#show ();
451 findRepl#toplevel#misc#grab_focus ()
453 let hide_find_Repl () = findRepl#toplevel#misc#hide () in
455 let highlight start end_ =
456 source_buffer#move_mark `INSERT ~where:start;
457 source_buffer#move_mark `SEL_BOUND ~where:end_;
458 source_view#scroll_mark_onscreen `INSERT
460 let text = findRepl#findEntry#text in
461 let iter = source_buffer#get_iter `SEL_BOUND in
462 match iter#forward_search text with
464 (match source_buffer#start_iter#forward_search text with
466 | Some (start,end_) -> highlight start end_)
467 | Some (start,end_) -> highlight start end_
470 let text = findRepl#replaceEntry#text in
471 let ins = source_buffer#get_iter `INSERT in
472 let sel = source_buffer#get_iter `SEL_BOUND in
473 if ins#compare sel < 0 then
475 ignore(source_buffer#delete_selection ());
476 source_buffer#insert text
479 connect_button findRepl#findButton find_forward;
480 connect_button findRepl#findReplButton replace;
481 connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
482 ignore(findRepl#toplevel#event#connect#delete
483 ~callback:(fun _ -> hide_find_Repl ();true));
486 (* phase 1: we save the actual status of the marks and we undo *)
487 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
488 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
489 let locked_iter_offset = locked_iter#offset in
492 (source_view#buffer#create_mark ~name:"lock_point"
493 ~left_gravity:true locked_iter) in
494 source_view#source_buffer#undo ();
495 (* phase 2: we save the cursor position and we redo, restoring
496 the previous status of all the marks *)
497 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
500 (source_view#buffer#create_mark ~name:"undo_point"
501 ~left_gravity:true cursor_iter)
503 source_view#source_buffer#redo ();
504 let mark_iter = source_view#buffer#get_iter_at_mark mark in
505 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
506 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
507 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
508 source_view#buffer#delete_mark mark;
509 source_view#buffer#delete_mark mark2;
510 (* phase 3: if after the undo the cursor was in the locked area,
511 then we move it there again and we perform a goto *)
512 if mark_iter#offset < locked_iter_offset then
514 source_view#buffer#move_mark `INSERT ~where:mark_iter;
515 (MatitaScript.current ())#goto `Cursor ();
517 (* phase 4: we perform again the undo. This time we are sure that
518 the text to undo is not locked *)
519 source_view#source_buffer#undo ();
520 source_view#misc#grab_focus () in
523 (* phase 1: we save the actual status of the marks, we redo and
525 let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
526 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
527 let locked_iter_offset = locked_iter#offset in
530 (source_view#buffer#create_mark ~name:"lock_point"
531 ~left_gravity:true locked_iter) in
532 source_view#source_buffer#redo ();
533 source_view#source_buffer#undo ();
534 (* phase 2: we save the cursor position and we restore
535 the previous status of all the marks *)
536 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
539 (source_view#buffer#create_mark ~name:"undo_point"
540 ~left_gravity:true cursor_iter)
542 let mark_iter = source_view#buffer#get_iter_at_mark mark in
543 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
544 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
545 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
546 source_view#buffer#delete_mark mark;
547 source_view#buffer#delete_mark mark2;
548 (* phase 3: if after the undo the cursor is in the locked area,
549 then we move it there again and we perform a goto *)
550 if mark_iter#offset < locked_iter_offset then
552 source_view#buffer#move_mark `INSERT ~where:mark_iter;
553 (MatitaScript.current ())#goto `Cursor ();
555 (* phase 4: we perform again the redo. This time we are sure that
556 the text to redo is not locked *)
557 source_view#source_buffer#redo ();
558 source_view#misc#grab_focus ()
560 connect_menu_item main#undoMenuItem safe_undo;
561 ignore(source_view#source_buffer#connect#can_undo
562 ~callback:main#undoMenuItem#misc#set_sensitive);
563 connect_menu_item main#redoMenuItem safe_redo;
564 ignore(source_view#source_buffer#connect#can_redo
565 ~callback:main#redoMenuItem#misc#set_sensitive);
566 ignore(source_view#connect#after#populate_popup
567 ~callback:(fun pre_menu ->
568 let menu = new GMenu.menu pre_menu in
569 let menuItems = menu#children in
570 let undoMenuItem, redoMenuItem =
572 [undo;redo;sep1;cut;copy;paste;delete;sep2;
573 selectall;sep3;inputmethod;insertunicodecharacter] ->
574 List.iter menu#remove [ copy; cut; delete; paste ];
576 | _ -> assert false in
578 let i = ref 2 in (* last occupied position *)
579 fun ?label ?stock () ->
581 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
584 let copy = add_menu_item ~stock:`COPY () in
585 let cut = add_menu_item ~stock:`CUT () in
586 let delete = add_menu_item ~stock:`DELETE () in
587 let paste = add_menu_item ~stock:`PASTE () in
588 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
589 copy#misc#set_sensitive self#canCopy;
590 cut#misc#set_sensitive self#canCut;
591 delete#misc#set_sensitive self#canDelete;
592 paste#misc#set_sensitive self#canPaste;
593 paste_pattern#misc#set_sensitive self#canPastePattern;
594 connect_menu_item copy self#copy;
595 connect_menu_item cut self#cut;
596 connect_menu_item delete self#delete;
597 connect_menu_item paste self#paste;
598 connect_menu_item paste_pattern self#pastePattern;
599 let new_undoMenuItem =
600 GMenu.image_menu_item
601 ~image:(GMisc.image ~stock:`UNDO ())
604 ~packing:(menu#insert ~pos:0) () in
605 new_undoMenuItem#misc#set_sensitive
606 (undoMenuItem#misc#get_flag `SENSITIVE);
607 menu#remove (undoMenuItem :> GMenu.menu_item);
608 connect_menu_item new_undoMenuItem safe_undo;
609 let new_redoMenuItem =
610 GMenu.image_menu_item
611 ~image:(GMisc.image ~stock:`REDO ())
614 ~packing:(menu#insert ~pos:1) () in
615 new_redoMenuItem#misc#set_sensitive
616 (redoMenuItem#misc#get_flag `SENSITIVE);
617 menu#remove (redoMenuItem :> GMenu.menu_item);
618 connect_menu_item new_redoMenuItem safe_redo));
620 connect_menu_item main#editMenu (fun () ->
621 main#copyMenuItem#misc#set_sensitive self#canCopy;
622 main#cutMenuItem#misc#set_sensitive self#canCut;
623 main#deleteMenuItem#misc#set_sensitive self#canDelete;
624 main#pasteMenuItem#misc#set_sensitive self#canPaste;
625 main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
626 connect_menu_item main#copyMenuItem self#copy;
627 connect_menu_item main#cutMenuItem self#cut;
628 connect_menu_item main#deleteMenuItem self#delete;
629 connect_menu_item main#pasteMenuItem self#paste;
630 connect_menu_item main#pastePatternMenuItem self#pastePattern;
631 connect_menu_item main#selectAllMenuItem (fun () ->
632 source_buffer#move_mark `INSERT source_buffer#start_iter;
633 source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
634 connect_menu_item main#findReplMenuItem show_find_Repl;
635 connect_menu_item main#externalEditorMenuItem self#externalEditor;
636 connect_menu_item main#ligatureButton self#nextLigature;
637 ignore (findRepl#findEntry#connect#activate find_forward);
638 (* interface lockers *)
640 main#buttonsToolbar#misc#set_sensitive false;
641 main#scriptMenu#misc#set_sensitive false;
642 source_view#set_editable false
645 main#buttonsToolbar#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 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
692 interactive_error_interp
693 ~all_passes:!all_disambiguation_passes source_buffer
694 notify_exn offset errorll (s())#filename
696 exc -> notify_exn exc);
703 worker_thread := Some (Thread.create thread_main ())
706 (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
707 let interrupt = ref None in
708 let old_callback = ref (function _ -> ()) in
709 let force_interrupt n =
710 (* This function is called just before the thread's timeslice ends *)
712 if Some(Thread.id(Thread.self())) = !interrupt then
713 (interrupt := None; raise Sys.Break) in
715 match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
716 Sys.Signal_handle f -> old_callback := f
718 | Sys.Signal_default -> assert false
721 match !worker_thread with
723 | Some t -> interrupt := Some (Thread.id t) in
727 f (); source_view#misc#grab_focus ()
729 exc -> source_view#misc#grab_focus (); raise exc in
731 (* file selection win *)
732 ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
733 ignore (fileSel#fileSelectionWin#connect#response (fun event ->
736 fileSel#fileSelectionWin#misc#hide ();
741 let fname = fileSel#fileSelectionWin#filename in
742 if Sys.file_exists fname then
744 if HExtlib.is_regular fname && not (_only_directory) then
746 else if _only_directory && HExtlib.is_dir fname then
751 if _ok_not_exists then
754 | `CANCEL -> return None
756 | `DELETE_EVENT -> return None));
758 List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
760 let adj = main#logScrolledWin#vadjustment in
761 ignore (adj#connect#changed
762 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
763 console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
764 (* natural deduction palette *)
765 main#tacticsButtonsHandlebox#misc#hide ();
766 MatitaGtkMisc.toggle_callback
768 if b then main#tacticsButtonsHandlebox#misc#show ()
769 else main#tacticsButtonsHandlebox#misc#hide ())
770 ~check:main#menuitemPalette;
771 connect_button main#butImpl_intro
772 (fun () -> source_buffer#insert "apply rule (⇒_i […] (…));\n");
773 connect_button main#butAnd_intro
774 (fun () -> source_buffer#insert
775 "apply rule (∧_i (…) (…));\n\t[\n\t|\n\t]\n");
776 connect_button main#butOr_intro_left
777 (fun () -> source_buffer#insert "apply rule (∨_i_l (…));\n");
778 connect_button main#butOr_intro_right
779 (fun () -> source_buffer#insert "apply rule (∨_i_r (…));\n");
780 connect_button main#butNot_intro
781 (fun () -> source_buffer#insert "apply rule (¬_i […] (…));\n");
782 connect_button main#butTop_intro
783 (fun () -> source_buffer#insert "apply rule (⊤_i);\n");
784 connect_button main#butImpl_elim
785 (fun () -> source_buffer#insert
786 "apply rule (⇒_e (…) (…));\n\t[\n\t|\n\t]\n");
787 connect_button main#butAnd_elim_left
788 (fun () -> source_buffer#insert "apply rule (∧_e_l (…));\n");
789 connect_button main#butAnd_elim_right
790 (fun () -> source_buffer#insert "apply rule (∧_e_r (…));\n");
791 connect_button main#butOr_elim
792 (fun () -> source_buffer#insert
793 "apply rule (∨_e (…) […] (…) […] (…));\n\t[\n\t|\n\t|\n\t]\n");
794 connect_button main#butNot_elim
795 (fun () -> source_buffer#insert
796 "apply rule (¬_e (…) (…));\n\t[\n\t|\n\t]\n");
797 connect_button main#butBot_elim
798 (fun () -> source_buffer#insert "apply rule (⊥_e (…));\n");
799 connect_button main#butRAA
800 (fun () -> source_buffer#insert "apply rule (RAA […] (…));\n");
801 connect_button main#butUseLemma
802 (fun () -> source_buffer#insert "apply rule (lem #premises name …);\n");
803 connect_button main#butDischarge
804 (fun () -> source_buffer#insert "apply rule (discharge […]);\n");
806 connect_button main#butForall_intro
807 (fun () -> source_buffer#insert "apply rule (∀_i {…} (…));\n");
808 connect_button main#butForall_elim
809 (fun () -> source_buffer#insert "apply rule (∀_e {…} (…));\n");
810 connect_button main#butExists_intro
811 (fun () -> source_buffer#insert "apply rule (∃_i {…} (…));\n");
812 connect_button main#butExists_elim
813 (fun () -> source_buffer#insert
814 "apply rule (∃_e (…) {…} […] (…));\n\t[\n\t|\n\t]\n");
818 main#scriptNotebook#remove_page 1;
819 main#scriptNotebook#set_show_tabs false;
820 (* / TO BE REMOVED *)
821 let module Hr = Helm_registry in
822 MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
824 | true -> main#toplevel#fullscreen ()
825 | false -> main#toplevel#unfullscreen ());
826 main#fullscreenMenuItem#set_active false;
827 MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
830 CicNotation.set_active_notations
831 (List.map fst (CicNotation.get_all_notations ()))
833 CicNotation.set_active_notations []);
834 MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
835 ~callback:(fun enabled -> Acic2content.hide_coercions := enabled);
836 MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
837 ~callback:(fun enabled ->
838 Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
839 main#unicodeAsTexMenuItem#set_active
840 (Helm_registry.get_bool "matita.paste_unicode_as_tex");
842 HLog.set_log_callback self#console#log_callback;
843 GtkSignal.user_handler :=
845 | MatitaScript.ActionCancelled s -> HLog.error s
847 if not (Helm_registry.get_bool "matita.debug") then
851 ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
853 match GSourceView.source_language_from_file BuildTimeConf.lang_file with
855 HLog.warn (sprintf "can't load language file %s"
856 BuildTimeConf.lang_file)
857 | Some matita_lang ->
858 source_buffer#set_language matita_lang;
859 source_buffer#set_highlight true
862 (s())#assignFileName None;
863 main#saveMenuItem#misc#set_sensitive false
865 let saveAsScript () =
867 match self#chooseFile ~ok_not_exists:true () with
870 script#assignFileName (Some f);
871 script#saveToFile ();
872 console#message ("'"^f^"' saved.\n");
878 if script#has_name then
879 (script#saveToFile ();
880 console#message ("'"^script#filename^"' saved.\n"))
883 let abandon_script () =
884 let lexicon_status = (s ())#lexicon_status in
885 let grafite_status = (s ())#grafite_status in
886 if source_view#buffer#modified then
887 (match ask_unsaved main#toplevel with
888 | `YES -> saveScript ()
890 | `CANCEL -> raise MatitaTypes.Cancel);
891 save_moo lexicon_status grafite_status
896 match self#chooseFile () with
900 script#assignFileName (Some f);
901 source_view#source_buffer#begin_not_undoable_action ();
902 script#loadFromFile f;
903 source_view#source_buffer#end_not_undoable_action ();
904 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
905 source_view#buffer#place_cursor source_view#buffer#start_iter;
906 console#message ("'"^f^"' loaded.\n");
909 with MatitaTypes.Cancel -> ()
913 source_view#source_buffer#begin_not_undoable_action ();
916 source_view#source_buffer#end_not_undoable_action ();
918 (s ())#assignFileName None
921 source_buffer#place_cursor
922 (source_buffer#get_iter_at_mark (`NAME "locked")) in
923 let advance _ = (MatitaScript.current ())#advance (); cursor () in
924 let retract _ = (MatitaScript.current ())#retract (); cursor () in
925 let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
926 let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
927 let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
928 let advance = locker (keep_focus advance) in
929 let retract = locker (keep_focus retract) in
930 let top = locker (keep_focus top) in
931 let bottom = locker (keep_focus bottom) in
932 let jump = locker (keep_focus jump) in
934 self#setQuitCallback (fun () ->
935 let script = MatitaScript.current () in
936 if source_view#buffer#modified then
937 match ask_unsaved main#toplevel with
940 save_moo script#lexicon_status script#grafite_status;
942 | `NO -> GMain.Main.quit ()
945 (save_moo script#lexicon_status script#grafite_status;
946 GMain.Main.quit ()));
947 connect_button main#scriptAdvanceButton advance;
948 connect_button main#scriptRetractButton retract;
949 connect_button main#scriptTopButton top;
950 connect_button main#scriptBottomButton bottom;
951 connect_button main#scriptJumpButton jump;
952 connect_button main#scriptAbortButton kill_worker;
953 connect_menu_item main#scriptAdvanceMenuItem advance;
954 connect_menu_item main#scriptRetractMenuItem retract;
955 connect_menu_item main#scriptTopMenuItem top;
956 connect_menu_item main#scriptBottomMenuItem bottom;
957 connect_menu_item main#scriptJumpMenuItem jump;
958 connect_menu_item main#openMenuItem loadScript;
959 connect_menu_item main#saveMenuItem saveScript;
960 connect_menu_item main#saveAsMenuItem saveAsScript;
961 connect_menu_item main#newMenuItem newScript;
962 connect_menu_item main#showCoercionsGraphMenuItem
964 let c = MatitaMathView.cicBrowser () in
965 c#load (`About `Coercions));
966 connect_menu_item main#showAutoGuiMenuItem
967 (fun _ -> MatitaAutoGui.auto_dialog Auto.get_auto_status);
968 connect_menu_item main#showTermGrammarMenuItem
970 let c = MatitaMathView.cicBrowser () in
971 c#load (`About `Grammar));
972 connect_menu_item main#showUnicodeTable
974 let c = MatitaMathView.cicBrowser () in
975 c#load (`About `TeX));
976 (* script monospace font stuff *)
977 self#updateFontSize ();
979 main#debugMenu#misc#hide ();
981 main#hintNotebook#misc#hide ();
983 main#hintLowImage#set_file (image_path "matita-bulb-low.png");
984 main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
985 main#hintHighImage#set_file (image_path "matita-bulb-high.png");
988 self#sourceView#misc#grab_focus ();
989 (* main win dimension *)
990 let width = Gdk.Screen.width () in
991 let height = Gdk.Screen.height () in
992 let main_w = width * 90 / 100 in
993 let main_h = height * 80 / 100 in
994 let script_w = main_w * 6 / 10 in
995 main#toplevel#resize ~width:main_w ~height:main_h;
996 main#hpaneScriptSequent#set_position script_w;
998 ignore(source_view#connect#after#paste_clipboard
999 ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1000 (* clean_locked is set to true only "during" a PRIMARY paste
1001 operation (i.e. by clicking with the second mouse button) *)
1002 let clean_locked = ref false in
1003 ignore(source_view#event#connect#button_press
1006 if GdkEvent.Button.button button = 2 then
1007 clean_locked := true;
1010 ignore(source_view#event#connect#button_release
1011 ~callback:(fun button -> clean_locked := false; false));
1012 ignore(source_view#buffer#connect#after#apply_tag
1014 fun tag ~start:_ ~stop:_ ->
1016 tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1019 clean_locked := false;
1020 (MatitaScript.current ())#clean_dirty_lock;
1021 clean_locked := true
1023 (* math view handling *)
1024 connect_menu_item main#newCicBrowserMenuItem (fun () ->
1025 ignore(MatitaMathView.cicBrowser ()));
1026 connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1027 self#increaseFontSize ();
1028 MatitaMathView.increase_font_size ();
1029 MatitaMathView.update_font_sizes ());
1030 connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1031 self#decreaseFontSize ();
1032 MatitaMathView.decrease_font_size ();
1033 MatitaMathView.update_font_sizes ());
1034 connect_menu_item main#normalFontSizeMenuItem (fun () ->
1035 self#resetFontSize ();
1036 MatitaMathView.reset_font_size ();
1037 MatitaMathView.update_font_sizes ());
1038 MatitaMathView.reset_font_size ();
1040 (** selections / clipboards handling *)
1042 method markupSelected = MatitaMathView.has_selection ()
1043 method private textSelected =
1044 (source_buffer#get_iter_at_mark `INSERT)#compare
1045 (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1046 method private somethingSelected = self#markupSelected || self#textSelected
1047 method private markupStored = MatitaMathView.has_clipboard ()
1048 method private textStored = clipboard#text <> None
1049 method private somethingStored = self#markupStored || self#textStored
1051 method canCopy = self#somethingSelected
1052 method canCut = self#textSelected
1053 method canDelete = self#textSelected
1054 method canPaste = self#somethingStored
1055 method canPastePattern = self#markupStored
1058 if self#textSelected
1060 MatitaMathView.empty_clipboard ();
1061 source_view#buffer#copy_clipboard clipboard;
1063 MatitaMathView.copy_selection ()
1065 source_view#buffer#cut_clipboard clipboard;
1066 MatitaMathView.empty_clipboard ()
1067 method delete () = ignore (source_view#buffer#delete_selection ())
1069 if MatitaMathView.has_clipboard ()
1070 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1071 else source_view#buffer#paste_clipboard clipboard;
1072 (MatitaScript.current ())#clean_dirty_lock
1073 method pastePattern () =
1074 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1076 method private nextLigature () =
1077 let iter = source_buffer#get_iter_at_mark `INSERT in
1078 let write_ligature len s =
1079 assert(Glib.Utf8.validate s);
1080 source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
1081 source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
1083 let get_ligature word =
1084 let len = String.length word in
1087 for i = len - 1 downto 0 do
1088 if HExtlib.is_alpha word.[i] then ()
1090 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
1094 if i = ~-1 then None else Some (String.sub word i (len - i))
1096 let aux_ligature () =
1098 for i = len - 1 downto 0 do
1099 if CicNotationLexer.is_ligature_char word.[i] then ()
1100 else raise (Found (i+1))
1106 Some (String.sub word i (len - i))
1107 with Invalid_argument _ -> None)
1109 match aux_tex () with
1110 | Some macro -> macro
1111 | None -> (match aux_ligature () with Some l -> l | None -> word)
1113 (match next_ligatures with
1114 | [] -> (* find ligatures and fill next_ligatures, then try again *)
1117 ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
1119 let ligature = get_ligature last_word in
1120 (match CicNotationLexer.lookup_ligatures ligature with
1123 write_ligature (MatitaGtkMisc.utf8_string_length ligature) hd;
1124 next_ligatures <- tl @ [ hd ])
1126 write_ligature 1 hd;
1127 next_ligatures <- tl @ [ hd ])
1129 method private externalEditor () =
1130 let cmd = Helm_registry.get "matita.external_editor" in
1131 (* ZACK uncomment to enable interactive ask of external editor command *)
1134 "External editor command:
1135 %f will be substitute for the script name,
1136 %p for the cursor position in bytes,
1137 %l for the execution point in bytes."
1139 ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1140 ~default:(Helm_registry.get "matita.external_editor") ()
1142 let script = MatitaScript.current () in
1143 let fname = script#filename in
1145 source_buffer#start_iter#get_slice
1146 ~stop:(source_buffer#get_iter_at_mark mark)
1148 let locked = `MARK script#locked_mark in
1149 let string_pos mark = string_of_int (String.length (slice mark)) in
1150 let cursor_pos = string_pos `INSERT in
1151 let locked_pos = string_pos locked in
1153 Pcre.replace ~pat:"%f" ~templ:fname
1154 (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1155 (Pcre.replace ~pat:"%l" ~templ:locked_pos
1158 let locked_before = slice locked in
1159 let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1160 ignore (Unix.system cmd);
1161 source_buffer#set_text (HExtlib.input_file fname);
1162 let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1163 source_buffer#move_mark locked locked_iter;
1164 source_buffer#apply_tag script#locked_tag
1165 ~start:source_buffer#start_iter ~stop:locked_iter;
1166 let locked_after = slice locked in
1170 for i = 0 to String.length locked_before - 1 do
1171 if locked_before.[i] <> locked_after.[i] then begin
1172 source_buffer#place_cursor
1173 ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1174 script#goto `Cursor ();
1176 end else if locked_before.[i] = '\n' then begin
1183 | Invalid_argument _ -> script#goto `Bottom ()
1185 method loadScript file =
1186 let script = MatitaScript.current () in
1188 script#assignFileName (Some file);
1189 let file = script#filename in
1191 if Sys.file_exists file then file
1192 else BuildTimeConf.script_template
1194 source_view#source_buffer#begin_not_undoable_action ();
1195 script#loadFromFile content;
1196 source_view#source_buffer#end_not_undoable_action ();
1197 source_view#buffer#move_mark `INSERT source_view#buffer#start_iter;
1198 source_view#buffer#place_cursor source_view#buffer#start_iter;
1199 console#message ("'"^file^"' loaded.");
1200 self#_enableSaveTo file
1203 let s = MatitaScript.current () in
1204 let w = main#toplevel in
1205 let set x = w#set_title x in
1207 "Matita - " ^ Filename.basename s#filename ^
1208 (if b then "*" else "") ^
1209 " in " ^ s#buri_of_current_file
1213 method private _enableSaveTo file =
1214 self#main#saveMenuItem#misc#set_sensitive true
1216 method console = console
1217 method sourceView: GSourceView.source_view =
1218 (source_view: GSourceView.source_view)
1219 method fileSel = fileSel
1220 method findRepl = findRepl
1223 method newBrowserWin () =
1225 inherit browserWin ()
1226 val combo = GEdit.entry ()
1228 self#check_widgets ();
1229 let combo_widget = combo#coerce in
1230 uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1231 combo#misc#grab_focus ()
1232 method browserUri = combo
1235 method newUriDialog () =
1236 let dialog = new uriChoiceDialog () in
1237 dialog#check_widgets ();
1240 method newConfirmationDialog () =
1241 let dialog = new confirmationDialog () in
1242 dialog#check_widgets ();
1245 method newEmptyDialog () =
1246 let dialog = new emptyDialog () in
1247 dialog#check_widgets ();
1250 method private addKeyBinding key callback =
1251 List.iter (fun evbox -> add_key_binding key callback evbox)
1254 method setQuitCallback callback =
1255 connect_menu_item main#quitMenuItem callback;
1256 ignore (main#toplevel#event#connect#delete
1257 (fun _ -> callback ();true));
1258 self#addKeyBinding GdkKeysyms._q callback
1260 method chooseFile ?(ok_not_exists = false) () =
1261 _ok_not_exists <- ok_not_exists;
1262 _only_directory <- false;
1263 fileSel#fileSelectionWin#show ();
1267 method private chooseDir ?(ok_not_exists = false) () =
1268 _ok_not_exists <- ok_not_exists;
1269 _only_directory <- true;
1270 fileSel#fileSelectionWin#show ();
1272 (* we should check that this is a directory *)
1275 method askText ?(title = "") ?(msg = "") () =
1276 let dialog = new textDialog () in
1277 dialog#textDialog#set_title title;
1278 dialog#textDialogLabel#set_label msg;
1279 let text = ref None in
1282 dialog#textDialog#destroy ();
1285 ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1286 connect_button dialog#textDialogCancelButton (fun _ -> return None);
1287 connect_button dialog#textDialogOkButton (fun _ ->
1288 let text = dialog#textDialogTextView#buffer#get_text () in
1289 return (Some text));
1290 dialog#textDialog#show ();
1294 method private updateFontSize () =
1295 self#sourceView#misc#modify_font_by_name
1296 (sprintf "%s %d" BuildTimeConf.script_font font_size);
1297 MatitaAutoGui.set_font_size font_size
1299 method increaseFontSize () =
1300 font_size <- font_size + 1;
1301 self#updateFontSize ()
1303 method decreaseFontSize () =
1304 font_size <- font_size - 1;
1305 self#updateFontSize ()
1307 method resetFontSize () =
1308 font_size <- default_font_size;
1309 self#updateFontSize ()
1314 let g = new gui () in
1315 gui_instance := Some g;
1316 MatitaMathView.set_gui g;
1319 let instance = singleton gui
1321 let non p x = not (p x)
1323 (* this is a shit and should be changed :-{ *)
1324 let interactive_uri_choice
1325 ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1326 ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false)
1327 ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO)
1331 let gui = instance () in
1332 let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1333 if (selection_mode <> `SINGLE) &&
1334 (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1336 Lazy.force nonvars_uris
1338 let dialog = gui#newUriDialog () in
1339 if hide_uri_entry then
1340 dialog#uriEntryHBox#misc#hide ();
1343 dialog#uriChoiceSelectedButton#misc#hide ();
1344 dialog#uriChoiceConstantsButton#misc#hide ();
1346 dialog#okLabel#set_label ok_label;
1347 dialog#uriChoiceTreeView#selection#set_mode
1348 (selection_mode :> Gtk.Tags.selection_mode);
1349 let model = new stringListModel dialog#uriChoiceTreeView in
1350 let choices = ref None in
1354 dialog#copyButton#misc#show ();
1355 connect_button dialog#copyButton
1357 match model#easy_selection () with
1360 dialog#uriChoiceDialog#set_title title;
1361 dialog#uriChoiceLabel#set_text msg;
1362 List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1363 dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1366 dialog#uriChoiceDialog#destroy ();
1369 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1370 connect_button dialog#uriChoiceConstantsButton (fun _ ->
1371 return (Some (Lazy.force nonvars_uris)));
1372 if ok_action = `AUTO then
1373 connect_button dialog#uriChoiceAutoButton (fun _ ->
1374 Helm_registry.set_bool "matita.auto_disambiguation" true;
1375 return (Some (Lazy.force nonvars_uris)))
1377 connect_button dialog#uriChoiceAutoButton (fun _ ->
1378 match model#easy_selection () with
1380 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1381 connect_button dialog#uriChoiceSelectedButton (fun _ ->
1382 match model#easy_selection () with
1384 | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1385 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1386 dialog#uriChoiceDialog#show ();
1388 (match !choices with
1389 | None -> raise MatitaTypes.Cancel
1390 | Some uris -> uris)
1394 let cols = new GTree.column_list in
1395 let id_col = cols#add Gobject.Data.string in
1396 let dsc_col = cols#add Gobject.Data.string in
1397 let interp_no_col = cols#add Gobject.Data.int in
1398 let tree_store = GTree.tree_store cols in
1399 let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1400 let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1401 let id_view_col = GTree.view_column ~renderer:id_renderer () in
1402 let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1403 fun tree_view choices ->
1406 tree_view#set_model (Some (tree_store :> GTree.model));
1407 ignore (tree_view#append_column id_view_col);
1408 ignore (tree_view#append_column dsc_view_col);
1409 let name_of_interp =
1410 (* try to find a reasonable name for an interpretation *)
1414 List.assoc "0" interp
1416 incr idx; string_of_int !idx
1418 tree_store#clear ();
1419 let idx = ref ~-1 in
1423 let interp_row = tree_store#append () in
1424 tree_store#set ~row:interp_row ~column:id_col
1425 (name_of_interp interp);
1426 tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1429 let row = tree_store#append ~parent:interp_row () in
1430 tree_store#set ~row ~column:id_col id;
1431 tree_store#set ~row ~column:dsc_col dsc;
1432 tree_store#set ~row ~column:interp_no_col !idx)
1436 method get_interp_no tree_path =
1437 let iter = tree_store#get_iter tree_path in
1438 tree_store#get ~row:iter ~column:interp_no_col
1442 let interactive_string_choice
1443 text prefix_len ?(title = "") ?(msg = "") () ~id locs uris
1445 let gui = instance () in
1446 let dialog = gui#newUriDialog () in
1447 dialog#uriEntryHBox#misc#hide ();
1448 dialog#uriChoiceSelectedButton#misc#hide ();
1449 dialog#uriChoiceAutoButton#misc#hide ();
1450 dialog#uriChoiceConstantsButton#misc#hide ();
1451 dialog#uriChoiceTreeView#selection#set_mode
1452 (`SINGLE :> Gtk.Tags.selection_mode);
1453 let model = new stringListModel dialog#uriChoiceTreeView in
1454 let choices = ref None in
1455 dialog#uriChoiceDialog#set_title title;
1456 let hack_len = MatitaGtkMisc.utf8_string_length text in
1457 let rec colorize acc_len = function
1459 let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1460 escape_pango_markup (fst(MatitaGtkMisc.utf8_parsed_text text floc))
1462 let start, stop = HExtlib.loc_of_floc he in
1463 let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1464 let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1465 let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1466 escape_pango_markup str1 ^ "<b>" ^
1467 escape_pango_markup str2 ^ "</b>" ^
1470 (* List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1471 Printf.eprintf "(%d,%d)" start stop) locs; *)
1475 fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2))
1478 (* prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1479 List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1480 Printf.eprintf "(%d,%d)" start stop) locs;
1481 prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1482 dialog#uriChoiceLabel#set_use_markup true;
1483 let txt = colorize 0 locs in
1484 let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1485 (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1487 dialog#uriChoiceLabel#set_label txt;
1488 List.iter model#easy_append uris;
1491 dialog#uriChoiceDialog#destroy ();
1494 ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1495 connect_button dialog#uriChoiceForwardButton (fun _ ->
1496 match model#easy_selection () with
1498 | uris -> return (Some uris));
1499 connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1500 dialog#uriChoiceDialog#show ();
1502 (match !choices with
1503 | None -> raise MatitaTypes.Cancel
1504 | Some uris -> uris)
1506 let interactive_interp_choice () text prefix_len choices =
1507 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1508 let filter_choices filter =
1509 let rec is_compatible filter =
1512 | ([],_,_)::tl -> is_compatible filter tl
1513 | (loc::tlloc,id,dsc)::tl ->
1515 if List.assoc (loc,id) filter = dsc then
1516 is_compatible filter ((tlloc,id,dsc)::tl)
1522 List.filter (fun (_,interp) -> is_compatible filter interp)
1524 let rec get_choices loc id =
1529 List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1531 dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1533 let example_interp =
1537 let ask_user id locs choices =
1538 interactive_string_choice
1540 ~title:"Ambiguous input"
1541 ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1543 let rec classify ids filter partial_interpretations =
1545 [] -> List.map fst partial_interpretations
1546 | ([],_,_)::tl -> classify tl filter partial_interpretations
1547 | (loc::tlloc,id,dsc)::tl ->
1548 let choices = get_choices loc id partial_interpretations in
1551 [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1554 match ask_user id [loc] choices with
1558 let filter = ((loc,id),chosen_dsc)::filter in
1559 let compatible_interps = filter_choices filter partial_interpretations in
1560 classify ((tlloc,id,dsc)::tl) filter compatible_interps
1562 let enumerated_choices =
1563 let idx = ref ~-1 in
1564 List.map (fun interp -> incr idx; !idx,interp) choices
1566 classify example_interp [] enumerated_choices
1569 (* disambiguator callbacks *)
1570 MultiPassDisambiguator.set_choose_uris_callback
1571 (fun ~selection_mode ?ok ?(enable_button_for_non_vars=false) ~title ~msg ->
1572 interactive_uri_choice ~selection_mode ?ok_label:ok ~title ~msg ());
1573 MultiPassDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1574 (* gtk initialization *)
1575 GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1576 GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1577 ignore (GMain.Main.init ())