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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
|
# Copyright 2019 DragonRuby LLC
# MIT License
# console.rb has been released under MIT (*only this file*).
# Contributors outside of DragonRuby who also hold Copyright:
# - Kevin Fischer: https://github.com/kfischer-okarin
module GTK
class Console
class Color
def initialize(color)
@color = color
@color << 255 if @color.size == 3
end
def mult_alpha(alpha_modifier)
Color.new [@color[0], @color[1], @color[2], (@color[3].to_f * alpha_modifier).to_i]
end
# Support splat operator
def to_a
@color
end
def to_h
{ r: @color[0], g: @color[1], b: @color[2], a: @color[3] }
end
end
class FontStyle
attr_reader :font, :size_enum, :line_height
def initialize(font:, size_enum:, line_height:)
@font = font
@size_enum = size_enum
@line_height = line_height
end
def letter_size
@letter_size ||= $gtk.calcstringbox 'W', size_enum, font
end
def line_height_px
@line_height_px ||= letter_size.y * line_height
end
def label(x:, y:, text:, color:, alignment_enum: 0)
{
x: x,
y: y.shift_up(line_height_px), # !!! FIXME: remove .shift_up(line_height_px) when we fix coordinate origin on labels.
text: text,
font: font,
size_enum: size_enum,
alignment_enum: alignment_enum,
**color.to_h,
}.label
end
end
class Prompt
attr_accessor :current_input_str, :font_style, :console_text_width
def initialize(font_style:, text_color:, console_text_width:)
@prompt = '-> '
@current_input_str = ''
@font_style = font_style
@text_color = text_color
@cursor_color = Color.new [187, 21, 6]
@console_text_width = console_text_width
@last_autocomplete_prefix = nil
@next_candidate_index = 0
end
def <<(str)
@current_input_str << str
reset_autocomplete
end
def backspace
@current_input_str.chop!
reset_autocomplete
end
def clear
@current_input_str = ''
reset_autocomplete
end
def autocomplete
if !@last_autocomplete_prefix
@last_autocomplete_prefix = calc_autocomplete_prefix
puts "* AUTOCOMPLETE CANDIDATES: #{current_input_str}.."
pretty_print_strings_as_table method_candidates(@last_autocomplete_prefix)
else
candidates = method_candidates(@last_autocomplete_prefix)
return if candidates.empty?
candidate = candidates[@next_candidate_index]
candidate = candidate[0..-2] + " = " if candidate.end_with? '='
@next_candidate_index += 1
@next_candidate_index = 0 if @next_candidate_index >= candidates.length
self.current_input_str = display_autocomplete_candidate(candidate)
end
end
def pretty_print_strings_as_table items
if items.length == 0
puts <<-S.strip
+--------+
| (none) |
+--------+
S
else
# figure out the largest string
string_width = items.sort_by { |c| -c.to_s.length }.first
# add spacing to each side of the string which represents the cell width
cell_width = string_width.length + 2
# add spacing to each side of the cell to represent the column width
column_width = cell_width + 2
# determine the max number of columns that can fit on the screen
columns = @console_text_width.idiv column_width
columns = items.length if items.length < columns
# partition the original list of items into a string to be printed
items.each_slice(columns).each_with_index do |cells, i|
pretty_print_row_seperator string_width, cell_width, column_width, columns
pretty_print_row cells, string_width, cell_width, column_width, columns
end
pretty_print_row_seperator string_width, cell_width, column_width, columns
end
end
def pretty_print_row cells, string_width, cell_width, column_width, columns
# if the number of cells doesn't match the number of columns, then pad the array with empty values
cells += (columns - cells.length).map { "" }
# right align each cell value
formated_row = "|" + cells.map do |c|
"#{" " * (string_width.length - c.length) } #{c} |"
end.join
# remove seperators between empty values
formated_row = formated_row.gsub(" | ", " ")
puts formated_row
end
def pretty_print_row_seperator string_width, cell_width, column_width, columns
# this is a joint: +--------
column_joint = "+#{"-" * cell_width}"
# multiple joints create a row seperator: +----+----+
puts (column_joint * columns) + "+"
end
def render(args, x:, y:)
args.outputs.reserved << font_style.label(x: x, y: y, text: "#{@prompt}#{current_input_str}", color: @text_color)
args.outputs.reserved << font_style.label(x: x - 2, y: y + 3, text: (" " * (@prompt.length + current_input_str.length)) + "|", color: @cursor_color)
end
private
def last_period_index
current_input_str.rindex('.')
end
def calc_autocomplete_prefix
if last_period_index
current_input_str[(last_period_index + 1)..-1]
else
current_input_str
end
end
def current_object
return Kernel unless last_period_index
Kernel.eval(current_input_str[0...last_period_index])
rescue NameError
nil
end
def method_candidates(prefix)
current_object.autocomplete_methods.map(&:to_s).select { |m| m.start_with? prefix }
end
def display_autocomplete_candidate(candidate)
if last_period_index
@current_input_str[0..last_period_index] + candidate.to_s
else
candidate.to_s
end
end
def reset_autocomplete
@last_autocomplete_prefix = nil
@next_candidate_index = 0
end
end
attr_accessor :show_reason, :log, :logo, :background_color,
:text_color, :animation_duration,
:max_log_lines, :max_history, :log,
:last_command_errored, :last_command, :error_color, :shown_at,
:header_color, :archived_log, :last_log_lines, :last_log_lines_count,
:suppress_left_arrow_behavior, :command_set_at,
:toast_ids,
:font_style
def initialize
@font_style = FontStyle.new(font: 'font.ttf', size_enum: 0, line_height: 1.1)
@disabled = false
@log_offset = 0
@visible = false
@toast_ids = []
@archived_log = []
@log = [ 'Console ready.' ]
@max_log_lines = 1000 # I guess...?
@max_history = 1000 # I guess...?
@command_history = []
@command_history_index = -1
@nonhistory_input = ''
@logo = 'console-logo.png'
@history_fname = 'console_history.txt'
@background_color = Color.new [0, 0, 0, 224]
@text_color = Color.new [255, 255, 255]
@error_color = Color.new [200, 50, 50]
@header_color = Color.new [100, 200, 220]
@animation_duration = 1.seconds
@shown_at = -1
load_history
end
def console_text_width
@console_text_width ||= ($gtk.logical_width - 20).idiv(font_style.letter_size.x)
end
def save_history
$gtk.ffi_file.storefile(@history_fname, @command_history.reverse.join("\n"))
end
def load_history
@command_history.clear
str = $gtk.ffi_file.loadfile(@history_fname)
return if str.nil? # no history to load.
str.chomp!("\n") # Don't let endlines at the end cause extra blank line.
str.chomp!("\r")
str.each_line { |s|
s.chomp!("\n")
s.chomp!("\r")
if s.length > 0
@command_history.unshift s
break if @command_history.length >= @max_history
end
}
@command_history.uniq!
end
def disable
@disabled = true
end
def enable
@disabled = false
end
def addsprite obj
obj[:id] ||= "id_#{obj[:path]}_#{Time.now.to_i}".to_sym
if @last_line_log_index &&
@last_sprite_line.is_a?(Hash) &&
@last_sprite_line[:id] == obj[:id]
@log[@last_line_log_index] = obj
return
end
@log << obj
@last_line_log_index = @log.length - 1
@last_sprite_line = obj
nil
end
def add_primitive obj
if obj.is_a? Hash
addsprite obj
else
addtext obj
end
nil
end
def addtext obj
@last_log_lines_count ||= 1
str = obj.to_s
log_lines = []
str.each_line do |s|
s.wrapped_lines(self.console_text_width).each do |l|
log_lines << l
end
end
if log_lines == @last_log_lines
@last_log_lines_count += 1
new_log_line_with_count = @last_log_lines.last + " (#{@last_log_lines_count})"
if log_lines.length > 1
@log = @log[0..-(@log.length - log_lines.length)] + log_lines[0..-2] + [new_log_line_with_count]
else
@log = @log[0..-2] + [new_log_line_with_count]
end
return
end
log_lines.each do |l|
@log.shift if @log.length > @max_log_lines
@log << l
end
@last_log_lines_count = 1
@last_log_lines = log_lines
nil
end
def ready?
visible? && @toggled_at.elapsed?(@animation_duration, Kernel.global_tick_count)
end
def hidden?
!@visible
end
def visible?
@visible
end
# @gtk
def show reason = nil
@shown_at = Kernel.global_tick_count
@show_reason = reason
toggle if hidden?
end
# @gtk
def hide
if visible?
toggle
@archived_log += @log
if @archived_log.length > @max_log_lines
@archived_log = @archived_log.drop(@archived_log.length - @max_log_lines)
end
@log.clear
@show_reason = nil
clear_toast
end
end
def close
hide
end
def clear_toast
@toasted_at = nil
@toast_duration = 0
end
def toggle
@visible = !@visible
@toggled_at = Kernel.global_tick_count
end
def currently_toasting?
return false if hidden?
return false unless @show_reason == :toast
return false unless @toasted_at
return false if @toasted_at.elapsed?(5.seconds, Kernel.global_tick_count)
return true
end
def toast_extended id = nil, duration = nil, *messages
if !id.is_a?(Symbol)
raise <<-S
* ERROR:
args.gtk.console.toast has the following signature:
def toast id, *messages
end
The id property uniquely defines the message and must be
a symbol.
After that, you can provide all the objects you want to
look at.
Example:
args.gtk.console.toast :say_hello,
\"Hello world.\",
args.state.tick_count
Toast messages autohide after 5 seconds.
If you need to look at something for longer, use
args.gtk.console.perma_toast instead (which you can manually dismiss).
S
end
return if currently_toasting?
return if @toast_ids.include? id
@toasted_at = Kernel.global_tick_count
log_once_info :perma_toast_tip, "Use console.perma_toast to show the toast for longer."
dwim_duration = 5.seconds
addtext "* toast :#{id}"
puts "* TOAST: :#{id}"
messages.each do |message|
lines = message.to_s.wrapped_lines(self.console_text_width)
dwim_duration += lines.length.seconds
addtext "** #{message}"
puts "** #{message}"
end
show :toast
@toast_duration += duration || dwim_duration
@toast_ids << id
set_command "$gtk.console.hide"
end
def perma_toast id = nil, messages
toast_extended id, 600.seconds, *messages
end
def toast id = nil, *messages
toast_extended id, nil, *messages
end
def console_toggle_keys
[
:backtick!,
:tilde!,
:superscript_two!,
:section_sign!,
:ordinal_indicator!,
:circumflex!,
]
end
def console_toggle_key_down? args
args.inputs.keyboard.key_down.any? console_toggle_keys
end
def eval_the_set_command
cmd = current_input_str.strip
if cmd.length != 0
@log_offset = 0
prompt.clear
@command_history.pop while @command_history.length >= @max_history
@command_history.unshift cmd
@command_history_index = -1
@nonhistory_input = ''
if cmd == 'quit' || cmd == ':wq' || cmd == ':q!' || cmd == ':q' || cmd == ':wqa'
$gtk.request_quit
else
puts "-> #{cmd}"
begin
@last_command = cmd
Kernel.eval("$results = (#{cmd})")
if $results.nil?
puts "=> nil"
elsif $results == :console_silent_eval
else
puts "=> #{$results}"
end
@last_command_errored = false
rescue Exception => e
@last_command_errored = true
puts "#{e}"
log "#{e}"
end
end
end
end
def inputs_scroll_up_full? args
return false if @disabled
args.inputs.keyboard.key_down.pageup ||
(args.inputs.keyboard.key_up.b && args.inputs.keyboard.key_up.control)
end
def scroll_up_full
@log_offset += lines_on_one_page
@log_offset = @log.size if @log_offset > @log.size
end
def inputs_scroll_up_half? args
return false if @disabled
args.inputs.keyboard.ctrl_u
end
def scroll_up_half
@log_offset += lines_on_one_page.idiv(2)
@log_offset = @log.size if @log_offset > @log.size
end
def inputs_scroll_down_full? args
return false if @disabled
args.inputs.keyboard.key_down.pagedown ||
(args.inputs.keyboard.key_up.f && args.inputs.keyboard.key_up.control)
end
def scroll_down_full
@log_offset -= lines_on_one_page
@log_offset = 0 if @log_offset < 0
end
def inputs_scroll_down_half? args
return false if @disabled
args.inputs.keyboard.ctrl_d
end
def inputs_clear_command? args
return false if @disabled
args.inputs.keyboard.escape || args.inputs.keyboard.ctrl_g
end
def scroll_down_half
@log_offset -= lines_on_one_page.idiv(2)
@log_offset = 0 if @log_offset < 0
end
def process_inputs args
if console_toggle_key_down? args
args.inputs.text.clear
toggle
end
return unless visible?
if !@suppress_left_arrow_behavior && args.inputs.keyboard.key_down.left && current_input_str.strip.length > 0
log_info "Use repl.rb!", <<-S
The Console is nice for quick commands, but for more complex edits, use repl.rb.
I've written the current command at the top of a file called ./repl.rb (right next to dragonruby(.exe)). Please open the the file and apply additional edits there.
S
if @last_command_written_to_repl_rb != current_input_str
@last_command_written_to_repl_rb = current_input_str
contents = $gtk.read_file 'app/repl.rb'
contents ||= ''
contents = <<-S + contents
# Remove the x from xrepl to run the command.
xrepl do
#{@last_command_written_to_repl_rb}
end
S
$gtk.suppress_hotload = true
$gtk.write_file 'app/repl.rb', contents
$gtk.reload_if_needed 'app/repl.rb', true
$gtk.suppress_hotload = false
end
return
end
args.inputs.text.each { |str| prompt << str }
args.inputs.text.clear
if args.inputs.keyboard.key_down.enter
eval_the_set_command
elsif args.inputs.keyboard.key_down.v
if args.inputs.keyboard.key_down.control || args.inputs.keyboard.key_down.meta
prompt << $gtk.ffi_misc.getclipboard
end
elsif args.inputs.keyboard.key_down.up
if @command_history_index == -1
@nonhistory_input = current_input_str
end
if @command_history_index < (@command_history.length - 1)
@command_history_index += 1
self.current_input_str = @command_history[@command_history_index].clone
end
elsif args.inputs.keyboard.key_down.down
if @command_history_index == 0
@command_history_index = -1
self.current_input_str = @nonhistory_input
@nonhistory_input = ''
elsif @command_history_index > 0
@command_history_index -= 1
self.current_input_str = @command_history[@command_history_index].clone
end
elsif inputs_scroll_up_full? args
scroll_up_full
elsif inputs_scroll_down_full? args
scroll_down_full
elsif inputs_scroll_up_half? args
scroll_up_half
elsif inputs_scroll_down_half? args
scroll_down_half
elsif inputs_clear_command? args
prompt.clear
@command_history_index = -1
@nonhistory_input = ''
elsif args.inputs.keyboard.key_down.backspace || args.inputs.keyboard.key_down.delete
prompt.backspace
elsif args.inputs.keyboard.key_down.tab
prompt.autocomplete
end
args.inputs.keyboard.key_down.clear
args.inputs.keyboard.key_up.clear
args.inputs.keyboard.key_held.clear
end
def write_primitive_and_return_offset(args, left, y, str, archived: false)
if str.is_a?(Hash)
padding = 10
args.outputs.reserved << [left + 10, y - padding * 1.66, str[:w], str[:h], str[:path]].sprite
return str[:h] + padding
else
write_line args, left, y, str, archived: archived
return line_height_px
end
end
def write_line(args, left, y, str, archived: false)
color = color_for_log_entry(str)
color = color.mult_alpha(0.5) if archived
args.outputs.reserved << font_style.label(x: left.shift_right(10), y: y, text: str, color: color)
end
def render args
return if !@toggled_at
if visible?
percent = @toggled_at.global_ease(@animation_duration, :flip, :quint, :flip)
else
percent = @toggled_at.global_ease(@animation_duration, :flip, :quint)
end
return if percent == 0
bottom = top - (h * percent)
args.outputs.reserved << [left, bottom, w, h, *@background_color.mult_alpha(percent)].solid
args.outputs.reserved << [right.shift_left(210), bottom.shift_up(540), 200, 200, @logo, 0, (80.0 * percent).to_i].sprite
y = bottom + 2 # just give us a little padding at the bottom.
prompt.render args, x: left.shift_right(10), y: y
y += line_height_px * 1.5
args.outputs.reserved << line(y: y, color: @text_color.mult_alpha(percent))
y += line_height_px.to_f / 2.0
((@log.size - @log_offset) - 1).downto(0) do |idx|
offset_after_write = write_primitive_and_return_offset args, left, y, @log[idx]
y += offset_after_write
break if y > top
end
# past log seperator
args.outputs.reserved << line(y: y + line_height_px.half, color: @text_color.mult_alpha(0.25 * percent))
y += line_height_px
((@archived_log.size - @log_offset) - 1).downto(0) do |idx|
offset_after_write = write_primitive_and_return_offset args, left, y, @archived_log[idx], archived: true
y += offset_after_write
break if y > top
end
render_log_offset args
end
def render_log_offset args
return if @log_offset <= 0
args.outputs.reserved << font_style.label(
x: right.shift_left(5),
y: top.shift_down(5 + line_height_px),
text: "[#{@log_offset}/#{@log.size}]",
color: @text_color,
alignment_enum: 2
)
end
def include_error_marker? text
include_any_words?(text.gsub('OutputsDeprecated', ''), error_markers)
end
def error_markers
["exception", "error", "undefined method", "failed", "syntax", "deprecated"]
end
def include_subdued_markers? text
include_any_words? text, subdued_markers
end
def include_any_words? text, words
words.any? { |w| text.downcase.include?(w) && !text.downcase.include?(":#{w}") }
end
def subdued_markers
["reloaded", "exported the"]
end
def calc args
if visible? &&
@show_reason == :toast &&
@toasted_at &&
@toasted_at.elapsed?(@toast_duration, Kernel.global_tick_count)
hide
end
if !$gtk.paused? && visible? && (show_reason == :exception || show_reason == :exception_on_load)
hide
end
if $gtk.files_reloaded.length > 0
clear_toast
@toast_ids.clear
end
end
def tick args
begin
return if @disabled
render args
calc args
process_inputs args
rescue Exception => e
@disabled = true
$stdout.puts e
$stdout.puts "* FATAL: The GTK::Console console threw an unhandled exception and has been reset. You should report this exception (along with reproduction steps) to DragonRuby."
end
end
def set_command_with_history_silent command, histories, show_reason = nil
@command_history.concat histories
@command_history << command if @command_history[-1] != command
self.current_input_str = command if @command_set_at != Kernel.global_tick_count
@command_set_at = Kernel.global_tick_count
@command_history_index = -1
save_history
end
def set_command_with_history command, histories, show_reason = nil
set_command_with_history_silent command, histories, show_reason
show show_reason
end
# @gtk
def set_command command, show_reason = nil
set_command_silent command, show_reason
show show_reason
end
def set_command_silent command, show_reason = nil
set_command_with_history_silent command, [], show_reason
end
private
def w
$gtk.logical_width
end
def h
$gtk.logical_height
end
# methods top; left; right
# Forward to grid
%i[top left right].each do |method|
define_method method do
$gtk.args.grid.send(method)
end
end
def line_height_px
font_style.line_height_px
end
def lines_on_one_page
(h - 4).idiv(line_height_px)
end
def line(y:, color:)
[left, y, right, y, *color].line
end
def include_row_marker? log_entry
log_entry[0] == "|"
end
def color_for_log_entry(log_entry)
if include_row_marker? log_entry
@text_color
elsif include_error_marker? log_entry
@error_color
elsif include_subdued_markers? log_entry
@text_color.mult_alpha(0.5)
elsif log_entry.start_with?("====") || log_entry.include?("app") && !log_entry.include?("apple")
@header_color
else
@text_color
end
end
def prompt
@prompt ||= Prompt.new(font_style: font_style, text_color: @text_color, console_text_width: console_text_width)
end
def current_input_str
prompt.current_input_str
end
def current_input_str=(str)
prompt.current_input_str = str
end
def clear
@archived_log.clear
@log.clear
@prompt.clear
:console_silent_eval
end
end
end
|