ozdenui 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +14 -0
  3. data/NOTICE +5 -0
  4. data/README.md +242 -0
  5. data/exe/ozdenui +17 -0
  6. data/lib/ozdenui/AGENTS.md +210 -0
  7. data/lib/ozdenui/COMPONENTS.md +3017 -0
  8. data/lib/ozdenui/app.rb +749 -0
  9. data/lib/ozdenui/command.rb +107 -0
  10. data/lib/ozdenui/components.rb +368 -0
  11. data/lib/ozdenui/dialogs.rb +212 -0
  12. data/lib/ozdenui/files.rb +124 -0
  13. data/lib/ozdenui/icon.png +0 -0
  14. data/lib/ozdenui/kit.json +1 -0
  15. data/lib/ozdenui/kit.rb +115 -0
  16. data/lib/ozdenui/look.rb +229 -0
  17. data/lib/ozdenui/objects.rb +652 -0
  18. data/lib/ozdenui/server.rb +270 -0
  19. data/lib/ozdenui/values.rb +273 -0
  20. data/lib/ozdenui/version.rb +15 -0
  21. data/lib/ozdenui/web/basic/LICENSE +14 -0
  22. data/lib/ozdenui/web/basic/basic.min.css +1 -0
  23. data/lib/ozdenui/web/basic/basic.min.js +78 -0
  24. data/lib/ozdenui/web/basic/font/open-sans/LICENSE.txt +206 -0
  25. data/lib/ozdenui/web/basic/font/open-sans/OpenSans-Bold.ttf +0 -0
  26. data/lib/ozdenui/web/basic/font/open-sans/OpenSans-Regular.ttf +0 -0
  27. data/lib/ozdenui/web/basic/scroll-bar.min.js +3 -0
  28. data/lib/ozdenui/web/bridge.js +584 -0
  29. data/lib/ozdenui/web/comp/accordion.js +659 -0
  30. data/lib/ozdenui/web/comp/action-button/add.png +0 -0
  31. data/lib/ozdenui/web/comp/action-button.js +521 -0
  32. data/lib/ozdenui/web/comp/action-tab-bar.js +383 -0
  33. data/lib/ozdenui/web/comp/app-bar.js +237 -0
  34. data/lib/ozdenui/web/comp/badge.js +292 -0
  35. data/lib/ozdenui/web/comp/bottom-bar.js +555 -0
  36. data/lib/ozdenui/web/comp/breadcrumbs.js +524 -0
  37. data/lib/ozdenui/web/comp/canvas.js +652 -0
  38. data/lib/ozdenui/web/comp/chat-view.js +827 -0
  39. data/lib/ozdenui/web/comp/check-box.js +490 -0
  40. data/lib/ozdenui/web/comp/code-editor.js +965 -0
  41. data/lib/ozdenui/web/comp/color-picker.js +636 -0
  42. data/lib/ozdenui/web/comp/context-menu.js +951 -0
  43. data/lib/ozdenui/web/comp/currency-field.js +209 -0
  44. data/lib/ozdenui/web/comp/data-table/arrow.svg +2 -0
  45. data/lib/ozdenui/web/comp/data-table.js +937 -0
  46. data/lib/ozdenui/web/comp/date-picker.js +1055 -0
  47. data/lib/ozdenui/web/comp/dialog.js +992 -0
  48. data/lib/ozdenui/web/comp/email-field.js +65 -0
  49. data/lib/ozdenui/web/comp/file-picker.js +920 -0
  50. data/lib/ozdenui/web/comp/filters.js +807 -0
  51. data/lib/ozdenui/web/comp/form.js +602 -0
  52. data/lib/ozdenui/web/comp/full-screen-select/arrow.svg +2 -0
  53. data/lib/ozdenui/web/comp/full-screen-select/cancel.svg +2 -0
  54. data/lib/ozdenui/web/comp/full-screen-select.js +614 -0
  55. data/lib/ozdenui/web/comp/gauge.js +439 -0
  56. data/lib/ozdenui/web/comp/graph-box.js +3911 -0
  57. data/lib/ozdenui/web/comp/grid-group.js +185 -0
  58. data/lib/ozdenui/web/comp/hold-to-confirm-button/trash-red.png +0 -0
  59. data/lib/ozdenui/web/comp/hold-to-confirm-button/trash.png +0 -0
  60. data/lib/ozdenui/web/comp/hold-to-confirm-button.js +289 -0
  61. data/lib/ozdenui/web/comp/image-view.js +598 -0
  62. data/lib/ozdenui/web/comp/item-list.js +1740 -0
  63. data/lib/ozdenui/web/comp/json-editor.js +3221 -0
  64. data/lib/ozdenui/web/comp/json-view.js +597 -0
  65. data/lib/ozdenui/web/comp/label-editor.js +1140 -0
  66. data/lib/ozdenui/web/comp/left-menu/data-table.png +0 -0
  67. data/lib/ozdenui/web/comp/left-menu/home.png +0 -0
  68. data/lib/ozdenui/web/comp/left-menu/reports.png +0 -0
  69. data/lib/ozdenui/web/comp/left-menu/setting.png +0 -0
  70. data/lib/ozdenui/web/comp/left-menu.js +548 -0
  71. data/lib/ozdenui/web/comp/line-progress-bar.js +343 -0
  72. data/lib/ozdenui/web/comp/loading-screen.js +413 -0
  73. data/lib/ozdenui/web/comp/log-view.js +530 -0
  74. data/lib/ozdenui/web/comp/login-page.js +685 -0
  75. data/lib/ozdenui/web/comp/markdown-view.js +1045 -0
  76. data/lib/ozdenui/web/comp/menu-bar.js +624 -0
  77. data/lib/ozdenui/web/comp/mini-graph-box.js +492 -0
  78. data/lib/ozdenui/web/comp/minimal-accent.js +208 -0
  79. data/lib/ozdenui/web/comp/notice.js +229 -0
  80. data/lib/ozdenui/web/comp/number-field.js +128 -0
  81. data/lib/ozdenui/web/comp/numeric-keyboard.js +298 -0
  82. data/lib/ozdenui/web/comp/page-control.js +762 -0
  83. data/lib/ozdenui/web/comp/page-header.js +191 -0
  84. data/lib/ozdenui/web/comp/password-field/hide-btn.png +0 -0
  85. data/lib/ozdenui/web/comp/password-field/hide-btn2.png +0 -0
  86. data/lib/ozdenui/web/comp/password-field/show-btn.png +0 -0
  87. data/lib/ozdenui/web/comp/password-field/show-btn2.png +0 -0
  88. data/lib/ozdenui/web/comp/password-field.js +192 -0
  89. data/lib/ozdenui/web/comp/period-bar.js +436 -0
  90. data/lib/ozdenui/web/comp/phone-field.js +322 -0
  91. data/lib/ozdenui/web/comp/progress-bar.js +992 -0
  92. data/lib/ozdenui/web/comp/property-panel.js +3639 -0
  93. data/lib/ozdenui/web/comp/radio-button.js +527 -0
  94. data/lib/ozdenui/web/comp/range-slider.js +569 -0
  95. data/lib/ozdenui/web/comp/rich-text-editor.js +1064 -0
  96. data/lib/ozdenui/web/comp/scroll-area.js +308 -0
  97. data/lib/ozdenui/web/comp/scrolling-text.js +297 -0
  98. data/lib/ozdenui/web/comp/search-input/clear-round.svg +1 -0
  99. data/lib/ozdenui/web/comp/search-input/clear.svg +1 -0
  100. data/lib/ozdenui/web/comp/search-input/filter.png +0 -0
  101. data/lib/ozdenui/web/comp/search-input/filter.svg +1 -0
  102. data/lib/ozdenui/web/comp/search-input/search.svg +1 -0
  103. data/lib/ozdenui/web/comp/search-input.js +725 -0
  104. data/lib/ozdenui/web/comp/search-results.js +596 -0
  105. data/lib/ozdenui/web/comp/select-box.js +1862 -0
  106. data/lib/ozdenui/web/comp/settings-row.js +299 -0
  107. data/lib/ozdenui/web/comp/side-panel.js +616 -0
  108. data/lib/ozdenui/web/comp/slider-field.js +952 -0
  109. data/lib/ozdenui/web/comp/slider.js +838 -0
  110. data/lib/ozdenui/web/comp/smart-button/alert-black.png +0 -0
  111. data/lib/ozdenui/web/comp/smart-button/clock.png +0 -0
  112. data/lib/ozdenui/web/comp/smart-button.js +981 -0
  113. data/lib/ozdenui/web/comp/smart-table/clock.png +0 -0
  114. data/lib/ozdenui/web/comp/smart-table/down.png +0 -0
  115. data/lib/ozdenui/web/comp/smart-table/scroll.png +0 -0
  116. data/lib/ozdenui/web/comp/smart-table/sort.png +0 -0
  117. data/lib/ozdenui/web/comp/smart-table/up.png +0 -0
  118. data/lib/ozdenui/web/comp/smart-table.js +1883 -0
  119. data/lib/ozdenui/web/comp/sortable-list.js +1181 -0
  120. data/lib/ozdenui/web/comp/spark-line-box.js +738 -0
  121. data/lib/ozdenui/web/comp/splitter.js +411 -0
  122. data/lib/ozdenui/web/comp/status-bar.js +408 -0
  123. data/lib/ozdenui/web/comp/step-bar.js +345 -0
  124. data/lib/ozdenui/web/comp/stepper.js +753 -0
  125. data/lib/ozdenui/web/comp/tabs.js +1366 -0
  126. data/lib/ozdenui/web/comp/tag-input.js +1107 -0
  127. data/lib/ozdenui/web/comp/tap-effect.js +170 -0
  128. data/lib/ozdenui/web/comp/text-area-field.js +233 -0
  129. data/lib/ozdenui/web/comp/text-field.js +1006 -0
  130. data/lib/ozdenui/web/comp/time-line.js +398 -0
  131. data/lib/ozdenui/web/comp/time-picker.js +1032 -0
  132. data/lib/ozdenui/web/comp/tiny-select/arrow.svg +1 -0
  133. data/lib/ozdenui/web/comp/tiny-select.js +322 -0
  134. data/lib/ozdenui/web/comp/tiny-table.js +283 -0
  135. data/lib/ozdenui/web/comp/toast.js +891 -0
  136. data/lib/ozdenui/web/comp/toggle.js +757 -0
  137. data/lib/ozdenui/web/comp/tool-bar.js +760 -0
  138. data/lib/ozdenui/web/comp/tooltip.js +534 -0
  139. data/lib/ozdenui/web/comp/tree-view.js +1179 -0
  140. data/lib/ozdenui/web/comp/ui-effects.js +1097 -0
  141. data/lib/ozdenui/web/comp/ui-standards.js +403 -0
  142. data/lib/ozdenui/web/comp/url-field.js +190 -0
  143. data/lib/ozdenui/web/comp/web-view.js +588 -0
  144. data/lib/ozdenui/web/components.js +123 -0
  145. data/lib/ozdenui/web/index.html +39 -0
  146. data/lib/ozdenui/window.rb +188 -0
  147. data/lib/ozdenui/window_cocoa.rb +221 -0
  148. data/lib/ozdenui.rb +32 -0
  149. metadata +200 -0
@@ -0,0 +1,749 @@
1
+ # Bismillah
2
+ #
3
+ # app.rb - ozdenui v0.1 (OzdenUI: basic.js for Ruby)
4
+ # The window, the tasks of the program and the commands that go to the page.
5
+ #
6
+ # Threads:
7
+ # - The main thread runs the window (macOS wants the first thread of the program).
8
+ # - The app thread runs the code of the program: the block of run, every event, every timer and ui { } task, one at a
9
+ # time. The code of the program never needs a lock.
10
+ # - The server (server.rb) takes the messages of the page on threads of its own: they only put a task in the queue.
11
+ #
12
+ # The commands of a task are sent to the page together, when the task ends (flush): one message for a whole window,
13
+ # not one for each object.
14
+ #
15
+ # Started Date: November 2026
16
+ # Webpage: https://bug7a.github.io/ozdenui-ruby/
17
+ #
18
+ # Copyright 2026 Bugra Ozden <bugra.ozden@gmail.com> (https://bug7a.github.io/)
19
+ # Licensed under the Apache License, Version 2.0
20
+ # SPDX-License-Identifier: Apache-2.0
21
+
22
+ module OzdenUI
23
+ # What the gem is made of. A program uses the methods of OzdenUI; these classes are behind them.
24
+ module Runtime
25
+ # A time that runs later (after) or again and again (every): timer.stop ends it.
26
+ class Timer
27
+ MIN_REPEAT = 0.001 # WHY: every(0) would spin a whole CPU core
28
+
29
+ # @api private
30
+ def initialize(app, milliseconds, repeat, task)
31
+ @app = app
32
+ @stopped = false
33
+ @queued = false # WHY: a slow task must not pile up ticks in the queue
34
+ seconds = [milliseconds.to_f / 1000, 0].max
35
+ seconds = [seconds, MIN_REPEAT].max if repeat
36
+ @thread = Thread.new do
37
+ next_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
38
+ loop do
39
+ # WHY from the time before: a clock that sleeps "a second" after every tick falls behind
40
+ next_at = [next_at + seconds, Process.clock_gettime(Process::CLOCK_MONOTONIC)].max
41
+ wait = next_at - Process.clock_gettime(Process::CLOCK_MONOTONIC)
42
+ sleep(wait) if wait.positive?
43
+ break if @stopped || app.closed?
44
+ unless @queued
45
+ @queued = true
46
+ app.tasks.put(proc do
47
+ @queued = false
48
+ task.call unless @stopped
49
+ end)
50
+ end
51
+ break unless repeat
52
+ end
53
+ app.forget_timer(self)
54
+ end
55
+ end
56
+
57
+ def stop
58
+ @stopped = true
59
+ @app.forget_timer(self)
60
+ nil
61
+ end
62
+ alias cancel stop
63
+
64
+ def stopped?
65
+ @stopped
66
+ end
67
+ end
68
+
69
+ # @api private
70
+ class TaskQueue
71
+ def initialize
72
+ @tasks = []
73
+ @mutex = Mutex.new
74
+ @condition = ConditionVariable.new
75
+ @closed = false
76
+ end
77
+
78
+ def put(task)
79
+ @mutex.synchronize do
80
+ @tasks << task
81
+ @condition.signal
82
+ end
83
+ end
84
+
85
+ def close
86
+ @mutex.synchronize do
87
+ @closed = true
88
+ @condition.broadcast
89
+ end
90
+ end
91
+
92
+ # The next task; nil when the window is closed.
93
+ def get
94
+ @mutex.synchronize do
95
+ @condition.wait(@mutex) while @tasks.empty? && !@closed
96
+ @closed ? nil : @tasks.shift
97
+ end
98
+ end
99
+ end
100
+
101
+ # Something that happens once, and the threads that wait for it.
102
+ # @api private
103
+ class Latch
104
+ def initialize
105
+ @mutex = Mutex.new
106
+ @condition = ConditionVariable.new
107
+ @set = false
108
+ end
109
+
110
+ def set
111
+ @mutex.synchronize do
112
+ @set = true
113
+ @condition.broadcast
114
+ end
115
+ end
116
+
117
+ def set?
118
+ @mutex.synchronize { @set }
119
+ end
120
+
121
+ # true when it happened before the time was over (nil: no end).
122
+ def wait(seconds = nil)
123
+ ends_at = seconds && Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
124
+ @mutex.synchronize do
125
+ until @set
126
+ left = ends_at && ends_at - Process.clock_gettime(Process::CLOCK_MONOTONIC)
127
+ return false if left && left <= 0
128
+ @condition.wait(@mutex, left)
129
+ end
130
+ true
131
+ end
132
+ end
133
+ end
134
+
135
+ # An answer the code waits for (a dialog): from the page, or nil when it can not come. Only the first one counts.
136
+ # @api private
137
+ class Answer
138
+ attr_reader :value
139
+
140
+ def initialize
141
+ @given = false
142
+ @value = nil
143
+ end
144
+
145
+ def give(value)
146
+ return if @given
147
+ @value = value
148
+ @given = true
149
+ end
150
+
151
+ def given?
152
+ @given
153
+ end
154
+ end
155
+
156
+ # @api private
157
+ class App
158
+ READY_TIMEOUT = 15
159
+ DARK_PAGE_COLOR = "#1C1C1B"
160
+ EARLY_PAGE_COLOR = "ozdenui-page-color:" # window.name of a page loaded again for another theme (bridge.js)
161
+ RELOAD_DELAY_MS = 50 # the page of set_theme loads itself again this much after the script that asks it
162
+ ACCENT_STYLE_NAME = "minimalAccent"
163
+ THEMES = %w[light dark auto].freeze
164
+ OPTION_NAMES = %i[title width height theme style accent accent_dark language debug icon].freeze
165
+
166
+ attr_reader :options, :theme, :server, :tasks, :objects, :leaving, :callbacks, :page, :ready, :drawn, :basic_version
167
+ attr_accessor :control, :containers
168
+
169
+ def initialize(options, start)
170
+ @options = { title: "OzdenUI", width: 800, height: 600, theme: "light", style: nil }.merge(options)
171
+ @options[:theme] = @options[:theme].to_s
172
+ @options[:style] = @options[:style].to_s if @options[:style]
173
+ # A picture of the dark window without a change of the program (OZDENUI_LOOK)
174
+ @options[:theme] = ENV["OZDENUI_THEME"] unless ENV["OZDENUI_THEME"].to_s.empty?
175
+ check_options
176
+ @start = start
177
+ @wanted_theme = @options[:theme]
178
+ @theme = @wanted_theme == "dark" ? "dark" : "light"
179
+ @tasks = TaskQueue.new
180
+ @ready = Latch.new # the page said it is ready for the first time
181
+ @closed = Latch.new # the window is gone
182
+ @drawn = Latch.new # the first drawing of the program is on the page
183
+ @commands = []
184
+ @containers = [] # the open boxes of the task that runs: the last one takes the new objects
185
+ @objects = {}
186
+ @leaving = {} # objects the page removed, until the events they sent before are handled
187
+ @callbacks = {} # id -> [block, owner id]
188
+ @failed_ids = {} # the objects the page could not make (an answer that belongs to one is nil)
189
+ @answers = {}
190
+ @timers = []
191
+ @timers_mutex = Mutex.new
192
+ @ready_mutex = Mutex.new
193
+ @is_ready = false
194
+ @next_object = 0
195
+ @next_callback = 0
196
+ @prefers_dark = false
197
+ @page_width = @options[:width]
198
+ @page_height = @options[:height]
199
+ @loading_for_theme = false
200
+ @has_started = false
201
+ @warned = {}
202
+ end
203
+
204
+ def check_options
205
+ unknown = @options.keys - OPTION_NAMES
206
+ unless unknown.empty?
207
+ raise Error, "run(#{unknown.first}: ...): the window takes #{OPTION_NAMES.map { |name| "#{name}:" }.join(', ')}"
208
+ end
209
+ theme, style = @options.values_at(:theme, :style)
210
+ raise Error, %(run(theme: #{theme.inspect}): it is "light", "dark" or "auto") unless THEMES.include?(theme)
211
+ raise Error, %(run(style: #{style.inspect}): it is nil or "minimal") unless style.nil? || style == "minimal"
212
+ raise Error, "run(accent_dark: ...): it goes with accent:" if @options[:accent_dark] && !@options[:accent]
213
+ return unless @options[:accent] && style != "minimal"
214
+ raise Error, %(run(accent: ...): the color of the minimal look; give style: "minimal" too)
215
+ end
216
+
217
+ # Opens the window and returns when it is closed.
218
+ def run
219
+ @server = Server.new(self)
220
+ @app_thread = Thread.new { run_app_thread }
221
+ Window.open(self, @server.address)
222
+ ensure
223
+ on_window_closed
224
+ @server&.stop
225
+ @app_thread&.join(1)
226
+ end
227
+
228
+ def closed?
229
+ @closed.set?
230
+ end
231
+
232
+ def closed_latch
233
+ @closed
234
+ end
235
+
236
+ def dark?
237
+ @theme == "dark"
238
+ end
239
+
240
+ def minimal?
241
+ @options[:style] == "minimal"
242
+ end
243
+
244
+ # *** TIMERS:
245
+
246
+ def new_timer(milliseconds, repeat, task)
247
+ timer = Timer.new(self, milliseconds, repeat, task)
248
+ @timers_mutex.synchronize { @timers << timer unless timer.stopped? }
249
+ timer
250
+ end
251
+
252
+ def forget_timer(timer)
253
+ @timers_mutex.synchronize { @timers.delete(timer) }
254
+ end
255
+
256
+ def stop_timers
257
+ timers = @timers_mutex.synchronize { @timers.dup }
258
+ timers.each(&:stop)
259
+ end
260
+
261
+ # *** THE APP THREAD:
262
+
263
+ def run_app_thread
264
+ unless @ready.wait(READY_TIMEOUT) || closed?
265
+ warn_plain("the page is not ready yet (basic.js or the bridge did not load)")
266
+ # WHY it goes on waiting: a page that comes late on a slow computer must still start the program
267
+ sleep(0.05) until @ready.set? || closed?
268
+ end
269
+ return if closed?
270
+ run_task(method(:start_page))
271
+ @drawn.set
272
+ run_tasks_until { false }
273
+ rescue SystemExit
274
+ # WHY: exit in a block of the program ends only this thread; the window would stay open with nobody behind it
275
+ @control&.close
276
+ end
277
+
278
+ def start_page
279
+ @has_started = true
280
+ make_page
281
+ add_accent_packages
282
+ Values.call_handler(@start, [@page])
283
+ end
284
+
285
+ def make_page
286
+ @page = UIObject.new(self, "page", :page)
287
+ @page.become_page(@page_width, @page_height)
288
+ @page.set(color: DARK_PAGE_COLOR) if dark?
289
+ end
290
+
291
+ def add_accent_packages
292
+ return unless @options[:accent]
293
+ flush
294
+ @server.request("kind" => "accent", "name" => ACCENT_STYLE_NAME, "color" => @options[:accent],
295
+ "colorDark" => @options[:accent_dark].to_s)
296
+ rescue PageGone, Error => error
297
+ warn_plain("run(accent: ...): #{error.message}")
298
+ end
299
+
300
+ def run_tasks_until
301
+ until yield
302
+ task = @tasks.get
303
+ return unless task
304
+ run_task(task)
305
+ end
306
+ end
307
+
308
+ def run_task(task)
309
+ # WHY its own open boxes: a task that runs while another one waits for a dialog (a click, a timer) would make its
310
+ # objects in the open box of that one; a task that failed in a box leaves nothing open either.
311
+ outer = @containers
312
+ @containers = []
313
+ begin
314
+ task.call
315
+ rescue StandardError, ScriptError => error
316
+ # WHY not the end of the program: one block that failed must not close the window with the work in it
317
+ trace = Values.program_trace(error)
318
+ $stderr.puts "ozdenui: a task failed: #{error.message} (#{error.class})", trace.map { |line| " #{line}" }
319
+ end
320
+ @containers = outer
321
+ flush
322
+ end
323
+
324
+ # Runs the other tasks until the block is true: the code that waits (a dialog) keeps the window working.
325
+ def wait_for
326
+ flush
327
+ run_tasks_until { yield || closed? }
328
+ end
329
+
330
+ def app_thread?
331
+ Thread.current == @app_thread
332
+ end
333
+
334
+ def check(what)
335
+ return if app_thread?
336
+ raise Error, "#{what} works only in the block of run, an event or a timer. From another thread: ui { ... }"
337
+ end
338
+
339
+ # *** THE COMMANDS:
340
+
341
+ def send_command(command)
342
+ check(command["op"])
343
+ @commands << command
344
+ end
345
+
346
+ def flush
347
+ return if @commands.empty? || closed? || @loading_for_theme
348
+ commands = @commands
349
+ @commands = []
350
+ after_apply(@server.request("kind" => "apply", "commands" => commands))
351
+ rescue PageGone
352
+ nil # the page is gone (closed, loaded again): its commands go with it
353
+ rescue Error => error
354
+ warn_plain(error.message)
355
+ end
356
+
357
+ def after_apply(result)
358
+ return unless result.is_a?(Hash)
359
+ (result["errors"] || []).each do |problem|
360
+ id = problem["id"].to_s
361
+ where = "#{problem['op']} #{id}".strip
362
+ where = "#{problem['src']}: #{where}" unless problem["src"].to_s.empty?
363
+ warn_plain("#{where}: #{problem['message']}")
364
+ give_up_answer_of(id) if problem["op"] == "create" && !id.empty?
365
+ end
366
+ removed = result["removed"] || []
367
+ return if removed.empty?
368
+ removed.each do |id|
369
+ object = @objects.delete(id)
370
+ @leaving[id] = object if object
371
+ end
372
+ # WHY later: a component sends an event and then leaves the page (a Dialog: onClose, then remove()). The events
373
+ # the page sent before this answer are already in the queue: the task that forgets comes after them.
374
+ @tasks.put(proc { forget_removed(removed) })
375
+ end
376
+
377
+ # WHY: the blocks given to a removed object would be kept for ever (a list made again every second grows).
378
+ def forget_removed(removed)
379
+ removed.each { |id| @leaving.delete(id) }
380
+ @callbacks.delete_if { |_id, entry| removed.include?(entry[1]) }
381
+ end
382
+
383
+ def give_up_answer_of(id)
384
+ @failed_ids[id] = true
385
+ @answers[id]&.give(nil)
386
+ end
387
+
388
+ def new_id
389
+ "o#{@next_object += 1}"
390
+ end
391
+
392
+ def register_callback(handler, owner_id)
393
+ id = "c#{@next_callback += 1}"
394
+ @callbacks[id] = [handler, owner_id]
395
+ id
396
+ end
397
+
398
+ def container_id
399
+ @containers.last || "page"
400
+ end
401
+
402
+ # Calls a function of a component (Toast.show, Dialog.confirm). wait: the function gives a Promise; its value is
403
+ # returned, and the window keeps working while the code waits for it. keep: the id of the object that stands for
404
+ # what the function returns (a bubble).
405
+ def call_static(target, method, args, wait: false, keep: nil)
406
+ command = { "op" => "static", "target" => target, "method" => method, "args" => args, "src" => Values.source_line }
407
+ command["keep"] = keep if keep
408
+ unless wait
409
+ send_command(command)
410
+ return nil
411
+ end
412
+ pending = Answer.new
413
+ id = register_callback(proc { |value| pending.give(value) }, "")
414
+ command["answer"] = id
415
+ send_command(command)
416
+ value = wait_for_answer(id, pending)
417
+ @callbacks.delete(id)
418
+ value
419
+ end
420
+
421
+ # Waits for an answer (the window keeps working). key: the callback id of the answer, or the id of the object that
422
+ # gives it (a Dialog). It is nil when it can not come: the object could not be made, the page was loaded again or
423
+ # the window was closed.
424
+ def wait_for_answer(key, pending)
425
+ @answers[key] = pending
426
+ wait_for do
427
+ pending.give(nil) if @failed_ids[key]
428
+ pending.given?
429
+ end
430
+ pending.value
431
+ ensure
432
+ @answers.delete(key)
433
+ end
434
+
435
+ def read(id, key)
436
+ flush
437
+ ruby_value(@server.request("kind" => "read", "id" => id, "key" => key))
438
+ end
439
+
440
+ def ask(id, method, args)
441
+ flush
442
+ ruby_value(@server.request("kind" => "ask", "id" => id, "method" => method, "args" => args))
443
+ end
444
+
445
+ def evaluate(script)
446
+ check("evaluate")
447
+ flush
448
+ ruby_value(@server.request("kind" => "eval", "script" => script))
449
+ rescue PageGone, Error => error
450
+ warn_at("evaluate: #{error.message}")
451
+ nil
452
+ end
453
+
454
+ # *** FROM THE PAGE (the threads of the server; they only queue tasks):
455
+
456
+ def on_page_ready(message)
457
+ is_first = @ready_mutex.synchronize do
458
+ first = !@is_ready
459
+ @is_ready = true
460
+ first
461
+ end
462
+ if is_first
463
+ take_ready(message)
464
+ @ready.set
465
+ return
466
+ end
467
+ # The page was loaded again (set_theme, the reload of the developer tools): its objects are gone, the block of
468
+ # run makes them again.
469
+ @tasks.put(proc do
470
+ take_ready(message)
471
+ start_again
472
+ end)
473
+ end
474
+
475
+ def take_ready(message)
476
+ @basic_version = message["basicVersion"]
477
+ @page_width = message["width"]
478
+ @page_height = message["height"]
479
+ @prefers_dark = message["prefersDark"] ? true : false
480
+ @theme = @prefers_dark ? "dark" : "light" if @wanted_theme == "auto"
481
+ end
482
+
483
+ def on_page_event(target, event, data)
484
+ @tasks.put(proc { dispatch(target, event, data.is_a?(Hash) ? data : Data.new) })
485
+ end
486
+
487
+ def dispatch(target, event, data)
488
+ case event
489
+ when "callback" then run_callback(target, data)
490
+ when "__message" then $stderr.puts "ozdenui (page #{data['kind']}): #{data['text']}"
491
+ else @objects[target]&.receive_event(event, data) # nil: an event of an object removed in the meantime
492
+ end
493
+ end
494
+
495
+ def run_callback(id, data)
496
+ handler, owner_id = @callbacks[id]
497
+ return unless handler
498
+ owner = @objects[owner_id] || @leaving[owner_id]
499
+ owner.take_state(data["state"]) if owner && data["state"].is_a?(Hash)
500
+ args = (data["args"] || []).map { |value| ruby_value(value) }
501
+ Values.call_handler(handler, args)
502
+ end
503
+
504
+ # A value from the page: a basic.js object becomes its object of the program; JSON data that came whole (the
505
+ # wholeArgs of a callback) becomes its value.
506
+ def ruby_value(value)
507
+ case value
508
+ when Hash
509
+ return object_value(value) if value.key?("__bpObject")
510
+ return JSON.parse(value["__bpJson"], object_class: Data) if value["__bpJson"].is_a?(String)
511
+ value.each { |key, item| value[key] = ruby_value(item) }
512
+ when Array
513
+ value.map! { |item| ruby_value(item) }
514
+ else
515
+ value
516
+ end
517
+ rescue JSON::ParserError
518
+ nil
519
+ end
520
+
521
+ # A basic.js object from the page: its object, or { "id", "data" } for a part of a component (a row of a list), or nil.
522
+ def object_value(value)
523
+ id = value["__bpObject"]
524
+ known = id.is_a?(String) ? (@objects[id] || @leaving[id]) : nil
525
+ return known if known
526
+ rest = Data.new
527
+ value.each { |key, item| rest[key] = ruby_value(item) unless key == "__bpObject" }
528
+ rest.empty? ? nil : rest
529
+ end
530
+
531
+ # *** ANOTHER THEME, A PAGE LOADED AGAIN:
532
+
533
+ # WHY the page is loaded again: a component takes its look when it is made, and a new page keeps nothing of the
534
+ # old one (an open menu or bubble, a listener of a component).
535
+ # WHY window.name: it stays over the load, so the new page has the ground of its theme from its first drawing.
536
+ def change_theme(theme)
537
+ return if closed? || theme == @wanted_theme
538
+ @wanted_theme = theme
539
+ theme = @prefers_dark ? "dark" : "light" if theme == "auto" # the page tells it again when it is ready
540
+ @theme = theme
541
+ stop_timers # WHY: a tick would send its commands to a page that is being loaded
542
+ color = theme == "dark" ? DARK_PAGE_COLOR : ""
543
+ flush
544
+ @loading_for_theme = true
545
+ name = JSON.generate(EARLY_PAGE_COLOR + color)
546
+ script = "window.name = #{name}; setTimeout(function () { location.reload(); }, #{RELOAD_DELAY_MS}); 0"
547
+ begin
548
+ @server.request("kind" => "eval", "script" => script)
549
+ rescue PageGone, Error
550
+ nil
551
+ end
552
+ end
553
+
554
+ def start_again
555
+ if @loading_for_theme
556
+ @loading_for_theme = false # WHY no word: the program asked for the new page (set_theme)
557
+ elsif @has_started
558
+ warn_plain("the page was loaded again: the block of run runs again")
559
+ end
560
+ # WHY: the dialogs of the old page are gone; the code that waits for one of them gets nil
561
+ @answers.each_value { |pending| pending.give(nil) }
562
+ @failed_ids = {}
563
+ stop_timers
564
+ @commands = []
565
+ @objects = {}
566
+ @leaving = {}
567
+ @callbacks = {}
568
+ start_page
569
+ end
570
+
571
+ def on_window_closed
572
+ return if closed?
573
+ @closed.set
574
+ @tasks.close
575
+ stop_timers
576
+ end
577
+
578
+ # The title of the page: the title of a browser window, and what the system lists.
579
+ def title=(title)
580
+ @options[:title] = title.to_s
581
+ @control&.title = title.to_s
582
+ script = "document.title = #{JSON.generate(title.to_s)}; 0"
583
+ @tasks.put(proc do
584
+ begin
585
+ @server.request("kind" => "eval", "script" => script)
586
+ rescue PageGone, Error
587
+ nil
588
+ end
589
+ end)
590
+ end
591
+
592
+ # *** WORDS TO THE TERMINAL:
593
+
594
+ # Tells once in the terminal, at the line of the program.
595
+ def warn_at(text)
596
+ text = "#{Values.source_line}: #{text}".sub(/\A: /, "")
597
+ return if @warned[text]
598
+ @warned[text] = true
599
+ $stderr.puts "ozdenui: #{text}"
600
+ end
601
+
602
+ def warn_plain(text)
603
+ $stderr.puts "ozdenui: #{text}"
604
+ end
605
+ end
606
+ end
607
+
608
+ @app = nil
609
+
610
+ class << self
611
+ # @api private
612
+ attr_reader :app
613
+
614
+ # @api private
615
+ def current_app
616
+ @app || raise(Runtime::Error, "make the objects in the block of run: OzdenUI.run(title: \"...\") { ... }")
617
+ end
618
+
619
+ # @api private
620
+ def warning(text)
621
+ @app ? @app.warn_at(text) : $stderr.puts("ozdenui: #{text}")
622
+ end
623
+ end
624
+
625
+ module_function
626
+
627
+ # Opens the window, runs the block when its page is ready (the block may take the page) and returns when the window
628
+ # is closed. Call it once, at the end of the program.
629
+ #
630
+ # OzdenUI.run(title: "Counter", width: 360, height: 260) do |page|
631
+ # Label(text: "Hello")
632
+ # end
633
+ #
634
+ # title:, width:, height:; theme: "light" (default), "dark" or "auto" (what the system asks); style: "minimal" (small,
635
+ # made of lines); accent: a color of the minimal look ("#2A78D6"), accent_dark: its color in a dark window;
636
+ # language: the language of the texts ("tr": capital letters, word breaks); debug: true (the developer tools of the
637
+ # web view); icon: a PNG for the Dock of macOS.
638
+ def run(start = nil, **options, &block)
639
+ start ||= block
640
+ raise Runtime::Error, "run takes a block (or a method: run(method(:start))) that makes the objects" unless Runtime::Values.callable?(start)
641
+ raise Runtime::Error, "run is called once in a program" if OzdenUI.app
642
+ app = Runtime::App.new(options, start)
643
+ OzdenUI.instance_variable_set(:@app, app)
644
+ app.run
645
+ nil
646
+ rescue Interrupt
647
+ nil # Ctrl+C in the terminal closes the window, as its red button does
648
+ end
649
+
650
+ # Closes the window (from any thread); run returns.
651
+ def close
652
+ app = OzdenUI.current_app
653
+ app.control ? app.control.close : app.tasks.put(proc { app.control&.close })
654
+ nil
655
+ end
656
+
657
+ # Changes the title of the window.
658
+ def set_title(title)
659
+ OzdenUI.current_app.title = title
660
+ nil
661
+ end
662
+
663
+ # The theme of the window: "light" or "dark".
664
+ def theme
665
+ OzdenUI.current_app.theme
666
+ end
667
+
668
+ # true in a dark window: color = dark? ? "#9AA3B5" : "#5A6270"
669
+ def dark?
670
+ OzdenUI.current_app.dark?
671
+ end
672
+
673
+ # Draws the window again in another theme: "light", "dark" or "auto" (what the system asks). The page is made again
674
+ # and the block of run runs again, as when the window opened: its objects start again (a text typed in a field is
675
+ # gone), what the program keeps in its own variables stays. Any thread may call it; the change comes after the task
676
+ # that runs now.
677
+ def set_theme(theme)
678
+ theme = theme.to_s
679
+ raise Runtime::Error, %(set_theme(#{theme.inspect}): it is "light", "dark" or "auto") unless Runtime::App::THEMES.include?(theme)
680
+ app = OzdenUI.current_app
681
+ app.tasks.put(proc { app.change_theme(theme) })
682
+ nil
683
+ end
684
+
685
+ # Runs the block on the thread of the window, after the task that runs now. Any thread may call it: it is the way a
686
+ # thread of the program (a download, a long job) changes the objects.
687
+ #
688
+ # Thread.new do
689
+ # text = download # the window does not wait for it
690
+ # ui { label.text = text }
691
+ # end
692
+ def ui(&task)
693
+ raise Runtime::Error, "ui takes a block: ui { label.text = text }" unless task
694
+ OzdenUI.current_app.tasks.put(task)
695
+ nil
696
+ end
697
+
698
+ # Runs the block once, after a time (milliseconds). It returns a timer: timer.cancel.
699
+ def after(milliseconds, &task)
700
+ raise Runtime::Error, "after takes a block: after(3000) { ... }" unless task
701
+ OzdenUI.current_app.new_timer(milliseconds, false, task)
702
+ end
703
+
704
+ # Runs the block again and again (the loop() of basic.js). It returns a timer: timer.stop.
705
+ def every(milliseconds, &task)
706
+ raise Runtime::Error, "every takes a block: every(1000) { ... }" unless task
707
+ OzdenUI.current_app.new_timer(milliseconds, true, task)
708
+ end
709
+
710
+ # Sends the waiting commands to the page now: a long task can show its progress.
711
+ def flush
712
+ app = OzdenUI.current_app
713
+ app.check("flush")
714
+ app.flush
715
+ nil
716
+ end
717
+
718
+ # Runs JavaScript on the page and returns its value (after the waiting commands).
719
+ def evaluate(script)
720
+ OzdenUI.current_app.evaluate(script)
721
+ end
722
+
723
+ # The page of the window (what the block of run gets): page.color = "...", page.on(:key_down) { ... }, page.width.
724
+ def page
725
+ OzdenUI.current_app.page
726
+ end
727
+
728
+ # Reads a flag that came from the page (the kit writes its flags as 1 / 0): true for 1, true and a text that is not empty.
729
+ def on?(value)
730
+ Runtime::Values.on?(value)
731
+ end
732
+
733
+ # How a component writes its numbers, where a param does not take the text itself: a text around one {} place.
734
+ #
735
+ # "{:,.2f} TL" 1,234.50 TL "{:.0f} kg" 12 kg "{:.1%}" 12.3% "$ {:,}" $ 1,234
736
+ #
737
+ # WHY not a block of the program: the page draws at once; the answer of the program would come too late.
738
+ def number_format(pattern)
739
+ Runtime::Values.number_format(pattern)
740
+ end
741
+
742
+ # The address of a picture for the page: of a file of this computer ("photo.png"), of the text of an SVG or of bytes
743
+ # (File.binread, a PNG made by the program). An address of the web stays as it is. A param of a component that names
744
+ # a file (icon_file:, image_file:) and the picture: of an Icon take a path by themselves; picture() is for the other
745
+ # places (the "icon" of an item of a list, a picture in a style).
746
+ def picture(source)
747
+ Runtime::Values.picture(source)
748
+ end
749
+ end