why3ide.ml 27.8 KB
Newer Older
1 2 3
open Format
open Why3
open Gconfig
4
open Stdlib
5

6 7
external reset_gc : unit -> unit = "ml_reset_gc"

8 9
let debug = Debug.lookup_flag "ide_info"

Clément Fumex's avatar
Clément Fumex committed
10 11 12 13
(*******************)
(* server protocol *)
(*******************)
open Itp_server
14

Clément Fumex's avatar
Clément Fumex committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
module Protocol_why3ide  = struct

  let debug_proto = Debug.register_flag "ide_proto"
      ~desc:"Print@ debugging@ messages@ about@ Why3Ide@ protocol@."

  let print_request_debug r =
    Debug.dprintf debug_proto "[request]";
    match r with
    | Command_req s -> Debug.dprintf debug_proto "command \"%s\"" s
    | Prove_req (prover, _rl) -> Debug.dprintf debug_proto "prove with %s" prover
    | Transform_req (tr, _args) -> Debug.dprintf debug_proto "transformation :%s" tr
    | Strategy_req st -> Debug.dprintf debug_proto "strategy %s" st
    | Open_req f -> Debug.dprintf debug_proto "open file %s" f
    | Set_max_tasks_req i -> Debug.dprintf debug_proto "set max tasks %i" i
    | Get_task -> Debug.dprintf debug_proto "get task"
    | Get_Session_Tree_req -> Debug.dprintf debug_proto "get session tree"
    | Save_req -> Debug.dprintf debug_proto "save"
    | Reload_req -> Debug.dprintf debug_proto "reload"
    | Replay_req -> Debug.dprintf debug_proto "replay"
    | Exit_req -> Debug.dprintf debug_proto "exit"

  let print_msg_debug m = match m with
    | Proof_error (_ids, s) -> Debug.dprintf debug_proto "proof error %s" s
    | Transf_error (_ids, s) -> Debug.dprintf debug_proto "transf error %s" s
    | Strat_error (_ids, s) -> Debug.dprintf debug_proto "start error %s" s
    | Replay_Info s -> Debug.dprintf debug_proto "replay info %s" s
    | Query_Info (_ids, s) -> Debug.dprintf debug_proto "query info %s" s
    | Query_Error (_ids, s) -> Debug.dprintf debug_proto "query error %s" s
    | Help _s -> Debug.dprintf debug_proto "help"
    | Information s -> Debug.dprintf debug_proto "info %s" s
    | Task_Monitor _ -> Debug.dprintf debug_proto "task montor"

  let print_notify_debug n =
    Debug.dprintf debug_proto "[notification]";
    match n with
    | Node_change (_ni, _nf) -> Debug.dprintf debug_proto "node change"
    | New_node (_ni, _pni, _nt,  _nf) -> Debug.dprintf debug_proto "new node"
    | Remove _ni -> Debug.dprintf debug_proto "remove"
    | Initialized _gi -> Debug.dprintf debug_proto "initialized"
    | Saved -> Debug.dprintf debug_proto "saved"
    | Message msg ->
      Debug.dprintf debug_proto "[message] ";
      print_msg_debug msg
    | Dead s -> Debug.dprintf debug_proto "dead :%s" s
    | Proof_update (_ni, _pas) -> Debug.dprintf debug_proto "proof update"
    | Task (_ni, _s) -> Debug.dprintf debug_proto "task"

  let list_requests: ide_request list ref = ref []

  let get_requests () =
    if List.length !list_requests > 0 then
      Debug.dprintf debug_proto "get requests@.";
    let l = List.rev !list_requests in
    list_requests := [];
    l

  let send_request r =
    print_request_debug (fst r);
    Debug.dprintf debug_proto "@.";
    list_requests := r :: !list_requests

  let notification_list: notification list ref = ref []

  let notify n =
    print_notify_debug n;
    Debug.dprintf debug_proto "@.";
    notification_list := n :: !notification_list

  let get_notified () =
    if List.length !notification_list > 0 then
      Debug.dprintf debug_proto "get notified@.";
    let l = List.rev !notification_list in
    notification_list := [];
    l
Sylvain Dailler's avatar
Sylvain Dailler committed
89 90 91

end

Clément Fumex's avatar
Clément Fumex committed
92
let get_notified = Protocol_why3ide.get_notified
Sylvain Dailler's avatar
Sylvain Dailler committed
93

Clément Fumex's avatar
Clément Fumex committed
94
let send_request = Protocol_why3ide.send_request
Sylvain Dailler's avatar
Sylvain Dailler committed
95

Clément Fumex's avatar
Clément Fumex committed
96 97 98
(****************************************)
(* server instance on the GTK scheduler *)
(****************************************)
99

Clément Fumex's avatar
Clément Fumex committed
100 101 102
module S = struct
    let idle ~prio f =
      let (_ : GMain.Idle.id) = GMain.Idle.add ~prio f in ()
103

Clément Fumex's avatar
Clément Fumex committed
104 105 106 107
    let timeout ~ms f =
      let (_ : GMain.Timeout.id) = GMain.Timeout.add ~ms ~callback:f in
      ()
end
108

Clément Fumex's avatar
Clément Fumex committed
109
module Server = Itp_server.Make (S) (Protocol_why3ide)
Sylvain Dailler's avatar
Sylvain Dailler committed
110

Clément Fumex's avatar
Clément Fumex committed
111 112 113
(************************)
(* parsing command line *)
(************************)
114

Clément Fumex's avatar
Clément Fumex committed
115 116 117 118 119 120 121 122
let files : string Queue.t = Queue.create ()
let opt_parser = ref None

let spec = Arg.align [
  "-F", Arg.String (fun s -> opt_parser := Some s),
      "<format> select input format (default: \"why\")";
  "--format", Arg.String (fun s -> opt_parser := Some s),
      " same as -F";
Sylvain Dailler's avatar
Sylvain Dailler committed
123
(*
Clément Fumex's avatar
Clément Fumex committed
124 125 126
  "-f",
   Arg.String (fun s -> input_files := s :: !input_files),
   "<file> add file to the project (ignored if it is already there)";
Sylvain Dailler's avatar
Sylvain Dailler committed
127
*)
Clément Fumex's avatar
Clément Fumex committed
128 129
  Termcode.arg_extra_expl_prefix
]
130

Clément Fumex's avatar
Clément Fumex committed
131 132 133
let usage_str = sprintf
  "Usage: %s [options] [<file.why>|<project directory>]..."
  (Filename.basename Sys.argv.(0))
MARCHE Claude's avatar
MARCHE Claude committed
134

Clément Fumex's avatar
Clément Fumex committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
let gconfig = try
    let config,base_config = Server.get_configs () in
    Whyconf.Args.parse spec (fun f -> Queue.add f files) usage_str;
    if Queue.is_empty files then
      Whyconf.Args.exit_with_usage spec usage_str;
    Gconfig.load_config config base_config;
    Gconfig.config ()

  with e when not (Debug.test_flag Debug.stack_trace) ->
    eprintf "%a@." Exn_printer.exn_printer e;
    exit 1

let () =
  Debug.dprintf debug "[GUI] Init the GTK interface...@?";
  ignore (GtkMain.Main.init ());
  Debug.dprintf debug " done.@.";
  Gconfig.init ()

(********************)
(* Terminal history *)
(********************)

module type Historic_type = sig
  type historic

  val create_historic: unit -> historic
  val print_next_command: historic -> string option
  val print_prev_command: historic -> string option
  val add_command: historic -> string -> unit

end

module Historic : Historic_type = struct
  type 'a hole_list = 'a list * 'a list

  (* TODO this looks like we can make it more efficient either with imperative
     feature or by being more clever.  With DLlists, we could have added a
     command in O(1). *)
  let add e l =
    match l with
    | ll, lr ->  [], e :: (List.rev ll) @ lr

  let next l =
    match l with
    | ll, [] -> ll, []
    | ll, [hd] -> ll, [hd]
    (* Get acts on the right list so we never empty right list *)
    | ll, cur :: lr -> cur :: ll, lr

  let prev l =
    match l with
    | hd :: ll, lr -> ll, hd :: lr
    | [], lr -> [], lr

  let get l =
    match l with
    | _, hd :: _ -> Some hd
    | _, [] -> None

  type historic = {mutable lc : string hole_list;
                   mutable tr : bool}
(* tr is used to know what was the last query from user because cases for the
   first element of the historic and other elements is not the same *)

  let create_historic () : historic =
    {lc = [], [];
     tr = false}

  let get_current h =
    get h.lc

  let print_next_command h =
    if h.tr then
      begin
        h.lc <- next h.lc;
        get_current h
      end
    else
      begin
        let s = get_current h in
        h.tr <- true;
        s
      end

  let print_prev_command h =
    if h.tr then
      begin
        h.lc <- prev h.lc;
        get_current h
      end
    else
      None

  let add_command h e =
    h.lc <- add e h.lc;
    h.tr <- false

end
233

Clément Fumex's avatar
Clément Fumex committed
234
open Historic
MARCHE Claude's avatar
MARCHE Claude committed
235

MARCHE Claude's avatar
MARCHE Claude committed
236 237 238 239 240
(********************************)
(* Source language highlighting *)
(********************************)

let (why_lang, any_lang) =
Clément Fumex's avatar
Clément Fumex committed
241 242
  let main = Whyconf.get_main gconfig.config in
  let load_path = Filename.concat (Whyconf.datadir main) "lang" in
MARCHE Claude's avatar
MARCHE Claude committed
243 244 245 246 247 248 249 250
  let languages_manager =
    GSourceView2.source_language_manager ~default:true
  in
  languages_manager#set_search_path
    (load_path :: languages_manager#search_path);
  let why_lang =
    match languages_manager#language "why3" with
    | None ->
Clément Fumex's avatar
Clément Fumex committed
251
        eprintf "language file for 'why3' not found in directory %s@."
MARCHE Claude's avatar
MARCHE Claude committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
          load_path;
        exit 1
    | Some _ as l -> l in
  let any_lang filename =
    match languages_manager#guess_language ~filename () with
    | None -> why_lang
    | Some _ as l -> l in
  (why_lang, any_lang)

(* Borrowed from Frama-C src/gui/source_manager.ml:
Try to convert a source file either as UTF-8 or as locale. *)
let try_convert s =
  try
    if Glib.Utf8.validate s then s else Glib.Convert.locale_to_utf8 s
  with Glib.Convert.Error _ ->
    try
      Glib.Convert.convert_with_fallback
        ~fallback:"#neither UTF-8 nor locale nor ISO-8859-15#"
        ~to_codeset:"UTF-8"
        ~from_codeset:"ISO_8859-15"
        s
    with Glib.Convert.Error _ as e -> Printexc.to_string e


276 277 278
(**********************)
(* Graphical elements *)
(**********************)
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315

let main_window =
  let w = GWindow.window
            ~allow_grow:true ~allow_shrink:true
            ~width:gconfig.window_width
            ~height:gconfig.window_height
            ~title:"Why3 Interactive Proof Session" ()
  in
  (* callback to record the new size of the main window when changed, so
   that on restart the window size is the same as the last session *)
  let (_ : GtkSignal.id) =
    w#misc#connect#size_allocate
      ~callback:
      (fun {Gtk.width=w;Gtk.height=h} ->
       gconfig.window_height <- h;
       gconfig.window_width <- w)
  in w

(* the main window contains a vertical box, containing:
   1. the menu
   2. an horizontal box
 *)

let vbox = GPack.vbox ~packing:main_window#add ()

let menubar = GMenu.menu_bar
  ~packing:(vbox#pack ?from:None ?expand:None ?fill:None ?padding:None)
  ()

let hb = GPack.hbox ~packing:vbox#add ()

(* 1. Menu *)

let factory = new GMenu.factory menubar

let accel_group = factory#accel_group

MARCHE Claude's avatar
MARCHE Claude committed
316 317
(* 1.1 "File" menu *)

318 319 320 321
let file_menu = factory#add_submenu "_File"
let file_factory = new GMenu.factory file_menu ~accel_group

let exit_function ~destroy () =
Clément Fumex's avatar
Clément Fumex committed
322 323
  (* will this be treated before gmain quit ?!? *)
  send_request (Exit_req, root_node);
324 325 326 327 328
  ignore(destroy); GMain.quit ()

let (_ : GtkSignal.id) = main_window#connect#destroy
  ~callback:(exit_function ~destroy:true)

329 330
let (_ : GMenu.menu_item) =
  file_factory#add_item ~key:GdkKeysyms._S "_Save session"
Clément Fumex's avatar
Clément Fumex committed
331
    ~callback:(fun () -> send_request (Save_req, root_node))
332 333 334 335

let (replay_menu_item : GMenu.menu_item) =
  file_factory#add_item ~key:GdkKeysyms._R "_Replay all"

336 337
let (_ : GMenu.menu_item) =
  file_factory#add_item ~key:GdkKeysyms._Q "_Quit"
Clément Fumex's avatar
Clément Fumex committed
338
    ~callback:(exit_function ~destroy:false)
339

MARCHE Claude's avatar
MARCHE Claude committed
340 341 342 343 344 345 346

(* 1.2 "View" menu

   the entries in that menu are defined later

*)

347 348 349 350
(* 2. horizontal box contains:
   2.1 TODO: a tool box ?
   2.2 a horizontal paned containing:
     2.2.1 a scrolled window to hold the tree view of the session
Clément Fumex's avatar
Clément Fumex committed
351
     2.2.2 a vertical paned containing
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
*)

let hp = GPack.paned `HORIZONTAL ~packing:hb#add ()

let scrollview =
  let sv =
    GBin.scrolled_window
      ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
      ~width:gconfig.tree_width ~shadow_type:`ETCHED_OUT
      ~packing:hp#add ()
  in
  let (_ : GtkSignal.id) =
    sv#misc#connect#size_allocate
      ~callback:
      (fun {Gtk.width=w;Gtk.height=_h} ->
       gconfig.tree_width <- w)
  in sv

Clément Fumex's avatar
Clément Fumex committed
370
let vpan222 = GPack.paned `VERTICAL ~packing:hp#add ()
371 372 373 374 375 376

(*  the scrolled window 2.2.1 contains a GTK tree

*)


MARCHE Claude's avatar
MARCHE Claude committed
377 378 379 380 381 382 383 384
(* view for the session tree *)
let scrolled_session_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT
    ~packing:scrollview#add
    ()

385 386
let cols = new GTree.column_list
let name_column = cols#add Gobject.Data.string
Clément Fumex's avatar
Clément Fumex committed
387
let node_id_column = cols#add Gobject.Data.int
388
let status_column = cols#add Gobject.Data.gobject
MARCHE Claude's avatar
MARCHE Claude committed
389

390 391 392 393
let name_renderer = GTree.cell_renderer_text [`XALIGN 0.]
let view_name_column = GTree.view_column ~title:"Theories/Goals" ()
let () =
  view_name_column#pack name_renderer;
394 395 396 397 398 399
  view_name_column#add_attribute name_renderer "text" name_column;
  view_name_column#set_sizing `AUTOSIZE

let status_renderer = GTree.cell_renderer_pixbuf [ ]
let view_status_column = GTree.view_column ~title:"Status"
    ~renderer:(status_renderer, ["pixbuf", status_column])()
400

401 402 403 404 405 406 407 408 409
let goals_model,goals_view =
  Debug.dprintf debug "[GUI] Creating tree model...@?";
  let model = GTree.tree_store cols in
  let view = GTree.view ~model ~packing:scrolled_session_view#add () in
(*
  let () = view#selection#set_mode (* `SINGLE *) `MULTIPLE in
  let () = view#set_rules_hint true in
 *)
  ignore (view#append_column view_name_column);
410
  ignore (view#append_column view_status_column);
411 412 413 414 415 416
(*
  ignore (view#append_column view_status_column);
  ignore (view#append_column view_time_column);
*)
  Debug.dprintf debug " done@.";
  model,view
417

Clément Fumex's avatar
Clément Fumex committed
418
(* vpan222 contains:
419
   2.2.2.1 a view of the current task
Clément Fumex's avatar
Clément Fumex committed
420 421
   2.2.2.2 a vertiacal pan which contains
     2.2.2.2.1 the input field to type commands
422
     2.2.2.2.2 a scrolled window to hold the output of the commands
423 424 425 426 427 428
 *)

let scrolled_task_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT
Clément Fumex's avatar
Clément Fumex committed
429
    ~packing:vpan222#add ()
430 431 432 433

let task_view =
  GSourceView2.source_view
    ~editable:false
Clément Fumex's avatar
Clément Fumex committed
434
    ~cursor_visible:false
435 436 437 438
    ~show_line_numbers:true
    ~packing:scrolled_task_view#add
    ()

Clément Fumex's avatar
Clément Fumex committed
439
let vbox2222 = GPack.vbox ~packing:vpan222#add  ()
440

441 442 443 444 445 446
let hbox22221 =
  GPack.hbox
    ~packing:(vbox2222#pack ?from:None ?expand:None ?fill:None ?padding:None) ()

let monitor =
  GMisc.label
MARCHE Claude's avatar
MARCHE Claude committed
447 448 449
    ~text:"  0/0/0"
    ~width:80
    ~xalign:0.0
450
    ~packing:(hbox22221#pack ?from:None ?expand:None ?fill:None ?padding:None) ()
451

MARCHE Claude's avatar
MARCHE Claude committed
452 453
let command_entry = GEdit.entry ~packing:hbox22221#add ()

MARCHE Claude's avatar
MARCHE Claude committed
454
let message_zone =
455 456 457 458
  let sv = GBin.scrolled_window
      ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
      ~shadow_type:`ETCHED_OUT ~packing:vbox2222#add ()
  in
MARCHE Claude's avatar
MARCHE Claude committed
459
  GText.view ~editable:false ~cursor_visible:false
460 461
    ~packing:sv#add ()

462
(**** Monitor *****)
Clément Fumex's avatar
Clément Fumex committed
463

464 465 466 467 468 469 470 471 472 473 474 475 476
let fan n =
  match n mod 4 with
    | 0 -> "|"
    | 1 | -3 -> "\\"
    | 2 | -2 -> "-"
    | 3 | -1 -> "/"
    | _ -> assert false

let update_monitor =
  let c = ref 0 in
  fun t s r ->
  reset_gc ();
  incr c;
MARCHE Claude's avatar
MARCHE Claude committed
477 478 479
  let f = if r=0 then "  " else fan (!c / 2) ^ " " in
  monitor#set_text
    (f ^ (string_of_int t) ^ "/" ^ (string_of_int s) ^ "/" ^ (string_of_int r))
Clément Fumex's avatar
Clément Fumex committed
480

MARCHE Claude's avatar
MARCHE Claude committed
481

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
(****************************)
(* command entry completion *)
(****************************)

let completion_cols = new GTree.column_list
let completion_col = completion_cols#add Gobject.Data.string
let completion_model = GTree.tree_store completion_cols

let command_entry_completion : GEdit.entry_completion =
  GEdit.entry_completion ~model:completion_model ~minimum_key_length:1 ~entry:command_entry ()

let add_completion_entry s =
  let row = completion_model#append () in
  completion_model#set ~row ~column:completion_col s

497 498 499 500 501 502 503
let match_function s iter =
  let candidate = completion_model#get ~row:iter ~column:completion_col in
  try
    ignore (Str.search_forward (Str.regexp s) candidate 0);
    true
  with Not_found -> false

Clément Fumex's avatar
Clément Fumex committed
504
let init_completion provers transformations commands =
505
  (* add the names of all the the transformations *)
Clément Fumex's avatar
Clément Fumex committed
506
  List.iter add_completion_entry transformations;
507
  (* add the name of the commands *)
Clément Fumex's avatar
Clément Fumex committed
508
  List.iter add_completion_entry commands;
509 510
  (* todo: add queries *)

511
  (* add provers *)
Clément Fumex's avatar
Clément Fumex committed
512 513
  List.iter add_completion_entry provers;

514 515 516
  add_completion_entry "auto";
  add_completion_entry "auto 2";

517
  command_entry_completion#set_text_column completion_col;
518
  command_entry_completion#set_match_func match_function;
519

520
  command_entry#set_completion command_entry_completion
521

Sylvain Dailler's avatar
Sylvain Dailler committed
522 523 524 525
(*********************)
(* Terminal historic *)
(*********************)

526
let list_commands = create_historic()
Sylvain Dailler's avatar
Sylvain Dailler committed
527 528 529

let _ =
  command_entry#event#connect#key_press
530 531 532
    ~callback:(fun (ev: 'a Gdk.event) ->
      match GdkEvent.Key.keyval ev with
      | k when k = GdkKeysyms._Up -> (* Arrow up *)
533 534 535 536 537
          let s = print_next_command list_commands in
          (match s with
          | None -> true
          | Some s ->
              (command_entry#set_text s; true))
538
      | k when k = GdkKeysyms._Down -> (* Arrow down *)
539 540 541 542 543
          let s = print_prev_command list_commands in
          (match s with
          | None -> true
          | Some s ->
              (command_entry#set_text s; true))
Sylvain Dailler's avatar
Sylvain Dailler committed
544 545 546
      | _ -> false
      )

Clément Fumex's avatar
Clément Fumex committed
547 548 549 550
let () =
  let n = gconfig.session_nb_processes in
  Debug.dprintf debug "[IDE] setting max proof tasks to %d@." n;
  send_request (Set_max_tasks_req n, root_node)
551

552 553
let (_ : GtkSignal.id) =
  replay_menu_item#connect#activate
Clément Fumex's avatar
Clément Fumex committed
554
    ~callback:(fun () -> send_request (Replay_req, root_node))
555 556 557 558

(***********************************)
(* Mapping session to the GTK tree *)
(***********************************)
559

Clément Fumex's avatar
Clément Fumex committed
560 561
let node_id_type : node_type Hint.t = Hint.create 17
let node_id_info : node_info Hint.t = Hint.create 17
562

Clément Fumex's avatar
Clément Fumex committed
563 564
let get_node_type id = Hint.find node_id_type id
let get_node_info id = Hint.find node_id_info id
Sylvain Dailler's avatar
Sylvain Dailler committed
565

Clément Fumex's avatar
Clément Fumex committed
566
let get_node_id iter = goals_model#get ~row:iter ~column:node_id_column
567

Clément Fumex's avatar
Clément Fumex committed
568 569 570 571
(* To each node we have the corresponding row_reference *)
let node_id_to_gtree : GTree.row_reference Hint.t = Hint.create 42
(* TODO exception for those: *)
let get_node_row id = Hint.find node_id_to_gtree id
572 573 574 575 576

let image_of_result ~obsolete rOpt =
  match rOpt with
  | None -> !image_undone
  | Some r ->
Clément Fumex's avatar
Clément Fumex committed
577
    match r with
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    | Call_provers.Valid ->
      if obsolete then !image_valid_obs else !image_valid
    | Call_provers.Invalid ->
      if obsolete then !image_invalid_obs else !image_invalid
    | Call_provers.Timeout ->
      if obsolete then !image_timeout_obs else !image_timeout
    | Call_provers.OutOfMemory ->
      if obsolete then !image_outofmemory_obs else !image_outofmemory
    | Call_provers.StepLimitExceeded ->
      if obsolete then !image_steplimitexceeded_obs
      else !image_steplimitexceeded
    | Call_provers.Unknown _ ->
      if obsolete then !image_unknown_obs else !image_unknown
    | Call_provers.Failure _ ->
      if obsolete then !image_failure_obs else !image_failure
    | Call_provers.HighFailure ->
      if obsolete then !image_failure_obs else !image_failure
595

Clément Fumex's avatar
Clément Fumex committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609
let set_status_column iter =
  let id = get_node_id iter in
  let proved = (get_node_info id).proved in
  let image = match get_node_type id with
    | NRoot -> assert false
    | NFile
    | NTheory
    | NTransformation
    | NGoal ->
      if proved
      then !image_valid
      else !image_unknown
    | NProofAttempt (pa, obs) ->
      image_of_result ~obsolete:obs pa
610 611
  in
  goals_model#set ~row:iter ~column:status_column image
612

Clément Fumex's avatar
Clément Fumex committed
613 614 615 616 617 618 619 620 621 622 623 624 625 626
let new_node ?parent ?(collapse=false) id typ info =
  if not (Hint.mem node_id_to_gtree id) then begin
    Hint.add node_id_type id typ;
    Hint.add node_id_info id info;
    let parent = Opt.map (fun x -> x#iter) parent in
    let iter = goals_model#append ?parent () in
    goals_model#set ~row:iter ~column:name_column info.name;
    goals_model#set ~row:iter ~column:node_id_column id;
    let new_ref = goals_model#get_row_reference (goals_model#get_path iter) in
    (* By default expand_path when creating a new node *)
    if not collapse then goals_view#expand_to_path (goals_model#get_path iter);
    Hint.add node_id_to_gtree id new_ref;
    set_status_column iter
  end
627

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
(*******************************)
(* commands of the "View" menu *)
(*******************************)

let view_menu = factory#add_submenu "_View"
let view_factory = new GMenu.factory view_menu ~accel_group

(* goals view is not yet multi-selectable
let (_ : GMenu.image_menu_item) =
  view_factory#add_image_item ~key:GdkKeysyms._A
    ~label:"Select all"
    ~callback:(fun () -> goals_view#selection#select_all ()) ()
 *)

let (_ : GMenu.menu_item) =
  view_factory#add_item ~key:GdkKeysyms._plus
Clément Fumex's avatar
Clément Fumex committed
644
    ~callback:enlarge_fonts "Enlarge font"
645 646 647

let (_ : GMenu.menu_item) =
    view_factory#add_item ~key:GdkKeysyms._minus
Clément Fumex's avatar
Clément Fumex committed
648
      ~callback:reduce_fonts "Reduce font"
649 650 651 652 653

let (_ : GMenu.image_menu_item) =
  view_factory#add_image_item ~key:GdkKeysyms._E
    ~label:"Expand all" ~callback:(fun () -> goals_view#expand_all ()) ()

Clément Fumex's avatar
Clément Fumex committed
654
(* let collapse_iter iter =
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
  let path = goals_model#get_path iter in
  goals_view#collapse_row path

let rec collapse_proven_goals_from_pn pn =
  match pn_proved cont pn with
  | true  -> collapse_iter (row_from_pn pn)#iter
  | false ->
    List.iter collapse_proven_goals_from_tn
      (get_transformations cont.controller_session pn)
and collapse_proven_goals_from_tn tn =
  match tn_proved cont tn with
  | true  -> collapse_iter (row_from_tn tn)#iter
  | false ->
    List.iter collapse_proven_goals_from_pn
      (get_sub_tasks cont.controller_session tn)

let collapse_proven_goals_from_th th =
  match th_proved cont th with
  | true  -> collapse_iter (row_from_th th)#iter
  | false -> List.iter collapse_proven_goals_from_pn (theory_goals th)

let collapse_proven_goals_from_file file =
  match file_proved cont file with
  | true  -> collapse_iter (row_from_file file)#iter
  | false -> List.iter collapse_proven_goals_from_th file.file_theories

let collapse_proven_goals_from_iter iter =
682
  let index = get_index iter in
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
  match index with
  | Inone              -> assert false
  | IproofAttempt _    -> ()
  | IproofNode pn      -> collapse_proven_goals_from_pn pn
  | Itransformation tn -> collapse_proven_goals_from_tn tn
  | Itheory th         -> collapse_proven_goals_from_th th
  | Ifile file         -> collapse_proven_goals_from_file file

let collapse_proven_goals () =
  match goals_model#get_iter_first with
  | None -> ()
  | Some root_iter -> collapse_proven_goals_from_iter root_iter

let (_ : GMenu.image_menu_item) =
  view_factory#add_image_item ~key:GdkKeysyms._C
Clément Fumex's avatar
Clément Fumex committed
698
    ~label:"Collapse proven goals" ~callback:(fun () -> collapse_proven_goals ()) () *)
699 700 701 702 703 704 705

let () =
  Gconfig.add_modifiable_sans_font_view goals_view#misc;
  Gconfig.add_modifiable_mono_font_view monitor#misc;
  Gconfig.add_modifiable_mono_font_view task_view#misc;
  Gconfig.add_modifiable_mono_font_view command_entry#misc;
  Gconfig.add_modifiable_mono_font_view message_zone#misc;
MARCHE Claude's avatar
MARCHE Claude committed
706
  task_view#source_buffer#set_language why_lang;
Clément Fumex's avatar
Clément Fumex committed
707
  Gconfig.set_fonts ()
708

709 710 711 712
(******************)
(*    actions     *)
(******************)

Clément Fumex's avatar
Clément Fumex committed
713 714 715 716
let get_selected_row_references () =
  List.map
    (fun path -> goals_model#get_row_reference path)
    goals_view#selection#get_selected_rows
717

718 719 720 721 722 723 724 725 726
let image_of_pa_status ~obsolete pa_status =
  match pa_status with
    | Controller_itp.Interrupted   -> !image_undone
    | Controller_itp.Unedited      -> !image_editor
    | Controller_itp.JustEdited    -> !image_unknown
    | Controller_itp.Scheduled     -> !image_scheduled
    | Controller_itp.Running       -> !image_running
    | Controller_itp.InternalFailure _
    | Controller_itp.Uninstalled _ -> !image_failure
Clément Fumex's avatar
Clément Fumex committed
727 728
    | Controller_itp.Done r        ->
      image_of_result ~obsolete (Some r.Call_provers.pr_answer)
729 730

let rec update_status_column_from_iter cont iter =
Clément Fumex's avatar
Clément Fumex committed
731
  set_status_column iter;
732
  match goals_model#iter_parent iter with
733
  | Some p -> update_status_column_from_iter cont p
734 735
  | None -> ()

736 737
let move_current_row_selection_up () =
  let current_view = List.hd (goals_view#selection#get_selected_rows) in
738 739 740
  ignore (GTree.Path.up current_view);
  let row_up = goals_model#get_row_reference current_view in
  goals_view#selection#select_iter row_up#iter
741 742 743 744 745 746 747 748 749 750 751 752 753

let move_current_row_selection_down () =
  let current_iter =
    try
      let current_view = List.hd (goals_view#selection#get_selected_rows) in
      let current_row = goals_model#get_row_reference current_view in
      Some current_row#iter
    with Not_found ->
      None
  in
  let child = goals_model#iter_children current_iter in
  goals_view#selection#select_iter child

754
let clear_command_entry () = command_entry#set_text ""
MARCHE Claude's avatar
MARCHE Claude committed
755 756

let interp cmd =
Clément Fumex's avatar
Clément Fumex committed
757 758 759 760 761 762 763 764 765 766 767
  (* TODO: do some preprocessing for queries, or leave everything to server ? *)
  (* TODO: treat multiple rows *)
  let rows = get_selected_row_references () in
  let id = if List.length rows > 0 then
      get_node_id ((List.hd rows)#iter)
    else
      root_node
  in
  send_request (Command_req cmd, id)
(*
   let id =
MARCHE Claude's avatar
MARCHE Claude committed
768 769 770 771
    match !current_selected_index with
    | IproofNode id -> Some id
    | _ -> None
  in
772 773
  try
  match interp cont id cmd with
774 775
    | Transform(s,_t,args) ->
       clear_command_entry ();
776
       apply_transform cont s args
777
    | Query s ->
MARCHE Claude's avatar
MARCHE Claude committed
778
       clear_command_entry ();
779
       message_zone#buffer#set_text s
780 781 782 783 784
    | Other(s,args) ->
      begin
        match parse_prover_name gconfig.config s args with
        | Some (prover_config, limit) ->
          clear_command_entry ();
785
          test_schedule_proof_attempt cont prover_config limit
786 787
        | None ->
          match s with
MARCHE Claude's avatar
MARCHE Claude committed
788 789 790
          | "auto" ->
             let s =
               match args with
MARCHE Claude's avatar
MARCHE Claude committed
791 792
               | "2"::_ -> "2"
               | _ -> "1"
MARCHE Claude's avatar
MARCHE Claude committed
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
             in
             clear_command_entry ();
             run_strategy_on_task s
          | "help" ->
             clear_command_entry ();
             let text = Pp.sprintf
                          "Please type a command among the following (automatic completion available)@\n\
                           @\n\
                           @ <transformation name> [arguments]@\n\
                           @ <prover name> [<time limit> [<mem limit>]]@\n\
                           @ <query> [arguments]@\n\
                           @ auto [auto level]@\n\
                           @\n\
                           Available queries are:@\n@[%a@]" help_on_queries ()
             in
             message_zone#buffer#set_text text
809 810
          | _ ->
             message_zone#buffer#set_text ("unknown command '"^s^"'")
811
      end
812
  with e when not (Debug.test_flag Debug.stack_trace) ->
Clément Fumex's avatar
Clément Fumex committed
813
       message_zone#buffer#set_text (Pp.sprintf "anomaly: %a" Exn_printer.exn_printer e) *)
MARCHE Claude's avatar
MARCHE Claude committed
814 815 816

let (_ : GtkSignal.id) =
  command_entry#connect#activate
Clément Fumex's avatar
Clément Fumex committed
817
    ~callback:(fun () -> add_command list_commands command_entry#text; interp command_entry#text)
818

819 820
let on_selected_row r =
  try
Clément Fumex's avatar
Clément Fumex committed
821 822 823 824 825
    let id = get_node_id r#iter in
    let typ = get_node_type id in
    match typ with
    | NGoal ->
      send_request (Get_task, id)
826 827 828
    | _ -> task_view#source_buffer#set_text ""
  with
    | Not_found -> task_view#source_buffer#set_text ""
Clément Fumex's avatar
Clément Fumex committed
829

830 831 832 833 834 835
let (_ : GtkSignal.id) =
  goals_view#selection#connect#after#changed ~callback:
    (fun () ->
      match get_selected_row_references () with
        | [r] -> on_selected_row r
        | _ -> ())
Clément Fumex's avatar
Clément Fumex committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891

(*************************)
(* Notification Handling *)
(*************************)

let add_to_msg_zone s =
  let s = message_zone#buffer#get_text () ^ "\n" ^ s in
  message_zone#buffer#set_text s;
  message_zone#scroll_to_mark `INSERT

let treat_message_notification msg = match msg with
  (* TODO: do something ! *)
  | Proof_error (_id, s)    -> add_to_msg_zone s
  | Transf_error (_id, s)   -> add_to_msg_zone s
  | Strat_error (_id, s)    -> add_to_msg_zone s
  | Replay_Info s          -> add_to_msg_zone s
  | Query_Info (_id, s)     -> add_to_msg_zone s
  | Query_Error (_id, s)    -> add_to_msg_zone s
  | Help s                 -> add_to_msg_zone s
  | Information s          -> add_to_msg_zone s
  | Task_Monitor (t, s, r) -> update_monitor t s r

let treat_notification n = match n with
  | Node_change (id, info)        ->
    Hint.replace node_id_info id info;
    set_status_column (get_node_row id)#iter
  | New_node (id, pid, typ, info) ->
    begin try
        let parent = get_node_row pid in
        new_node ~parent id typ info
      with Not_found ->
        new_node id typ info
    end
  | Remove _id                     -> (* TODO *)
    add_to_msg_zone "got a Remove notification not yet supported\n"
  | Initialized g_info            ->
    (* TODO: treat other *)
    init_completion g_info.provers g_info.transformations g_info.commands;
  | Saved                         -> (* TODO *)
    add_to_msg_zone "got a Saved notification not yet supported\n"
  | Message (msg)                 -> treat_message_notification msg
  | Proof_update (id, pa)         -> (* TODO *)
    let r = get_node_row id in
    let obsolete = match get_node_type id with
      | NProofAttempt (_, obsolete) -> obsolete
      | _ -> assert false
    in
    goals_model#set ~row:r#iter ~column:status_column
      (image_of_pa_status ~obsolete pa)
  | Dead _s                        -> (* TODO *)
    add_to_msg_zone "got a Dead notification not yet supported\n"
  | Task (_id, s)                  ->
    (* TODO: check that the id is the current one *)
    task_view#source_buffer#set_text s;
    (* scroll to end of text *)
    task_view#scroll_to_mark `INSERT
892 893

(***********************)
894
(* start the interface *)
895
(***********************)
896

Clément Fumex's avatar
Clément Fumex committed
897 898 899
let () =
  S.timeout ~ms:100 (fun () -> List.iter treat_notification (get_notified ()); true);
  Queue.iter (fun f -> send_request (Open_req f, root_node)) files;
900
  (* temporary *)
Clément Fumex's avatar
Clément Fumex committed
901
  vpan222#set_position 500;
902
  goals_view#expand_all ();
903 904
  main_window#add_accel_group accel_group;
  main_window#set_icon (Some !Gconfig.why_icon);
905
  message_zone#buffer#set_text "Welcome to Why3 IDE\ntype 'help' for help";
906 907
  main_window#show ();
  GMain.main ()