why3ide.ml 33.5 KB
Newer Older
1
open Why3
2
open Format
3
open Gconfig
4
open Stdlib
Sylvain Dailler's avatar
Sylvain Dailler committed
5 6
open Ide_utils
open History
7 8
open Itp_communication
open Itp_server
9

10 11
external reset_gc : unit -> unit = "ml_reset_gc"

12 13
let debug = Debug.lookup_flag "ide_info"

14 15 16 17 18
(***************************)
(* Debugging Json protocol *)
(***************************)


19
(* TODO remove print_request_json and print_notification_json *)
20 21 22 23 24
exception Badparsing

let print_request_json fmt (r: ide_request) =
  (try (
    let s = Pp.string_of Json_util.print_request r in
25
    let x = Json_util.parse_request s in
26 27 28 29 30 31 32
    if r = x then () else raise Badparsing)
  with
    _ -> Format.eprintf "Bad parsing@.");
  Json_util.print_request fmt r

let print_notification_json fmt (n: notification) =
  (try (
33
    let x = Json_util.parse_notification (Pp.string_of Json_util.print_notification n) in
34 35 36 37 38 39 40 41
    if n = x then () else raise Badparsing)
  with
    _ -> Format.eprintf "Bad parsing@.");
  Json_util.print_notification fmt n

let debug_json = Debug.register_flag "json_proto"
    ~desc:"Print@ json@ requests@ and@ notifications@"

Clément Fumex's avatar
Clément Fumex committed
42 43 44
(*******************)
(* server protocol *)
(*******************)
45

46
module Protocol_why3ide = struct
Clément Fumex's avatar
Clément Fumex committed
47 48

  let debug_proto = Debug.register_flag "ide_proto"
49
      ~desc:"Print@ debugging@ messages@ about@ Why3Ide@ protocol@"
Clément Fumex's avatar
Clément Fumex committed
50 51 52

  let print_request_debug r =
    Debug.dprintf debug_proto "[request]";
53 54
    Debug.dprintf debug_proto "%a@." print_request r;
    Debug.dprintf debug_json "%a@." print_request_json r
Clément Fumex's avatar
Clément Fumex committed
55

Sylvain Dailler's avatar
Sylvain Dailler committed
56 57 58
  let print_msg_debug m =
    Debug.dprintf debug_proto "[message]";
    Debug.dprintf debug_proto "%a@." print_msg m
Clément Fumex's avatar
Clément Fumex committed
59 60 61

  let print_notify_debug n =
    Debug.dprintf debug_proto "[notification]";
62 63
    Debug.dprintf debug_proto "%a@." print_notify n;
    Debug.dprintf debug_json "%a@." print_notification_json n
Clément Fumex's avatar
Clément Fumex committed
64 65 66 67 68 69 70 71 72 73 74

  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 =
75
    print_request_debug r;
Clément Fumex's avatar
Clément Fumex committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    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
92 93 94

end

Clément Fumex's avatar
Clément Fumex committed
95
let get_notified = Protocol_why3ide.get_notified
Sylvain Dailler's avatar
Sylvain Dailler committed
96

Clément Fumex's avatar
Clément Fumex committed
97
let send_request = Protocol_why3ide.send_request
Sylvain Dailler's avatar
Sylvain Dailler committed
98

Clément Fumex's avatar
Clément Fumex committed
99 100 101
(****************************************)
(* server instance on the GTK scheduler *)
(****************************************)
102

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

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

112 113
module Server = Itp_server.Make (S) (Protocol_why3ide)

Clément Fumex's avatar
Clément Fumex committed
114 115 116
(************************)
(* parsing command line *)
(************************)
117

Clément Fumex's avatar
Clément Fumex committed
118 119 120 121 122 123 124 125
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
126
(*
Clément Fumex's avatar
Clément Fumex committed
127 128 129
  "-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
130
*)
Clément Fumex's avatar
Clément Fumex committed
131 132
  Termcode.arg_extra_expl_prefix
]
133

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

138 139 140
let env, gconfig = try
  let config, base_config, env =
    Whyconf.Args.initialize spec (fun f -> Queue.add f files) usage_str in
Clément Fumex's avatar
Clément Fumex committed
141 142 143
    if Queue.is_empty files then
      Whyconf.Args.exit_with_usage spec usage_str;
    Gconfig.load_config config base_config;
144
    env, Gconfig.config ()
Clément Fumex's avatar
Clément Fumex committed
145 146 147 148 149

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

150 151
(* Initialization of config, provers, task_driver and controller in the server *)
let () = Server.init_server gconfig.config env
152

Clément Fumex's avatar
Clément Fumex committed
153 154 155 156 157 158
let () =
  Debug.dprintf debug "[GUI] Init the GTK interface...@?";
  ignore (GtkMain.Main.init ());
  Debug.dprintf debug " done.@.";
  Gconfig.init ()

MARCHE Claude's avatar
MARCHE Claude committed
159

MARCHE Claude's avatar
MARCHE Claude committed
160 161 162 163 164
(********************************)
(* Source language highlighting *)
(********************************)

let (why_lang, any_lang) =
Clément Fumex's avatar
Clément Fumex committed
165 166
  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
167 168 169 170 171 172 173 174
  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
175
        eprintf "language file for 'why3' not found in directory %s@."
MARCHE Claude's avatar
MARCHE Claude committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
          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

199 200 201
(**********************)
(* Graphical elements *)
(**********************)
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 233 234 235 236 237 238

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
239 240
(* 1.1 "File" menu *)

241 242 243 244
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
245
  (* will this be treated before gmain quit ?!? *)
Sylvain Dailler's avatar
Sylvain Dailler committed
246
  send_request Exit_req;
247 248 249 250 251
  ignore(destroy); GMain.quit ()

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

MARCHE Claude's avatar
MARCHE Claude committed
252 253 254 255 256 257
(* 1.2 "View" menu

   the entries in that menu are defined later

*)

258 259 260 261
(* 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
262
     2.2.2 a vertical paned containing
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
*)

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
281
let vpan222 = GPack.paned `VERTICAL ~packing:hp#add ()
282 283 284 285 286 287

(*  the scrolled window 2.2.1 contains a GTK tree

*)


MARCHE Claude's avatar
MARCHE Claude committed
288 289 290 291 292 293 294 295
(* view for the session tree *)
let scrolled_session_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT
    ~packing:scrollview#add
    ()

296 297
let cols = new GTree.column_list
let name_column = cols#add Gobject.Data.string
Clément Fumex's avatar
Clément Fumex committed
298
let node_id_column = cols#add Gobject.Data.int
299
let status_column = cols#add Gobject.Data.gobject
300
let time_column = cols#add Gobject.Data.string
MARCHE Claude's avatar
MARCHE Claude committed
301

302 303 304 305
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;
306
  view_name_column#add_attribute name_renderer "text" name_column;
307 308 309
(*  view_name_column#set_sizing `AUTOSIZE; *)
  view_name_column#set_resizable true;
  view_name_column#set_max_width 500
310 311 312

let status_renderer = GTree.cell_renderer_pixbuf [ ]
let view_status_column = GTree.view_column ~title:"Status"
313 314 315 316 317 318 319
    ~renderer:(status_renderer, ["pixbuf", status_column])
    ()

let view_time_column =
  let renderer = GTree.cell_renderer_text [`XALIGN 0.] in
  GTree.view_column ~title:"Time"
    ~renderer:(renderer, ["text", time_column]) ()
320

321 322 323 324 325 326 327 328 329
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);
330
  ignore (view#append_column view_status_column);
331
  ignore (view#append_column view_time_column);
332 333 334 335 336
  view_status_column#set_resizable false;
  view_status_column#set_visible true;
  view_time_column#set_resizable false;
  view_time_column#set_visible true;
  Debug.dprintf debug "[GTK IDE] done@.";
337
  model,view
338

339 340 341 342 343 344 345 346 347 348 349 350

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

type pa_status = Controller_itp.proof_attempt_status
      * bool   (* obsolete or not *) (* TODO *)
      * Call_provers.resource_limit

let node_id_type : node_type Hint.t = Hint.create 17
let node_id_proved : bool Hint.t = Hint.create 17
let node_id_pa : pa_status Hint.t = Hint.create 17
351
let node_id_detached : bool Hint.t = Hint.create 17
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

let get_node_type id = Hint.find node_id_type id
let get_node_proved id = Hint.find node_id_proved id
let get_node_id_pa id = Hint.find node_id_pa id

let get_obs (pa_st: pa_status) = match pa_st with
| _, b, _ -> b

let get_proof_attempt (pa_st: pa_status) = match pa_st with
| pa, _, _ -> pa

let get_limit (pa_st: pa_status) = match pa_st with
| _, _, l -> l

let get_node_obs id = get_obs (get_node_id_pa id)
let get_node_proof_attempt id = get_proof_attempt (get_node_id_pa id)
let get_node_limit id = get_limit (get_node_id_pa id)

let get_node_id iter = goals_model#get ~row:iter ~column:node_id_column

(* 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

377 378 379
let get_node_detached id =
  Hint.find node_id_detached id

380 381 382 383 384 385 386 387 388 389 390 391 392 393
(******************************)
(* Initialization of the tree *)
(******************************)

let remove_tree goals_model =
  Hint.iter (fun _x i ->
    try ignore(goals_model#remove (i#iter)) with _ -> ())
    node_id_to_gtree

let clear_tree_and_table goals_model =
  remove_tree goals_model;
  Hint.clear node_id_to_gtree;
  Hint.clear node_id_type;
  Hint.clear node_id_proved;
394 395
  Hint.clear node_id_pa;
  Hint.clear node_id_detached
396 397


398

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
(**************)
(* Menu items *)
(**************)
let (_ : GMenu.menu_item) =
  file_factory#add_item ~key:GdkKeysyms._S "_Save session"
    ~callback:(fun () -> send_request Save_req)

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

let (_ : GMenu.menu_item) =
  file_factory#add_item ~key:GdkKeysyms._Q "_Quit"
    ~callback:(exit_function ~destroy:false)

(* TODO key stroked to be decided *)
let reload_menu_item : GMenu.menu_item =
415
  file_factory#add_item ~key:GdkKeysyms._E "r_Eload session"
416 417 418 419 420
    ~callback:(fun () ->
      (* Clearing the tree *)
      clear_tree_and_table goals_model;
      send_request Reload_req)

421

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

429 430 431 432 433 434 435 436 437 438 439
(*************************************)
(*    notebook on the right 2.2.2.1  *)
(*************************************)

let notebook = GPack.notebook ~packing:vpan222#add ()

let task_page,scrolled_task_view =
  let label = GMisc.label ~text:"Task" () in
  0, GPack.vbox ~homogeneous:false ~packing:
    (fun w -> ignore(notebook#append_page ~tab_label:label#coerce w)) ()

440 441 442 443
let scrolled_task_view =
  GBin.scrolled_window
    ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
    ~shadow_type:`ETCHED_OUT
444
    ~packing:scrolled_task_view#add ()
445

446
(* Showing current task *)
447 448 449
let task_view =
  GSourceView2.source_view
    ~editable:false
Clément Fumex's avatar
Clément Fumex committed
450
    ~cursor_visible:false
451 452 453 454
    ~show_line_numbers:true
    ~packing:scrolled_task_view#add
    ()

455 456
let source_view_table : (int * GSourceView2.source_view) Hstr.t =
  Hstr.create 14
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493

let create_source_view =
  let n = ref 1 in
  let create_source_view f content =
    if not (Hstr.mem source_view_table f) then
      begin
        let source_page, scrolled_source_view =
          let label = GMisc.label ~text:f () in
          !n, GPack.vbox ~homogeneous:false ~packing:
            (fun w -> ignore(notebook#append_page ~tab_label:label#coerce w)) () in
        let scrolled_source_view =
          GBin.scrolled_window
            ~hpolicy: `AUTOMATIC ~vpolicy: `AUTOMATIC
            ~shadow_type:`ETCHED_OUT
            ~packing:scrolled_source_view#add () in
        let source_view =
          GSourceView2.source_view
            ~auto_indent:true
            ~insert_spaces_instead_of_tabs:true ~tab_width:2
            ~show_line_numbers:true
            ~right_margin_position:80 ~show_right_margin:true
            (* ~smart_home_end:true *)
            ~editable:true
            ~packing:scrolled_source_view#add
            () in
        Hstr.add source_view_table f (source_page, source_view);
        n := !n + 1;
        source_view#source_buffer#set_text content;
        Gconfig.add_modifiable_mono_font_view source_view#misc;
        source_view#source_buffer#set_language why_lang;
        Gconfig.set_fonts ()
      end in
  create_source_view

(* End of notebook *)


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

496 497 498 499 500 501
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
502 503 504
    ~text:"  0/0/0"
    ~width:80
    ~xalign:0.0
505
    ~packing:(hbox22221#pack ?from:None ?expand:None ?fill:None ?padding:None) ()
506

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

MARCHE Claude's avatar
MARCHE Claude committed
509
let message_zone =
510 511 512 513
  let sv = GBin.scrolled_window
      ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
      ~shadow_type:`ETCHED_OUT ~packing:vbox2222#add ()
  in
MARCHE Claude's avatar
MARCHE Claude committed
514
  GText.view ~editable:false ~cursor_visible:false
515 516
    ~packing:sv#add ()

517 518 519
(**** Message-zone printing functions *****)

(* Function used to print stuff on the message_zone *)
MARCHE Claude's avatar
MARCHE Claude committed
520
let print_message fmt =
521
  (* Format.kasprintf is not available in Ocaml 4.02.3 :-(
MARCHE Claude's avatar
MARCHE Claude committed
522 523 524
  Format.kasprintf
    message_zone#buffer#set_text
    fmt
525 526 527 528 529 530 531
   *)
  Format.kfprintf
    (fun _ -> let s = flush_str_formatter () in
              message_zone#buffer#set_text s)
    str_formatter
    fmt

532 533 534 535 536 537

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

538
(**** Monitor *****)
Clément Fumex's avatar
Clément Fumex committed
539

540 541 542 543 544 545 546 547 548 549 550 551 552
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
553 554 555
  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
556

MARCHE Claude's avatar
MARCHE Claude committed
557

558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
(****************************)
(* 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

573 574 575 576 577 578 579
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
580
let init_completion provers transformations commands =
581
  (* add the names of all the the transformations *)
Clément Fumex's avatar
Clément Fumex committed
582
  List.iter add_completion_entry transformations;
583
  (* add the name of the commands *)
Clément Fumex's avatar
Clément Fumex committed
584
  List.iter add_completion_entry commands;
585 586
  (* todo: add queries *)

587
  (* add provers *)
Clément Fumex's avatar
Clément Fumex committed
588 589
  List.iter add_completion_entry provers;

590 591 592
  add_completion_entry "auto";
  add_completion_entry "auto 2";

593
  command_entry_completion#set_text_column completion_col;
594
  command_entry_completion#set_match_func match_function;
595

596
  command_entry#set_completion command_entry_completion
597

Sylvain Dailler's avatar
Sylvain Dailler committed
598
(*********************)
599
(* Terminal history  *)
Sylvain Dailler's avatar
Sylvain Dailler committed
600 601
(*********************)

602
let list_commands = create_history()
Sylvain Dailler's avatar
Sylvain Dailler committed
603 604 605

let _ =
  command_entry#event#connect#key_press
606 607 608
    ~callback:(fun (ev: 'a Gdk.event) ->
      match GdkEvent.Key.keyval ev with
      | k when k = GdkKeysyms._Up -> (* Arrow up *)
609 610 611 612 613
          let s = print_next_command list_commands in
          (match s with
          | None -> true
          | Some s ->
              (command_entry#set_text s; true))
614
      | k when k = GdkKeysyms._Down -> (* Arrow down *)
615 616 617 618 619
          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
620 621 622
      | _ -> false
      )

Clément Fumex's avatar
Clément Fumex committed
623 624 625
let () =
  let n = gconfig.session_nb_processes in
  Debug.dprintf debug "[IDE] setting max proof tasks to %d@." n;
626
  send_request (Set_max_tasks_req n)
627

628 629
let (_ : GtkSignal.id) =
  replay_menu_item#connect#activate
630
    ~callback:(fun () -> send_request Replay_req)
631

632 633 634
(**************************)
(* Graphical proof status *)
(**************************)
635

Sylvain Dailler's avatar
Sylvain Dailler committed
636 637
let image_of_pa_status ~obsolete pa =
  match pa with
638 639 640 641 642 643 644
  | Controller_itp.Unedited -> !image_scheduled (* TODO !image_unedited *)
  | Controller_itp.JustEdited -> !image_scheduled (* TODO !image_edited *)
  | Controller_itp.Interrupted -> !image_scheduled (* TODO !image_interrrupted *)
  | Controller_itp.Scheduled -> !image_scheduled
  | Controller_itp.Running -> !image_running
  | Controller_itp.InternalFailure _e -> !image_failure
  | Controller_itp.Uninstalled _p -> !image_failure (* TODO !image_uninstalled *)
Sylvain Dailler's avatar
Sylvain Dailler committed
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
(*  | None -> !image_undone*)
  | Controller_itp.Done r ->
    let pr_answer = r.Call_provers.pr_answer in
    begin
      match pr_answer with
      | 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
    end
668

Clément Fumex's avatar
Clément Fumex committed
669 670
let set_status_column iter =
  let id = get_node_id iter in
671
  let proved = get_node_proved id in
672
  let detached = get_node_detached id in
Clément Fumex's avatar
Clément Fumex committed
673 674 675 676 677 678
  let image = match get_node_type id with
    | NRoot -> assert false
    | NFile
    | NTheory
    | NTransformation
    | NGoal ->
679 680 681 682 683 684
      if detached then
        !image_valid_obs
      else
        if proved
        then !image_valid
        else !image_unknown
685
    | NProofAttempt ->
Sylvain Dailler's avatar
Sylvain Dailler committed
686 687 688
      let pa = get_node_proof_attempt id in
      let obs = get_node_obs id in
      image_of_pa_status ~obsolete:obs pa
689 690
  in
  goals_model#set ~row:iter ~column:status_column image
691

692
let new_node ?parent ?(collapse=false) id name typ proved detached =
Clément Fumex's avatar
Clément Fumex committed
693 694
  if not (Hint.mem node_id_to_gtree id) then begin
    Hint.add node_id_type id typ;
Sylvain Dailler's avatar
Sylvain Dailler committed
695
    Hint.add node_id_proved id proved;
696
    Hint.add node_id_detached id detached;
Sylvain Dailler's avatar
Sylvain Dailler committed
697 698 699 700 701 702 703
    (* The tree does not have a root by default so the task is a forest with
       several root files *)
    let iter =
      match parent with
      | None -> goals_model#append ()
      | Some p -> goals_model#append ~parent:p#iter ()
    in
Sylvain Dailler's avatar
Sylvain Dailler committed
704
    goals_model#set ~row:iter ~column:name_column name;
Clément Fumex's avatar
Clément Fumex committed
705 706 707 708 709
    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;
710 711
    set_status_column iter;
    new_ref
Clément Fumex's avatar
Clément Fumex committed
712
  end
713 714
  else
    Hint.find node_id_to_gtree id
715

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
(*******************************)
(* 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
732
    ~callback:enlarge_fonts "Enlarge font"
733 734 735

let (_ : GMenu.menu_item) =
    view_factory#add_item ~key:GdkKeysyms._minus
Clément Fumex's avatar
Clément Fumex committed
736
      ~callback:reduce_fonts "Reduce font"
737 738 739 740 741

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

742
let collapse_iter iter =
743 744 745
  let path = goals_model#get_path iter in
  goals_view#collapse_row path

746 747 748 749 750 751 752 753 754 755
let rec collapse_proven_goals_from_iter iter =
  let node_id = get_node_id iter in
  let is_proved = get_node_proved node_id in
  if is_proved then
    collapse_iter iter
  else
    let n = goals_model#iter_n_children (Some iter) in
    for i = 0 to (n - 1) do
      collapse_proven_goals_from_iter (goals_model#iter_children ?nth:(Some i) (Some iter))
    done
756 757 758 759 760 761 762 763

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
764
    ~label:"Collapse proven goals" ~callback:(fun () -> collapse_proven_goals ()) ()
765 766 767 768 769 770 771

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
772
  task_view#source_buffer#set_language why_lang;
Clément Fumex's avatar
Clément Fumex committed
773
  Gconfig.set_fonts ()
774

775 776 777 778
(******************)
(*    actions     *)
(******************)

Clément Fumex's avatar
Clément Fumex committed
779 780 781 782
let get_selected_row_references () =
  List.map
    (fun path -> goals_model#get_row_reference path)
    goals_view#selection#get_selected_rows
783

784
let rec update_status_column_from_iter cont iter =
Clément Fumex's avatar
Clément Fumex committed
785
  set_status_column iter;
786
  match goals_model#iter_parent iter with
787
  | Some p -> update_status_column_from_iter cont p
788 789
  | None -> ()

790 791
let move_current_row_selection_up () =
  let current_view = List.hd (goals_view#selection#get_selected_rows) in
792 793 794
  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
795 796 797 798 799 800 801 802 803 804 805 806 807

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

808
let clear_command_entry () = command_entry#set_text ""
MARCHE Claude's avatar
MARCHE Claude committed
809 810

let interp cmd =
Clément Fumex's avatar
Clément Fumex committed
811 812 813 814 815 816
  (* 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
Sylvain Dailler's avatar
Sylvain Dailler committed
817
      (* If no nodes are in the tree send command on default root node *)
Clément Fumex's avatar
Clément Fumex committed
818 819
      root_node
  in
Sylvain Dailler's avatar
Sylvain Dailler committed
820
  send_request (Command_req (id, cmd));
821
  clear_command_entry ()
MARCHE Claude's avatar
MARCHE Claude committed
822 823 824

let (_ : GtkSignal.id) =
  command_entry#connect#activate
825 826
    ~callback:(fun () -> add_command list_commands command_entry#text;
      interp command_entry#text)
827

828 829
let on_selected_row r =
  try
Clément Fumex's avatar
Clément Fumex committed
830 831 832 833
    let id = get_node_id r#iter in
    let typ = get_node_type id in
    match typ with
    | NGoal ->
834 835 836 837 838
      let detached = get_node_detached id in
      if detached then
        task_view#source_buffer#set_text ""
      else
        send_request (Get_task id)
839
    | _ ->  send_request (Get_task id)
840 841
  with
    | Not_found -> task_view#source_buffer#set_text ""
Clément Fumex's avatar
Clément Fumex committed
842

843 844 845
let (_ : GtkSignal.id) =
  goals_view#selection#connect#after#changed ~callback:
    (fun () ->
MARCHE Claude's avatar
MARCHE Claude committed
846 847 848 849 850 851
     begin
       match get_selected_row_references () with
       | [r] -> on_selected_row r
       | _ -> ()
     end (* ;
     command_entry#misc#grab_focus () *))
Clément Fumex's avatar
Clément Fumex committed
852

853 854 855 856 857 858 859
let remove_item: GMenu.menu_item =
  file_factory#add_item "Remove"
    ~callback:(fun () ->
      match get_selected_row_references () with
      | [r] -> let id = get_node_id r#iter in send_request (Remove_subtree id)
      | _ -> print_message "Select only one node to perform this action")

Sylvain Dailler's avatar
Sylvain Dailler committed
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 892 893 894 895 896 897 898 899 900 901 902 903
(*************************************)
(* Commands of the Experimental menu *)
(*************************************)

let exp_menu = factory#add_submenu "_Experimental"
let exp_factory = new GMenu.factory exp_menu ~accel_group


(* Current copied node *)
let saved_copy = ref None

let copy () =
  match get_selected_row_references () with
  | [r] -> let n = get_node_id r#iter in
    saved_copy := Some n
  | _ -> ()

let paste () =
  match get_selected_row_references () with
  | [r] ->
      let m = get_node_id r#iter in
    (match !saved_copy with
    | Some n -> send_request (Copy_paste (n, m))
    | None -> ())
  | _ -> ()

let detached_copy () =
  match get_selected_row_references () with
  | [r] -> let n = get_node_id r#iter in
    send_request (Copy_detached n)
  | _ -> ()

let (_ : GMenu.menu_item) =
  exp_factory#add_item ~key:GdkKeysyms._C
    ~callback:copy "Copy"

let (_ : GMenu.menu_item) =
  exp_factory#add_item ~key:GdkKeysyms._V
    ~callback:paste "Paste"

let (_ : GMenu.menu_item) =
  exp_factory#add_item ~key:GdkKeysyms._D
    ~callback:detached_copy "Detached copy"

904 905 906 907 908 909 910 911 912 913 914 915 916
let save_sources () =
  Hstr.iter
    (fun k (_n, (s: GSourceView2.source_view)) ->
      let text_to_save = s#source_buffer#get_text () in
      send_request (Save_file_req (k, text_to_save))
    )
    source_view_table

(* TODO replace this with menu items *)
let (_ : GMenu.menu_item) =
  exp_factory#add_item ~key:GdkKeysyms._X "Save files"
    ~callback:(fun () -> save_sources ())

917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
(*********************************)
(* add a new file in the project *)
(*********************************)

let filter_all_files () =
  let f = GFile.filter ~name:"All" () in
  f#add_pattern "*" ;
  f

let filter_why_files () =
  GFile.filter
    ~name:"Why3 source files"
    ~patterns:[ "*.why"; "*.mlw"] ()

let select_file ~request =
  let d = GWindow.file_chooser_dialog ~action:`OPEN
    ~title:"Why3: Add file in project"
    ()
  in
  d#add_button_stock `CANCEL `CANCEL ;
  d#add_select_button_stock `OPEN `OPEN ;
  d#add_filter (filter_why_files ()) ;
  d#add_filter (filter_all_files ()) ;
  begin match d#run () with
  | `OPEN ->
      begin
        match d#filename with
          | None -> ()
          | Some f -> request f
      end
  | `DELETE_EVENT | `CANCEL -> ()
  end ;
  d#destroy ()

let open_item: GMenu.menu_item =
  file_factory#add_item ~key:GdkKeysyms._A "_Add file"
    ~callback:(fun () ->
      select_file ~request:(fun f -> send_request (Add_file_req f)))

let open_session: GMenu.menu_item =
  file_factory#add_item ~key:GdkKeysyms._O "Open session"
    ~callback:(fun () ->
      select_file ~request:(fun f ->
        (* Clearing the ide tree *)
        clear_tree_and_table goals_model;
        send_request (Open_session_req f)))

Clément Fumex's avatar
Clément Fumex committed
964 965 966 967 968 969
(*************************)
(* Notification Handling *)
(*************************)

let treat_message_notification msg = match msg with
  (* TODO: do something ! *)
MARCHE Claude's avatar
MARCHE Claude committed
970 971 972 973 974 975 976 977
  | Proof_error (_id, s)   -> print_message "%s" s
  | Transf_error (_id, s)  -> print_message "%s" s
  | Strat_error (_id, s)   -> print_message "%s" s
  | Replay_Info s          -> print_message "%s" s
  | Query_Info (_id, s)    -> print_message "%s" s
  | Query_Error (_id, s)   -> print_message "%s" s
  | Help s                 -> print_message "%s" s
  | Information s          -> print_message "%s" s
Clément Fumex's avatar
Clément Fumex committed
978
  | Task_Monitor (t, s, r) -> update_monitor t s r
MARCHE Claude's avatar
MARCHE Claude committed
979
  | Open_File_Error s      -> print_message "%s" s
980
  | Parse_Or_Type_Error s  -> print_message "%s" s
981
  | File_Saved s           -> print_message "%s was saved" s
982 983
  | Error s                ->
      if Debug.test_flag debug then
MARCHE Claude's avatar
MARCHE Claude committed
984
        print_message "%s" s
985
      else
MARCHE Claude's avatar
MARCHE Claude committed
986
        print_message "%s" "Request failed. You can get details using --debug ide_info"
Clément Fumex's avatar
Clément Fumex committed
987

Sylvain Dailler's avatar
Sylvain Dailler committed
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

(***********************)
(* First Unproven goal *)
(***********************)

let is_goal node =
  get_node_type node = NGoal

let proved node =
  get_node_proved node

let children node =
  let iter = (get_node_row node)#iter in
  let n = goals_model#iter_n_children (Some iter) in
  let acc = ref [] in
  for i = 0 to (n-1) do
    let new_iter = goals_model#iter_children ?nth:(Some i) (Some iter) in
    let child_node = get_node_id new_iter in
    if (get_node_type child_node != NProofAttempt) then
      acc := child_node :: !acc
  done;
  !acc

let get_parent node =
  let iter = (get_node_row node)#iter in
  let parent_iter = goals_model#iter_parent iter in
  match parent_iter with
  | None -> None
  | Some parent -> Some (get_node_id parent)

1018 1019 1020 1021
let if_selected_alone id f =
  match get_selected_row_references () with
  | [r] ->
     let i = get_node_id r#iter in
1022
     if i = id || Some i = get_parent id then f id
1023 1024
  | _ -> ()

MARCHE Claude's avatar
MARCHE Claude committed
1025
let treat_notification n =
1026
  begin match n with
Sylvain Dailler's avatar
Sylvain Dailler committed
1027
  | Node_change (id, uinfo)        ->
1028 1029 1030
     begin
       match uinfo with
       | Proved b ->
1031 1032 1033 1034 1035
           Hint.replace node_id_proved id b;
           set_status_column (get_node_row id)#iter;
           (* Trying to move cursor on first unproven goal around on all cases
              but not when proofAttempt is updated because ad hoc debugging. *)
           send_request (Get_first_unproven_node id)
1036
       | Proof_status_change (pa, obs, l) ->
Sylvain Dailler's avatar
Sylvain Dailler committed
1037 1038 1039
          let r = get_node_row id in
          Hint.replace node_id_pa id (pa, obs, l);
          goals_model#set ~row:r#iter ~column:status_column
1040
                          (image_of_pa_status ~obsolete:obs pa)
1041 1042 1043 1044 1045 1046
     end
  | Next_Unproven_Node_Id (asked_id, next_unproved_id) ->
      if_selected_alone asked_id
          (fun _ ->
            let iter = (get_node_row next_unproved_id)#iter in
            goals_view#selection#select_iter iter)
1047
  | New_node (id, parent_id, typ, name, detached) ->
1048
     begin
MARCHE Claude's avatar
MARCHE Claude committed
1049 1050 1051 1052 1053
       let name =
         if typ = NGoal then
           List.hd (Strings.rev_split '.' name)
         else name
       in
1054 1055 1056 1057 1058 1059
       try
         let parent = get_node_row parent_id in
         ignore (new_node ~parent id name typ false detached)
       with Not_found ->
         ignore (new_node id name typ false detached)
     end
1060
  | Remove id                     ->
1061 1062 1063 1064 1065 1066
     let n = get_node_row id in
     ignore (goals_model#remove(n#iter));
     Hint.remove node_id_to_gtree id;
     Hint.remove node_id_type id;
     Hint.remove node_id_proved id;
     Hint.remove node_id_pa id
Clément Fumex's avatar
Clément Fumex committed
1067
  | Initialized g_info            ->
1068 1069
     (* TODO: treat other *)
     init_completion g_info.provers g_info.transformations g_info.commands;
MARCHE Claude's avatar
MARCHE Claude committed
1070
  | Saved                         ->
1071
     print_message "Session saved."
Clément Fumex's avatar
Clément Fumex committed
1072
  | Message (msg)                 -> treat_message_notification msg
1073 1074 1075 1076 1077 1078
  | Task (id, s)                  ->
     if_selected_alone
       id
       (fun _ -> task_view#source_buffer#set_text s;
                 (* scroll to end of text *)
                 task_view#scroll_to_mark `INSERT)
1079 1080 1081 1082 1083 1084 1085 1086
  | File_contents (file_name, content) ->
    begin
      try
        let (_, sc_view) = Hstr.find source_view_table file_name in
        sc_view#source_buffer#set_text content
      with
      | Not_found -> create_source_view file_name content
    end
MARCHE Claude's avatar
MARCHE Claude committed
1087
  | Dead _ ->
1088
     print_message "Serveur sent an unexpected notification '%a'. Please report." print_notify n
1089 1090 1091 1092 1093
  end;
  (* temporary: this should be better executed each time
     one clicks on the tree view *)
(*  command_entry#misc#grab_focus () *)
  ()
MARCHE Claude's avatar
MARCHE Claude committed
1094

1095

MARCHE Claude's avatar
MARCHE Claude committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

(*************)
(* Help menu *)
(*************)


let help_menu = factory#add_submenu "_Help"
let help_factory = new GMenu.factory help_menu ~accel_group

let (_ : GMenu.image_menu_item) =
  help_factory#add_image_item
    ~label:"Legend"
    ~callback:show_legend_window
    ()

let (_ : GMenu.image_menu_item) =
  help_factory#add_image_item
    ~label:"About"
    ~callback:show_about_window
    ()



1119
(***********************)
1120
(* start the interface *)
1121
(***********************)
1122

Clément Fumex's avatar
Clément Fumex committed
1123 1124
let () =
  S.timeout ~ms:100 (fun () -> List.iter treat_notification (get_notified ()); true);
Sylvain Dailler's avatar
Sylvain Dailler committed
1125 1126 1127
  let f = Queue.pop files in
  send_request (Open_session_req f);
  Queue.iter (fun f -> send_request (Add_file_req f)) files;
1128
  (* temporary *)
Clément Fumex's avatar
Clément Fumex committed
1129
  vpan222#set_position 500;
1130
  goals_view#expand_all ();
1131 1132
  main_window#add_accel_group accel_group;
  main_window#set_icon (Some !Gconfig.why_icon);
1133
  message_zone#buffer#set_text "Welcome to Why3 IDE\ntype 'help' for help";
1134 1135
  main_window#show ();
  GMain.main ()