This repository has been archived by the owner on Jul 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
RME.rb
17400 lines (15960 loc) · 638 KB
/
RME.rb
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#==============================================================================
# ** RME v2.1.0
#------------------------------------------------------------------------------
# With :
# xvw
# Joke
# Grim
# Raho
# Zeus81
# Hiino
# Zangther
# Fabien
# Kaelar
# Spyrojojo
# Boubou le hibou
# FalconPilot
# Husk
# Hinola
# Ulis
# msp
#------------------------------------------------------------------------------
# RME is the successor of Event Extender. It offers a collection of tools to
# promote the personalization of an RPG Maker VX Ace project. It is the result
# of the work of many people and any contribution is welcome.
#------------------------------------------------------------------------------
# GitHub: https://github.com/RMEx/RME
#==============================================================================
=begin # MIT License
Copyright (c) 2012-2020 RMEx
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
=end # MIT License
#==============================================================================
# ** RME
#------------------------------------------------------------------------------
# Provide information about RME
#==============================================================================
module RME
module Config
KEY_EVAL = :f3
KEY_TONE = :f4
MAP_RELOAD = :f11
EXTENSIONS = {
# Add command to deal with Event-Making loop
extender_loop: false,
# Hack to use Resolution.change(w, h) with value over 640x480.
# The extension is unsafe and you should not use it !
enlarge_resolution: false,
}
end
class << self
#--------------------------------------------------------------------------
# * Version
# * With RMEPackage, it's seems useless ?
#--------------------------------------------------------------------------
def version; define_version(2,1,0); end
#--------------------------------------------------------------------------
# * define Version
#--------------------------------------------------------------------------
def define_version(x, y, z)
return RME::Version_Label.new(x, y, z)
end
#--------------------------------------------------------------------------
# * Check version
#--------------------------------------------------------------------------
def check_version(oth)
version >= oth
end
#--------------------------------------------------------------------------
# * Allowed Extension
#--------------------------------------------------------------------------
def allowed?(key)
RME::Config::EXTENSIONS[key] || false
end
#--------------------------------------------------------------------------
# * Enabled Gui components
#--------------------------------------------------------------------------
def gui_enabled?
true
end
#--------------------------------------------------------------------------
# * Deprecation
#--------------------------------------------------------------------------
def deprecated(message)
puts "[deprecated] #{message}"
end
def deprecated_command(command, message = "this command is deprecated")
puts "[deprecated command '#{command}'] #{message}"
end
end
#==============================================================================
# ** Doc
#------------------------------------------------------------------------------
# Documentation representation
#==============================================================================
module Doc
#--------------------------------------------------------------------------
# * Singleton
#--------------------------------------------------------------------------
class << self
attr_accessor :schema
attr_accessor :header
attr_accessor :commands
attr_accessor :links
attr_accessor :vocab
attr_accessor :to_fix
attr_accessor :internals
Doc.internals ||= Array.new
Doc.to_fix ||= Array.new
Doc.schema ||= Hash.new
Doc.links ||= Hash.new
Doc.commands ||= Hash.new
end
#--------------------------------------------------------------------------
# * classname
#--------------------------------------------------------------------------
def classname
self.to_s.to_sym
end
#--------------------------------------------------------------------------
# * add internals
#--------------------------------------------------------------------------
def add_internals(*args)
Doc.internals += args
end
#--------------------------------------------------------------------------
# * Init doc
#--------------------------------------------------------------------------
def init_doc_statement
Doc.schema[classname] ||= Hash.new
Doc.schema[classname][:attributes] ||= Hash.new
Doc.schema[classname][:methods] ||= Hash.new
end
#--------------------------------------------------------------------------
# * Register Command Category
#--------------------------------------------------------------------------
def register_command_category(key, name, desc)
Doc.commands[key.to_sym] ||= {:desc => desc, :name => name, :commands => {}}
end
#--------------------------------------------------------------------------
# * Register Command
#--------------------------------------------------------------------------
def register_command(cat, name)
d = Doc.schema[classname][:methods][name.to_sym]
register_command_category(cat, "undefined", "undefined")
Doc.commands[cat][:commands][name.to_sym] = d if d
Doc.to_fix << name.to_sym unless d
end
#--------------------------------------------------------------------------
# * Class documentation
#--------------------------------------------------------------------------
def link_class_documentation(descr)
init_doc_statement
Doc.schema[classname][:description] = descr
end
#--------------------------------------------------------------------------
# * Attributes documentation
#--------------------------------------------------------------------------
def link_attr_documentation(name, descr)
init_doc_statement
Doc.schema[classname][:attributes][name.to_sym] = descr
end
#--------------------------------------------------------------------------
# * Method documentation
#--------------------------------------------------------------------------
def link_method_documentation(name, descr, attributes, returned = false)
init_doc_statement
Doc.schema[classname][:methods][name.to_sym] = Hash.new
Doc.schema[classname][:methods][name.to_sym][:description] = descr
Doc.schema[classname][:methods][name.to_sym][:attributes] = attributes
Doc.schema[classname][:methods][name.to_sym][:returnable] = returned
end
#--------------------------------------------------------------------------
# * Snippet documentation
#--------------------------------------------------------------------------
def link_snippet(meth, value)
init_doc_statement
Doc.schema[classname][:methods][meth.to_sym][:snippet] = value
end
#--------------------------------------------------------------------------
# * Additional links
#--------------------------------------------------------------------------
def documentation_add_link(name, link)
Doc.links[name] = link
end
#--------------------------------------------------------------------------
# * Vocab
#--------------------------------------------------------------------------
def documentation_define(sadly_useless_dude, vocab)
Doc.vocab = vocab
end
end
#==============================================================================
# ** Version_Label
#------------------------------------------------------------------------------
# Version representation
#==============================================================================
class Version_Label < Struct.new(:major, :sub, :last)
#--------------------------------------------------------------------------
# * to_s
#--------------------------------------------------------------------------
def to_s
"#{self.major}.#{self.sub}.#{self.last}"
end
#--------------------------------------------------------------------------
# * Compare operation
#--------------------------------------------------------------------------
def cmp(oth)
if oth.is_a?(Version_Label)
return -1 if oth.major > self.major
return 1 if oth.major < self.major
return -1 if oth.sub > self.sub
return 1 if oth.sub < self.sub
return -1 if oth.last > self.last
return 1 if oth.last < self.last
return 0
else raise RuntimeError.new("Must be a Version_Label")
end
end
#--------------------------------------------------------------------------
# * Operators overloading
#--------------------------------------------------------------------------
def ==(o); self.cmp(o) == 0; end
def >(o); self.cmp(o) > 0; end
def <(o); self.cmp(o) < 0; end
def >=(o); self.cmp(o) >= 0; end
def <=(o); self.cmp(o) <= 0; end
end
end
#--------------------------------------------------------------------------
# * Win32API Extension
#--------------------------------------------------------------------------
#==============================================================================
# ** Externlib
#------------------------------------------------------------------------------
# win32/registry is registry accessor library for Win32 platform.
# It uses dl/import to call Win32 Registry APIs.
#==============================================================================
module Externlib
#--------------------------------------------------------------------------
# * Library as constants
#--------------------------------------------------------------------------
CloseClipboard = Win32API.new('user32', 'CloseClipboard', 'v', 'i')
EmptyClipboard = Win32API.new('user32', 'EmptyClipboard', 'v', 'i')
CloseSocket = Win32API.new('ws2_32', 'closesocket', 'p', 'l')
Connect = Win32API.new('ws2_32', 'connect', 'ppl', 'l')
FindWindow = Win32API.new('user32', 'FindWindow', 'pp', 'i')
GetClipboardData = Win32API.new('user32', 'GetClipboardData', 'i', 'i')
GetCursorPos = Win32API.new('user32', 'GetCursorPos', 'p', 'i')
GetKeyboardState = Win32API.new('user32', 'GetKeyboardState', 'p', 'i')
GetPrivateProfileStringA= Win32API.new('kernel32', 'GetPrivateProfileStringA', 'pppplp', 'l')
GetWindowRect = Win32API.new('user32', 'GetWindowRect', 'lp', 'i')
GetClientRect = Win32API.new('user32', 'GetClientRect', 'ip', 'i')
GlobalAlloc = Win32API.new('kernel32', 'GlobalAlloc', 'ii', 'i')
GlobalFree = Win32API.new('kernel32', 'GlobalFree', 'i', 'i')
GlobalLock = Win32API.new('kernel32', 'GlobalLock', 'i', 'l')
GlobalSize = Win32API.new('kernel32', 'GlobalSize', 'l', 'l')
GlobalUnlock = Win32API.new('kernel32', 'GlobalUnlock', 'l', 'v')
Htons = Win32API.new('ws2_32', 'htons', 'l', 'l')
Inet_Addr = Win32API.new('ws2_32', 'inet_addr', 'p', 'l')
LoadLibraryA = Win32API.new('kernel32', 'LoadLibraryA', 'p', 'i')
Memcpy = Win32API.new('msvcrt', 'memcpy', 'ppi', 'i')
MessageBox = Win32API.new('user32','MessageBox','lppl','i')
MultiByteToWideChar = Win32API.new('kernel32', 'MultiByteToWideChar', 'ilpipi', 'i')
OpenClipboard = Win32API.new('user32', 'OpenClipboard', 'i', 'i')
Recv = Win32API.new('ws2_32', 'recv', 'ppll', 'l')
RegisterClipboardFormat = Win32API.new('user32', 'RegisterClipboardFormat', 'p', 'i')
RtlMoveMemory = Win32API.new('kernel32', 'RtlMoveMemory', 'ppi', 'i')
ScreenToClient = Win32API.new('user32', 'ScreenToClient', 'ip', 'i')
Send = Win32API.new('ws2_32', 'send', 'ppll', 'l')
SetClipboardData = Win32API.new('user32', 'SetClipboardData', 'ii', 'i')
SetWindowPos = Win32API.new('user32', 'SetWindowPos', 'iiiiiii', 'i')
ShowCursor = Win32API.new('user32', 'ShowCursor','i', 'i')
Shutdown = Win32API.new('ws2_32', 'shutdown', 'pl', 'l')
Socket = Win32API.new('ws2_32', 'socket', 'lll', 'l')
ToUnicode = Win32API.new('user32', 'ToUnicode', 'iippii', 'l')
WideCharToMultiByte = Win32API.new('kernel32', 'WideCharToMultiByte', 'iipipipp', 'i')
#--------------------------------------------------------------------------
# * 360 Game Pad WIN32API's
#--------------------------------------------------------------------------
xinput = ->(dll){ return dll, Win32API.new(dll, 'XInputGetState', 'ip', 'i')}
xdll, XInputGetState = xinput.('xinput1_3') rescue
xinput.('xinput1_2') rescue
xinput.('xinput1_1') rescue
xinput.('xinput8_1_0') rescue
[nil, nil]
XInputSetState = Win32API.new(xdll, 'XInputSetState', 'ip', 'i') if xdll
tmpbuff = [].pack('x256')
GetPrivateProfileStringA.call("Game","Library","",tmpbuff, 256, './Game.ini')
RGSSDLL = File.expand_path(tmpbuff.delete!("\x00"))
end
#--------------------------------------------------------------------------
# * Ruby Extension
#--------------------------------------------------------------------------
#==============================================================================
# ** Object
#------------------------------------------------------------------------------
# The superclass of all classes. Defines the general behavior of objects.
#==============================================================================
class Object
#--------------------------------------------------------------------------
# * Eigenclass
#--------------------------------------------------------------------------
class << self
#--------------------------------------------------------------------------
# * Dynamic definition
#--------------------------------------------------------------------------
def dynlink(name, &block); send(:define_method, name, block); end
private :dynlink
#--------------------------------------------------------------------------
# * Define method as delegator instance method with an optional alias name
# * m_alias. Method calls to alias will be delegated to accessor.method.
#--------------------------------------------------------------------------
def delegate(obj, method, m_alias = method)
dynlink(m_alias) do |*args|
instance = (obj[0] == "@") ?
instance_variable_get(obj) :
send(obj)
instance.send(method, *args)
end
end
#--------------------------------------------------------------------------
# * Delegate attr_accessor
#--------------------------------------------------------------------------
def delegate_accessor(obj, field)
delegate(obj, field)
delegate(obj, "#{field}=")
end
#--------------------------------------------------------------------------
# * Import Callable as a method
#--------------------------------------------------------------------------
def externalize(obj, m_alias)
dynlink(m_alias) do |*args|
obj.call(*args)
end
end
#--------------------------------------------------------------------------
# * Calls another method when the instance variable is changing
#--------------------------------------------------------------------------
def attr_accessor_callback(to_call, m)
define_method("#{m}=") do |v|
if instance_variable_get("@#{m}") != v
instance_variable_set("@#{m}", v)
method(to_call).call
end
end
end
end # End of Object.self
#--------------------------------------------------------------------------
# * Identity (Blank operation)
#--------------------------------------------------------------------------
def identity
return self
end
#--------------------------------------------------------------------------
# * Returns an Hash of instance variables :name => value
#--------------------------------------------------------------------------
def attr_values
values = self.instance_variables.collect do |key|
[key, self.instance_variable_get(key)]
end
return Hash[values]
end
#--------------------------------------------------------------------------
# * Create buffer (for Win32API)
#--------------------------------------------------------------------------
def buffer(size = 4)
"\0" * size
end
#--------------------------------------------------------------------------
# * Check type: bool
#--------------------------------------------------------------------------
def boolean?
return false
end
#--------------------------------------------------------------------------
# * Convert to Bool
#--------------------------------------------------------------------------
def to_bool
true
end
#--------------------------------------------------------------------------
# * Deep clone (to be improved)
#--------------------------------------------------------------------------
def custom_deep_clone
value = self.clone
return Marshal.load(Marshal.dump(value))
end
#--------------------------------------------------------------------------
# * Setup transition for the given method
#--------------------------------------------------------------------------
def set_transition(method, target, duration, easing = :InLinear)
m = method
return method("#{m}=")[target] if duration == 0
return if (base = method(m).call).nil? || base == target
instance_variable_set("@trans_b_#{m}", base)
instance_variable_set("@trans_c_#{m}", target - base)
instance_variable_set("@trans_f_#{m}", easing)
instance_variable_set("@trans_d_#{m}", duration)
instance_variable_set("@trans_t_#{m}", 1.0)
end
#--------------------------------------------------------------------------
# * Update transition for the given method
#--------------------------------------------------------------------------
def update_transition(method)
m = method
return if (d = instance_variable_get("@trans_d_#{m}")).nil? || d==0
return if (t = instance_variable_get("@trans_t_#{m}")) > d
b = instance_variable_get("@trans_b_#{m}")
c = instance_variable_get("@trans_c_#{m}")
f = instance_variable_get("@trans_f_#{m}")
f = Easing::FUNCTIONS[f]
v = t==0 ? b : t==d ? b + c : b + c*f[t/d]
instance_variable_set("@trans_t_#{m}", t + 1)
method("#{m}=")[v]
end
end # End of Object
#==============================================================================
# ** Color
#------------------------------------------------------------------------------
# The RGBA color class. Each component is handled with a floating-point
# value (Float).
#==============================================================================
class Color
def to_hex
r = ((self.red / 255.0) * 15.0).to_i.to_s(16)
g = ((self.green / 255.0) * 15.0).to_i.to_s(16)
b = ((self.blue / 255.0) * 15.0).to_i.to_s(16)
[r, g, b].join.to_i(16)
end
end
#==============================================================================
# ** Exception
#------------------------------------------------------------------------------
# Try to retreive last exception
#==============================================================================
class Exception
class << self
attr_accessor :last_noMethod
end
end
#==============================================================================
# ** NilClass
#------------------------------------------------------------------------------
# The Nil class. nil is the only instance of the NilClass class.
# nil, like false, denotes a FALSE condition, while all other objects are TRUE.
#==============================================================================
class NilClass
#--------------------------------------------------------------------------
# * Convert to Bool
#--------------------------------------------------------------------------
def to_bool
false
end
end
#==============================================================================
# ** FalseClass
#------------------------------------------------------------------------------
# The false class. false is the only instance of the FalseClass class.
# false, like nil, denotes a FALSE condition, while all other objects are TRUE.
#==============================================================================
class FalseClass
#--------------------------------------------------------------------------
# * Convert to Bool
#--------------------------------------------------------------------------
alias_method :to_bool, :identity
#--------------------------------------------------------------------------
# * Check type: bool
#--------------------------------------------------------------------------
def boolean?
true
end
#--------------------------------------------------------------------------
# * Cast to integer
#--------------------------------------------------------------------------
def to_i
0
end
end
#==============================================================================
# ** TrueClass
#------------------------------------------------------------------------------
# The true class. true is the only instance of the TrueClass class.
# true is a representative object that denotes a TRUE condition.
#==============================================================================
class TrueClass
#--------------------------------------------------------------------------
# * Convert to Bool
#--------------------------------------------------------------------------
alias_method :to_bool, :identity
#--------------------------------------------------------------------------
# * Check type: bool
#--------------------------------------------------------------------------
def boolean?
true
end
#--------------------------------------------------------------------------
# * Cast to integer
#--------------------------------------------------------------------------
def to_i
1
end
end
#==============================================================================
# ** Module
#------------------------------------------------------------------------------
# Link documentation
#==============================================================================
class Module
#--------------------------------------------------------------------------
# * Documentation linking
#--------------------------------------------------------------------------
include RME::Doc
extend RME::Doc
end
#==============================================================================
# ** Fixnum
#------------------------------------------------------------------------------
# Integer representation
#==============================================================================
class Fixnum
#--------------------------------------------------------------------------
# * Number const
#--------------------------------------------------------------------------
NUMBER = [
:zero,
:one,
:two,
:three,
:four,
:five,
:six,
:seven,
:eight,
:nine
]
#--------------------------------------------------------------------------
# * Cast integer to digit
#--------------------------------------------------------------------------
def to_digit
return NUMBER[self] if self <= 9 && self >= 0
NUMBER[0]
end
end
#==============================================================================
# ** Array
#------------------------------------------------------------------------------
# Arrays are ordered, integer-indexed collections of any object.
#==============================================================================
class Array
#--------------------------------------------------------------------------
# * Exclude data
#--------------------------------------------------------------------------
def not(*ids, &block)
self.delete_if{|e| ids.include?(e)}.delete_if(&block)
end
#--------------------------------------------------------------------------
# * Extract Point object from array "[x,y]" or "[Point]"
#--------------------------------------------------------------------------
def to_point
if length == 2
p = Point.new(*self)
elsif length == 1
p = self[0].clone
end
return p
end
#--------------------------------------------------------------------------
# * Extract x, y from array "[x,y]" or "[Point]"
#--------------------------------------------------------------------------
def to_xy
a = self
a = [a[0].x, a[0].y] if length == 1
return *a
end
end
#==============================================================================
# ** Numeric
#------------------------------------------------------------------------------
# Managing digits separately
#==============================================================================
class Numeric
#--------------------------------------------------------------------------
# * handle isoler
#--------------------------------------------------------------------------
def isole_int(i); (self%(10**i))/(10**(i-1)).to_i; end
#--------------------------------------------------------------------------
# * Int isoler
#--------------------------------------------------------------------------
[:units, :tens, :hundreds, :thousands,
:tens_thousands, :hundreds_thousands,
:millions, :tens_millions,
:hundreds_millions ].each.with_index{|m, i|define_method(m){isole_int(i+1)}}
#--------------------------------------------------------------------------
# * alias
#--------------------------------------------------------------------------
alias :unites :units
alias :dizaines :tens
alias :centaines :hundreds
alias :milliers :thousands
alias :dizaines_milliers :tens_thousands
alias :centaines_milliers :hundreds_thousands
alias :dizaines_millions :tens_millions
alias :centaines_millions :hundreds_millions
#--------------------------------------------------------------------------
# * Int Bound value
#--------------------------------------------------------------------------
def bound(min, max)
begin
b_min = min - ((min-self) & (min-self)>>31)
b_min + ((max-b_min) & (max-b_min)>>31)
rescue
fbound(min, max)
end
end
#--------------------------------------------------------------------------
# * Float Bound value
#--------------------------------------------------------------------------
def fbound(min, max)
[[min, self].max, max].min
end
end
#==============================================================================
# ** String
#------------------------------------------------------------------------------
# String char extension
#==============================================================================
class String
#--------------------------------------------------------------------------
# * Import
#--------------------------------------------------------------------------
externalize Externlib::WideCharToMultiByte, :to_multibyte
externalize Externlib::MultiByteToWideChar, :to_widechar
ASCII8BIT = 0
UTF8 = 65001
#--------------------------------------------------------------------------
# * Convert
#--------------------------------------------------------------------------
def convert_format(from, to)
size = to_widechar(from, 0, self, -1, nil, 0)
buff = [].pack("x#{size*2}")
to_widechar(from, 0, self, -1, buff, buff.size/2)
size = to_multibyte(to, 0, buff, -1, nil, 0, nil, nil)
sbuf = [].pack("x#{size}")
to_multibyte(to, 0, buff, -1, sbuf, sbuf.size, nil, nil)
sbuf.delete!("\000") if to == 65001
sbuf.delete!("\x00") if to == 0
sbuf
end
#--------------------------------------------------------------------------
# * return self in ASCII-8BIT
#--------------------------------------------------------------------------
def to_ascii; convert_format(UTF8, ASCII8BIT);end
#--------------------------------------------------------------------------
# * convert self in ASCII-8BIT
#--------------------------------------------------------------------------
def to_ascii!; replace(to_ascii); end
#--------------------------------------------------------------------------
# * return self to UTF8
#--------------------------------------------------------------------------
def to_utf8; convert_format(ASCII8BIT, UTF8); end
#--------------------------------------------------------------------------
# * convert self in UTF8
#--------------------------------------------------------------------------
def to_utf8!; replace(to_utf8); end
#--------------------------------------------------------------------------
# * Extract number
#--------------------------------------------------------------------------
def extract_numbers
scan(/-*\d+/).collect{|n|n.to_i}
end
#--------------------------------------------------------------------------
# * Calcul the Damerau Levenshtein 's Distance
#--------------------------------------------------------------------------
def damerau_levenshtein(other)
n, m = self.length, other.length
return m if n == 0
return n if m == 0
matrix = Array.new(n+1) do |i|
Array.new(m+1) do |j|
if i == 0 then j
elsif j == 0 then i
else 0 end
end
end
(1..n).each do |i|
(1..m).each do |j|
cost = (self[i] == other[j]) ? 0 : 1
delete = matrix[i-1][j] + 1
insert = matrix[i][j-1] + 1
substitution = matrix[i-1][j-1] + cost
matrix[i][j] = [delete, insert, substitution].min
if (i > 1) && (j > 1) && (self[i] == other[j-1]) && (self[i-1] == other[j])
matrix[i][j] = [matrix[i][j], matrix[i-2][j-2] + cost].min
end
end
end
return matrix.last.last
end
#--------------------------------------------------------------------------
# * Autocomplete
#--------------------------------------------------------------------------
def auto_complete(words)
words.sort_by do |wordA|
placeholder = wordA[0...length]
(placeholder == self) ? 0 : damerau_levenshtein(placeholder)+1
end
end
#--------------------------------------------------------------------------
# * Delete at
#--------------------------------------------------------------------------
def insert_at(pos, char)
a = slice(0, pos) || ""
b = slice(pos, length) || ""
a + char + b
end
#--------------------------------------------------------------------------
# * Delete at
#--------------------------------------------------------------------------
def delete_at(pos)
a = slice(0, pos) || ""
b = slice(pos+1, length) || ""
a + b
end
#--------------------------------------------------------------------------
# * Delete between
#--------------------------------------------------------------------------
def delete_between(a, b)
a = slice(0, a) || ""
b = slice(b, length) || ""
a + b
end
#--------------------------------------------------------------------------
# * Split each
#--------------------------------------------------------------------------
def split_each(len)
self.scan(Regexp.new(".{1,#{len}}"))
end
#--------------------------------------------------------------------------
# * Format a string
#--------------------------------------------------------------------------
def stretch(len_line)
n_s = [""]
i = 0
self.split(' ').each do |l|
if (n_s[i].length + l.length) > len_line
if l.length > len_line
n_l = l.scan(/.{0,#{len_line-1}}/)
n_l[0..-3].collect!{|e|e<<'-'}
n_s += n_l
i += n_l.length - 1
next
else
i += 1
end
end
n_s[i] ||= ""
n_s[i] += ' ' << l
end
n_s = n_s.join('\n').split('\n')
n_s.compact.collect(&:strip)
end
#--------------------------------------------------------------------------
# * AST Extract_tokens
#--------------------------------------------------------------------------
def extract_tokens(position=nil)
position ||= length - 1
substring = self[0..position].gsub(/\s+|;|\(|\)|,|\{|\}|\[|\]/, "\0")
substring.split(/(\0)/).map do |elt|
(elt.empty? || elt =~ /^\d+/ || elt == "\0") ? false : elt
end
end
#--------------------------------------------------------------------------
# * AST Extract_tokens
#--------------------------------------------------------------------------
def ast_extract_tokens(at_point = -1)
substring = self[0, at_point]
reg = [
'\(\+?\d+\.\d*\)', '\(\+?\d+\.\d*\)',
'\+?\d+', '\-?\d+',
'\w+\[.*\]',
'\:\w+', '\:\"\w+\"', '\:\'\w+\'',
'\'[^\']*\'', '"[\s*\w*]*"',
'\!\w+',
'\.', '::', '\$\w+', '\w+', '\s*'
]
scan(Regexp.new(reg.join("|"))).select {|e| not e.empty?}
end
#--------------------------------------------------------------------------
# * AST Complete at point
# Work in progress /!\ Not finished !
#--------------------------------------------------------------------------
def ast_complete_at_point(i)
tokens = ast_extract_tokens(i-1)
token = tokens[-1]
p tokens
return [nil, []] unless token
if tokens[-2] == '.' && tokens[-3]
# Standard receiver case
begin
raw_receiver = tokens.reverse.take_while.with_index do |v, i|
(i%2 != 0) ? v == '.' : true
end.reverse.join('')
p raw_receiver
receiver = eval(raw_receiver) # NEED A RECURSION !
container = receiver.methods
rescue Exception => exc
p exc
return [nil, []]
end
elsif tokens[-2] == '::' && tokens[-3]
# Static or constant context
receiver = tokens[-3]
else
return [token, tokens[-2].methods[0..7]] if tokens[-2] && token == '.'
# atomic keyword
gv = global_variables
cm = Command.singleton_methods
co = Object.constants
pu = Kernel.methods
container = (gv + cm + co + pu).uniq
end
candidates = container.map do |meth|
[token.damerau_levenshtein(meth[0..(token.length-1)]), meth]
end.select {|r| r[0] < 2}.sort_by {|r| r[0]}.map {|e| e[1]}
return (token.length < 4 && candidates.length > 30) ?
[token, candidates[0..7]] : [token, candidates]
end
#--------------------------------------------------------------------------
# * Complete at point
#--------------------------------------------------------------------------
def complete_at_point(i)
tokens = extract_tokens(i-1).map {|s| (!s) ? [s] : s.split(/\s/)}.flatten
token = tokens[-1]
return [] unless token
container = Command.singleton_methods
candidates = token.auto_complete(container)
k = candidates.select { |e| token.damerau_levenshtein(e[0..(token.length-1)]) < 3 }
return k[0..7].unshift(token)
end
end
#==============================================================================
# ** Point
#------------------------------------------------------------------------------
# Point(x, y) representation
#==============================================================================
class Point
attr_reader :x, :y
attr_accessor :rect
#--------------------------------------------------------------------------
# * Initialize
#--------------------------------------------------------------------------
def initialize(x, y, rect = nil)
@rect = rect
set(x, y, rect)
end
#--------------------------------------------------------------------------
# * Set coords
#--------------------------------------------------------------------------
def set(x, y, rect = nil)
@rect ||= rect
self.x = x
self.y = y
end
#--------------------------------------------------------------------------
# * x accessor
#--------------------------------------------------------------------------
def x=(new_x)
new_x = new_x.bound(@rect.x, @rect.x + @rect.width) if @rect
@x = new_x
end
#--------------------------------------------------------------------------
# * y accessor
#--------------------------------------------------------------------------
def y=(new_y)
new_y = new_y.bound(@rect.y, @rect.y + @rect.height) if @rect
@y = new_y
end
#--------------------------------------------------------------------------
# * Translation after a rotation from a point
#--------------------------------------------------------------------------
def rotate(angle, *p)
return if angle == 0
ox, oy = p.to_xy
angle *= Math::PI/180
c, s = Math.cos(angle), Math.sin(angle)
x, y = self.x, self.y
x, y = x-ox, y-oy
x, y = (x*c+y*s), (-x*s+y*c)