Source

planets / options.ml

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 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
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
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
494
495
496
497
498
499
500
501
502
503
504
505
open Core.Std
open Tk
open Common

exception Unimplemented

(****************************************************************)
(**  Utility Functions   ****************************************)
(****************************************************************)

let random_chr () =
  let rand = Random.int (Char.to_int 'z' - Char.to_int 'a') in
  Char.of_int_exn (Char.to_int 'a' + rand)

let random_name length =
  let str = String.create length in
  for i = 0 to length -1 do
    str.[i] <-  random_chr ()
  done;
  str

(*****************************************************************)
(**  Live Values  ************************************************)
(*****************************************************************)

(*  Values that have a list of callbacks that are called whenever the value
 *  is updated.  This is useful both for keeping the optionbox up to date,
 *  and for doing whatever needs to be done to accomodate changing options.
 *)


class ['a] live_value (init:'a) =
object (_self)
  val mutable name = None
  val mutable value = init
  val mutable callback_list = []

  method set newval =
    value <- newval;
    List.iter
      ~f:(fun cb ->
        try cb value newval
        with exn -> debug_msg
          (match name with
          | None -> (sprintf "live_value#set: Callback failed with exn <%s>"
                       (Exn.to_string exn))
          | Some name -> (sprintf "live_value#set %s: Callback failed with exn <%s>"
                            name (Exn.to_string exn))))
      callback_list

  method set_name newname = name <- Some newname
  method v = value
  method get () = value
  method register_callback cb =
    callback_list <- cb::callback_list
end

let named_live_value name init =
  let v = new live_value init in
  v#set_name name;
  v

(****************************************************)

class live_toggle init =
object (self)
  inherit [bool] live_value init

  method flip = self#set (not value)
end

exception Option_exists of string


(*********************************************************************)
(*********************************************************************)
(*********************************************************************)

class type ['a] display_type =
object
  method display : live:bool -> ('a Widget.widget -> unit)
  method tk_to_real : unit
  method name : string
end

(*********************************************************************)
(* 'a is the data type, 'b is the widget type *)

class virtual ['a,'b] option ?name ~text ~set:(set:'a->unit) ~get () =
  let name = (match name with
      None -> random_name 10
    | Some name -> name ) in
object (self)
  val mutable widget = None

  val tk_var = Textvariable.coerce name
  val name = name
  val text = (text : string)

  method virtual build_widget : live:bool -> 'b
  method display ~live parent =
    ignore (self#build_widget ~live parent);
    match widget with
      None -> failwith "option#display: widget unexpectedly missing"
    | Some widget ->
      Pack.configure ~anchor:`W [widget]

  method virtual get_tk : 'a
  method virtual set_tk : 'a -> unit
  method set_real v = set v
  method tk_to_real = set self#get_tk
  method real_to_tk = self#set_tk (get ())
  method name = name
  method text = text

  method upcast = (self :> 'c display_type)
end


(*********************)

class ['b] toggle_option ?name ~text ~set ~get () =
object (self)
  inherit [bool,'b] option ?name ~text ~set ~get ()

  method set_tk bool =
    Textvariable.set tk_var (if bool then "true" else "false")

  method get_tk =
    let string = Textvariable.get tk_var in
    if string = "true"  then true
    else if string = "false" then false
    else failwith "toggle_option#get_tk: bad string value"

  method build_widget ~live parent =
    let new_widget = Checkbutton.create  ~name ~text
      ~onvalue:"true" ~offvalue:"false" parent in
    (if live then
        Checkbutton.configure ~command:(fun () -> self#tk_to_real)
          new_widget);
    widget <- Some new_widget;
    self#real_to_tk;
    new_widget

end

(*********************)

class ['b] int_scale_option ?name ~min ~max ~text ~set ~get () =
object (self)
  inherit [int,'b] option ?name ~text ~set ~get ()
  val min = min
  val max = max

  method min = min
  method max = max

  method get_tk = match widget with
    None -> failwith ("int_scale_option#get_tk called when " ^
                         "no widget exists")
  | Some widget ->
    if Winfo.exists widget
    then Int.of_float (Scale.get widget)
    else failwith ("int_scale_option#get_tk called when " ^
                      "widget does not exist")
  method set_tk v = match widget with
    None -> ()
  | Some widget ->
    if Winfo.exists widget
    then Scale.set widget (Float.of_int v)


  method build_widget ~live parent =
    let new_widget = Scale.create ~name ~label:text
      ~orient:`Horizontal ~min ~max parent in
    widget <- Some new_widget;
    self#real_to_tk;
    (if live then Scale.configure
        ~command:(fun value -> self#set_real
          (Int.of_float value)) new_widget);
    new_widget

end


(*******************************************************)

class ['b] float_scale_option ?name ~min ~max ?(resolution=1.0)
  ~text ~set ~get () =
object (self)
  inherit [float, 'b] option ?name ~text ~set ~get ()
  val min = min
  val max = max

  method min = min
  method max = max

  method get_tk = match widget with
    None -> failwith ("float_scale_option#get_tk called when " ^
                         "no widget exists")
  | Some widget ->
    if Winfo.exists widget
    then Scale.get widget
    else failwith ("float_scale_option#get_tk called when " ^
                      "widget does not exist")

  method set_tk v = match widget with
    None -> ()
  | Some widget ->
    if Winfo.exists widget
    then Scale.set widget v


  method build_widget ~live parent =
    let new_widget = Scale.create ~name ~resolution ~label:text
      ~orient:`Horizontal ~min ~max parent in
    widget <- Some new_widget;
    self#real_to_tk;
    (if live then Scale.configure
        ~command:(fun value -> self#set_real value) new_widget);
    new_widget
end

(*******************************************************)

let string_of_float x =
  let string = Float.to_string x in
  if string.[String.length string - 1] = '.'
  then string ^ "0"
  else string

class ['b] float_entry_option ?name ?(mult=1.1)
  ~text ~set ~get () =
object (self)
  inherit [float, 'b] option ?name ~text ~set ~get ()

  val mutable entry = None

  method get_tk = match entry with
    None -> failwith ( "float_entry_option#get_tk called " ^
                         "when no widget exists" )
  | Some entry ->
    let float = Float.of_string (Entry.get entry) in
    let float = if float <= 0.0 then get () else float in
    let string_rep = string_of_float float in
    Entry.delete_range ~start:(`Num 0) ~stop:`End entry;
    Entry.insert entry ~index:(`Num 0) ~text:string_rep;
    float

  method set_tk v = match widget with
  | None -> ()
  | Some _widget ->
    match entry with
      None ->  failwith ("float_entry_option#set_tk" ^
                            " called when no widget exists")
    | Some entry ->
      if Winfo.exists entry then (
        Entry.delete_range ~start:(`Num 0)
          ~stop:`End entry;
        Entry.insert entry ~index:(`Num 0)
          ~text:(string_of_float v)
      )

  method build_widget ~live parent =
    let frame = Frame.create parent in
    let nentry = Entry.create ~width:6 frame in
    let label = Label.create ~text frame in
    let action ev =
      if ev.ev_KeySymString = "Return" then
        self#tk_to_real
      else if ev.ev_KeySymString = "Up" then
        let newval = (mult *. self#get_tk) in
        self#set_real newval;
        self#set_tk newval
      else if ev.ev_KeySymString = "Down" then
        let newval = (self#get_tk /. mult) in
        self#set_real newval;
        self#set_tk newval
    in
    if live then
      begin
        bind ~events:[`KeyPress] ~fields:[`KeySymString]
          ~action nentry;
        bind ~events:[`FocusOut] ~fields:[`KeySymString]
          ~action:(fun _ev -> self#tk_to_real) nentry;
      end;
    Pack.configure ~side:`Left [nentry];
    Pack.configure ~side:`Left [label];
    widget <- Some frame;
    entry <- Some nentry;
    self#real_to_tk;
    frame
end



(*******************************************************)

class ['b] float_entry_display ?name ~text ~set ~get () =
object (self)
  inherit [float, 'b] option ?name ~text ~set ~get ()

  val mutable display = None

  method get_tk = raise Unimplemented

  method set_tk v = match widget with
    None -> ()
  | Some _widget ->
    match display with
      None -> failwith ("float_entry_display#set_tk" ^
                           " called when no widget exists")
    | Some display ->
      if Winfo.exists display
      then Label.configure ~text:(sprintf "%8.4f" v)
        display

  method build_widget ~live:_ parent =
    let frame = Frame.create parent in
    let label = Label.create ~text frame in
    let ndisplay = Label.create frame
    in
    Pack.configure ~side:`Left [label];
    Pack.configure ~side:`Left [ndisplay];
    widget <- Some frame;
    display <- Some ndisplay;
    self#real_to_tk;
    frame
end

(*******************************************************)

class ['b] int_entry_display ?name ~text ~set ~get () =
object (self)
  inherit [int, 'b] option ?name ~text ~set ~get ()

  val mutable display = None

  method get_tk = raise Unimplemented

  method set_tk v = match widget with
    None -> ()
  | Some _widget ->
    match display with
      None -> failwith ("int_entry_option#set_tk" ^
                           " called when no widget exists")
    | Some display ->
      if Winfo.exists display
      then Label.configure ~text:(sprintf "%d" v)
        display

  method build_widget ~live:_ parent =
    let frame = Frame.create parent in
    let label = Label.create ~text frame in
    let ndisplay = Label.create frame
    in
    Pack.configure ~side:`Left [label];
    Pack.configure ~side:`Left [ndisplay];
    widget <- Some frame;
    display <- Some ndisplay;
    self#real_to_tk;
    frame
end

(*******************************************************)

class ['b] void_entry_display ?name ~text () =
object (_self)
  inherit [unit, 'b] option ?name ~text
    ~set:(fun _ -> ()) ~get:(fun () -> ())
    ()

  method get_tk = raise Unimplemented

  method set_tk _ = ()

  method build_widget ~live:_ parent =
    let frame = Frame.create parent in
    let label = Label.create ~text frame in
    Pack.configure ~side:`Left [label];
    widget <- Some frame;
    frame
end

(*****************************************************************)
(**  Option Box   ************************************************)
(*****************************************************************)

(***********************************************************)
(* Some helper functions to simplify the optionbox class.
 * The reason they are here instead of being inside of optionbox
 * is that putting them outside allows for a greater degree
 * of polymorphism. *)
(************************************************************)


let add_option optionbox ?register_cb option =
  (match register_cb with
    None -> ()
  | Some register ->
    register
      (fun oldval newval -> ignore (oldval = newval);
        option#set_tk newval));
  optionbox#add_option option#upcast

let add_option_live optionbox lvalue option =
  add_option optionbox ~register_cb:lvalue#register_callback option

(****************************************************************)
(****************************************************************)
(****************************************************************)

class ['a,'b] optionbox toplevel =
object (self)

  val mutable widget = None

  val mutable display_map = String.Map.empty
  val mutable display_names = []


  val mutable mapped = false

  val mutable live = true
  method set_liveness bool = live <- bool

  method add_option (option : 'a display_type) =
    if Map.mem display_map option#name then
      raise (Option_exists option#name)
    else
      ( display_map <- Map.add ~key:option#name
          ~data:option display_map;
        display_names <- option#name::display_names;
      )

  (*************************************************************)
  (* private toggle methods *)

  (*  Called when OK button is pressed to commit all toggles.
      Not useful in live option dialog. *)
  method private read_options =
    Map.iter
      ~f:(fun ~key:_ ~data:display ->
        try display#tk_to_real with Unimplemented -> ()
      )
      display_map

  method destroy =
    match widget with
      None -> failwith "Attempt to destroy non-existant widget"
    | Some widget -> destroy widget

  method private display frame live =
    List.iter
      ~f:(fun name ->
        try
          let display = Map.find_exn display_map name in
          display#display ~live frame;
        with
          Not_found -> failwith ("Options.display_from_map: BUG." ^
                                    " name not found in map."))
      (List.rev display_names)

  method mapped = mapped

  method create_dialog ?(title=Lstrings.get `options)
    ?geometry ?(clas="Option") ?(transient:'b) () =
    if not mapped then
      begin
        mapped <- true;
        let topwin = Toplevel.create ~takefocus:true ~clas ~name:"options"
          toplevel in
        let frame = Frame.create ~name:"options" topwin in
        let buttons =
          if not live then
            let cancel_button = Button.create ~text:"Cancel"
              ~command:(fun () -> destroy topwin)
              frame
            and ok_button = Button.create ~text:"Ok"
              ~command:(fun () -> self#read_options;
                destroy topwin) frame
            in
            [cancel_button; ok_button]
          else
            let dismiss_button = Button.create ~text:(Lstrings.get `dismiss)
              ~command:(fun () -> self#read_options;
                destroy topwin) frame
            in [dismiss_button]
        in
        widget <- Some topwin;
        bind ~events:[`Destroy] ~action:(fun _ -> mapped <- false) frame;
        Pack.configure [frame];
        self#display frame live;
        Pack.configure ~side:`Left buttons;
        (match transient with
          None -> ()
        | Some master -> Wm.transient_set topwin ~master);
        (match geometry with
          None -> ()
        | Some geometry -> Wm.geometry_set topwin geometry);
        Wm.title_set topwin title
      end
    else
      debug_msg "Attempt to map already-mapped option dialog"
end
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.