Debian Codegraph @

src/core/ulib_std.cpp

raw symbols SCIP
1 /*----------------------------------------------------------------------------
2 ChucK Strongly-timed Audio Programming Language
3 Compiler, Virtual Machine, and Synthesis Engine
4
5 Copyright (c) 2003 Ge Wang and Perry R. Cook. All rights reserved.
6 http://chuck.stanford.edu/
7 http://chuck.cs.princeton.edu/
8
9 This program is free software; you can redistribute it and/or modify
10 it under the dual-license terms of EITHER the MIT License OR the GNU
11 General Public License (the latter as published by the Free Software
12 Foundation; either version 2 of the License or, at your option, any
13 later version).
14
15 This program is distributed in the hope that it will be useful and/or
16 interesting, but WITHOUT ANY WARRANTY; without even the implied warranty
17 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 MIT Licence and/or the GNU General Public License for details.
19
20 You should have received a copy of the MIT License and the GNU General
21 Public License (GPL) along with this program; a copy of the GPL can also
22 be obtained by writing to the Free Software Foundation, Inc., 59 Temple
23 Place, Suite 330, Boston, MA 02111-1307 U.S.A.
24 -----------------------------------------------------------------------------*/
25
26 //-----------------------------------------------------------------------------
27 // file: ulib_std.cpp
28 // desc: standard class library
29 //
30 // author: Ge Wang ([email protected] | [email protected])
31 // date: Spring 2004
32 //-----------------------------------------------------------------------------
33 #include "ulib_std.h"
34 #include "util_buffers.h"
35 #include "util_math.h"
36 #include "util_string.h"
37 #include "util_platforms.h"
38
39 #ifndef __DISABLE_PROMPTER__
40 #include "util_console.h"
41 #endif
42
43 #ifndef __DISABLE_THREADS__
44 #include "util_thread.h"
45 #endif
46
47 #include "chuck.h"
48 #include "chuck_type.h"
49 #include "chuck_compile.h"
50 #include "chuck_instr.h"
51
52 #include <stdlib.h>
53 #include <time.h>
54 #include <math.h>
55 #include <cstring>
56
57 #ifdef __PLATFORM_WINDOWS__
58 #ifndef __CHUNREAL_ENGINE__
59 #include <windows.h>
60 #else
61 // 1.5.0.0 (ge) | #chunreal
62 // unreal engine on windows disallows including windows.h
63 #include "Windows/MinWindows.h"
64 #endif // #ifndef __CHUNREAL_ENGINE__
65 int setenv( const char *n, const char *v, int i )
66 {
67 #ifndef __CHUNREAL_ENGINE__
68 return !SetEnvironmentVariable(n, v);
69 #else
70 // #chunreal explicitly call ASCII version
71 return !SetEnvironmentVariableA(n, v);
72 #endif
73 }
74 #else
75 #include <unistd.h>
76 #endif // #ifdef __PLATFORM_WINDOWS__
77
78 // for ConsoleInput and StringTokenizer
79 #include <sstream>
80 #include <iostream>
81 #ifndef __DISABLE_THREADS__
82 #include "util_thread.h"
83 #endif
84 using namespace std;
85
86
87 #ifndef __DISABLE_KBHIT__
88 // KBHit
89 CK_DLL_CTOR( KBHit_ctor );
90 CK_DLL_DTOR( KBHit_dtor );
91 CK_DLL_MFUN( KBHit_on );
92 CK_DLL_MFUN( KBHit_off );
93 CK_DLL_MFUN( KBHit_state );
94 CK_DLL_MFUN( KBHit_hit );
95 CK_DLL_MFUN( KBHit_more );
96 CK_DLL_MFUN( KBHit_getchar );
97 CK_DLL_MFUN( KBHit_can_wait );
98
99 static t_CKUINT KBHit_offset_data = 0;
100 #endif // __DISABLE_KBHIT__
101
102 #ifndef __DISABLE_PROMPTER__
103 // Skot functions
104 CK_DLL_CTOR( Skot_ctor );
105 CK_DLL_DTOR( Skot_dtor );
106 CK_DLL_MFUN( Skot_prompt );
107 CK_DLL_MFUN( Skot_prompt2 );
108 CK_DLL_MFUN( Skot_more );
109 CK_DLL_MFUN( Skot_getLine );
110 CK_DLL_MFUN( Skot_can_wait );
111
112 static t_CKUINT Skot_offset_data = 0;
113 #endif // __DISABLE_PROMPTER__
114
115 // StrTok functions
116 CK_DLL_CTOR( StrTok_ctor );
117 CK_DLL_CTOR( StrTok_ctor_line );
118 CK_DLL_CTOR( StrTok_ctor_line_delims );
119 CK_DLL_DTOR( StrTok_dtor );
120 CK_DLL_MFUN( StrTok_set );
121 CK_DLL_MFUN( StrTok_reset );
122 CK_DLL_MFUN( StrTok_more );
123 CK_DLL_MFUN( StrTok_next );
124 CK_DLL_MFUN( StrTok_next2 );
125 CK_DLL_MFUN( StrTok_get );
126 CK_DLL_MFUN( StrTok_get2 );
127 CK_DLL_MFUN( StrTok_size );
128 CK_DLL_MFUN( StrTok_get_delims );
129 CK_DLL_MFUN( StrTok_set_delims );
130
131 static t_CKUINT StrTok_offset_data = 0;
132
133 #ifdef AJAY
134
135 #include <fstream>
136
137 // VCR functions
138 CK_DLL_CTOR( VCR_ctor );
139 CK_DLL_MFUN( VCR_load );
140 CK_DLL_MFUN( VCR_reset );
141 CK_DLL_MFUN( VCR_seek );
142 CK_DLL_MFUN( VCR_more );
143 CK_DLL_MFUN( VCR_curr );
144 CK_DLL_MFUN( VCR_next );
145 CK_DLL_MFUN( VCR_pos );
146 CK_DLL_MFUN( VCR_size );
147 CK_DLL_MFUN( VCR_name );
148
149 static t_CKUINT VCR_offset_data = 0;
150
151 // Cereal functions
152 CK_DLL_CTOR( Cereal_ctor );
153 CK_DLL_MFUN( Cereal_open );
154 CK_DLL_MFUN( Cereal_close );
155 CK_DLL_MFUN( Cereal_send );
156 CK_DLL_MFUN( Cereal_recv );
157 CK_DLL_MFUN( Cereal_more );
158
159 static t_CKUINT Cereal_offset_data = 0;
160
161 #endif
162
163
164 // variable to random max
165 static t_CKINT g_randMax = CK_RANDOM_MAX;
166
167
168 //-----------------------------------------------------------------------------
169 // name: libstd_query()
170 // desc: query entry point
171 //-----------------------------------------------------------------------------
172 DLL_QUERY libstd_query( Chuck_DL_Query * QUERY )
173 {
174 // get global
175 Chuck_Env * env = QUERY->env();
176 // set name
177 QUERY->setname( QUERY, "Std" );
178
179 // register deprecate
180 type_engine_register_deprecate( env, "std", "Std" );
181
182 // begin class
183 QUERY->begin_class( QUERY, "Std", "Object" );
184 QUERY->doc_class( QUERY, "a standard library in ChucK, which includes utility functions for random number generation, unit conversions, and absolute value." );
185
186 // add abs
187 QUERY->add_sfun( QUERY, abs_impl, "int", "abs" );
188 QUERY->add_arg( QUERY, "int", "value" );
189 QUERY->doc_func( QUERY, "Return absolute value of integer." );
190
191 // add fabs
192 QUERY->add_sfun( QUERY, fabs_impl, "float", "fabs" );
193 QUERY->add_arg( QUERY, "float", "value" );
194 QUERY->doc_func( QUERY, "Return absolute value of float." );
195
196 // add rand
197 QUERY->add_sfun( QUERY, rand_impl, "int", "rand"); //! return int between 0 and max
198 QUERY->doc_func( QUERY, "generate a random integer between 0 and Std.RAND_MAX. (NOTE: this is deprecated; use Math.random())." );
199
200 // add rand2
201 QUERY->add_sfun( QUERY, rand2_impl, "int", "rand2" ); //! integer between [min,max]
202 QUERY->add_arg( QUERY, "int", "min" );
203 QUERY->add_arg( QUERY, "int", "max" );
204 QUERY->doc_func( QUERY, "Generate a random integer in range [min, max]. (NOTE: this is deprecated; use Math.random2())." );
205
206 // add rand
207 QUERY->add_sfun( QUERY, randf_impl, "float", "randf" ); //! rand between -1.0,1.0
208 QUERY->doc_func( QUERY, "Generate random floating point number in the range [-1, 1]. (Note: this is deprecated; use Math.randomf())" );
209
210 // add rand2
211 QUERY->add_sfun( QUERY, rand2f_impl, "float", "rand2f" ); //! rand between min and max
212 QUERY->add_arg( QUERY, "float", "min" );
213 QUERY->add_arg( QUERY, "float", "max" );
214 QUERY->doc_func( QUERY, "Generate random floating point number in the range [min, max]. (NOTE: this is deprecated; use Math.random2f())" );
215
216 // add srand
217 QUERY->add_sfun( QUERY, srand_impl, "void", "srand" );
218 QUERY->add_arg( QUERY, "int", "seed" );
219 QUERY->doc_func( QUERY, "seed the random number generator. Different seeds will likely generate different sequences of random numbers even if the seeds are close together; alternatively, a sequence of random numbers can be repeated by setting the same seed. (NOTE: this is deprecated; use Math.srandom())" );
220
221 // random max
222 QUERY->add_svar( QUERY, "int", "RAND_MAX", TRUE, &g_randMax );
223 QUERY->doc_var( QUERY, "The largest possible value returned by Std.rand()." );
224
225 // add sgn
226 QUERY->add_sfun( QUERY, sgn_impl, "float", "sgn" ); //! return sign of value (-1, 0, 1)
227 QUERY->add_arg( QUERY, "float", "value" );
228 QUERY->doc_func( QUERY, "get sign of value as -1 (negative), 0, or 1 (positive)." );
229
230 // add system
231 //! see \example std.ck
232 QUERY->add_sfun( QUERY, system_impl, "int", "system" ); //! issue system command
233 QUERY->add_arg( QUERY, "string", "cmd" );
234 QUERY->doc_func( QUERY, "pass a command to be executed in the shell (requires --caution-to-the-wind flag to be set)." );
235
236 // add atoi
237 QUERY->add_sfun( QUERY, atoi_impl, "int", "atoi" ); //! string to integer
238 QUERY->add_arg( QUERY, "string", "value" );
239 QUERY->doc_func( QUERY, "convert ascii (string) to integer (int)." );
240
241 // add atof
242 QUERY->add_sfun( QUERY, atof_impl, "float", "atof" ); //! string to float
243 QUERY->add_arg( QUERY, "string", "value" );
244 QUERY->doc_func( QUERY, "converts ascii (string) to floating point value (float)." );
245
246 // add itoa
247 QUERY->add_sfun( QUERY, itoa_impl, "string", "itoa" ); //! int to string
248 QUERY->add_arg( QUERY, "int", "i" );
249 QUERY->doc_func( QUERY, "converts integer (int) to ascii (string)." );
250
251 // add ftoa
252 QUERY->add_sfun( QUERY, ftoa_impl, "string", "ftoa" ); //! float to string
253 QUERY->add_arg( QUERY, "float", "f" );
254 QUERY->add_arg( QUERY, "int", "precision" );
255 QUERY->doc_func( QUERY, "converts floating point value (float) to ascii (string) with specified precision (number of decimal digits)." );
256
257 // add ftoi
258 QUERY->add_sfun( QUERY, ftoi_impl, "int", "ftoi" ); //! float to int
259 QUERY->add_arg( QUERY, "float", "f" );
260 QUERY->doc_func( QUERY, "convert float to integer." );
261
262 // add getenv
263 QUERY->add_sfun( QUERY, getenv_impl, "string", "getenv" ); //! fetch environment variable
264 QUERY->add_arg( QUERY, "string", "key" );
265 QUERY->doc_func( QUERY, "get the value of an environment variable (e.g., PATH)." );
266
267 QUERY->add_sfun( QUERY, getenv2_impl, "string", "getenv" );//! fetch environment variable with default
268 QUERY->add_arg( QUERY, "string", "key" );
269 QUERY->add_arg( QUERY, "string", "default" );
270 QUERY->doc_func( QUERY, "get the value of an environment variable, returning the provided default if unset." );
271
272 // add setenv
273 QUERY->add_sfun( QUERY, setenv_impl, "int", "setenv" ); //! set environment variable
274 QUERY->add_arg( QUERY, "string", "key" );
275 QUERY->add_arg( QUERY, "string", "value" );
276 QUERY->doc_func( QUERY, "set the value of environment variable named 'key'" );
277
278 // add mtof
279 //! see \example mand-o-matic.ck
280 QUERY->add_sfun( QUERY, mtof_impl, "float", "mtof" ); //! midi note to frequency
281 QUERY->add_arg( QUERY, "float", "value" );
282 QUERY->doc_func( QUERY, "Convert a MIDI note number to frequency (Hz). Note the input value is of type float (supports fractional note number). For reference, MIDI note number 60 is Middle C; each whole number is one semitone." );
283
284 // add ftom
285 QUERY->add_sfun( QUERY, ftom_impl, "float", "ftom" ); //! frequency to midi note
286 QUERY->add_arg( QUERY, "float", "value" );
287 QUERY->doc_func( QUERY, "Convert frequency (Hz) to MIDI note number space." );
288
289 // add powtodb
290 QUERY->add_sfun( QUERY, powtodb_impl, "float", "powtodb" ); //! linear power to decibel
291 QUERY->add_arg( QUERY, "float", "value" );
292 QUERY->doc_func( QUERY, "Convert signal power ratio to decibels (dB)." );
293
294 // add rmstodb
295 QUERY->add_sfun( QUERY, rmstodb_impl, "float", "rmstodb" ); //! rms to decibel
296 QUERY->add_arg( QUERY, "float", "value" );
297 QUERY->doc_func( QUERY, "Convert rms to decibels (dB)." );
298
299 // add dbtopow
300 QUERY->add_sfun( QUERY, dbtopow_impl, "float", "dbtopow" ); //! decibel to linear
301 QUERY->add_arg( QUERY, "float", "value" );
302 QUERY->doc_func( QUERY, "Convert decibels (dB) to signal power ratio." );
303
304 // add dbtorms
305 QUERY->add_sfun( QUERY, dbtorms_impl, "float", "dbtorms" ); //! decibel to rms
306 QUERY->add_arg( QUERY, "float", "value" );
307 QUERY->doc_func( QUERY, "Convert decibels (dB) to rms." );
308
309 // add dbtolin
310 QUERY->add_sfun( QUERY, dbtolin_impl, "float", "dbtolin" ); //! decibel to linear
311 QUERY->add_arg( QUERY, "float", "value" );
312 QUERY->doc_func( QUERY, "Convert decibels (dB) to linear amplitude." );
313
314 // add lintodb
315 QUERY->add_sfun( QUERY, lintodb_impl, "float", "lintodb" ); //! linear to decibel
316 QUERY->add_arg( QUERY, "float", "value" );
317 QUERY->doc_func( QUERY, "Convert linear amplitude to decibels (dB).");
318
319 // add clamp
320 QUERY->add_sfun( QUERY, clamp_impl, "int", "clamp" ); //! clamp to range (int)
321 QUERY->add_arg( QUERY, "int", "value" );
322 QUERY->add_arg( QUERY, "int", "min" );
323 QUERY->add_arg( QUERY, "int", "max" );
324 QUERY->doc_func( QUERY, "Clamp integer to range [min, max]." );
325
326 // add clampf
327 QUERY->add_sfun( QUERY, clampf_impl, "float", "clampf" ); //! clamp to range (float)
328 QUERY->add_arg( QUERY, "float", "value" );
329 QUERY->add_arg( QUERY, "float", "min" );
330 QUERY->add_arg( QUERY, "float", "max" );
331 QUERY->doc_func( QUERY, "Clamp float to range [min, max]." );
332
333 // add scalef
334 QUERY->add_sfun( QUERY, scalef_impl, "float", "scalef" ); //! scale from source range to dest range (float)
335 QUERY->add_arg( QUERY, "float", "value" );
336 QUERY->add_arg( QUERY, "float", "srcmin" );
337 QUERY->add_arg( QUERY, "float", "srcmax" );
338 QUERY->add_arg( QUERY, "float", "dstmin" );
339 QUERY->add_arg( QUERY, "float", "dstmax" );
340 QUERY->doc_func( QUERY, "Scale a float from source range to destination range." );
341
342 // add range functions | 1.5.1.1 (nshaheed)
343 QUERY->add_sfun(QUERY, range1_impl, "int[]", "range"); //! fetch environment variable
344 QUERY->add_arg(QUERY, "int", "stop");
345 QUERY->doc_func(QUERY, "Return array containing the range [0,stop).");
346
347 QUERY->add_sfun(QUERY, range2_impl, "int[]", "range"); //! fetch environment variable
348 QUERY->add_arg(QUERY, "int", "start");
349 QUERY->add_arg(QUERY, "int", "stop");
350 QUERY->doc_func(QUERY, "Return array containing the range [start,stop).");
351
352 QUERY->add_sfun(QUERY, range3_impl, "int[]", "range"); //! fetch environment variable
353 QUERY->add_arg(QUERY, "int", "start");
354 QUERY->add_arg(QUERY, "int", "stop");
355 QUERY->add_arg(QUERY, "int", "step");
356 QUERY->doc_func(QUERY, "Return array containing values from start up to (but not including) stop, hopping by step.");
357
358 // finish class
359 QUERY->end_class( QUERY );
360
361 // seed rand()
362 // (NOTE: ck_srandom(time(NULL)) is invoked in ulib_math.cpp)
363 // srand( (unsigned)time( NULL ) );
364
365 Chuck_DL_Func * func = NULL;
366
367 #ifndef __DISABLE_KBHIT__
368 // doc string
369 string doc = "KBHit (terminal only) is a simple mechanism for capturing keyboard input; for a more flexible mechanism, see HID. (On Linux, KBHit does not require granting device permissions; it works out of the box.)";
370
371 // begin class (KBHit)
372 if( !type_engine_import_class_begin( env, "KBHit", "Event",
373 env->global(), KBHit_ctor,
374 KBHit_dtor, doc.c_str() ) )
375 return FALSE;
376
377 // add examples
378 if( !type_engine_import_add_ex( env, "hid/kbhit/kbhit.ck" ) ) goto error;
379 if( !type_engine_import_add_ex( env, "hid/kbhit/kbhit2.ck" ) ) goto error;
380 if( !type_engine_import_add_ex( env, "hid/kbhit/clix.ck" ) ) goto error;
381 if( !type_engine_import_add_ex( env, "hid/kbhit/clix2.ck" ) ) goto error;
382 if( !type_engine_import_add_ex( env, "hid/kbhit/clix3.ck" ) ) goto error;
383
384 // add member variable
385 KBHit_offset_data = type_engine_import_mvar( env, "int", "@KBHit_data", FALSE );
386 if( KBHit_offset_data == CK_INVALID_OFFSET ) goto error;
387
388 // add on()
389 func = make_new_mfun( "void", "on", KBHit_on );
390 func->doc = "Enable the KBHit.";
391 if( !type_engine_import_mfun( env, func ) ) goto error;
392
393 // add off()
394 func = make_new_mfun( "void", "off", KBHit_off );
395 func->doc = "Disable the KBHit.";
396 if( !type_engine_import_mfun( env, func ) ) goto error;
397
398 // add state()
399 func = make_new_mfun( "void", "state", KBHit_state );
400 func->doc = "Get whether the KBHit is currently enabled.";
401 if( !type_engine_import_mfun( env, func ) ) goto error;
402
403 // add hit()
404 func = make_new_mfun( "Event", "hit", KBHit_hit );
405 func->doc = "Return itself as an Event to wait on; this is largely unnecessary as the KBHit instance can be directly => to 'now'.";
406 if( !type_engine_import_mfun( env, func ) ) goto error;
407
408 // add more()
409 func = make_new_mfun( "int", "more", KBHit_more );
410 func->doc = "Return whether there are unprocessed KBHit events (e.g., if a user presses multiple keys at once).";
411 if( !type_engine_import_mfun( env, func ) ) goto error;
412
413 // add getchar()
414 func = make_new_mfun( "int", "getchar", KBHit_getchar );
415 func->doc = "Get the ASCII value of the last keyboard press.";
416 if( !type_engine_import_mfun( env, func ) ) goto error;
417
418 // add can_wait()
419 func = make_new_mfun( "int", "can_wait", KBHit_can_wait );
420 func->doc = "(internal) used by virtual machine for synthronization.";
421 if( !type_engine_import_mfun( env, func ) ) goto error;
422
423 // end class
424 type_engine_import_class_end( env );
425
426 // start it
427 KBHitManager::init();
428 #endif // __DISABLE_KBHIT__
429
430
431 // register deprecate
432 type_engine_register_deprecate( env, "Skot", "ConsoleInput" );
433
434 #ifndef __DISABLE_PROMPTER__
435 // begin class (Skot)
436 if( !type_engine_import_class_begin( env, "ConsoleInput", "Event",
437 env->global(), Skot_ctor, Skot_dtor,
438 "(Terminal only) a utility for prompting user input on the command line." ) )
439 return FALSE;
440
441 // add member variable
442 Skot_offset_data = type_engine_import_mvar( env, "int", "@Skot_data", FALSE );
443 if( Skot_offset_data == CK_INVALID_OFFSET ) goto error;
444
445 // add prompt()
446 func = make_new_mfun( "Event", "prompt", Skot_prompt );
447 func->doc = "Return an Event to wait on.";
448 if( !type_engine_import_mfun( env, func ) ) goto error;
449
450 // add prompt()
451 func = make_new_mfun( "Event", "prompt", Skot_prompt2 );
452 func->add_arg( "string", "what" );
453 func->doc = "Print a prompt text and return an Event to wait on.";
454 if( !type_engine_import_mfun( env, func ) ) goto error;
455
456 // add more()
457 func = make_new_mfun( "int", "more", Skot_more );
458 func->doc = "Return whether there is more input to read.";
459 if( !type_engine_import_mfun( env, func ) ) goto error;
460
461 // add getString()
462 func = make_new_mfun( "string", "getLine", Skot_getLine );
463 func->doc = "Return the next line of input as a string.";
464 if( !type_engine_import_mfun( env, func ) ) goto error;
465
466 // add can_wait()
467 func = make_new_mfun( "int", "can_wait", Skot_can_wait );
468 func->doc = "(internal) used by virtual machine for synthronization.";
469 if( !type_engine_import_mfun( env, func ) ) goto error;
470
471 // add examples
472 if( !type_engine_import_add_ex( env, "string/readline.ck" ) ) goto error;
473 if( !type_engine_import_add_ex( env, "ai/word2vec/word2vec-prompt.ck" ) ) goto error;
474 if( !type_engine_import_add_ex( env, "ai/word2vec/poem-ungenerate.ck" ) ) goto error;
475
476 // end class
477 type_engine_import_class_end( env );
478 #endif // __DISABLE_PROMPTER__
479
480
481 // register deprecate
482 type_engine_register_deprecate( env, "PRC", "StringTokenizer" );
483
484 // begin class (StrTok)
485 if( !type_engine_import_class_begin( env, "StringTokenizer", "Object",
486 env->global(), StrTok_ctor, StrTok_dtor,
487 "Break a string into tokens, using (by default) whitespace characters as delimiters. Use the overloaded constructors StringTokenizer(string line) or StringTokenizer( string line, string delims ) to initialize with specific line and delimiters." ) )
488 return FALSE;
489
490 // overload ctor( string line )
491 func = make_new_ctor( StrTok_ctor_line );
492 func->add_arg( "string", "line" );
493 func->doc = "construct a StringTokenizer with a string to tokenize; this will use the default whitespace delimiters.";
494 if ( !type_engine_import_ctor( env, func ) ) goto error;
495
496 // overload ctor( string line, string delims )
497 func = make_new_ctor( StrTok_ctor_line_delims );
498 func->add_arg( "string", "line" );
499 func->add_arg( "string", "delimiters" );
500 func->doc = "construct a StringTokenizer with a string to tokenize, as well as custom delimiters; if the latter is empty string, default whitespace characters will be used.";
501 if ( !type_engine_import_ctor( env, func ) ) goto error;
502
503 // add member variable
504 StrTok_offset_data = type_engine_import_mvar( env, "int", "@StrTok_data", FALSE );
505 if( StrTok_offset_data == CK_INVALID_OFFSET ) goto error;
506
507 // add set()
508 func = make_new_mfun( "void", "set", StrTok_set );
509 func->add_arg( "string", "line" );
510 func->doc = "Set the string to be tokenized.";
511 if( !type_engine_import_mfun( env, func ) ) goto error;
512
513 // add reset()
514 func = make_new_mfun( "void", "reset", StrTok_reset );
515 func->doc = "Reset token iteration back to the beginning of the set string.";
516 if( !type_engine_import_mfun( env, func ) ) goto error;
517
518 // add more()
519 func = make_new_mfun( "int", "more", StrTok_more );
520 func->doc = "Return true (1) if there are still more tokens, false (0) if no more tokens.";
521 if( !type_engine_import_mfun( env, func ) ) goto error;
522
523 // add next()
524 func = make_new_mfun( "string", "next", StrTok_next );
525 func->doc = "Return the next token string.";
526 if( !type_engine_import_mfun( env, func ) ) goto error;
527
528 // add get()
529 func = make_new_mfun( "string", "next", StrTok_next2 );
530 func->add_arg( "string", "out" );
531 func->doc = "Return the next token string. Additionally, write the token string to the 'out' string variable.";
532 if( !type_engine_import_mfun( env, func ) ) goto error;
533
534 // add get()
535 func = make_new_mfun( "string", "get", StrTok_get );
536 func->add_arg( "int", "index" );
537 func->doc = "Return the i-th token in the set string.";
538 if( !type_engine_import_mfun( env, func ) ) goto error;
539
540 // add get()
541 func = make_new_mfun( "string", "get", StrTok_get2 );
542 func->add_arg( "int", "index" );
543 func->add_arg( "string", "out" );
544 func->doc = "Return the i-th token in the set string. Additionally, write the token string to the `out` string variable.";
545 if( !type_engine_import_mfun( env, func ) ) goto error;
546
547 // add size()
548 func = make_new_mfun( "int", "size", StrTok_size );
549 func->doc = "Returns the number of token strings that the set string can be broken into.";
550 if( !type_engine_import_mfun( env, func ) ) goto error;
551
552 // (1.5.5.6) nshaheed add delimiter get and set
553 func = make_new_mfun( "string", "delims", StrTok_get_delims );
554 func->doc = "Returns the string delimination characters.";
555 if( !type_engine_import_mfun( env, func ) ) goto error;
556
557 func = make_new_mfun( "string", "delims", StrTok_set_delims );
558 func->add_arg( "string", "delimiters" );
559 func->doc = "Sets the delimination characters as a string. If the argument is an empty string, default whitespace characters \" \\f\\n\\r\\t\\v\" will be used. Also, calling this method resets the state for the token retrieval loop (e.g., .more() and .next())";
560 if( !type_engine_import_mfun( env, func ) ) goto error;
561
562 // add examples
563 if( !type_engine_import_add_ex( env, "string/token.ck" ) ) goto error;
564 if( !type_engine_import_add_ex( env, "string/readline.ck" ) ) goto error;
565 if( !type_engine_import_add_ex( env, "io/read-tokens.ck" ) ) goto error;
566 if( !type_engine_import_add_ex( env, "io/jabberwocky.txt" ) ) goto error;
567 if( !type_engine_import_add_ex( env, "ai/word2vec/word2vec-prompt.ck" ) ) goto error;
568
569 // end class
570 type_engine_import_class_end( env );
571
572
573 #ifdef AJAY
574
575 // begin class
576 // init base class
577 if( !type_engine_import_class_begin( env, "VCR", "Object",
578 env->global(), VCR_ctor ) )
579 return FALSE;
580
581 // add member variable
582 VCR_offset_data = type_engine_import_mvar( env, "int", "@me", FALSE );
583 if( VCR_offset_data == CK_INVALID_OFFSET ) goto error;
584
585 // add load()
586 func = make_new_mfun( "int", "load", VCR_load );
587 func->add_arg( "string", "filename" );
588 func->add_arg( "int", "column" );
589 if( !type_engine_import_mfun( env, func ) ) goto error;
590
591 // add reset()
592 func = make_new_mfun( "int", "reset", VCR_reset );
593 if( !type_engine_import_mfun( env, func ) ) goto error;
594
595 // add seek()
596 func = make_new_mfun( "int", "seek", VCR_seek );
597 func->add_arg( "int", "where" );
598 if( !type_engine_import_mfun( env, func ) ) goto error;
599
600 // add more()
601 func = make_new_mfun( "int", "more", VCR_more );
602 if( !type_engine_import_mfun( env, func ) ) goto error;
603
604 // add curr()
605 func = make_new_mfun( "float", "curr", VCR_curr );
606 if( !type_engine_import_mfun( env, func ) ) goto error;
607
608 // add next()
609 func = make_new_mfun( "int", "next", VCR_next );
610 if( !type_engine_import_mfun( env, func ) ) goto error;
611
612 // add pos()
613 func = make_new_mfun( "int", "pos", VCR_pos );
614 if( !type_engine_import_mfun( env, func ) ) goto error;
615
616 // add size()
617 func = make_new_mfun( "int", "size", VCR_size );
618 if( !type_engine_import_mfun( env, func ) ) goto error;
619
620 // add name()
621 func = make_new_mfun( "string", "name", VCR_name );
622 if( !type_engine_import_mfun( env, func ) ) goto error;
623
624 // end the class import
625 type_engine_import_class_end( env );
626
627
628 #if defined(__PLATFORM_WINDOWS__)
629 // begin class (Cereal)
630 if( !type_engine_import_class_begin( env, "Cereal", "Object",
631 env->global(), Cereal_ctor ) )
632 return FALSE;
633
634 // add member
635 Cereal_offset_data = type_engine_import_mvar( env, "int", "@Cereal_data", FALSE );
636 if( Cereal_offset_data == CK_INVALID_OFFSET ) goto error;
637
638 // add open()
639 func = make_new_mfun( "int", "open", Cereal_open );
640 func->add_arg( "string", "name" );
641 func->add_arg( "int", "baudrate" );
642 if( !type_engine_import_mfun( env, func ) ) goto error;
643
644 // add close()
645 func = make_new_mfun( "void", "close", Cereal_close );
646 if( !type_engine_import_mfun( env, func ) ) goto error;
647
648 // add more()
649 func = make_new_mfun( "int", "more", Cereal_more );
650 if( !type_engine_import_mfun( env, func ) ) goto error;
651
652 // add send()
653 func = make_new_mfun( "int", "send", Cereal_send );
654 func->add_arg( "int", "bite" );
655 if( !type_engine_import_mfun( env, func ) ) goto error;
656
657 // add recv()
658 func = make_new_mfun( "int", "recv", Cereal_recv );
659 if( !type_engine_import_mfun( env, func ) ) goto error;
660
661 // end class
662 type_engine_import_class_end( env );
663 #endif
664
665 return TRUE;
666
667 #else
668
669 return TRUE;
670
671 #endif
672
673 error:
674
675 // end the class import
676 type_engine_import_class_end( env );
677
678 return FALSE;
679 }
680
681 // abs
682 CK_DLL_SFUN( abs_impl )
683 {
684 t_CKINT v = GET_CK_INT(ARGS);
685 RETURN->v_int = v >= 0 ? v : -v;
686 }
687
688 // fabs
689 CK_DLL_SFUN( fabs_impl )
690 {
691 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
692 RETURN->v_float = v >= 0.0 ? v : -v;
693 //RETURN->v_float = ::fabs( GET_CK_FLOAT(ARGS) );
694 }
695
696 // rand
697 CK_DLL_SFUN( rand_impl )
698 {
699 // 1.5.0.1 (ge) use ck_random()
700 RETURN->v_int = ck_random();
701 }
702
703 // randf
704 CK_DLL_SFUN( randf_impl )
705 {
706 // 1.5.0.4 (ge) use ck_random_f()
707 RETURN->v_float = ( 2.0 * ck_random_f() - 1.0 );
708 }
709
710 // randf
711 CK_DLL_SFUN( rand2f_impl )
712 {
713 t_CKFLOAT min = GET_CK_FLOAT(ARGS), max = *((t_CKFLOAT *)ARGS + 1);
714 // 1.5.0.4 (ge) use ck_random_f()
715 RETURN->v_float = min + (max-min)*::ck_random_f();
716 }
717
718 // randi
719 CK_DLL_SFUN( rand2_impl ) // inclusive.
720 {
721 // 1.3.1.0: converted int to t_CKINT for 64-bit compatibility
722 t_CKINT min = *(t_CKINT *)ARGS, max = *((t_CKINT *)ARGS + 1);
723 t_CKINT range = max - min;
724 if ( range == 0 )
725 {
726 RETURN->v_int = min;
727 }
728 else
729 {
730 if( range > 0 )
731 {
732 RETURN->v_int = min + (t_CKINT)( (1.0 + range) * ( ::ck_random()/(CK_RANDOM_MAX+1.0) ) );
733 }
734 else
735 {
736 RETURN->v_int = min - (t_CKINT)( (-range + 1.0) * ( ::ck_random()/(CK_RANDOM_MAX+1.0) ) );
737 }
738 }
739 }
740
741 // srand
742 CK_DLL_SFUN( srand_impl )
743 {
744 t_CKINT seed = GET_CK_INT(ARGS);
745 // 1.5.0.1 (ge) updated to ck_srandom()
746 ck_srandom( (unsigned)seed );
747 }
748
749 // sgn
750 CK_DLL_SFUN( sgn_impl )
751 {
752 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
753 RETURN->v_float = v == 0.0f ? 0.0f : ( v > 0.0f ? 1.0f : -1.0f );
754 }
755
756 // system
757 CK_DLL_SFUN( system_impl )
758 {
759 const char * cmd = GET_CK_STRING(ARGS)->str().c_str();
760
761 #ifndef __CHIP_MODE__
762 // check globals for permission
763 if( !ChucK::enableSystemCall )
764 {
765 CK_FPRINTF_STDERR( "[chuck]:error: VM not authorized to call Std.system( string )...\n" );
766 CK_FPRINTF_STDERR( "[chuck]: (command string was: \"%s\")\n", cmd );
767 CK_FPRINTF_STDERR( "[chuck]: (note: enable via --caution-to-the-wind flag or other means)\n" );
768 RETURN->v_int = 0;
769 }
770 else
771 {
772 // log
773 EM_log( CK_LOG_HERALD, "invoking system( CMD )..." );
774 EM_pushlog();
775 EM_log( CK_LOG_HERALD, "CMD: \"%s\"", cmd );
776 EM_poplog();
777 RETURN->v_int = system( cmd );
778 }
779 #else
780 CK_FPRINTF_STDERR( "[chuck]:error: VM not authorized to call Std.system( string )...\n" );
781 CK_FPRINTF_STDERR( "[chuck]: (command string was: \"%s\")\n", cmd );
782 CK_FPRINTF_STDERR( "[chuck]: (note: Std.system() disabled on iOS)\n" );
783 RETURN->v_int = 0;
784 #endif
785 }
786
787 // aoti
788 CK_DLL_SFUN( atoi_impl )
789 {
790 Chuck_String * str = GET_CK_STRING(ARGS);
791 if( str )
792 {
793 const char * v = str->str().c_str();
794 RETURN->v_int = atoi( v );
795 }
796 else
797 {
798 RETURN->v_int = 0;
799 }
800 }
801
802 // atof
803 CK_DLL_SFUN( atof_impl )
804 {
805 Chuck_String * str = GET_CK_STRING(ARGS);
806 if( str )
807 {
808 const char * v = GET_CK_STRING(ARGS)->str().c_str();
809 RETURN->v_float = atof( v );
810 }
811 else
812 {
813 RETURN->v_float = 0.0;
814 }
815 }
816
817 // itoa
818 CK_DLL_SFUN( itoa_impl )
819 {
820 t_CKINT i = GET_CK_INT(ARGS);
821 // TODO: memory leak, please fix. Thanks.
822 Chuck_String * a = (Chuck_String *)instantiate_and_initialize_object( SHRED->vm_ref->env()->ckt_string, SHRED );
823 a->set( ck_itoa( i ) );
824 RETURN->v_string = a;
825 }
826
827 // ftoa
828 CK_DLL_SFUN( ftoa_impl )
829 {
830 t_CKFLOAT f = GET_NEXT_FLOAT(ARGS);
831 t_CKINT p = GET_NEXT_INT(ARGS);
832 Chuck_String * a = (Chuck_String *)instantiate_and_initialize_object( SHRED->vm_ref->env()->ckt_string, SHRED );
833 a->set( ck_ftoa( f, (t_CKUINT)p ) );
834 RETURN->v_string = a;
835 }
836
837 // ftoi
838 CK_DLL_SFUN( ftoi_impl )
839 {
840 t_CKFLOAT f = GET_NEXT_FLOAT(ARGS);
841 RETURN->v_int = (t_CKINT) f;
842 }
843
844 // getenv
845 CK_DLL_SFUN( getenv_impl )
846 {
847 // get chuck string key
848 Chuck_String * ckstr_key = GET_NEXT_STRING(ARGS);
849 // check for null
850 if( !ckstr_key )
851 {
852 // instantiate
853 Chuck_String * empty = (Chuck_String *)instantiate_and_initialize_object( SHRED->vm_ref->env()->ckt_string, SHRED );
854 // return value
855 RETURN->v_string = empty;
856 // return out of this function
857 return;
858 }
859
860 const char * v = ckstr_key->str().c_str();
861 const char * s = getenv( v );
862 Chuck_String * a = (Chuck_String *)instantiate_and_initialize_object( SHRED->vm_ref->env()->ckt_string, SHRED );
863 a->set( s ? s : "" );
864 RETURN->v_string = a;
865 }
866
867 // getenv with default value fallback | 1.5.0.8 (@ynohtna) added
868 CK_DLL_SFUN( getenv2_impl )
869 {
870 // get chuck string key and default
871 Chuck_String * ckstr_key = GET_NEXT_STRING(ARGS);
872 Chuck_String * ckstr_default = GET_NEXT_STRING(ARGS);
873 // check for null
874 if( !ckstr_key )
875 {
876 // return default
877 RETURN->v_string = ckstr_default;
878 // return out of this function
879 return;
880 }
881
882 // get key as c str
883 const char * k = ckstr_key->str().c_str();
884 // get env value
885 const char * v = getenv( k );
886 if( v ) {
887 Chuck_String * a = (Chuck_String *)instantiate_and_initialize_object( SHRED->vm_ref->env()->ckt_string, SHRED );
888 a->set( v ? v : "" );
889 RETURN->v_string = a;
890 } else {
891 Chuck_String * d = ckstr_default;
892 RETURN->v_string = d;
893 }
894 }
895
896 // setenv
897 CK_DLL_SFUN( setenv_impl )
898 {
899 const char * v1 = GET_NEXT_STRING(ARGS)->str().c_str();
900 const char * v2 = GET_NEXT_STRING(ARGS)->str().c_str();
901 RETURN->v_int = setenv( v1, v2, 1 );
902 }
903
904 // mtof
905 CK_DLL_SFUN( mtof_impl )
906 {
907 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
908 RETURN->v_float = ck_mtof(v);
909 }
910
911 // ftom
912 CK_DLL_SFUN( ftom_impl )
913 {
914 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
915 RETURN->v_float = ck_ftom(v);
916 }
917
918 // powtodb
919 CK_DLL_SFUN( powtodb_impl )
920 {
921 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
922 RETURN->v_float = ck_powtodb(v);
923 }
924
925 // rmstodb
926 CK_DLL_SFUN( rmstodb_impl )
927 {
928 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
929 RETURN->v_float = ck_rmstodb(v);
930 }
931
932 // dbtopow
933 CK_DLL_SFUN( dbtopow_impl )
934 {
935 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
936 RETURN->v_float = ck_dbtopow(v);
937 }
938
939 // dbtorms
940 CK_DLL_SFUN( dbtorms_impl )
941 {
942 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
943 RETURN->v_float = ck_dbtorms(v);
944 }
945
946 CK_DLL_SFUN( dbtolin_impl )
947 {
948 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
949 RETURN->v_float = pow(10.0, v/20.0);
950 }
951
952 CK_DLL_SFUN( lintodb_impl )
953 {
954 t_CKFLOAT v = GET_CK_FLOAT(ARGS);
955 RETURN->v_float = 20.0*log10(v);
956 }
957
958 CK_DLL_SFUN( clamp_impl )
959 {
960 t_CKINT v = GET_NEXT_INT(ARGS);
961 t_CKINT min = GET_NEXT_INT(ARGS);
962 t_CKINT max = GET_NEXT_INT(ARGS);
963
964 if(v < min) RETURN->v_int = min;
965 else if(v > max) RETURN->v_int = max;
966 else RETURN->v_int = v;
967 }
968
969 CK_DLL_SFUN( clampf_impl )
970 {
971 t_CKFLOAT v = GET_NEXT_FLOAT(ARGS);
972 t_CKFLOAT min = GET_NEXT_FLOAT(ARGS);
973 t_CKFLOAT max = GET_NEXT_FLOAT(ARGS);
974
975 if(v < min) RETURN->v_float = min;
976 else if( v > max) RETURN->v_float = max;
977 else RETURN->v_float = v;
978 }
979
980 CK_DLL_SFUN( scalef_impl )
981 {
982 t_CKFLOAT v = GET_NEXT_FLOAT(ARGS);
983 t_CKFLOAT srcmin = GET_NEXT_FLOAT(ARGS);
984 t_CKFLOAT srcmax = GET_NEXT_FLOAT(ARGS);
985 t_CKFLOAT dstmin = GET_NEXT_FLOAT(ARGS);
986 t_CKFLOAT dstmax = GET_NEXT_FLOAT(ARGS);
987
988 RETURN->v_float = dstmin + (dstmax-dstmin) * ((v-srcmin)/(srcmax-srcmin));
989 }
990
991 // common internal function for range() | 1.5.1.1 (nshaheed)
992 static Chuck_ArrayInt * ck_range( t_CKINT start, t_CKINT stop, t_CKINT step, Chuck_VM_Shred * SHRED )
993 {
994 // size
995 t_CKINT size = 0;
996 // calculate size based on comparing start and stop
997 if( start < stop && step > 0 ) size = (stop-start)/step + ((stop-start)%step ? 1 : 0);
998 else if( start > stop && step < 0 ) size = (start-stop)/(-step) + ((start-stop)%(-step) ? 1 : 0);
999
1000 // allocate array object
1001 Chuck_ArrayInt * range = new Chuck_ArrayInt(FALSE, size);
1002 // initialize with trappings of Object
1003 initialize_object(range, SHRED->vm_ref->env()->ckt_array, SHRED, SHRED->vm_ref);
1004
1005 // the value
1006 t_CKINT value = start;
1007 // populate the array
1008 for (t_CKINT i = 0; i < size; i++) {
1009 range->set(i, value);
1010 value += step;
1011 }
1012
1013 // return the array reference
1014 return range;
1015 }
1016
1017 // basic range function - make array with values from [0,stop)
1018 CK_DLL_SFUN(range1_impl)
1019 {
1020 t_CKINT start = 0;
1021 t_CKINT stop = GET_NEXT_INT(ARGS);
1022 t_CKINT step = stop > start ? 1 : -1;
1023 RETURN->v_object = ck_range( start, stop, step, SHRED );
1024 }
1025
1026 // start/stop range function - make array with values from [start,stop)
1027 CK_DLL_SFUN(range2_impl)
1028 {
1029 t_CKINT start = GET_NEXT_INT(ARGS);
1030 t_CKINT stop = GET_NEXT_INT(ARGS);
1031 t_CKINT step = stop > start ? 1 : -1;
1032 RETURN->v_object = ck_range( start, stop, step, SHRED );
1033 }
1034
1035 // start/stop/step range function - make array with values from [start,stop) with step stride
1036 CK_DLL_SFUN(range3_impl)
1037 {
1038 t_CKINT start = GET_NEXT_INT(ARGS);
1039 t_CKINT stop = GET_NEXT_INT(ARGS);
1040 t_CKINT step = GET_NEXT_INT(ARGS);
1041
1042 // check and flip signs to match with stop-start
1043 if( (start < stop && step < 0) ||
1044 (start > stop && step > 0 ) ) step = -step;
1045
1046 RETURN->v_object = ck_range( start, stop, step, SHRED );
1047 }
1048
1049
1050
1051
1052 #ifndef __DISABLE_KBHIT__
1053 // static
1054 CBufferAdvance * KBHitManager::the_buf = NULL;
1055 t_CKINT KBHitManager::the_onoff = 0;
1056 t_CKBOOL KBHitManager::the_init = FALSE;
1057 XThread * KBHitManager::the_thread;
1058 #define BUFFER_SIZE 1024
1059
1060
1061 #if !defined(__PLATFORM_WINDOWS__) || defined(__WINDOWS_PTHREAD__)
1062 static void * kb_loop( void * )
1063 #else
1064 static unsigned int __stdcall kb_loop( void * )
1065 #endif
1066 {
1067 t_CKINT c;
1068 // EM_log( CK_LOG_INFO, "starting kb loop..." );
1069
1070 // go
1071 while( KBHitManager::the_init )
1072 {
1073 // if on
1074 if( KBHitManager::the_onoff )
1075 {
1076 // see if we have kb hit
1077 while( kb_hit() )
1078 {
1079 // get the next char
1080 c = kb_getch();
1081 // queue it
1082 KBHitManager::the_buf->put( &c, 1 );
1083 }
1084 }
1085
1086 // wait
1087 ck_usleep( 5000 );
1088 }
1089
1090 return 0;
1091 }
1092
1093
1094 // init
1095 t_CKBOOL KBHitManager::init()
1096 {
1097 // sanity check
1098 if( the_buf ) return FALSE;
1099
1100 EM_log( CK_LOG_INFO, "initializing KBHitManager..." );
1101 the_buf = new CBufferAdvance;
1102 if( !the_buf->initialize( BUFFER_SIZE, sizeof(t_CKINT) ) )
1103 {
1104 EM_log( CK_LOG_HERALD, "KBHitManager: couldn't allocate central KB buffer..." );
1105 CK_SAFE_DELETE( the_buf );
1106 return FALSE;
1107 }
1108
1109 the_onoff = 0;
1110 the_init = TRUE;
1111 the_thread = new XThread;
1112 EM_pushlog();
1113 EM_log( CK_LOG_INFO, "starting kb loop..." );
1114 EM_poplog();
1115 the_thread->start( kb_loop, NULL );
1116
1117 return TRUE;
1118 }
1119
1120
1121 // shutdown
1122 void KBHitManager::shutdown()
1123 {
1124 EM_log( CK_LOG_INFO, "shutting down KBHitManager..." );
1125 CK_SAFE_DELETE( the_buf );
1126 kb_endwin();
1127
1128 the_onoff = 0;
1129 the_init = FALSE;
1130 }
1131
1132
1133 // on()
1134 void KBHitManager::on()
1135 {
1136 the_onoff++;
1137 if( !kb_ready() )
1138 kb_initscr();
1139 }
1140
1141
1142 // off()
1143 void KBHitManager::off()
1144 {
1145 the_onoff--;
1146 if( kb_ready() && the_onoff == 0 )
1147 kb_endwin();
1148 }
1149
1150
1151 // open()
1152 t_CKBOOL KBHitManager::open( KBHit * kb )
1153 {
1154 if( the_buf == NULL ) return FALSE;
1155 if( kb->m_buffer != NULL ) return FALSE;
1156
1157 EM_log( CK_LOG_INFO, "adding KBHit..." );
1158 // init the kb
1159 kb->m_buffer = the_buf;
1160 // read index
1161 kb->m_read_index = kb->m_buffer->join( (Chuck_Event *)kb->SELF );
1162
1163 return TRUE;
1164 }
1165
1166
1167 // close()
1168 t_CKBOOL KBHitManager::close( KBHit * kb )
1169 {
1170 if( the_buf == NULL ) return FALSE;
1171 if( kb->m_buffer == NULL ) return FALSE;
1172
1173 EM_log( CK_LOG_INFO, "removing KBHit..." );
1174 // unjoin
1175 kb->m_buffer->resign( kb->m_read_index );
1176 // done
1177 kb->m_read_index = 0;
1178
1179 return TRUE;
1180 }
1181
1182
1183 // KBHit
1184 KBHit::KBHit()
1185 {
1186 m_buffer = NULL;
1187 m_read_index = 0;
1188 m_valid = FALSE;
1189 m_onoff = FALSE;
1190 m_echo = FALSE;
1191 SELF = NULL;
1192 }
1193
1194
1195 // ~KBHit()
1196 KBHit::~KBHit()
1197 {
1198 this->close();
1199 }
1200
1201
1202 // open()
1203 t_CKBOOL KBHit::open()
1204 {
1205 return KBHitManager::open( this );
1206 }
1207
1208
1209 // close()
1210 t_CKBOOL KBHit::close()
1211 {
1212 return KBHitManager::close( this );
1213 }
1214
1215
1216 // on()
1217 void KBHit::on()
1218 {
1219 if( m_onoff == FALSE )
1220 {
1221 KBHitManager::on();
1222 open();
1223 m_onoff = TRUE;
1224 }
1225 }
1226
1227
1228 // off()
1229 void KBHit::off()
1230 {
1231 if( m_onoff == TRUE )
1232 {
1233 KBHitManager::off();
1234 open();
1235 m_onoff = FALSE;
1236 }
1237 }
1238
1239
1240 // empty
1241 t_CKBOOL KBHit::empty()
1242 {
1243 if( m_buffer == NULL ) return TRUE;
1244 if( m_onoff == FALSE ) return TRUE;
1245 // if( m_read_index == 0 ) return TRUE;
1246 return m_buffer->empty( m_read_index );
1247 }
1248
1249
1250 // getch
1251 t_CKINT KBHit::getch()
1252 {
1253 t_CKINT c;
1254 if( empty() ) return 0;
1255 m_buffer->get( &c, 1, m_read_index );
1256 return c;
1257 }
1258
1259
1260 // ctor
1261 CK_DLL_CTOR( KBHit_ctor )
1262 {
1263 KBHit * kb = new KBHit;
1264 OBJ_MEMBER_INT(SELF, KBHit_offset_data) = (t_CKINT)kb;
1265 kb->SELF = SELF;
1266 kb->on();
1267 }
1268
1269
1270 // dtor
1271 CK_DLL_DTOR( KBHit_dtor )
1272 {
1273 delete (KBHit *)OBJ_MEMBER_INT(SELF, KBHit_offset_data);
1274 OBJ_MEMBER_INT(SELF, KBHit_offset_data) = 0;
1275 }
1276
1277 // on
1278 CK_DLL_MFUN( KBHit_on )
1279 {
1280 KBHit * kb = (KBHit *)(OBJ_MEMBER_INT(SELF, KBHit_offset_data));
1281 kb->on();
1282 }
1283
1284
1285 // off
1286 CK_DLL_MFUN( KBHit_off )
1287 {
1288 KBHit * kb = (KBHit *)(OBJ_MEMBER_INT(SELF, KBHit_offset_data));
1289 kb->off();
1290 }
1291
1292
1293 // state
1294 CK_DLL_MFUN( KBHit_state )
1295 {
1296 KBHit * kb = (KBHit *)(OBJ_MEMBER_INT(SELF, KBHit_offset_data));
1297 RETURN->v_int = kb->state();
1298 }
1299
1300
1301 // hit
1302 CK_DLL_MFUN( KBHit_hit )
1303 {
1304 //KBHit * kb = (KBHit *)(OBJ_MEMBER_INT(SELF, KBHit_offset_data));
1305 RETURN->v_object = SELF;
1306 }
1307
1308
1309 // more
1310 CK_DLL_MFUN( KBHit_more )
1311 {
1312 KBHit * kb = (KBHit *)(OBJ_MEMBER_INT(SELF, KBHit_offset_data));
1313 RETURN->v_int = (kb->empty() == FALSE);
1314 }
1315
1316
1317 // getchar
1318 CK_DLL_MFUN( KBHit_getchar )
1319 {
1320 KBHit * kb = (KBHit *)(OBJ_MEMBER_INT(SELF, KBHit_offset_data));
1321 RETURN->v_int = kb->getch();
1322 }
1323
1324
1325 // can wait
1326 CK_DLL_MFUN( KBHit_can_wait )
1327 {
1328 KBHit * kb = (KBHit *)(OBJ_MEMBER_INT(SELF, KBHit_offset_data));
1329 RETURN->v_int = kb->empty();
1330 }
1331 #endif // __DISABLE_KBHIT__
1332
1333
1334
1335
1336 #ifndef __DISABLE_PROMPTER__
1337 class LineEvent : public Chuck_Event
1338 {
1339 public:
1340 LineEvent( Chuck_Event * SELF );
1341 ~LineEvent();
1342
1343 public:
1344 void prompt( const string & what = "" );
1345 t_CKBOOL more();
1346 string getLine();
1347 t_CKBOOL can_wait();
1348 void enqueue( const string & line )
1349 { m_q.push( line ); }
1350
1351 Chuck_Event * SELF;
1352
1353 protected:
1354 queue<string> m_q;
1355 };
1356
1357 // global variables
1358 t_CKBOOL g_le_launched = FALSE;
1359 t_CKBOOL g_le_wait = TRUE;
1360 CHUCK_THREAD g_le_thread = 0;
1361 map<LineEvent *, LineEvent *> g_le_map;
1362 XMutex g_le_mutex;
1363 string g_le_what;
1364
1365 // final cleanup (per host)
1366 void le_cleanup()
1367 {
1368 if( g_le_thread )
1369 {
1370 // cancel thread
1371 #if !defined(__PLATFORM_WINDOWS__) || defined(__WINDOWS_PTHREAD__)
1372 pthread_cancel( g_le_thread );
1373 #else
1374 CloseHandle( g_le_thread );
1375 #endif
1376 g_le_thread = 0;
1377 // reset
1378 g_le_launched = FALSE;
1379 g_le_wait = TRUE;
1380 }
1381 }
1382
1383 // le callback
1384 void * le_cb( void * p )
1385 {
1386 char line[2048];
1387 map<LineEvent *, LineEvent *>::iterator iter;
1388 LineEvent * le = NULL;
1389
1390 // loop
1391 while( true )
1392 {
1393 // wait
1394 while( g_le_wait )
1395 ck_usleep( 10000 );
1396
1397 // REFACTOR-2017: TODO Ge:
1398 // I removed the check here for if there are no more vms running
1399 // Theoretically, we will always just kill this thread from outside of
1400 // it. Does that sound right to you?
1401
1402 // do the prompt
1403 cout << g_le_what;
1404 cout.flush();
1405 if( !cin.getline( line, 2048 ) ) break;
1406
1407 // lock
1408 g_le_mutex.acquire();
1409 // go through
1410 for( iter = g_le_map.begin(); iter != g_le_map.end(); iter++ )
1411 {
1412 // get the line event
1413 le = (*iter).first;
1414 // add to its queue
1415 le->enqueue( line );
1416 // broadcast it
1417 le->SELF->queue_broadcast();
1418 }
1419 // unlock
1420 g_le_mutex.release();
1421
1422 // reset wait
1423 g_le_wait = TRUE;
1424 }
1425
1426 return NULL;
1427 }
1428
1429
1430 LineEvent::LineEvent( Chuck_Event * SELF )
1431 {
1432 // launch the cb
1433 if( !g_le_launched )
1434 {
1435 #if !defined(__PLATFORM_WINDOWS__) || defined(__WINDOWS_PTHREAD__)
1436 pthread_create( &g_le_thread, NULL, le_cb, NULL );
1437 #else
1438 g_le_thread = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)le_cb, NULL, 0, 0 );
1439 #endif
1440 g_le_launched = TRUE;
1441 }
1442
1443 // lock
1444 g_le_mutex.acquire();
1445 // add
1446 g_le_map[this] = this;
1447 this->SELF = SELF;
1448 // unlock
1449 g_le_mutex.release();
1450 }
1451
1452 LineEvent::~LineEvent()
1453 {
1454 // remove from global map
1455 g_le_map.erase( this );
1456 }
1457
1458 void LineEvent::prompt( const string & what )
1459 {
1460 // set what
1461 g_le_what = what;
1462
1463 // remove the extra space
1464 // if( g_le_what != "" ) g_le_what += " ";
1465
1466 // signal
1467 g_le_wait = FALSE;
1468 }
1469
1470 t_CKBOOL LineEvent::more()
1471 {
1472 // more
1473 return m_q.size() > 0;
1474 }
1475
1476 string LineEvent::getLine()
1477 {
1478 string ret;
1479
1480 // lock
1481 g_le_mutex.acquire();
1482 // get next line
1483 if( m_q.size() )
1484 {
1485 // get it
1486 ret = m_q.front();
1487 // dequeue it
1488 m_q.pop();
1489 }
1490 else
1491 {
1492 ret = "[ERROR -> getLine() called on empty Skot]";
1493 }
1494 // unlock
1495 g_le_mutex.release();
1496
1497 return ret;
1498 }
1499
1500 t_CKBOOL LineEvent::can_wait()
1501 {
1502 return !more();
1503 }
1504
1505
1506 // Skot
1507 CK_DLL_CTOR( Skot_ctor )
1508 {
1509 LineEvent * le = new LineEvent((Chuck_Event *)SELF);
1510 OBJ_MEMBER_INT(SELF, Skot_offset_data) = (t_CKINT)le;
1511 }
1512
1513 CK_DLL_DTOR( Skot_dtor )
1514 {
1515 delete (LineEvent *)OBJ_MEMBER_INT(SELF, Skot_offset_data);
1516 OBJ_MEMBER_INT(SELF, Skot_offset_data) = 0;
1517 }
1518
1519 CK_DLL_MFUN( Skot_prompt )
1520 {
1521 LineEvent * le = (LineEvent *)OBJ_MEMBER_INT(SELF, Skot_offset_data);
1522 le->prompt();
1523 RETURN->v_int = (t_CKINT)(SELF);
1524 }
1525
1526 CK_DLL_MFUN( Skot_prompt2 )
1527 {
1528 LineEvent * le = (LineEvent *)OBJ_MEMBER_INT(SELF, Skot_offset_data);
1529 const char * v = GET_CK_STRING(ARGS)->str().c_str();
1530 le->prompt( v );
1531 RETURN->v_int = (t_CKINT)(SELF);
1532 }
1533
1534 CK_DLL_MFUN( Skot_more )
1535 {
1536 LineEvent * le = (LineEvent *)OBJ_MEMBER_INT(SELF, Skot_offset_data);
1537 RETURN->v_int = le->more();
1538 }
1539
1540 CK_DLL_MFUN( Skot_getLine )
1541 {
1542 LineEvent * le = (LineEvent *)OBJ_MEMBER_INT(SELF, Skot_offset_data);
1543 // TODO: memory leak
1544 Chuck_String * a = (Chuck_String *)instantiate_and_initialize_object( SHRED->vm_ref->env()->ckt_string, SHRED );
1545 a->set( le->getLine() );
1546 RETURN->v_string = a;
1547 }
1548
1549 CK_DLL_MFUN( Skot_can_wait )
1550 {
1551 LineEvent * le = (LineEvent *)OBJ_MEMBER_INT(SELF, Skot_offset_data);
1552 RETURN->v_int = le->can_wait();
1553 }
1554 #endif // __DISABLE_PROMPTER__
1555
1556
1557 // StrTok
1558 class StrTok
1559 {
1560 public:
1561 StrTok();
1562 StrTok( const string & delimiters );
1563 ~StrTok();
1564
1565 public:
1566 void setLine( const string & line );
1567 string setDelims( const string & delimiters );
1568 string getDelims() const;
1569 void reset();
1570 t_CKBOOL more();
1571 string next();
1572 string get( t_CKINT index );
1573 t_CKINT size();
1574
1575 protected:
1576 string m_line;
1577 string m_delims;
1578 string m_next;
1579 vector<string> m_tokens;
1580 vector<string>::size_type m_index;
1581 };
1582
1583 StrTok::StrTok()
1584 {
1585 m_index = 0;
1586 // set default delims with empty string
1587 setDelims( "" );
1588 }
1589
1590 StrTok::StrTok( const string & delims )
1591 {
1592 m_index = 0;
1593 // set delims
1594 setDelims( delims );
1595 }
1596
1597 StrTok::~StrTok()
1598 { }
1599
1600 void StrTok::setLine( const string & line )
1601 {
1602 // reset index
1603 reset();
1604 // clear tokens list
1605 m_tokens.clear();
1606 // copy the line
1607 m_line = line;
1608
1609 // "c string"
1610 std::vector<char> cstr( line.length() + 1 );
1611 // copy
1612 strncpy( cstr.data(), line.c_str(), line.length()+1 );
1613 // delimiters
1614 const char * delimiter = m_delims.c_str();
1615
1616 // first call
1617 char * token = strtok( cstr.data(), delimiter );
1618 // loop
1619 while( token != NULL )
1620 {
1621 // append token
1622 m_tokens.push_back( token );
1623 // subsequent calls
1624 token = strtok( NULL, delimiter );
1625 }
1626 }
1627
1628 void StrTok::reset()
1629 {
1630 m_index = 0;
1631 }
1632
1633 t_CKBOOL StrTok::more()
1634 {
1635 return m_index < m_tokens.size();
1636 }
1637
1638 string StrTok::next()
1639 {
1640 if( !more() ) return "";
1641 return m_tokens[m_index++];
1642 }
1643
1644 string StrTok::get( t_CKINT index )
1645 {
1646 if( index >= (t_CKINT)m_tokens.size() ) return "";
1647 return m_tokens[index];
1648 }
1649
1650 t_CKINT StrTok::size()
1651 {
1652 return (t_CKINT)m_tokens.size();
1653 }
1654
1655 string StrTok::getDelims() const
1656 {
1657 return m_delims;
1658 }
1659
1660 string StrTok::setDelims( const string & delims )
1661 {
1662 // copy
1663 m_delims = delims;
1664
1665 // if empty string, use default
1666 // ' 'space,
1667 // \f form feed
1668 // \n line feed
1669 // \r carriage return
1670 // \t horizontal tab
1671 // \v vertical tab
1672 if( m_delims == "" ) m_delims = " \f\n\r\t\v";
1673
1674 // re-tokenize
1675 setLine( m_line );
1676
1677 // done
1678 return m_delims;
1679 }
1680
1681 CK_DLL_CTOR( StrTok_ctor )
1682 {
1683 StrTok * tokens = new StrTok;
1684 OBJ_MEMBER_INT(SELF, StrTok_offset_data) = (t_CKINT)tokens;
1685 }
1686
1687 CK_DLL_CTOR( StrTok_ctor_line )
1688 {
1689 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1690 Chuck_String * line = GET_NEXT_STRING(ARGS);
1691 tokens->setLine( line ? line->c_str() : "" );
1692 }
1693
1694 CK_DLL_CTOR( StrTok_ctor_line_delims )
1695 {
1696 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1697 // line
1698 Chuck_String * line = GET_NEXT_STRING(ARGS);
1699 tokens->setLine( line ? line->c_str() : "" );
1700 // delims
1701 Chuck_String * delims = GET_NEXT_STRING(ARGS);
1702 tokens->setDelims( delims ? delims->c_str() : "" );
1703 }
1704
1705 CK_DLL_DTOR( StrTok_dtor )
1706 {
1707 delete (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1708 OBJ_MEMBER_INT(SELF, StrTok_offset_data) = 0;
1709 }
1710
1711 CK_DLL_MFUN( StrTok_set )
1712 {
1713 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1714 Chuck_String * s = GET_CK_STRING(ARGS);
1715 tokens->setLine( s ? s->str() : "" );
1716 }
1717
1718 CK_DLL_MFUN( StrTok_reset )
1719 {
1720 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1721 tokens->reset();
1722 }
1723
1724 CK_DLL_MFUN( StrTok_more )
1725 {
1726 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1727 RETURN->v_int = (t_CKINT)tokens->more();
1728 }
1729
1730 CK_DLL_MFUN( StrTok_next )
1731 {
1732 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1733 Chuck_String * a = (Chuck_String *)instantiate_and_initialize_object( SHRED->vm_ref->env()->ckt_string, SHRED );
1734 a->set( tokens->next() );
1735 RETURN->v_string = a;
1736 }
1737
1738 CK_DLL_MFUN( StrTok_next2 )
1739 {
1740 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1741 Chuck_String * a = GET_CK_STRING(ARGS);
1742 string s = tokens->next();
1743 if( a ) a->set( s );
1744 RETURN->v_string = a;
1745 }
1746
1747 CK_DLL_MFUN( StrTok_get )
1748 {
1749 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1750 t_CKINT index = GET_NEXT_INT(ARGS);
1751 Chuck_String * a = (Chuck_String *)instantiate_and_initialize_object( SHRED->vm_ref->env()->ckt_string, SHRED );
1752 string s = tokens->get( index );
1753 a->set( s );
1754 RETURN->v_string = a;
1755 }
1756
1757 CK_DLL_MFUN( StrTok_get2 )
1758 {
1759 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1760 t_CKINT index = GET_NEXT_INT(ARGS);
1761 Chuck_String * a = GET_NEXT_STRING(ARGS);
1762 string s = tokens->get( index );
1763 if( a ) a->set( s );
1764 RETURN->v_string = a;
1765 }
1766
1767 CK_DLL_MFUN( StrTok_size )
1768 {
1769 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1770 RETURN->v_int = tokens->size();
1771 }
1772
1773 CK_DLL_MFUN( StrTok_get_delims )
1774 {
1775 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1776 Chuck_String * a = (Chuck_String *)instantiate_and_initialize_object( SHRED->vm_ref->env()->ckt_string, SHRED );
1777 a->set( tokens->getDelims() );
1778 RETURN->v_string = a;
1779 }
1780
1781 CK_DLL_MFUN( StrTok_set_delims )
1782 {
1783 StrTok * tokens = (StrTok *)OBJ_MEMBER_INT(SELF, StrTok_offset_data);
1784 Chuck_String * ckstr = GET_CK_STRING(ARGS);
1785 tokens->setDelims( ckstr ? ckstr->c_str() : "" );
1786 RETURN->v_string = ckstr;
1787 }
1788
1789
1790
1791
1792 #ifdef AJAY
1793
1794
1795 class ColumnReader
1796 {
1797 public:
1798 ColumnReader();
1799 virtual ~ColumnReader();
1800
1801 bool init( const string & filename, long col );
1802
1803 bool reset() { if( !fin.good() ) return false; where = 0; return true; }
1804 bool seek( long pos ) { if( pos < 0 || pos >= values.size() ) return false; where = pos; return true; }
1805 bool more() { return where < values.size(); }
1806 double curr();
1807 bool next() { if( where < values.size() ) where++; return more(); }
1808 long pos() { return where; }
1809 long size() { return values.size(); }
1810 string name() { return n; }
1811
1812 Chuck_String s;
1813
1814 protected:
1815 bool get_str( string & out );
1816 bool get_double( double & out );
1817
1818 protected:
1819 ifstream fin;
1820 string n;
1821 long column;
1822 long where;
1823 char line[0x1000];
1824 long len;
1825
1826 vector<double> values;
1827 };
1828
1829
1830 ColumnReader::ColumnReader()
1831 {
1832 n = "[NONE]";
1833 column = -1;
1834 where = -1;
1835 len = 0x1000;
1836 }
1837
1838
1839 ColumnReader::~ColumnReader()
1840 {
1841 // close file
1842 if( fin.good() )
1843 fin.close();
1844 }
1845
1846 bool ColumnReader::init( const string & filename, long col )
1847 {
1848 // hmm
1849 if( col < 1 )
1850 {
1851 CK_STDCERR << "column must be greater than 0!!!" << CK_STDENDL;
1852 return false;
1853 }
1854
1855 // open file
1856 fin.open( filename.c_str(), ios::in );
1857 // yes
1858 if( !fin.good() )
1859 {
1860 CK_STDCERR << "ColumnReader: cannot open file: '" << filename << "'..." << CK_STDENDL;
1861 return false;
1862 }
1863
1864 // set column
1865 column = col;
1866
1867 // read first line
1868 if( !fin.getline( line, len ) )
1869 {
1870 CK_STDCERR << "ColumnReader: cannot read first line: '" << filename << "'..." << CK_STDENDL;
1871 return false;
1872 }
1873
1874 // get the name
1875 if( !get_str( n ) )
1876 {
1877 CK_STDCERR << "ColumnReader: cannot seek to column " << col << ": " << filename << "..." << CK_STDENDL;
1878 return false;
1879 }
1880
1881 double v;
1882 long i = 1;
1883 // read values
1884 while( fin.getline( line, len ) )
1885 {
1886 v = 0.0;
1887 // get value
1888 if( !get_double( v ) )
1889 {
1890 CK_STDCERR << "ColumnReader: cannot read column " << v << " on line i: " << n << "..." << CK_STDENDL;
1891 return false;
1892 }
1893
1894 values.push_back( v );
1895 }
1896
1897 // well
1898 if( values.size() == 0 )
1899 {
1900 CK_STDCERR << "ColumnReader: file doesn't not contain data after first line: " << n << "..." << CK_STDENDL;
1901 return false;
1902 }
1903
1904 // set location
1905 where = 0;
1906
1907 s.str = n;
1908
1909 return true;
1910 }
1911
1912 double ColumnReader::curr()
1913 {
1914 if( where >= values.size() )
1915 {
1916 CK_STDCERR << "ColumnReader: trying to read beyond end of file: " << n << "..." << CK_STDENDL;
1917 return 0.0;
1918 }
1919
1920 return values[where];
1921 }
1922
1923 bool ColumnReader::get_double( double & out )
1924 {
1925 assert( column > 0 );
1926 long c = 1;
1927
1928 char * start = line;
1929 char * curr = start;
1930
1931 while( c < column )
1932 {
1933 // move past value
1934 while( *curr && *curr != ',' ) curr++;
1935 // move past ,
1936 while( *curr && *curr == ',' ) curr++;
1937 // check
1938 if( *curr == '\0' )
1939 {
1940 CK_STDCERR << "ColumnReader: cannot find column " << column << ": " << n << CK_STDENDL;
1941 return false;
1942 }
1943
1944 // increment
1945 c++;
1946 // set start
1947 start = curr;
1948 }
1949
1950 // move past value
1951 while( *curr && *curr != ',' ) curr++;
1952 // end
1953 *curr = '\0';
1954
1955 out = atof( start );
1956
1957 return true;
1958 }
1959
1960
1961 bool ColumnReader::get_str( string & out )
1962 {
1963 assert( column > 0 );
1964 long c = 1;
1965
1966 char * start = line;
1967 char * curr = start;
1968
1969 while( c < column )
1970 {
1971 // move past value
1972 while( *curr && *curr != ',' ) curr++;
1973 // move past ,
1974 while( *curr && *curr == ',' ) curr++;
1975 // check
1976 if( *curr == '\0' )
1977 {
1978 CK_STDCERR << "ColumnReader: cannot find column " << column << ": " << n << CK_STDENDL;
1979 return false;
1980 }
1981
1982 // increment
1983 c++;
1984 // set start
1985 start = curr;
1986 }
1987
1988 // move past value
1989 while( *curr && *curr != ',' ) curr++;
1990 // end
1991 *curr = '\0';
1992
1993 out = start;
1994
1995 return true;
1996 }
1997
1998
1999 CK_DLL_CTOR( VCR_ctor )
2000 {
2001 OBJ_MEMBER_INT(SELF, VCR_offset_data) = (t_CKUINT)new ColumnReader;
2002 }
2003
2004 CK_DLL_MFUN( VCR_load )
2005 {
2006 ColumnReader * vcr = (ColumnReader*)OBJ_MEMBER_INT(SELF, VCR_offset_data);
2007 const char * filename = GET_NEXT_STRING(ARGS)->str.c_str();
2008 t_CKINT column = GET_NEXT_INT(ARGS);
2009 RETURN->v_int = vcr->init( filename, column );
2010 }
2011
2012 CK_DLL_MFUN( VCR_reset )
2013 {
2014 ColumnReader * vcr = (ColumnReader*)OBJ_MEMBER_INT(SELF, VCR_offset_data);
2015 RETURN->v_int = vcr->reset();
2016 }
2017
2018 CK_DLL_MFUN( VCR_seek )
2019 {
2020 ColumnReader * vcr = (ColumnReader*)OBJ_MEMBER_INT(SELF, VCR_offset_data);
2021 t_CKINT where = GET_CK_INT(ARGS);
2022 RETURN->v_int = vcr->seek( where );
2023 }
2024
2025 CK_DLL_MFUN( VCR_more )
2026 {
2027 ColumnReader * vcr = (ColumnReader*)OBJ_MEMBER_INT(SELF, VCR_offset_data);
2028 RETURN->v_int = vcr->more();
2029 }
2030
2031 CK_DLL_MFUN( VCR_curr )
2032 {
2033 ColumnReader * vcr = (ColumnReader*)OBJ_MEMBER_INT(SELF, VCR_offset_data);
2034 RETURN->v_float = vcr->curr();
2035 }
2036
2037 CK_DLL_MFUN( VCR_next )
2038 {
2039 ColumnReader * vcr = (ColumnReader*)OBJ_MEMBER_INT(SELF, VCR_offset_data);
2040 RETURN->v_int = vcr->next();
2041 }
2042
2043 CK_DLL_MFUN( VCR_pos )
2044 {
2045 ColumnReader * vcr = (ColumnReader*)OBJ_MEMBER_INT(SELF, VCR_offset_data);
2046 RETURN->v_int = vcr->pos();
2047 }
2048
2049 CK_DLL_MFUN( VCR_size )
2050 {
2051 ColumnReader * vcr = (ColumnReader*)OBJ_MEMBER_INT(SELF, VCR_offset_data);
2052 RETURN->v_int = vcr->size();
2053 }
2054
2055 CK_DLL_MFUN( VCR_name )
2056 {
2057 ColumnReader * vcr = (ColumnReader*)OBJ_MEMBER_INT(SELF, VCR_offset_data);
2058 RETURN->v_string = &(vcr->s);
2059 }
2060
2061
2062 #ifdef __PLATFORM_WINDOWS__
2063
2064
2065 // jeff's cereal
2066 class Serial
2067 {
2068 public:
2069 // one stop bit, 8 bits, no parity
2070 Serial();
2071 ~Serial();
2072
2073 unsigned read( char * buffer, unsigned numberOfBytesToRead );
2074 unsigned write( char * buffer, unsigned numberOfBytesToWrite );
2075
2076 void write( char c );
2077 char read();
2078
2079 unsigned available() const;
2080
2081 t_CKBOOL open( char * port, t_CKUINT baudrate );
2082 void close();
2083
2084 private:
2085 HANDLE serialFile;
2086 };
2087
2088
2089 Serial::Serial( )
2090 {
2091 serialFile = NULL;
2092 }
2093
2094 Serial::~Serial( )
2095 {
2096 close();
2097 }
2098
2099 t_CKBOOL Serial::open( char * port, t_CKUINT baudrate )
2100 {
2101 if( serialFile )
2102 close();
2103
2104 // open port
2105 serialFile = CreateFile( port,
2106 GENERIC_READ | GENERIC_WRITE,
2107 0,
2108 0,
2109 OPEN_EXISTING,
2110 FILE_ATTRIBUTE_NORMAL,
2111 0 );
2112 if( serialFile == INVALID_HANDLE_VALUE )
2113 {
2114 if( GetLastError() == ERROR_FILE_NOT_FOUND )
2115 {
2116 EM_log( CK_LOG_SYSTEM, "error: cannot open serial port '%s'...", port );
2117 }
2118 else
2119 {
2120 EM_log( CK_LOG_SYSTEM, "error opening serial port '%s'...", port );
2121 }
2122
2123 return FALSE;
2124 }
2125
2126 // set params
2127 DCB dcbSerialParams = {0};
2128 dcbSerialParams.DCBlength = sizeof( dcbSerialParams );
2129 if( !GetCommState( serialFile, &dcbSerialParams) )
2130 {
2131 EM_log( CK_LOG_SYSTEM, "error getting serial state..." );
2132 close();
2133 return FALSE;
2134 }
2135
2136 dcbSerialParams.BaudRate = baudrate;
2137 dcbSerialParams.ByteSize = 8;
2138 dcbSerialParams.StopBits = ONESTOPBIT;
2139 dcbSerialParams.Parity = NOPARITY;
2140 if( !SetCommState( serialFile, &dcbSerialParams ) )
2141 {
2142 EM_log( CK_LOG_SYSTEM, "error setting serial state..." );
2143 close();
2144 return FALSE;
2145 }
2146
2147 // SET TIMEOUTS
2148 /*
2149 COMMTIMEOUTS timeouts = {0};
2150 timeouts.ReadIntervalTimeout = 50;
2151 timeouts.ReadTotalTimeoutConstant = 50;
2152 timeouts.ReadTotalTimeoutMultiplier = 10;
2153 timeouts.WriteTotalTimeoutConstant= 50;
2154 timeouts.WriteTotalTimeoutMultiplier = 10;
2155 if( !SetCommTimeouts( serialFile, &timeouts ) )
2156 {
2157 //error occureed. Inform user
2158 }
2159 */
2160
2161 return TRUE;
2162 }
2163
2164 void Serial::close()
2165 {
2166 if( serialFile )
2167 {
2168 CloseHandle( serialFile );
2169 serialFile = NULL;
2170 }
2171 }
2172
2173 void Serial::write( char c )
2174 {
2175 write( &c, 1 );
2176 }
2177
2178 char Serial::read()
2179 {
2180 char c = '\0';
2181 read( &c, 1 );
2182 return c;
2183 }
2184
2185 unsigned Serial::available() const
2186 {
2187 struct _COMSTAT status;
2188 unsigned long etat;
2189 memset( &status, 0, sizeof(status) );
2190
2191 if( serialFile )
2192 {
2193 ClearCommError( serialFile, &etat, &status);
2194 return status.cbInQue;
2195 }
2196
2197 return 0;
2198 }
2199
2200 // try to read numberOfBytesToRead into buffer, return how many bytes read
2201 unsigned Serial::read( char * buffer, unsigned numberOfBytesToRead )
2202 {
2203 DWORD bytesRead = 0;
2204 if( serialFile )
2205 ReadFile( serialFile, buffer, numberOfBytesToRead, &bytesRead, NULL );
2206 return bytesRead;
2207 }
2208
2209 // try to write numberOfBytesToWrite to serial from buffer, return how many bytes written
2210 unsigned Serial::write( char * buffer, unsigned numberOfBytesToWrite )
2211 {
2212 DWORD bytesWritten = 0;
2213 if( serialFile )
2214 WriteFile( serialFile, buffer, numberOfBytesToWrite, &bytesWritten, NULL );
2215 return bytesWritten;
2216 }
2217
2218
2219 // ctor
2220 CK_DLL_CTOR( Cereal_ctor )
2221 {
2222 OBJ_MEMBER_UINT(SELF, Cereal_offset_data) = (t_CKUINT)new Serial;
2223 }
2224
2225 // open
2226 CK_DLL_MFUN( Cereal_open )
2227 {
2228 Serial * s = (Serial *)OBJ_MEMBER_UINT(SELF, Cereal_offset_data);
2229 Chuck_String * str = GET_NEXT_STRING(ARGS);
2230 t_CKINT i = GET_NEXT_INT(ARGS);
2231
2232 // close
2233 s->close();
2234
2235 if( str )
2236 RETURN->v_int = s->open( (char *)str->str.c_str(), i );
2237 else
2238 RETURN->v_int = 0;
2239 }
2240
2241 // close
2242 CK_DLL_MFUN( Cereal_close )
2243 {
2244 Serial * s = (Serial *)OBJ_MEMBER_UINT(SELF, Cereal_offset_data);
2245 s->close();
2246 }
2247
2248 // more
2249 CK_DLL_MFUN( Cereal_more )
2250 {
2251 Serial * s = (Serial *)OBJ_MEMBER_UINT(SELF, Cereal_offset_data);
2252 RETURN->v_int = s->available();
2253 }
2254
2255 // send
2256 CK_DLL_MFUN( Cereal_send )
2257 {
2258 Serial * s = (Serial *)OBJ_MEMBER_UINT(SELF, Cereal_offset_data);
2259 t_CKINT i = GET_NEXT_INT(ARGS);
2260 s->write( i );
2261 RETURN->v_int = i;
2262 }
2263
2264 // recv
2265 CK_DLL_MFUN( Cereal_recv )
2266 {
2267 Serial * s = (Serial *)OBJ_MEMBER_UINT(SELF, Cereal_offset_data);
2268 if( s->available() )
2269 RETURN->v_int = (t_CKINT)s->read();
2270 else
2271 RETURN->v_int = 0;
2272 }
2273
2274 #endif
2275
2276
2277 #endif