hexsha
stringlengths 40
40
| size
int64 5
129k
| content
stringlengths 5
129k
| avg_line_length
float64 4
98.3
| max_line_length
int64 5
660
| alphanum_fraction
float64 0.25
0.98
|
---|---|---|---|---|---|
9da601ea8cee5faa1cff3e2314e279f22d5cf492 | 19,356 | -- Copyright 2013-2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
require 'ljglibs.cdefs.gdk'
require 'ljglibs.cdefs.glib'
require 'ljglibs.cdefs.gio'
require 'ljglibs.cdefs.pango'
ffi.cdef [[
/* standard enums */
typedef enum
{
GTK_STATE_FLAG_NORMAL = 0,
GTK_STATE_FLAG_ACTIVE = 1 << 0,
GTK_STATE_FLAG_PRELIGHT = 1 << 1,
GTK_STATE_FLAG_SELECTED = 1 << 2,
GTK_STATE_FLAG_INSENSITIVE = 1 << 3,
GTK_STATE_FLAG_INCONSISTENT = 1 << 4,
GTK_STATE_FLAG_FOCUSED = 1 << 5
} GtkStateFlags;
typedef enum {
GTK_POS_LEFT,
GTK_POS_RIGHT,
GTK_POS_TOP,
GTK_POS_BOTTOM
} GtkPositionType;
typedef enum {
GTK_ORIENTATION_HORIZONTAL,
GTK_ORIENTATION_VERTICAL
} GtkOrientation;
typedef enum {
GTK_PACK_START,
GTK_PACK_END
} GtkPackType;
typedef enum {
GTK_JUSTIFY_LEFT,
GTK_JUSTIFY_RIGHT,
GTK_JUSTIFY_CENTER,
GTK_JUSTIFY_FILL
} GtkJustification;
typedef enum {
GTK_WIN_POS_NONE,
GTK_WIN_POS_CENTER,
GTK_WIN_POS_MOUSE,
GTK_WIN_POS_CENTER_ALWAYS,
GTK_WIN_POS_CENTER_ON_PARENT
} GtkWindowPosition;
typedef enum {
GTK_ALIGN_FILL,
GTK_ALIGN_START,
GTK_ALIGN_END,
GTK_ALIGN_CENTER,
GTK_ALIGN_BASELINE,
} GtkAlign;
/* GtkCssProvider */
typedef struct {} GtkStyleProvider;
typedef struct {} GtkCssProvider;
GtkCssProvider * gtk_css_provider_new (void);
gboolean gtk_css_provider_load_from_data (GtkCssProvider *css_provider,
const gchar *data,
gssize length,
GError **error);
/* GtkStyleContext */
typedef struct {} GtkStyleContext;
GtkStyleContext * gtk_style_context_new (void);
void gtk_style_context_add_class (GtkStyleContext *context,
const gchar *class_name);
void gtk_style_context_remove_class (GtkStyleContext *context, const gchar *class_name);
void gtk_style_context_get_background_color (GtkStyleContext *context,
GtkStateFlags state,
GdkRGBA *color);
void gtk_style_context_add_provider_for_screen (GdkScreen *screen,
GtkStyleProvider *provider,
guint priority);
/* GtkWidget */
typedef struct {} GtkWidget;
gboolean gtk_widget_in_destruction (GtkWidget *widget);
const gchar * gtk_widget_get_name (GtkWidget *widget);
void gtk_widget_realize (GtkWidget *widget);
void gtk_widget_show (GtkWidget *widget);
void gtk_widget_show_all (GtkWidget *widget);
void gtk_widget_hide (GtkWidget *widget);
GtkStyleContext * gtk_widget_get_style_context (GtkWidget *widget);
void gtk_widget_override_background_color (GtkWidget *widget,
GtkStateFlags state,
const GdkRGBA *color);
void gtk_widget_override_font (GtkWidget *widget,
const PangoFontDescription *font_desc);
GdkWindow * gtk_widget_get_window (GtkWidget *widget);
GdkScreen * gtk_widget_get_screen (GtkWidget *widget);
void gtk_widget_grab_focus (GtkWidget *widget);
void gtk_widget_destroy (GtkWidget *widget);
int gtk_widget_get_allocated_width (GtkWidget *widget);
int gtk_widget_get_allocated_height (GtkWidget *widget);
void gtk_widget_set_size_request (GtkWidget *widget,
gint width,
gint height);
GtkWidget * gtk_widget_get_toplevel (GtkWidget *widget);
gboolean gtk_widget_translate_coordinates (GtkWidget *src_widget,
GtkWidget *dest_widget,
gint src_x,
gint src_y,
gint *dest_x,
gint *dest_y);
PangoContext * gtk_widget_create_pango_context (GtkWidget *widget);
PangoContext * gtk_widget_get_pango_context (GtkWidget *widget);
void gtk_widget_add_events (GtkWidget *widget, gint events);
void gtk_widget_queue_allocate (GtkWidget *widget);
void gtk_widget_queue_draw (GtkWidget *widget);
void gtk_widget_queue_resize (GtkWidget *widget);
void gtk_widget_queue_draw_area (GtkWidget *widget,
gint x,
gint y,
gint width,
gint height);
GdkVisual * gtk_widget_get_visual(GtkWidget *widget);
void gtk_widget_set_visual(GtkWidget *widget, GdkVisual *visual);
/* GtkBin */
typedef struct {} GtkBin;
GtkWidget * gtk_bin_get_child (GtkBin *bin);
/* GtkGrid */
typedef struct {} GtkGrid;
GtkGrid * gtk_grid_new (void);
void gtk_grid_attach (GtkGrid *grid,
GtkWidget *child,
gint left,
gint top,
gint width,
gint height);
void gtk_grid_attach_next_to (GtkGrid *grid,
GtkWidget *child,
GtkWidget *sibling,
GtkPositionType side,
gint width,
gint height);
GtkWidget * gtk_grid_get_child_at (GtkGrid *grid, gint left, gint top);
void gtk_grid_insert_row (GtkGrid *grid, gint position);
void gtk_grid_insert_column (GtkGrid *grid, gint position);
void gtk_grid_remove_row (GtkGrid *grid, gint position);
void gtk_grid_remove_column (GtkGrid *grid, gint position);
void gtk_grid_insert_next_to (GtkGrid *grid,
GtkWidget *sibling,
GtkPositionType side);
/* GtkContainer */
typedef struct {} GtkContainer;
void gtk_container_add (GtkContainer *container, GtkWidget *widget);
void gtk_container_remove (GtkContainer *container, GtkWidget *widget);
GtkWidget * gtk_container_get_focus_child (GtkContainer *container);
void gtk_container_set_focus_child (GtkContainer *container, GtkWidget *child);
GList * gtk_container_get_children (GtkContainer *container);
void gtk_container_child_get (GtkContainer *container,
GtkWidget *child,
const gchar *first_prop_name,
...);
void gtk_container_child_set (GtkContainer *container,
GtkWidget *child,
const gchar *first_prop_name,
...);
/* GtkAlignment */
typedef struct {} GtkAlignment;
GtkAlignment * gtk_alignment_new (gfloat xalign,
gfloat yalign,
gfloat xscale,
gfloat yscale);
void gtk_alignment_set (GtkAlignment *alignment,
gfloat xalign,
gfloat yalign,
gfloat xscale,
gfloat yscale);
void gtk_alignment_get_padding (GtkAlignment *alignment,
guint *padding_top,
guint *padding_bottom,
guint *padding_left,
guint *padding_right);
void gtk_alignment_set_padding (GtkAlignment *alignment,
guint padding_top,
guint padding_bottom,
guint padding_left,
guint padding_right);
/* GtkBox */
typedef struct {} GtkBox;
GtkBox * gtk_box_new (GtkOrientation orientation, gint spacing);
void gtk_box_pack_start (GtkBox *box,
GtkWidget *child,
gboolean expand,
gboolean fill,
guint padding);
void gtk_box_pack_end (GtkBox *box,
GtkWidget *child,
gboolean expand,
gboolean fill,
guint padding);
/* GtkEventBox */
typedef struct {} GtkEventBox;
GtkEventBox * gtk_event_box_new (void);
/* GtkWindow */
typedef enum {
GTK_WINDOW_TOPLEVEL,
GTK_WINDOW_POPUP
} GtkWindowType;
typedef struct {} GtkWindow;
GtkWindow * gtk_window_new (GtkWindowType type);
const gchar * gtk_window_get_title (GtkWindow *window);
void gtk_window_set_title (GtkWindow *window, const gchar *title);
GtkWindowType gtk_window_get_window_type (GtkWindow *window);
void gtk_window_set_default_size (GtkWindow *window,
gint width,
gint height);
void gtk_window_get_size (GtkWindow *window, gint *width, gint *height);
void gtk_window_resize (GtkWindow *window, gint width, gint height);
void gtk_window_move (GtkWindow *window, gint x, gint y);
GtkWidget * gtk_window_get_focus (GtkWindow *window);
void gtk_window_set_focus (GtkWindow *window, GtkWidget *focus);
gboolean gtk_window_set_default_icon_from_file (const gchar *filename,
GError **err);
void gtk_window_fullscreen (GtkWindow *window);
void gtk_window_unfullscreen (GtkWindow *window);
void gtk_window_maximize (GtkWindow *window);
void gtk_window_unmaximize (GtkWindow *window);
/* GtkOffscreenWindow */
typedef struct {} GtkOffscreenWindow;
GtkOffscreenWindow * gtk_offscreen_window_new (void);
/* GtkApplication */
typedef struct {} GtkApplication;
GtkApplication * gtk_application_new (const gchar *application_id,
GApplicationFlags flags);
void gtk_application_add_window (GtkApplication *application, GtkWindow *window);
void gtk_application_remove_window (GtkApplication *application, GtkWindow *window);
/* GtkMisc */
typedef struct {} GtkMisc;
/* GtkLabel */
typedef struct {} GtkLabel;
GtkLabel * gtk_label_new (const gchar *str);
const gchar * gtk_label_get_text (GtkLabel *label);
void gtk_label_set_text (GtkLabel *label, const gchar *str);
/* GtkEntry */
typedef struct {} GtkEntry;
GtkEntry * gtk_entry_new (void);
/*** Clipboard & selections ***/
/* GtkTargetEntry */
typedef struct {} GtkTargetEntry;
typedef enum {
GTK_TARGET_SAME_APP = 1 << 0,
GTK_TARGET_SAME_WIDGET = 1 << 1,
GTK_TARGET_OTHER_APP = 1 << 2,
GTK_TARGET_OTHER_WIDGET = 1 << 3
} GtkTargetFlags;
GtkTargetEntry * gtk_target_entry_new (const gchar *target,
guint flags,
guint info);
void gtk_target_entry_free (GtkTargetEntry *data);
/* GtkTargetList */
typedef struct {} GtkTargetList;
GtkTargetList * gtk_target_list_new (const GtkTargetEntry *targets,
guint ntargets);
void gtk_target_list_unref (GtkTargetList *list);
void gtk_target_list_add (GtkTargetList *list,
GdkAtom target,
guint flags,
guint info);
/* GtkTargetTable */
GtkTargetEntry * gtk_target_table_new_from_list (GtkTargetList *list,
gint *n_targets);
void gtk_target_table_free (GtkTargetEntry *targets,
gint n_targets);
/* GtkSelectionData */
typedef struct {} GtkSelectionData;
gboolean gtk_selection_data_set_text (GtkSelectionData *selection_data,
const gchar *str,
gint len);
typedef struct {} GtkClipboard;
typedef GVCallback3 GtkClipboardTextReceivedFunc;
typedef GVCallback4 GtkClipboardGetFunc;
typedef GVCallback2 GtkClipboardClearFunc;
GtkClipboard * gtk_clipboard_get (GdkAtom selection);
gchar * gtk_clipboard_wait_for_text (GtkClipboard *clipboard);
void gtk_clipboard_request_text (GtkClipboard *clipboard,
GtkClipboardTextReceivedFunc callback,
gpointer user_data);
void gtk_clipboard_clear (GtkClipboard *clipboard);
void gtk_clipboard_set_text (GtkClipboard *clipboard,
const gchar *text,
gint len);
void gtk_clipboard_store (GtkClipboard *clipboard);
void gtk_clipboard_set_can_store (GtkClipboard *clipboard,
const GtkTargetEntry *targets,
gint n_targets);
gboolean gtk_clipboard_set_with_data (GtkClipboard *clipboard,
const GtkTargetEntry *targets,
guint n_targets,
GtkClipboardGetFunc get_func,
GtkClipboardClearFunc clear_func,
gpointer user_data);
/* GtkSpinner */
typedef struct {} GtkSpinner;
GtkSpinner * gtk_spinner_new (void);
void gtk_spinner_start (GtkSpinner *spinner);
void gtk_spinner_stop (GtkSpinner *spinner);
/* GtkDrawingArea */
typedef struct {} GtkDrawingArea;
GtkDrawingArea * gtk_drawing_area_new (void);
/* GtkAdjustment */
typedef struct {} GtkAdjustment;
GtkAdjustment * gtk_adjustment_new (gdouble value,
gdouble lower,
gdouble upper,
gdouble step_increment,
gdouble page_increment,
gdouble page_size);
gdouble gtk_adjustment_get_value (GtkAdjustment *adjustment);
void gtk_adjustment_set_value (GtkAdjustment *adjustment,
gdouble value);
void gtk_adjustment_clamp_page (GtkAdjustment *adjustment,
gdouble lower,
gdouble upper);
void gtk_adjustment_changed (GtkAdjustment *adjustment);
void gtk_adjustment_value_changed (GtkAdjustment *adjustment);
void gtk_adjustment_configure (GtkAdjustment *adjustment,
gdouble value,
gdouble lower,
gdouble upper,
gdouble step_increment,
gdouble page_increment,
gdouble page_size);
gdouble gtk_adjustment_get_lower (GtkAdjustment *adjustment);
gdouble gtk_adjustment_get_page_increment (GtkAdjustment *adjustment);
gdouble gtk_adjustment_get_page_size (GtkAdjustment *adjustment);
gdouble gtk_adjustment_get_step_increment (GtkAdjustment *adjustment);
gdouble gtk_adjustment_get_minimum_increment (GtkAdjustment *adjustment);
gdouble gtk_adjustment_get_upper (GtkAdjustment *adjustment);
void gtk_adjustment_set_lower (GtkAdjustment *adjustment,
gdouble lower);
void gtk_adjustment_set_page_increment (GtkAdjustment *adjustment,
gdouble page_increment);
void gtk_adjustment_set_page_size (GtkAdjustment *adjustment,
gdouble page_size);
void gtk_adjustment_set_step_increment (GtkAdjustment *adjustment,
gdouble step_increment);
void gtk_adjustment_set_upper (GtkAdjustment *adjustment,
gdouble upper);
/* GtkScrolledWindow */
typedef struct {} GtkScrolledWindow;
GtkScrolledWindow * gtk_scrolled_window_new (GtkAdjustment *hadjustment,
GtkAdjustment *vadjustment);
GtkAdjustment *
gtk_scrolled_window_get_hadjustment (GtkScrolledWindow *scrolled_window);
void
gtk_scrolled_window_set_hadjustment (GtkScrolledWindow *scrolled_window,
GtkAdjustment *hadjustment);
GtkAdjustment *
gtk_scrolled_window_get_vadjustment (GtkScrolledWindow *scrolled_window);
void
gtk_scrolled_window_set_vadjustment (GtkScrolledWindow *scrolled_window,
GtkAdjustment *vadjustment);
/* GtkRange */
typedef struct {} GtkRange;
/* GtkScrollbar */
typedef struct {} GtkScrollbar;
GtkScrollbar * gtk_scrollbar_new (GtkOrientation orientation,
GtkAdjustment *adjustment);
/* GtkViewport */
typedef struct {} GtkViewport;
GtkViewport * gtk_viewport_new (GtkAdjustment *hadjustment,
GtkAdjustment *vadjustment);
/* GtkSettings */
typedef struct {} GtkSettings;
GtkSettings * gtk_settings_get_default (void);
GtkSettings * gtk_settings_get_for_screen (GdkScreen *screen);
/* GtkIMContext */
typedef struct {} GtkIMContext;
void gtk_im_context_set_client_window (GtkIMContext *context,
GdkWindow *window);
void gtk_im_context_get_preedit_string (GtkIMContext *context,
gchar **str,
PangoAttrList **attrs,
gint *cursor_pos);
gboolean gtk_im_context_filter_keypress (GtkIMContext *context,
GdkEventKey *event);
void gtk_im_context_focus_in (GtkIMContext *context);
void gtk_im_context_focus_out (GtkIMContext *context);
void gtk_im_context_reset (GtkIMContext *context);
void gtk_im_context_set_cursor_location (GtkIMContext *context,
const GdkRectangle *area);
void gtk_im_context_set_use_preedit (GtkIMContext *context,
gboolean use_preedit);
void gtk_im_context_set_surrounding (GtkIMContext *context,
const gchar *text,
gint len,
gint cursor_index);
gboolean gtk_im_context_get_surrounding (GtkIMContext *context,
gchar **text,
gint *cursor_index);
gboolean gtk_im_context_delete_surrounding (GtkIMContext *context,
gint offset,
gint n_chars);
typedef struct {} GtkIMContextSimple;
GtkIMContextSimple * gtk_im_context_simple_new (void);
/* Misc */
gboolean gtk_cairo_should_draw_window (cairo_t *cr,
GdkWindow *window);
guint gtk_get_major_version (void);
guint gtk_get_minor_version (void);
guint gtk_get_micro_version (void);
const gchar * gtk_check_version (guint required_major,
guint required_minor,
guint required_micro);
]]
| 39.502041 | 90 | 0.589585 |
d8d1f80336424104a6e5111cbedc2a38c3e79d35 | 4,382 | -- Copyright 2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import bundle, mode, Buffer from howl
import Editor from howl.ui
describe 'C mode', ->
local m
local buffer, editor, lines
setup ->
bundle.load_by_name 'c'
m = mode.by_name 'c'
teardown -> bundle.unload 'c'
before_each ->
buffer = Buffer m
editor = Editor buffer
lines = buffer.lines
describe 'structure()', ->
assert_lines = (expected, actual) ->
assert.same ["#{l.nr}: #{l}" for l in *expected], ["#{l.nr}: #{l}" for l in *actual]
it 'includes function declarations in the structure', ->
buffer.text = trimmed_text [[
int example_line_1 (const char *s) {
}
void *
broken_up_line_5 (int32_t foo)
{
}
void broken_args_line_9(int first,
void *second) {
}
int broken_again_line_13(int first,
char continue)
{
}
]]
assert_lines {
lines[1],
lines[5],
lines[9],
lines[13]
}, m\structure editor
it 'includes struct declarations in the structure', ->
buffer.text = trimmed_text [[
struct Foo_Line1 {
int bar;
}
struct Bar_Line4
{
}
]]
assert_lines {
lines[1],
lines[4],
}, m\structure editor
it 'includes class declarations in the structure', ->
buffer.text = trimmed_text [[
class Foo_Line1 {
}
class Bar_Line3
{
}
class Zed_Line6 : Base {
}
]]
assert_lines {
lines[1],
lines[3],
lines[6],
}, m\structure editor
it 'includes namespaces in the structure', ->
buffer.text = trimmed_text [[
namespace Foo {
namespace Bar {
}
}
]]
assert_lines {
lines[1],
lines[2],
}, m\structure editor
it 'includes C++ const functions in the structure', ->
buffer.text = trimmed_text [[
int example_line_1 (const char *s) const {
}
void *
broken_up_line_5 (int32_t foo) const
{
}
void broken_args_line_9(int first,
void *second) const {
}
int broken_again_line_13(int first,
char continue) const
{
}
]]
assert_lines {
lines[1],
lines[5],
lines[9],
lines[13]
}, m\structure editor
it 'handles C++ class constructs', ->
buffer.text = trimmed_text [[
class Test
{
private:
int data1;
public:
void function1() {
data1 = 2;
}
float function2()
{
return data1;
}
};
]]
assert_lines {
lines[1],
lines[3],
lines[6],
lines[7],
lines[11],
}, m\structure editor
it 'handles C++ class constructs', ->
buffer.text = trimmed_text [[
Foo::Foo(QObject *parent) :
QObject(parent) {
}
]]
assert_lines {
lines[1],
}, m\structure editor
it 'handles trailing comments in various places', ->
buffer.text = trimmed_text [[
int example_line_1 (const char *s) { /* wat wat */
}
void *
broken_up_line_5 (int32_t foo) // c++ wat
{ /* close me! */
}
void broken_args_line_9(int first, // first wat
void *second) { /* second wat */
}
int broken_again_line_13(int first, // ugh
char continue) // blargh
{ // cloooooseee!
}
]]
assert_lines {
lines[1],
lines[5],
lines[9],
lines[13]
}, m\structure editor
it 'is not confused by irrelevant stuff', ->
buffer.text = trimmed_text [[
#if DEF
int bar(void *other_p) {
void *p = (struct Bar *)other_p;
try {
if (cond) {
}
} catch() {
}
if (call(one,
two)) {
}
}
#endif
]]
assert_lines {
lines[2],
}, m\structure editor
| 20.866667 | 90 | 0.479005 |
73a0948d7ccf1169d885e44e78685743ced38cf9 | 476 | List = zb2rhn9hxhbQp3UYpciYJSJzePFMibeWZaQXJsDV3wGkLmAXX
val = (List "val")
end = (List "end")
a = (val 1 (val 2 (val 3 (val 4 end))))
b = (val 5 (val 6 (val 7 (val 8 end))))
{
range: (List "range" 0 4)
sum: (List "sum" a)
filter: (List "filter" x => (gtn x 2) a)
concat: (List "concat" a b)
zipWith: (List "zipWith" (add) a b)
sum: (List "sum" a)
mul: (List "mul" a)
reverse: (List "reverse" a)
len: (List "len" a)
match: (List "match" a h => t => h 0)
}
| 26.444444 | 56 | 0.577731 |
033eb8f0688010f43ba9e031354a6b65349ce1ad | 3,862 |
import appfile from require "pl.app"
import makepath from require "pl.dir"
import dirname from require "pl.path"
import concat from table
colors = require "ansicolors"
pretty = require "pl.pretty"
multipart = require "moonrocks.multipart"
local encode_query_string
class Api
server: "luarocks.org"
version: "1"
new: (flags={}, name="config") =>
@config_fname = appfile(name) .. ".lua"
@server = flags.server
@debug = flags.debug
@config = setmetatable {}, __index: @
@read!
os.exit 1 unless @config.key or @login!
login: =>
print colors "%{bright yellow}You need an API key to continue."
print "Navigate to https://#{@config.server}/settings to get a key."
while true
io.stdout\write "Paste API key: "
key = io.stdin\read "*l"
break if not key or key == ""
@config.key = key
res = @raw_method "status"
if errors = res.errors
print colors "%{bright yellow}Server says:%{reset} #{errors[1]}"
else
break
if @config.key
@write!
true
else
print colors "%{bright red}Aborting"
false
check_version: =>
tool_version = require "moonrocks.version"
unless @_server_tool_version
res = @request "https://#{@config.server}/api/tool_version", current: tool_version
@_server_tool_version = assert res.version, "failed to fetch tool version"
if res.force_update
print colors "%{bright red}Error:%{reset} Your moonrocks is too out of date to continue (need #{res.version}, have #{tool_version})"
os.exit 1
if res.version != tool_version
print colors "%{bright yellow}Warning:%{reset} Your moonrocks is out of date (latest #{res.version}, have #{tool_version})"
method: (...) =>
with res = @raw_method ...
if res.errors
if res.errors[1] == "Invalid key"
res.errors[1] ..= " (run `moonrocks login` to change)"
msg = table.concat res.errors, ", "
error "API Failed: " .. msg
raw_method: (path, ...) =>
@check_version!
url = "https://#{@config.server}/api/#{@config.version}/#{@config.key}/#{path}"
@request url, ...
request: do
http = require "socket.http"
ltn12 = require "ltn12"
json = require "cjson"
(url, params, post_params=nil) =>
assert @config.key, "Must have API key before performing any actions"
local body
headers = {}
if params and next(params)
url ..= "?" .. encode_query_string params
if post_params
body, boundary = multipart.encode post_params
headers["Content-length"] = #body
headers["Content-type"] = "multipart/form-data; boundary=#{boundary}"
method = post_params and "POST" or "GET"
if @debug
io.stdout\write colors "%{yellow}[#{method}]%{reset} #{url} ... "
out = {}
_, status = http.request {
:url, :headers, :method
sink: ltn12.sink.table out
source: body and ltn12.source.string body
}
if @debug
print colors "%{green}#{status}"
assert status == 200, "API returned #{status} - #{url}"
json.decode concat out
read: =>
if f = io.open @config_fname, "r"
content = f\read "*a"
f\close!
config = pretty.read content
if config
for k,v in pairs config
@config[k] = v
write: =>
makepath dirname @config_fname
with io.open @config_fname, "w"
\write pretty.write @config
\close!
true
encode_query_string = do
url = require "socket.url"
(t, sep="&") ->
i = 0
buf = {}
for k,v in pairs t
if type(k) == "number" and type(v) == "table"
{k,v} = v
buf[i + 1] = url.escape k
buf[i + 2] = "="
buf[i + 3] = url.escape v
buf[i + 4] = sep
i += 4
buf[i] = nil
concat buf
{ :Api }
| 25.576159 | 140 | 0.590109 |
37f482661689d0bf580d82d025cbbdae57d5aae0 | 3,275 | import PropertyObject from howl.aux.moon
describe 'PropertyObject', ->
it 'allows specifying a getter and setter using get and set', ->
value = 'hello'
class Test extends PropertyObject
@property foo:
get: => value
set: (v) => value = v
o = Test!
assert.equal o.foo, 'hello'
o.foo = 'world'
assert.equal o.foo, 'world'
it 'assigning a property with only a getter raises a read-only error', ->
class Test extends PropertyObject
@property foo: get: => 'foo'
o = Test!
assert.raises 'read%-only', -> o.foo = 'bar'
assert.equal o.foo, 'foo'
it 'two objects of the same class have the same metatable', ->
class Test extends PropertyObject
@property foo: get: => 'foo'
assert.equal getmetatable(Test!), getmetatable(Test!)
it 'two objects of different classes have different metatables', ->
class Test1 extends PropertyObject
@property foo: get: => 'foo'
class Test2 extends PropertyObject
@property foo: get: => 'foo'
assert.is_not.equal getmetatable(Test1!), getmetatable(Test2!)
it 'meta methods are defined via the @meta function', ->
class Test extends PropertyObject
@meta __add: (o1, o2) -> 3 + o2
assert.equal 5, Test! + 2
describe 'inheritance', ->
it 'properties defined in any part of the chain works', ->
class Parent extends PropertyObject
new: (foo) =>
super!
@_foo = foo
@property foo:
get: => @_foo or 'wrong'
set: (v) => @_foo = v .. @foo
class SubClass extends Parent
new: (text) => super text
@property bar:
get: => @_bar
set: (v) => @_bar = v
parent = Parent 'parent'
assert.equal parent.foo, 'parent'
parent.foo = 'hello '
assert.equal parent.foo, 'hello parent'
s = SubClass 'editor'
assert.equal s.foo, 'editor'
s.foo = 'hello'
assert.equal s.foo, 'helloeditor'
s.bar = 'world'
assert.equal s.bar, 'world'
it 'overriding methods work', ->
class Parent extends PropertyObject
foo: => 'parent'
class SubClass extends Parent
foo: => 'sub'
assert.equal SubClass!\foo!, 'sub'
it 'write to read-only properties are detected', ->
class Parent extends PropertyObject
@property foo: get: => 1
class SubClass extends Parent
true
assert.raises 'read%-only', -> SubClass!.foo = 'bar'
it 'meta methods defined in any part of the chain works', ->
class Parent extends PropertyObject
@meta __add: (o1, o2) -> 3 + o2
class SubClass extends Parent
@meta __div: (o1, o2) -> 'div'
o = SubClass!
assert.equal 5, o + 2
assert.equal 'div', o / 2
describe 'delegation', ->
it 'allows delegating to a default object passed in the constructor', ->
target = {
foo: 'bar'
func: spy.new -> 'return'
}
class Delegating extends PropertyObject
new: => super target
@property frob: get: => 'nic'
o = Delegating!
assert.equals 'nic', o.frob
assert.equals 'bar', o.foo
assert.equals 'return', o\func!
assert.spy(target.func).was.called_with target
| 27.291667 | 76 | 0.596031 |
9516c8bc58f9faa25e7090f0b7824a0d6d921d6a | 3,186 |
import concat from table
unpack = unpack or table.unpack
type = type
moon =
is_object: (value) -> -- is a moonscript object
type(value) == "table" and value.__class
is_a: (thing, t) ->
return false unless type(thing) == "table"
cls = thing.__class
while cls
if cls == t
return true
cls = cls.__parent
false
type: (value) -> -- the moonscript object class
base_type = type value
if base_type == "table"
cls = value.__class
return cls if cls
base_type
-- convet position in text to line number
pos_to_line = (str, pos) ->
line = 1
for _ in str\sub(1, pos)\gmatch("\n")
line += 1
line
trim = (str) ->
str\match "^%s*(.-)%s*$"
get_line = (str, line_num) ->
-- todo: this returns an extra blank line at the end
for line in str\gmatch "([^\n]*)\n?"
return line if line_num == 1
line_num -= 1
get_closest_line = (str, line_num) ->
line = get_line str, line_num
if (not line or trim(line) == "") and line_num > 1
get_closest_line(str, line_num - 1)
else
line, line_num
split = (str, delim) ->
return {} if str == ""
str ..= delim
[m for m in str\gmatch("(.-)"..delim)]
dump = (what) ->
seen = {}
_dump = (what, depth=0) ->
t = type what
if t == "string"
'"'..what..'"\n'
elseif t == "table"
if seen[what]
return "recursion("..tostring(what) ..")...\n"
seen[what] = true
depth += 1
lines = for k,v in pairs what
(" ")\rep(depth*4).."["..tostring(k).."] = ".._dump(v, depth)
seen[what] = false
class_name = if what.__class
"<#{what.__class.__name}>"
"#{class_name or ""}{\n" .. concat(lines) .. (" ")\rep((depth - 1)*4) .. "}\n"
else
tostring(what).."\n"
_dump what
debug_posmap = (posmap, moon_code, lua_code) ->
tuples = [{k, v} for k, v in pairs posmap]
table.sort tuples, (a, b) -> a[1] < b[1]
lines = for pair in *tuples
lua_line, pos = unpack pair
moon_line = pos_to_line moon_code, pos
lua_text = get_line lua_code, lua_line
moon_text = get_closest_line moon_code, moon_line
"#{pos}\t #{lua_line}:[ #{trim lua_text} ] >> #{moon_line}:[ #{trim moon_text} ]"
concat(lines, "\n")
setfenv = setfenv or (fn, env) ->
local name
i = 1
while true
name = debug.getupvalue fn, i
break if not name or name == "_ENV"
i += 1
if name
debug.upvaluejoin fn, i, (-> env), 1
fn
getfenv = getfenv or (fn) ->
i = 1
while true
name, val = debug.getupvalue fn, i
break unless name
return val if name == "_ENV"
i += 1
nil
-- moves the last argument to the front if it's a table, or returns empty table
-- inserted to the front of args
get_options = (...) ->
count = select "#", ...
opts = select count, ...
if type(opts) == "table"
opts, unpack {...}, nil, count - 1
else
{}, ...
safe_module = (name, tbl) ->
setmetatable tbl, {
__index: (key) =>
error "Attempted to import non-existent `#{key}` from #{name}"
}
{
:moon, :pos_to_line, :get_closest_line, :get_line, :trim, :split, :dump,
:debug_posmap, :getfenv, :setfenv, :get_options, :unpack, :safe_module
}
| 22.595745 | 85 | 0.580038 |
6c560aa02fe2518fd8c2f7bd20cbdc60a0a83682 | 410 | discount = require "discount"
lapis = require "lapis"
oleg = require "lib/oleg"
class Projects extends lapis.Application
[resume: "/resume"]: =>
@title = "Resume"
@page = "resume"
@doc = oleg.cache "caches", "resume", ->
local data
with io.open "static/resume/min/resume.md", "r"
data = \read "*a"
discount data, "toc", "nopants", "autolink"
render: true
| 22.777778 | 53 | 0.592683 |
0bb5fe248dc78017b375d19ee2cb37879ff323e7 | 575 | import perform, handle, Effect from require 'mae'
Print = Effect 'print'
Readline = Effect 'readline'
handle {
->
perform Print 'before'
handle {
->
val = perform Readline
perform Print val
handle {
->
perform Print val
[Print]: (v) ->
perform Print 'transformed '..v
}
[Readline]: ->
'not really IO'
}
perform Print 'after'
val = perform Readline -- crashes, nothing handles Readline here
[Print]: (v) ->
print v
}
-- prints:
-- before
-- not really IO
-- transformed not really IO
-- after
-- [crashes]
| 15.131579 | 66 | 0.603478 |
52c0bcb2d0e522576d4df00a4fb5bd124fea1a7e | 458 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import MenuPopup from howl.ui
describe 'MenuPopup', ->
context 'resource management', ->
items = {'one', 'two', 'three'}
it 'popups are collected as they should', ->
o = MenuPopup items, (->)
list = setmetatable {o}, __mode: 'v'
o\destroy!
o = nil
collectgarbage!
assert.is_nil list[1]
| 26.941176 | 79 | 0.637555 |
b3793e002349166955e0803e4e5d32d58a2e3649 | 8 | "1.0.6"
| 4 | 7 | 0.375 |
f5c46e4508bd5138a3c277623a785317c49c0f8d | 51,775 |
-- Copyright (C) 2017-2020 DBotThePony
-- 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.
ENABLE_FULLBRIGHT = CreateConVar('ppm2_editor_fullbright', '1', {FCVAR_ARCHIVE}, 'Disable lighting in editor')
ADVANCED_MODE = CreateConVar('ppm2_editor_advanced', '0', {FCVAR_ARCHIVE}, 'Show all options. Keep in mind Editor3 acts different with this option.')
inRadius = (val, min, max) -> val >= min and val <= max
inBox = (pointX, pointY, x, y, w, h) -> inRadius(pointX, x - w, x + w) and inRadius(pointY, y - h, y + h)
-- loal
surface.CreateFont('PPM2BackButton', {
font: 'Roboto'
size: ScreenScale(24)\floor()
weight: 600
})
surface.CreateFont('PPM2EditorPanelHeaderText', {
font: 'PT Serif'
size: ScreenScale(16)\floor()
weight: 600
})
import HUDCommons from DLib
drawCrosshair = (x, y, radius = ScreenScale(10), arcColor = Color(255, 255, 255), boxesColor = Color(200, 200, 200)) ->
x -= radius / 2
y -= radius / 2
HUDCommons.DrawCircleHollow(x, y, radius, radius * 2, radius * 0.2, arcColor)
h = radius * 0.1
w = radius * 0.6
surface.SetDrawColor(boxesColor)
surface.DrawRect(x - w / 2, y + radius / 2 - h / 2, w, h)
surface.DrawRect(x + radius / 2 + w / 2, y + radius / 2 - h / 2, w, h)
surface.DrawRect(x + radius / 2 - h / 2, y - w / 2, h, w)
surface.DrawRect(x + radius / 2 - h / 2, y + radius / 2 + w / 3, h, w)
MODEL_BOX_PANEL = {
SEQUENCE_STAND: 22
PONY_VEC_Z: 64 * .7
SEQUENCES: {
'Standing': 22
'Moving': 316
'Walking': 232
'Sit': 202
'Swim': 370
'Run': 328
'Crouch walk': 286
'Crouch': 76
'Jump': 160
}
Init: =>
@animRate = 1
@seq = @SEQUENCE_STAND
@hold = false
@holdOnPoint = false
@holdRightClick = false
@canHold = true
@lastTick = RealTimeL()
@startAnimStart = RealTimeL() + 2
@startAnimEnd = RealTimeL() + 8
@startAnimStart2 = RealTimeL() + 2.5
@startAnimEnd2 = RealTimeL() + 9
@menuPanelsCache = {}
@updatePanels = {}
@holdLast = 0
@mouseX, @mouseY = 0, 0
@crosshairCircleInactive = Color(150, 150, 150)
@crosshairBoxInactive = Color(100, 100, 100)
@crosshairCircleHovered = Color(137, 195, 196)
@crosshairBoxHovered = Color(200, 200, 200)
@crosshairCircleSelected = Color(0, 0, 0, 0)
@crosshairBoxSelected = Color(211, 255, 192)
@angle = Angle(-10, -30, 0)
@distToPony = 90
@ldistToPony = 90
@trackBone = -1
@trackBoneName = 'LrigSpine2'
@trackAttach = -1
@trackAttachName = ''
@shouldAutoTrack = true
@autoTrackPos = Vector(0, 0, 0)
@lautoTrackPos = Vector(0, 0, 0)
@fixedDistanceToPony = 100
@lfixedDistanceToPony = 100
@vectorPos = Vector(@fixedDistanceToPony, 0, 0)
@VectorPos = Vector(@fixedDistanceToPony, 0, 0)
@targetPos = Vector(0, 0, @PONY_VEC_Z * .7)
@ldrawAngle = Angle()
@SetCursor('none')
@SetMouseInputEnabled(true)
@buildingModel = ClientsideModel('models/ppm/ppm2_stage.mdl', RENDERGROUP_OTHER)
@buildingModel\SetNoDraw(true)
@buildingModel\SetModelScale(0.9)
with @seqButton = vgui.Create('DComboBox', @)
\SetSize(120, 20)
\SetValue('Standing')
\AddChoice(choice, num) for choice, num in pairs @SEQUENCES
.OnSelect = (pnl = box, index = 1, value = '', data = value) -> @SetSequence(data)
UpdateAttachsIDs: =>
@trackBone = @model\LookupBone(@trackBoneName) or -1 if @trackBoneName ~= ''
@trackAttach = @model\LookupAttachment(@trackAttachName) or -1 if @trackAttachName ~= ''
GetTrackedPosition: =>
return @lautoTrackPos if @shouldAutoTrack
return @targetPos
UpdateSeqButtonsPos: (inMenus = @InMenu2()) =>
if inMenus
bX, bY = @GetSize()
bW, bH = 0, 0
bX -= ScreenScale(6)
bY = ScreenScale(4)
bX, bY = @backButton\GetPos() if IsValid(@backButton)
bW, bH = @backButton\GetSize() if IsValid(@backButton)
w, h = @GetSize()
W, H = @seqButton\GetSize()
@seqButton\SetPos(w - ScreenScale(6) - W, bY + bH + ScreenScale(8))
W, H = @emotesPanel\GetSize()
@emotesPanel\SetPos(w - ScreenScale(6) - W, bY + bH + ScreenScale(8) + 30)
else
@seqButton\SetPos(10, 10)
@emotesPanel\SetPos(10, 40)
PerformLayout: (w = 0, h = 0) =>
if IsValid(@lastVisibleMenu) and @lastVisibleMenu\IsVisible()
@UpdateSeqButtonsPos(true)
x, y = @GetPos()
W, H = @GetSize()
width = ScreenScale(120)
with @lastVisibleMenu
\SetPos(x, y)
\SetSize(width, H)
else
@UpdateSeqButtonsPos(@InMenu2())
OnMousePressed: (code = MOUSE_LEFT) =>
if code == MOUSE_LEFT and @canHold
if not @selectPoint
@hold = true
@SetCursor('sizeall')
@holdLast = RealTimeL() + .1
@mouseX, @mouseY = gui.MousePos()
else
@holdOnPoint = true
@SetCursor('crosshair')
elseif code == MOUSE_RIGHT
@holdRightClick = true
OnMouseReleased: (code = MOUSE_LEFT) =>
if code == MOUSE_LEFT and @canHold
@holdOnPoint = false
@SetCursor('none')
if not @selectPoint
@hold = false
else
@PushMenu(@selectPoint.linkTable)
elseif code == MOUSE_RIGHT
@holdRightClick = false
SetController: (val) => @controller = val
OnMouseWheeled: (wheelDelta = 0) =>
if @canHold
@distToPony = math.clamp(@distToPony - wheelDelta * 10, 20, 150)
GetModel: => @model
GetSequence: => @seq
GetAnimRate: => @animRate
SetAnimRate: (val = 1) => @animRate = val
SetSequence: (val = @SEQUENCE_STAND) =>
@seq = val
@model\SetSequence(@seq) if IsValid(@model)
ResetSequence: => @SetSequence(@SEQUENCE_STAND)
ResetSeq: => @SetSequence(@SEQUENCE_STAND)
GetParentTarget: => @parentTarget
SetParentTarget: (val) => @parentTarget = val
DoUpdate: => panel\DoUpdate() for _, panel in ipairs @updatePanels when panel\IsValid()
UpdateMenu: (menu, goingToDelete = false) =>
if @InMenu2() and not goingToDelete
x, y = @GetPos()
frame = @GetParentTarget() or @GetParent() or @
W, H = @GetSize()
width = ScreenScale(120)
if not @menuPanelsCache[menu.id]
if menu.menus
local targetPanel
with settingsPanel = vgui.Create('DPropertySheet', frame)
\SetPos(x, y)
\SetSize(width, H)
@menuPanelsCache[menu.id] = settingsPanel
for menuName, menuPopulate in pairs menu.menus
with menuPanel = vgui.Create('PPM2SettingsBase', settingsPanel)
@saves = settingsPanel if menu.id == 'saves'
table.insert(@updatePanels, menuPanel)
.frame = @frame
with vgui.Create('DLabel', menuPanel)
\Dock(TOP)
\SetFont('PPM2EditorPanelHeaderText')
\SetText(menuName)
\SizeToContents()
settingsPanel\AddSheet(menuName, menuPanel)
\SetTargetData(@controllerData)
@saves = menuPanel if menuName == 'gui.ppm2.editor.tabs.files'
@savesOld = menuPanel if menuName == 'gui.ppm2.editor.tabs.old_files'
\Dock(FILL)
.Populate = menuPopulate
targetPanel = menuPanel if menu.selectmenu == menuName
-- god i hate gmod
if targetPanel
for _, item in ipairs \GetItems()
if item.Panel == targetPanel
\SetActiveTab(item.Tab)
else
with settingsPanel = vgui.Create('PPM2SettingsBase', frame)
@menuPanelsCache[menu.id] = settingsPanel
@saves = settingsPanel if menu.id == 'saves'
.frame = @frame
table.insert(@updatePanels, settingsPanel)
with vgui.Create('DLabel', settingsPanel)
\Dock(TOP)
\SetFont('PPM2EditorPanelHeaderText')
\SetText(menu.name or '<unknown>')
\SizeToContents()
\SetPos(x, y)
\SetSize(width, H)
\SetTargetData(@controllerData)
.Populate = menu.populate
with @menuPanelsCache[menu.id]
\SetVisible(true)
\SetPos(x, y)
\SetSize(width, H)
@lastVisibleMenu = @menuPanelsCache[menu.id]
@UpdateSeqButtonsPos(true)
elseif IsValid(@menuPanelsCache[menu.id])
@menuPanelsCache[menu.id]\SetVisible(false)
@seqButton\SetPos(10, 10)
@emotesPanel\SetPos(10, 40)
PushMenu: (menu) =>
@UpdateMenu(@stack[#@stack], true)
table.insert(@stack, menu)
if not IsValid(@backButton)
with @backButton = vgui.Create('DButton', @)
x, y = @GetPos()
w, h = @GetSize()
\SetText('↩')
\SetFont('PPM2BackButton')
\SizeToContents()
W, H = \GetSize()
W += ScreenScale(8)
\SetSize(W, H)
\SetPos(w - ScreenScale(6) - W, ScreenScale(4))
.DoClick = -> @PopMenu()
@UpdateMenu(menu)
@fixedDistanceToPony = menu.dist
@angle = Angle(menu.defang)
@distToPony = 90
return @
PopMenu: =>
assert(#@stack > 1, 'invalid stack size to pop from')
_menu = @stack[#@stack]
table.remove(@stack)
@UpdateMenu(_menu, true)
@backButton\Remove() if #@stack == 1 and IsValid(@backButton)
menu = @stack[#@stack]
@UpdateMenu(menu)
@fixedDistanceToPony = menu.dist
@angle = Angle(menu.defang)
@distToPony = 90
return @
CurrentMenu: => @stack[#@stack]
InRoot: => #@stack == 1
InSelection: => @CurrentMenu().type == 'level'
InMenu: => @CurrentMenu().type == 'menu'
InMenu2: => @CurrentMenu().type == 'menu' or @CurrentMenu().populate or @CurrentMenu().menus
ResetModel: (ponydata, model = 'models/ppm/player_default_base_new_nj.mdl') =>
@model\Remove() if IsValid(@model)
with @model = ClientsideModel(model)
\SetNoDraw(true)
.__PPM2_PonyData = ponydata
\SetSequence(@seq)
\FrameAdvance(0)
\SetPos(Vector())
\InvalidateBoneCache()
@emotesPanel\Remove() if IsValid(@emotesPanel)
with @emotesPanel = PPM2.CreateEmotesPanel(@, @model, false)
\SetPos(10, 40)
\SetMouseInputEnabled(true)
\SetVisible(true)
@UpdateAttachsIDs()
return @model
Think: =>
rtime = RealTimeL()
delta = rtime - @lastTick
@lastTick = rtime
lerp = (delta * 15)\min(1)
if IsValid(@model)
@model\FrameAdvance(delta * @animRate)
@model\SetPlaybackRate(1)
@model\SetPoseParameter('move_x', 1)
if @shouldAutoTrack
menu = @CurrentMenu()
if menu.getpos
@autoTrackPos = menu.getpos(@model)
@lautoTrackPos = LerpVector(lerp, @lautoTrackPos, @autoTrackPos)
elseif @trackAttach ~= -1
{:Ang, :Pos} = @model\GetAttachment(@trackAttach)
@autoTrackPos = Pos or Vector()
@lautoTrackPos = LerpVector(lerp, @lautoTrackPos, @autoTrackPos)
elseif @trackBone ~= -1
@autoTrackPos = @model\GetBonePosition(@trackBone) or Vector()
@lautoTrackPos = LerpVector(lerp, @lautoTrackPos, @autoTrackPos)
else
@shouldAutoTrack = false
@hold = @IsHovered() if @hold
if @hold
x, y = gui.MousePos()
deltaX, deltaY = x - @mouseX, y - @mouseY
@mouseX, @mouseY = x, y
{:pitch, :yaw, :roll} = @angle
yaw -= deltaX * .5
pitch = math.clamp(pitch - deltaY * .5, -45, 45)
@angle = Angle(pitch, yaw % 360, roll)
@lfixedDistanceToPony = Lerp(lerp, @lfixedDistanceToPony, @fixedDistanceToPony)
@ldistToPony = Lerp(lerp, @ldistToPony, @distToPony)
@vectorPos = Vector(@lfixedDistanceToPony, 0, 0)
@vectorPos\Rotate(@angle)
@VectorPos = LerpVector(lerp, @VectorPos, @vectorPos)
@drawAngle = Angle([email protected], @angle.y - 180)
@ldrawAngle = LerpAngle(lerp, @ldrawAngle, @drawAngle)
FLOOR_VECTOR: Vector(0, 0, -30)
FLOOR_ANGLE: Vector(0, 0, 1)
DRAW_WALLS: {
{Vector(-4000, 0, 900), Vector(1, 0, 0), 8000, 2000}
{Vector(4000, 0, 900), Vector(-1, 0, 0), 8000, 2000}
{Vector(0, -4000, 900), Vector(0, 1, 0), 8000, 2000}
{Vector(0, 4000, 900), Vector(0, -1, 0), 8000, 2000}
{Vector(0, 0, 900), Vector(0, 0, -1), 8000, 8000}
}
WALL_COLOR: Color() - 255
FLOOR_COLOR: Color() - 255
EMPTY_VECTOR: Vector()
WIREFRAME: Material('models/wireframe')
Paint: (w = 0, h = 0) =>
surface.SetDrawColor(0, 0, 0)
surface.DrawRect(0, 0, w, h)
return if not IsValid(@model)
x, y = @LocalToScreen(0, 0)
drawpos = @VectorPos + @GetTrackedPosition()
cam.Start3D(drawpos, @ldrawAngle, @ldistToPony, x, y, w, h)
if @holdRightClick
@model\SetEyeTarget(drawpos)
turnpitch, turnyaw = DLib.combat.turnAngle(@EMPTY_VECTOR, drawpos, Angle())
if not inRadius(turnyaw, -20, 20)
if turnyaw < 0
@model\SetPoseParameter('head_yaw', turnyaw + 20)
else
@model\SetPoseParameter('head_yaw', turnyaw - 20)
else
@model\SetPoseParameter('head_yaw', 0)
turnpitch = turnpitch + 2000 / @lfixedDistanceToPony
if not inRadius(turnpitch, -10, 0)
if turnpitch < 0
@model\SetPoseParameter('head_pitch', turnpitch + 10)
else
@model\SetPoseParameter('head_pitch', turnpitch)
else
@model\SetPoseParameter('head_pitch', 0)
else
@model\SetEyeTarget(@EMPTY_VECTOR)
@model\SetPoseParameter('head_yaw', 0)
@model\SetPoseParameter('head_pitch', 0)
if ENABLE_FULLBRIGHT\GetBool()
render.SuppressEngineLighting(true)
render.ResetModelLighting(1, 1, 1)
render.SetColorModulation(1, 1, 1)
progression = RealTimeL()\progression(@startAnimStart, @startAnimEnd)
progression2 = RealTimeL()\progression(@startAnimStart2, @startAnimEnd2)
if progression2 == 1
@buildingModel\DrawModel()
else
old = render.EnableClipping(true)
render.SetBlend(0.2)
render.MaterialOverride(@WIREFRAME)
for layer = -16, 16
render.PushCustomClipPlane(Vector(0, 0, -1), (1 - progression) * 1200 + layer * 9 - 800)
@buildingModel\DrawModel()
render.PopCustomClipPlane()
render.MaterialOverride()
render.SetBlend(1)
render.PushCustomClipPlane(Vector(0, 0, -1), (1 - progression2) * 1200 - 800)
@buildingModel\DrawModel()
render.PopCustomClipPlane()
render.EnableClipping(old)
ctrl = @controller\GetRenderController()
if bg = @controller\GetBodygroupController()
bg\ApplyBodygroups()
with @model\PPMBonesModifier()
\ResetBones()
hook.Call('PPM2.SetupBones', nil, @model, @controller)
\Think(true)
with ctrl
\DrawModels()
\HideModels(true)
\PreDraw(@model)
@model\DrawModel()
ctrl\PostDraw(@model)
render.SuppressEngineLighting(false) if ENABLE_FULLBRIGHT\GetBool()
menu = @CurrentMenu()
@drawPoints = false
lx, ly = x, y
@model\InvalidateBoneCache()
if type(menu.points) == 'table'
@drawPoints = true
@pointsData = for _, point in ipairs menu.points
vecpos = point.getpos(@model, @controller\GetPonySize())
position = vecpos\ToScreen()
{position, point, vecpos\Distance(drawpos)}
elseif @InMenu() and menu.getpos
{:x, :y} = menu.getpos(@model)\ToScreen(drawpos)
x, y = x - lx, y - ly
cam.End3D()
if @drawPoints
mx, my = gui.MousePos()
mx, my = mx - lx, my - ly
radius = ScreenScale(10)
local drawnSelected
min = 9999
for _, pointdata in ipairs @pointsData
{:x, :y} = pointdata[1]
x, y = x - lx, y - ly
pointdata[1].x, pointdata[1].y = x, y
if inBox(mx, my, x, y, radius, radius)
if min > pointdata[3]
drawnSelected = pointdata
min = pointdata[3]
@selectPoint = drawnSelected and drawnSelected[2] or false
for _, pointdata in ipairs @pointsData
{:x, :y} = pointdata[1]
if pointdata == drawnSelected
drawCrosshair(x, y, radius, @crosshairCircleHovered, @crosshairBoxHovered)
else
drawCrosshair(x, y, radius, @crosshairCircleInactive, @crosshairBoxInactive)
if not @hold and not @holdOnPoint
if drawnSelected
@SetCursor('hand')
else
@SetCursor('none')
else
@selectPoint = false
if @InMenu() and menu.getpos
radius = ScreenScale(10)
drawCrosshair(x, y, radius, @crosshairCircleSelected, @crosshairBoxSelected)
DLib.blur.RefreshNow(true)
OnRemove: =>
@model\Remove() if IsValid(@model)
@buildingModel\Remove() if IsValid(@buildingModel)
panel\Remove() for _, panel in ipairs @menuPanelsCache when panel\IsValid()
}
vgui.Register('PPM2Model2Panel', MODEL_BOX_PANEL, 'EditablePanel')
-- 0 LrigPelvis
-- 1 Lrig_LEG_BL_Femur
-- 2 Lrig_LEG_BL_Tibia
-- 3 Lrig_LEG_BL_LargeCannon
-- 4 Lrig_LEG_BL_PhalanxPrima
-- 5 Lrig_LEG_BL_RearHoof
-- 6 Lrig_LEG_BR_Femur
-- 7 Lrig_LEG_BR_Tibia
-- 8 Lrig_LEG_BR_LargeCannon
-- 9 Lrig_LEG_BR_PhalanxPrima
-- 10 Lrig_LEG_BR_RearHoof
-- 11 LrigSpine1
-- 12 LrigSpine2
-- 13 LrigRibcage
-- 14 Lrig_LEG_FL_Scapula
-- 15 Lrig_LEG_FL_Humerus
-- 16 Lrig_LEG_FL_Radius
-- 17 Lrig_LEG_FL_Metacarpus
-- 18 Lrig_LEG_FL_PhalangesManus
-- 19 Lrig_LEG_FL_FrontHoof
-- 20 Lrig_LEG_FR_Scapula
-- 21 Lrig_LEG_FR_Humerus
-- 22 Lrig_LEG_FR_Radius
-- 23 Lrig_LEG_FR_Metacarpus
-- 24 Lrig_LEG_FR_PhalangesManus
-- 25 Lrig_LEG_FR_FrontHoof
-- 26 LrigNeck1
-- 27 LrigNeck2
-- 28 LrigNeck3
-- 29 LrigScull
-- 30 Jaw
-- 31 Ear_L
-- 32 Ear_R
-- 33 Mane02
-- 34 Mane03
-- 35 Mane03_tip
-- 36 Mane04
-- 37 Mane05
-- 38 Mane06
-- 39 Mane07
-- 40 Mane01
-- 41 Lrigweaponbone
-- 42 right_hand
-- 43 Tail01
-- 44 Tail02
-- 45 Tail03
-- 46 wing_l
-- 47 wing_r
-- 48 wing_l_bat
-- 49 wing_r_bat
-- 50 wing_open_l
-- 51 wing_open_r
genEyeMenu = (publicName) ->
return =>
@ScrollPanel()
@CheckBox('gui.ppm2.editor.eyes.separate', 'SeparateEyes')
@Hr()
prefix = ''
tprefix = 'def'
if publicName ~= ''
tprefix = publicName\lower()
prefix = publicName .. ' '
@Label('gui.ppm2.editor.eyes.url')
@URLInput("EyeURL#{publicName}")
if ADVANCED_MODE\GetBool()
@Label('gui.ppm2.editor.eyes.lightwarp_desc')
ttype = publicName == '' and 'BEyes' or publicName == 'Left' and 'LEye' or 'REye'
@CheckBox("gui.ppm2.editor.eyes.#{tprefix}.lightwarp.shader", "EyeRefract#{publicName}")
@CheckBox("gui.ppm2.editor.eyes.#{tprefix}.lightwarp.cornera", "EyeCornerA#{publicName}")
@ComboBox('gui.ppm2.editor.eyes.lightwarp', ttype .. 'Lightwarp')
@Label('gui.ppm2.editor.eyes.desc1')
@URLInput(ttype .. 'LightwarpURL')
@Label('gui.ppm2.editor.eyes.desc2')
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.lightwarp.glossiness", 'EyeGlossyStrength' .. publicName, 2)
@Label('gui.ppm2.editor.eyes.url_desc')
@ComboBox("gui.ppm2.editor.eyes.#{tprefix}.type", "EyeType#{publicName}")
@ComboBox("gui.ppm2.editor.eyes.#{tprefix}.reflection_type", "EyeReflectionType#{publicName}")
@CheckBox("gui.ppm2.editor.eyes.#{tprefix}.lines", "EyeLines#{publicName}")
@CheckBox("gui.ppm2.editor.eyes.#{tprefix}.derp", "DerpEyes#{publicName}")
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.derp_strength", "DerpEyesStrength#{publicName}", 2)
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.iris_size", "IrisSize#{publicName}", 2)
if ADVANCED_MODE\GetBool()
@CheckBox("gui.ppm2.editor.eyes.#{tprefix}.points_inside", "EyeLineDirection#{publicName}")
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.width", "IrisWidth#{publicName}", 2)
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.height", "IrisHeight#{publicName}", 2)
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.pupil.width", "HoleWidth#{publicName}", 2)
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.pupil.height", "HoleHeight#{publicName}", 2) if ADVANCED_MODE\GetBool()
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.pupil.size", "HoleSize#{publicName}", 2)
if ADVANCED_MODE\GetBool()
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.pupil.shift_x", "HoleShiftX#{publicName}", 2)
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.pupil.shift_y", "HoleShiftY#{publicName}", 2)
@NumSlider("gui.ppm2.editor.eyes.#{tprefix}.pupil.rotation", "EyeRotation#{publicName}", 0)
@Hr()
@ColorBox("gui.ppm2.editor.eyes.#{tprefix}.background", "EyeBackground#{publicName}")
@ColorBox("gui.ppm2.editor.eyes.#{tprefix}.pupil_size", "EyeHole#{publicName}")
@ColorBox("gui.ppm2.editor.eyes.#{tprefix}.top_iris", "EyeIrisTop#{publicName}")
@ColorBox("gui.ppm2.editor.eyes.#{tprefix}.bottom_iris", "EyeIrisBottom#{publicName}")
@ColorBox("gui.ppm2.editor.eyes.#{tprefix}.line1", "EyeIrisLine1#{publicName}")
@ColorBox("gui.ppm2.editor.eyes.#{tprefix}.line2", "EyeIrisLine2#{publicName}")
@ColorBox("gui.ppm2.editor.eyes.#{tprefix}.reflection", "EyeReflection#{publicName}")
@ColorBox("gui.ppm2.editor.eyes.#{tprefix}.effect", "EyeEffect#{publicName}")
BackgroundColors = {
Color(200, 200, 200)
Color(150, 150, 150)
Color(255, 255, 255)
Color(131, 255, 240)
Color(131, 255, 143)
Color(206, 131, 255)
Color(131, 135, 255)
Color(92, 98, 228)
Color(92, 201, 228)
Color(92, 228, 201)
Color(228, 155, 92)
Color(228, 92, 110)
}
EDIT_TREE = {
type: 'level'
name: 'Pony overview'
dist: 100
defang: Angle(-10, -30, 0)
selectmenu: 'gui.ppm2.editor.tabs.main'
menus: {
'gui.ppm2.editor.tabs.main': =>
@Button 'gui.ppm2.editor.io.newfile.title', ->
data = @GetTargetData()
return if not data
confirmed = ->
data\SetFilename("new_pony-#{math.random(1, 100000)}")
data\Reset()
@ValueChanges()
@frame.DoUpdate()
Derma_Query('gui.ppm2.editor.io.newfile.confirm', 'gui.ppm2.editor.io.newfile.toptext', 'gui.ppm2.editor.generic.yes', confirmed, 'gui.ppm2.editor.generic.no')
@Button 'gui.ppm2.editor.io.random', ->
data = @GetTargetData()
return if not data
confirmed = ->
PPM2.Randomize(data, false)
@ValueChanges()
@frame.DoUpdate()
Derma_Query('Really want to randomize?', 'Randomize', 'gui.ppm2.editor.generic.yes', confirmed, 'gui.ppm2.editor.generic.no')
@ComboBox('gui.ppm2.editor.misc.race', 'Race')
@ComboBox('gui.ppm2.editor.misc.wings', 'WingsType')
@CheckBox('gui.ppm2.editor.misc.gender', 'Gender')
@NumSlider('gui.ppm2.editor.misc.chest', 'MaleBuff', 2)
@NumSlider('gui.ppm2.editor.misc.weight', 'Weight', 2)
@NumSlider('gui.ppm2.editor.misc.size', 'PonySize', 2)
size = (_, label) ->
size = @frame.controller\GetSizeController()
return if not size
label\SetText(DLib.i18n.localize('gui.ppm2.editor.size.pony', DLib.i18n.FormatHU(size\CalculatePonyHeight())))
@LabelFunc(size)
size = (_, label) ->
size = @frame.controller\GetSizeController()
return if not size
label\SetText(DLib.i18n.localize('gui.ppm2.editor.size.pony2', DLib.i18n.FormatHU(size\CalculatePonyHeightFull())))
@LabelFunc(size)
return if not ADVANCED_MODE\GetBool()
@CheckBox('gui.ppm2.editor.misc.hide_weapons', 'HideWeapons')
@Hr()
@CheckBox('gui.ppm2.editor.misc.no_flexes2', 'NoFlex')
@Label('gui.ppm2.editor.misc.no_flexes_desc')
flexes = @Spoiler('gui.ppm2.editor.misc.flexes')
for _, {:flex, :active} in ipairs PPM2.PonyFlexController.FLEX_LIST
@CheckBox("Disable #{flex} control", "DisableFlex#{flex}")\SetParent(flexes) if active
flexes\SizeToContents()
'gui.ppm2.editor.tabs.files': PPM2.EditorBuildNewFilesPanel
'gui.ppm2.editor.tabs.old_files': PPM2.EditorBuildOldFilesPanel
'gui.ppm2.editor.tabs.about': =>
title = @Label('PPM/2')
title\SetFont('PPM2.Title')
title\SizeToContents()
@URLLabel('gui.ppm2.editor.info.discord', 'https://discord.gg/HG9eS79')\SetFont('PPM2.AboutLabels')
@URLLabel('gui.ppm2.editor.info.ponyscape', 'http://steamcommunity.com/groups/Ponyscape')\SetFont('PPM2.AboutLabels')
@URLLabel('gui.ppm2.editor.info.creator', 'https://steamcommunity.com/profiles/76561198077439269')\SetFont('PPM2.AboutLabels')
@URLLabel('gui.ppm2.editor.info.newmodels', 'https://steamcommunity.com/profiles/76561198013875404')\SetFont('PPM2.AboutLabels')
@URLLabel('gui.ppm2.editor.info.cppmmodels', 'http://steamcommunity.com/profiles/76561198084938735')\SetFont('PPM2.AboutLabels')
@URLLabel('gui.ppm2.editor.info.oldmodels', 'https://github.com/ChristinaTech/PonyPlayerModels')\SetFont('PPM2.AboutLabels')
@URLLabel('gui.ppm2.editor.info.bugs', 'https://gitlab.com/DBotThePony/PPM2/issues')\SetFont('PPM2.AboutLabels')
@URLLabel('gui.ppm2.editor.info.sources', 'https://gitlab.com/DBotThePony/PPM2')\SetFont('PPM2.AboutLabels')
@URLLabel('gui.ppm2.editor.info.githubsources', 'https://github.com/roboderpy/PPM2')\SetFont('PPM2.AboutLabels')
@Label('gui.ppm2.editor.info.thanks')\SetFont('PPM2.AboutLabels')
}
points: {
{
type: 'bone'
target: 'LrigScull'
link: 'head_submenu'
}
{
type: 'bone'
target: 'Lrig_LEG_BL_Femur'
link: 'cutiemark'
}
{
type: 'bone'
target: 'Lrig_LEG_BR_Femur'
link: 'cutiemark'
}
{
type: 'bone'
target: 'LrigSpine1'
link: 'spine'
}
{
type: 'bone'
target: 'Tail03'
link: 'tail'
}
{
type: 'bone'
target: 'Lrig_LEG_FL_Metacarpus'
link: 'legs_submenu'
}
{
type: 'bone'
target: 'Lrig_LEG_FR_Metacarpus'
link: 'legs_submenu'
}
{
type: 'bone'
target: 'Lrig_LEG_BR_LargeCannon'
link: 'legs_submenu'
}
{
type: 'bone'
target: 'Lrig_LEG_BL_LargeCannon'
link: 'legs_submenu'
}
}
children: {
cutiemark: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.cutiemark'
dist: 30
defang: Angle(0, -90, 0)
populate: =>
@CheckBox('gui.ppm2.editor.cutiemark.display', 'CMark')
@ComboBox('gui.ppm2.editor.cutiemark.type', 'CMarkType')
@markDisplay = vgui.Create('EditablePanel', @)
with @markDisplay
\Dock(TOP)
\SetSize(320, 320)
\DockMargin(20, 20, 20, 20)
.currentColor = BackgroundColors[1]
.lerpChange = 0
.colorIndex = 2
.nextColor = BackgroundColors[2]
.Paint = (pnl, w = 0, h = 0) ->
data = @GetTargetData()
return if not data
controller = data\GetNetworkObject()
return if not controller
rcontroller = controller\GetRenderController()
return if not rcontroller
tcontroller = rcontroller\GetTextureController()
return if not tcontroller
mat = tcontroller\GetCMarkGUI()
return if not mat
.lerpChange += RealFrameTime() / 4
if .lerpChange >= 1
.lerpChange = 0
.currentColor = BackgroundColors[.colorIndex]
.colorIndex += 1
if .colorIndex > #BackgroundColors
.colorIndex = 1
.nextColor = BackgroundColors[.colorIndex]
{r: r1, g: g1, b: b1} = .currentColor
{r: r2, g: g2, b: b2} = .nextColor
r, g, b = r1 + (r2 - r1) * .lerpChange, g1 + (g2 - g1) * .lerpChange, r1 + (b2 - b1) * .lerpChange
surface.SetDrawColor(r, g, b, 100)
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial(mat)
surface.DrawTexturedRect(0, 0, w, h)
@NumSlider('gui.ppm2.editor.cutiemark.size', 'CMarkSize', 2)
@ColorBox('gui.ppm2.editor.cutiemark.color', 'CMarkColor')
@Hr()
@Label('gui.ppm2.editor.cutiemark.input')\DockMargin(5, 10, 5, 10)
@URLInput('CMarkURL')
}
head_submenu: {
type: 'level'
name: 'gui.ppm2.editor.tabs.head'
dist: 40
defang: Angle(-7, -30, 0)
points: {
{
type: 'attach'
target: 'eyes'
link: 'eyes'
}
{
type: 'attach'
target: 'eyes'
link: 'eyel'
addvector: Vector(-5, 5, 2)
}
{
type: 'attach'
target: 'eyes'
link: 'mane_horn'
addvector: Vector(-5, 0, 13)
}
{
type: 'attach'
target: 'eyes'
link: 'eyer'
addvector: Vector(-5, -5, 2)
}
}
children: {
eyes: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.eyes'
dist: 30
defang: Angle(-10, 0, 0)
menus: {
'gui.ppm2.editor.tabs.eyes': genEyeMenu('')
'gui.ppm2.editor.tabs.face': =>
@ScrollPanel()
@ComboBox('gui.ppm2.editor.face.eyelashes', 'EyelashType')
@ColorBox('gui.ppm2.editor.face.eyelashes_color', 'EyelashesColor')
@ColorBox('gui.ppm2.editor.face.eyebrows_color', 'EyebrowsColor')
@ComboBox('gui.ppm2.editor.clothes.eye', 'EyeClothes')
@ComboBox('gui.ppm2.editor.clothes.neck', 'NeckClothes')
@ComboBox('gui.ppm2.editor.clothes.head', 'HeadClothes')
if ADVANCED_MODE\GetBool()
for {internal, publicName} in *{{'head', 'Head'}, {'neck', 'Neck'}, {'eye', 'Eye'}}
@Hr()
@CheckBox("gui.ppm2.editor.clothes_col.#{internal}_use", "#{publicName}ClothesUseColor")
for i = 1, PPM2.MAX_CLOTHES_URLS
@Label('gui.ppm2.editor.clothes.' .. internal .. '_url' .. i)
@URLInput("#{publicName}ClothesURL#{i}")
@ColorBox("gui.ppm2.editor.clothes_col.#{internal}_#{i}", "#{publicName}ClothesColor#{i}") for i = 1, PPM2.MAX_CLOTHES_COLORS
@CheckBox('gui.ppm2.editor.face.new_muzzle', 'NewMuzzle')
if ADVANCED_MODE\GetBool()
@Hr()
@CheckBox('gui.ppm2.editor.face.inherit.lips', 'LipsColorInherit')
@CheckBox('gui.ppm2.editor.face.inherit.nose', 'NoseColorInherit')
@ColorBox('gui.ppm2.editor.face.lips', 'LipsColor')
@ColorBox('gui.ppm2.editor.face.nose', 'NoseColor')
@Hr()
@CheckBox('gui.ppm2.editor.face.eyebrows_glow', 'GlowingEyebrows')
@NumSlider('gui.ppm2.editor.face.eyebrows_glow_strength', 'EyebrowsGlowStrength', 2)
@CheckBox('gui.ppm2.editor.face.eyelashes_separate_phong', 'SeparateEyelashesPhong')
PPM2.EditorPhongPanels(@, 'Eyelashes', 'gui.ppm2.editor.face.eyelashes_phong')
'gui.ppm2.editor.tabs.mouth': =>
@CheckBox('gui.ppm2.editor.mouth.fangs', 'Fangs')
@CheckBox('gui.ppm2.editor.mouth.alt_fangs', 'AlternativeFangs')
@NumSlider('gui.ppm2.editor.mouth.fangs', 'FangsStrength', 2) if ADVANCED_MODE\GetBool()
@CheckBox('gui.ppm2.editor.mouth.claw', 'ClawTeeth')
@NumSlider('gui.ppm2.editor.mouth.claw', 'ClawTeethStrength', 2) if ADVANCED_MODE\GetBool()
@Hr()
@ColorBox('gui.ppm2.editor.mouth.teeth', 'TeethColor')
@ColorBox('gui.ppm2.editor.mouth.mouth', 'MouthColor')
@ColorBox('gui.ppm2.editor.mouth.tongue', 'TongueColor')
PPM2.EditorPhongPanels(@, 'Teeth', 'gui.ppm2.editor.mouth.teeth_phong')
PPM2.EditorPhongPanels(@, 'Mouth', 'gui.ppm2.editor.mouth.mouth_phong')
PPM2.EditorPhongPanels(@, 'Tongue', 'gui.ppm2.editor.mouth.tongue_phong')
}
}
eyel: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.left_eye'
dist: 20
defang: Angle(-7, 30, 0)
populate: genEyeMenu('Left')
}
eyer: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.right_eye'
dist: 20
populate: genEyeMenu('Right')
}
mane_horn: {
type: 'level'
name: 'gui.ppm2.editor.tabs.mane_horn'
dist: 50
defang: Angle(-25, -120, 0)
points: {
{
type: 'attach'
target: 'eyes'
link: 'mane'
addvector: Vector(-15, 0, 14)
}
{
type: 'attach'
target: 'eyes'
link: 'horn'
addvector: Vector(-2, 0, 14)
}
{
type: 'attach'
target: 'eyes'
link: 'ears'
addvector: Vector(-16, -8, 8)
}
{
type: 'attach'
target: 'eyes'
link: 'ears'
addvector: Vector(-16, 8, 8)
}
}
children: {
mane: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.mane'
defang: Angle(-7, -120, 0)
menus: {
'gui.ppm2.editor.tabs.main': =>
@ComboBox('gui.ppm2.editor.mane.type', 'ManeTypeNew')
@CheckBox('gui.ppm2.editor.misc.hide_pac3', 'HideManes')
@CheckBox('gui.ppm2.editor.misc.hide_mane', 'HideManesMane')
@ComboBox('gui.ppm2.editor.clothes.head', 'HeadClothes')
if ADVANCED_MODE\GetBool()
for {internal, publicName} in *{{'head', 'Head'}}
@Hr()
@CheckBox("gui.ppm2.editor.clothes_col.#{internal}_use", "#{publicName}ClothesUseColor")
for i = 1, PPM2.MAX_CLOTHES_URLS
@Label('gui.ppm2.editor.clothes.' .. internal .. '_url' .. i)
@URLInput("#{publicName}ClothesURL#{i}")
@ColorBox("gui.ppm2.editor.clothes_col.#{internal}_#{i}", "#{publicName}ClothesColor#{i}") for i = 1, PPM2.MAX_CLOTHES_COLORS
@Hr()
@CheckBox('gui.ppm2.editor.mane.phong', 'SeparateManePhong') if ADVANCED_MODE\GetBool()
PPM2.EditorPhongPanels(@, 'Mane', 'gui.ppm2.editor.mane.mane_phong') if ADVANCED_MODE\GetBool()
@ColorBox("gui.ppm2.editor.mane.color#{i}", "ManeColor#{i}") for i = 1, 2
@Hr()
@ColorBox("gui.ppm2.editor.mane.detail_color#{i}", "ManeDetailColor#{i}") for i = 1, 6
'gui.ppm2.editor.tabs.details': =>
@CheckBox('gui.ppm2.editor.mane.phong_sep', 'SeparateMane')
PPM2.EditorPhongPanels(@, 'UpperMane', 'gui.ppm2.editor.mane.up.phong') if ADVANCED_MODE\GetBool()
PPM2.EditorPhongPanels(@, 'LowerMane', 'gui.ppm2.editor.mane.down.phong') if ADVANCED_MODE\GetBool()
@Hr()
@ColorBox("gui.ppm2.editor.mane.up.color#{i}", "UpperManeColor#{i}") for i = 1, 2
@ColorBox("gui.ppm2.editor.mane.down.color#{i}", "LowerManeColor#{i}") for i = 1, 2
@Hr()
@ColorBox("gui.ppm2.editor.mane.up.detail_color#{i}", "UpperManeDetailColor#{i}") for i = 1, 6
@ColorBox("gui.ppm2.editor.mane.down.detail_color#{i}", "LowerManeDetailColor#{i}") for i = 1, 6
'gui.ppm2.editor.tabs.url_details': =>
for i = 1, ADVANCED_MODE\GetBool() and 6 or 1
@Label("gui.ppm2.editor.url_mane.desc#{i}")
@URLInput("ManeURL#{i}")
@ColorBox("gui.ppm2.editor.url_mane.color#{i}", "ManeURLColor#{i}")
@Hr()
'gui.ppm2.editor.tabs.url_separated_details': =>
for i = 1, ADVANCED_MODE\GetBool() and 6 or 1
@Hr()
@Label("gui.ppm2.editor.url_mane.sep.up.desc#{i}")
@URLInput("UpperManeURL#{i}")
@ColorBox("gui.ppm2.editor.url_mane.sep.up.color#{i}", "UpperManeURLColor#{i}")
for i = 1, ADVANCED_MODE\GetBool() and 6 or 1
@Hr()
@Label("gui.ppm2.editor.url_mane.sep.down.desc#{i}")
@URLInput("LowerManeURL#{i}")
@ColorBox("gui.ppm2.editor.url_mane.sep.down.color#{i}", "LowerManeURLColor#{i}")
}
}
ears: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.ears'
defang: Angle(-12, -110, 0)
populate: =>
@CheckBox('gui.ppm2.editor.ears.bat', 'BatPonyEars')
@NumSlider('gui.ppm2.editor.ears.bat', 'BatPonyEarsStrength', 2) if ADVANCED_MODE\GetBool()
if ADVANCED_MODE\GetBool()
@NumSlider('gui.ppm2.editor.ears.size', 'EarsSize', 2)
}
horn: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.horn'
dist: 30
defang: Angle(-13, -20, 0)
menus: {
'gui.ppm2.editor.tabs.main': =>
@CheckBox('gui.ppm2.editor.horn.separate_color', 'SeparateHorn')
@ColorBox('gui.ppm2.editor.horn.detail_color', 'HornDetailColor')
@CheckBox('gui.ppm2.editor.horn.glowing_detail', 'HornGlow')
@NumSlider('gui.ppm2.editor.horn.glow_strength', 'HornGlowSrength', 2)
@ColorBox('gui.ppm2.editor.horn.color', 'HornColor')
@CheckBox('gui.ppm2.editor.horn.separate_magic_color', 'SeparateMagicColor')
@ColorBox('gui.ppm2.editor.horn.magic', 'HornMagicColor')
if ADVANCED_MODE\GetBool()
@Hr()
@CheckBox('gui.ppm2.editor.horn.use_new', 'UseNewHorn')
@ComboBox('gui.ppm2.editor.horn.new_type', 'NewHornType')
@CheckBox('gui.ppm2.editor.horn.separate_phong', 'SeparateHornPhong') if ADVANCED_MODE\GetBool()
PPM2.EditorPhongPanels(@, 'Horn', 'gui.ppm2.editor.horn.horn_phong') if ADVANCED_MODE\GetBool()
'gui.ppm2.editor.tabs.details': =>
for i = 1, 3
@Label('gui.ppm2.editor.horn.detail.desc' .. i)
@URLInput("HornURL#{i}")
@ColorBox('gui.ppm2.editor.horn.detail.color' .. i, "HornURLColor#{i}")
@Hr()
}
}
}
}
}
}
spine: {
type: 'level'
name: 'gui.ppm2.editor.tabs.back'
dist: 80
defang: Angle(-30, -90, 0)
points: {
{
type: 'bone'
target: 'LrigSpine1'
link: 'overall_body'
}
{
type: 'bone'
target: 'LrigNeck2'
link: 'neck'
}
{
type: 'bone'
target: 'wing_l'
link: 'wings'
}
{
type: 'bone'
target: 'wing_r'
link: 'wings'
}
}
children: {
wings: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.wings'
dist: 40
defang: Angle(-12, -30, 0)
menus: {
'gui.ppm2.editor.tabs.main': =>
@CheckBox('gui.ppm2.editor.wings.separate_color', 'SeparateWings')
@ColorBox('gui.ppm2.editor.wings.color', 'WingsColor')
@CheckBox('gui.ppm2.editor.wings.separate_phong', 'SeparateWingsPhong') if ADVANCED_MODE\GetBool()
@Hr()
@ColorBox('gui.ppm2.editor.wings.bat_color', 'BatWingColor')
@ColorBox('gui.ppm2.editor.wings.bat_skin_color', 'BatWingSkinColor')
PPM2.EditorPhongPanels(@, 'BatWingsSkin', 'gui.ppm2.editor.wings.bat_skin_phong') if ADVANCED_MODE\GetBool()
'gui.ppm2.editor.tabs.left': =>
@NumSlider('gui.ppm2.editor.wings.left.size', 'LWingSize', 2)
@NumSlider('gui.ppm2.editor.wings.left.fwd', 'LWingX', 2)
@NumSlider('gui.ppm2.editor.wings.left.up', 'LWingY', 2)
@NumSlider('gui.ppm2.editor.wings.left.inside', 'LWingZ', 2)
'gui.ppm2.editor.tabs.right': =>
@NumSlider('gui.ppm2.editor.wings.right.size', 'RWingSize', 2)
@NumSlider('gui.ppm2.editor.wings.right.fwd', 'RWingX', 2)
@NumSlider('gui.ppm2.editor.wings.right.up', 'RWingY', 2)
@NumSlider('gui.ppm2.editor.wings.right.inside', 'RWingZ', 2)
'gui.ppm2.editor.tabs.details': =>
@Label('gui.ppm2.editor.wings.normal')
@Hr()
for i = 1, 3
@Label('gui.ppm2.editor.wings.details.def.detail' .. i)
@URLInput("WingsURL#{i}")
@ColorBox('gui.ppm2.editor.wings.details.def.color' .. i, "WingsURLColor#{i}")
@Hr()
@Label('gui.ppm2.editor.wings.bat')
@Hr()
for i = 1, 3
@Label('gui.ppm2.editor.wings.details.bat.detail' .. i)
@URLInput("BatWingURL#{i}")
@ColorBox('gui.ppm2.editor.wings.details.bat.color' .. i, "BatWingURLColor#{i}")
@Hr()
@Label('gui.ppm2.editor.wings.bat_skin')
@Hr()
for i = 1, 3
@Label('gui.ppm2.editor.wings.details.batskin.detail' .. i)
@URLInput("BatWingSkinURL#{i}")
@ColorBox('gui.ppm2.editor.wings.details.batskin.color' .. i, "BatWingSkinURLColor#{i}")
@Hr()
}
}
neck: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.neck'
dist: 40
defang: Angle(-7, -15, 0)
populate: =>
@NumSlider('gui.ppm2.editor.neck.height', 'NeckSize', 2)
size = (_, label) ->
size = @frame.controller\GetNeckSize() * 4.3 * @frame.controller\GetPonySize()
label\SetText(DLib.i18n.localize('gui.ppm2.editor.size.neck', DLib.i18n.FormatHU(size)))
@LabelFunc(size)
size = (_, label) ->
size = @frame.controller\GetSizeController()
return if not size
label\SetText(DLib.i18n.localize('gui.ppm2.editor.size.pony', DLib.i18n.FormatHU(size\CalculatePonyHeight())))
@LabelFunc(size)
size = (_, label) ->
size = @frame.controller\GetSizeController()
return if not size
label\SetText(DLib.i18n.localize('gui.ppm2.editor.size.pony2', DLib.i18n.FormatHU(size\CalculatePonyHeightFull())))
@LabelFunc(size)
}
overall_body: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.body'
dist: 90
defang: Angle(-3, -90, 0)
menus: {
'gui.ppm2.editor.tabs.main': =>
@ComboBox('gui.ppm2.editor.body.suit', 'Bodysuit')
@ColorBox('gui.ppm2.editor.body.color', 'BodyColor')
@ComboBox('gui.ppm2.editor.clothes.body', 'BodyClothes')
@ComboBox('gui.ppm2.editor.clothes.neck', 'NeckClothes')
if ADVANCED_MODE\GetBool()
for {internal, publicName} in *{{'neck', 'Neck'}, {'body', 'Body'}}
@Hr()
@CheckBox("gui.ppm2.editor.clothes_col.#{internal}_use", "#{publicName}ClothesUseColor")
for i = 1, PPM2.MAX_CLOTHES_URLS
@Label('gui.ppm2.editor.clothes.' .. internal .. '_url' .. i)
@URLInput("#{publicName}ClothesURL#{i}")
@ColorBox("gui.ppm2.editor.clothes_col.#{internal}_#{i}", "#{publicName}ClothesColor#{i}") for i = 1, PPM2.MAX_CLOTHES_COLORS
'gui.ppm2.editor.tabs.back': =>
@NumSlider('gui.ppm2.editor.body.spine_length', 'BackSize', 2)
size = (_, label) ->
size = @frame.controller\GetBackSize() * 7 * @frame.controller\GetPonySize()
label\SetText(DLib.i18n.localize('gui.ppm2.editor.size.back', DLib.i18n.FormatHU(size)))
@LabelFunc(size)
'gui.ppm2.editor.tabs.details': =>
@NumSlider('gui.ppm2.editor.body.bump', 'BodyBumpStrength', 2)
for i = 1, ADVANCED_MODE\GetBool() and PPM2.MAX_BODY_DETAILS or 3
@ComboBox('gui.ppm2.editor.body.detail.desc' .. i, "BodyDetail#{i}")
@ColorBox('gui.ppm2.editor.body.detail.color' .. i, "BodyDetailColor#{i}")
if ADVANCED_MODE\GetBool()
@CheckBox('gui.ppm2.editor.body.detail.first', "BodyDetailFirst#{i}")
@CheckBox('gui.ppm2.editor.body.detail.glow' .. i, "BodyDetailGlow#{i}")
@NumSlider('gui.ppm2.editor.body.detail.glow_strength' .. i, "BodyDetailGlowStrength#{i}", 2)
@Hr()
@Label('gui.ppm2.editor.body.url_desc')
@Hr()
for i = 1, ADVANCED_MODE\GetBool() and PPM2.MAX_BODY_DETAILS or 2
@Label('gui.ppm2.editor.body.detail.url.desc' .. i)
@URLInput("BodyDetailURL#{i}")
@CheckBox('gui.ppm2.editor.body.detail.first', "BodyDetailURLFirst#{i}")
@ColorBox('gui.ppm2.editor.body.detail.url.color' .. i, "BodyDetailURLColor#{i}")
@Hr()
'gui.ppm2.editor.tabs.tattoos': =>
@ScrollPanel()
for i = 1, PPM2.MAX_TATTOOS
spoiler = @Spoiler('gui.ppm2.editor.tattoo.layer' .. i)
updatePanels = {}
@Button('gui.ppm2.editor.tattoo.edit_keyboard', (-> @GetFrame()\EditTattoo(i, updatePanels)), spoiler)
@ComboBox('gui.ppm2.editor.tattoo.type', "TattooType#{i}", nil, spoiler)
table.insert(updatePanels, @NumSlider('gui.ppm2.editor.tattoo.tweak.rotate', "TattooRotate#{i}", 0, spoiler))
table.insert(updatePanels, @NumSlider('gui.ppm2.editor.tattoo.tweak.x', "TattooPosX#{i}", 2, spoiler))
table.insert(updatePanels, @NumSlider('gui.ppm2.editor.tattoo.tweak.y', "TattooPosY#{i}", 2, spoiler))
table.insert(updatePanels, @NumSlider('gui.ppm2.editor.tattoo.tweak.width', "TattooScaleX#{i}", 2, spoiler))
table.insert(updatePanels, @NumSlider('gui.ppm2.editor.tattoo.tweak.height', "TattooScaleY#{i}", 2, spoiler))
@CheckBox('gui.ppm2.editor.tattoo.over', "TattooOverDetail#{i}", spoiler)
@CheckBox('gui.ppm2.editor.tattoo.glow', "TattooGlow#{i}", spoiler)
@NumSlider('gui.ppm2.editor.tattoo.glow_strength', "TattooGlowStrength#{i}", 2, spoiler)
box, collapse = @ColorBox('gui.ppm2.editor.tattoo.color', "TattooColor#{i}", spoiler)
collapse\SetExpanded(true)
}
}
}
}
tail: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.tail'
dist: 50
defang: Angle(-10, -90, 0)
menus: {
'gui.ppm2.editor.tabs.main': =>
@ComboBox('gui.ppm2.editor.tail.type', 'TailTypeNew')
@CheckBox('gui.ppm2.editor.misc.hide_pac3', 'HideManes')
@CheckBox('gui.ppm2.editor.misc.hide_tail', 'HideManesTail')
@NumSlider('gui.ppm2.editor.tail.size', 'TailSize', 2)
@ColorBox('gui.ppm2.editor.tail.color' .. i, "TailColor#{i}") for i = 1, 2
@Hr()
@CheckBox('gui.ppm2.editor.tail.separate', 'SeparateTailPhong') if ADVANCED_MODE\GetBool()
PPM2.EditorPhongPanels(@, 'Tail', 'gui.ppm2.editor.tail.tail_phong') if ADVANCED_MODE\GetBool()
@ColorBox('gui.ppm2.editor.tail.detail' .. i, "TailDetailColor#{i}") for i = 1, ADVANCED_MODE\GetBool() and 6 or 4
'gui.ppm2.editor.tabs.details': =>
for i = 1, ADVANCED_MODE\GetBool() and 6 or 1
@Hr()
@Label('gui.ppm2.editor.tail.url.detail' .. i)
@URLInput("TailURL#{i}")
@ColorBox('gui.ppm2.editor.tail.url.color' .. i, "TailURLColor#{i}")
}
}
legs_submenu: {
type: 'level'
name: 'gui.ppm2.editor.tabs.hooves'
dist: 50
defang: Angle(-10, -50, 0)
points: {
{
type: 'bone'
target: 'Lrig_LEG_BR_RearHoof'
link: 'bottom_hoof'
}
{
type: 'bone'
target: 'Lrig_LEG_BL_RearHoof'
link: 'bottom_hoof'
defang: Angle(0, 90, 0)
}
{
type: 'bone'
target: 'Lrig_LEG_FL_FrontHoof'
link: 'bottom_hoof'
defang: Angle(0, 90, 0)
}
{
type: 'bone'
target: 'Lrig_LEG_FR_FrontHoof'
link: 'bottom_hoof'
}
{
type: 'bone'
target: 'Lrig_LEG_FL_Metacarpus'
link: 'legs_generic'
defang: Angle(0, 90, 0)
}
{
type: 'bone'
target: 'Lrig_LEG_FR_Metacarpus'
link: 'legs_generic'
}
{
type: 'bone'
target: 'Lrig_LEG_BR_LargeCannon'
link: 'legs_generic'
}
{
type: 'bone'
target: 'Lrig_LEG_BL_LargeCannon'
link: 'legs_generic'
defang: Angle(0, 90, 0)
}
}
children: {
bottom_hoof: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.bottom_hoof'
dist: 30
defang: Angle(0, -90, 0)
populate: =>
@CheckBox('gui.ppm2.editor.hoof.fluffers', 'HoofFluffers')
@NumSlider('gui.ppm2.editor.hoof.fluffers', 'HoofFluffersStrength', 2)
@Hr()
@CheckBox('gui.ppm2.editor.body.disable_hoofsteps', 'DisableHoofsteps')
@CheckBox('gui.ppm2.editor.body.disable_wander_sounds', 'DisableWanderSounds')
@CheckBox('gui.ppm2.editor.body.disable_new_step_sounds', 'DisableStepSounds')
@CheckBox('gui.ppm2.editor.body.disable_jump_sound', 'DisableJumpSound')
@CheckBox('gui.ppm2.editor.body.disable_falldown_sound', 'DisableFalldownSound')
@Hr()
@CheckBox('gui.ppm2.editor.body.call_playerfootstep', 'CallPlayerFootstepHook')
@Label('gui.ppm2.editor.body.call_playerfootstep_desc')
}
legs_generic: {
type: 'menu'
name: 'gui.ppm2.editor.tabs.legs'
dist: 30
defang: Angle(0, -90, 0)
menus: {
'gui.ppm2.editor.tabs.main': =>
@CheckBox('gui.ppm2.editor.misc.hide_pac3', 'HideManes')
@CheckBox('gui.ppm2.editor.misc.hide_socks', 'HideManesSocks')
@NumSlider('gui.ppm2.editor.legs.height', 'LegsSize', 2)
'gui.ppm2.editor.tabs.socks': =>
@CheckBox('gui.ppm2.editor.legs.socks.simple', 'Socks') if ADVANCED_MODE\GetBool()
@CheckBox('gui.ppm2.editor.legs.socks.model', 'SocksAsModel')
@ColorBox('gui.ppm2.editor.legs.socks.color', 'SocksColor')
if ADVANCED_MODE\GetBool()
@Hr()
PPM2.EditorPhongPanels(@, 'Socks', 'gui.ppm2.editor.legs.socks.socks_phong')
@ComboBox('gui.ppm2.editor.legs.socks.texture', 'SocksTexture')
@Label('gui.ppm2.editor.legs.socks.url_texture')
@URLInput('SocksTextureURL')
@Hr()
@ColorBox('gui.ppm2.editor.legs.socks.color' .. i, 'SocksDetailColor' .. i) for i = 1, 6
'gui.ppm2.editor.tabs.newsocks': =>
@CheckBox('gui.ppm2.editor.legs.newsocks.model', 'SocksAsNewModel')
@ColorBox('gui.ppm2.editor.legs.newsocks.color1', 'NewSocksColor1')
@ColorBox('gui.ppm2.editor.legs.newsocks.color1', 'NewSocksColor2')
@ColorBox('gui.ppm2.editor.legs.newsocks.color1', 'NewSocksColor3')
if ADVANCED_MODE\GetBool()
@Label('gui.ppm2.editor.legs.newsocks.url')
@URLInput('NewSocksTextureURL')
}
}
}
}
}
}
patchSubtree = (node) ->
if type(node.children) == 'table'
for childID, child in pairs node.children
child.id = childID
child.defang = child.defang or Angle(node.defang)
child.dist = child.dist or node.dist
patchSubtree(child)
if type(node.points) == 'table'
for _, point in ipairs node.points
point.addvector = point.addvector or Vector()
switch point.type
when 'point'
point.getpos = => Vector(point.target)
when 'bone'
point.getpos = (ponysize = 1) =>
if not point.targetID or point.targetID == -1
point.targetID = @LookupBone(point.target) or -1
if point.targetID == -1
return point.addvector * ponysize
else
--bonepos = @GetBonePosition(point.targetID)
--print(point.target, bonepos) if bonepos == Vector()
return @GetBonePosition(point.targetID) + point.addvector * ponysize
when 'attach'
point.getpos = (ponysize = 1) =>
if not point.targetID or point.targetID == -1
point.targetID = @LookupAttachment(point.target) or -1
if point.targetID == -1
return point.addvector * ponysize
else
{:Pos, :Ang} = @GetAttachment(point.targetID)
return Pos and (Pos + point.addvector * ponysize) or point.addvector * ponysize
if type(node.children) == 'table'
point.linkTable = table.Copy(node.children[point.link])
if type(point.linkTable) == 'table'
point.linkTable.getpos = point.getpos
if point.defang
point.linkTable.defang = Angle(point.defang)
else
PPM2.Message('Editor3: Missing submenu ' .. point.link .. ' of ' .. node.id .. '!')
EDIT_TREE.id = 'root'
patchSubtree(EDIT_TREE)
if IsValid(PPM2.EDITOR3)
PPM2.EDITOR3\Remove()
net.Start('PPM2.EditorStatus')
net.WriteBool(false)
net.SendToServer()
ppm2_editor3 = ->
if IsValid(PPM2.EDITOR3)
PPM2.EDITOR3\SetVisible(true)
PPM2.EDITOR3\MakePopup()
return PPM2.EDITOR3
PPM2.EDITOR3 = vgui.Create('DLib_Window')
self = PPM2.EDITOR3
@SetSize(ScrWL(), ScrHL())
@SetPos(0, 0)
@MakePopup()
@SetDraggable(false)
@RemoveResize()
@SetDeleteOnClose(false)
with @modelPanel = vgui.Create('PPM2Model2Panel', @)
\Dock(FILL)
\DockMargin(3, 3, 3, 3)
copy = PPM2.GetMainData()\Copy()
ply = LocalPlayer()
ent = @modelPanel\ResetModel()
@data = copy
controller = copy\CreateCustomController(ent)
controller\SetFlexLerpMultiplier(1.3)
copy\SetNetworkObject(controller)
@controller = controller
@modelPanel\SetController(controller)
controller\SetupEntity(ent)
controller\SetDisableTask(true)
@modelPanel.frame = @
@modelPanel.stack = {EDIT_TREE}
@modelPanel\SetParentTarget(@)
@modelPanel.controllerData = copy
@modelPanel\UpdateMenu(@modelPanel\CurrentMenu())
@SetTitle('gui.ppm2.editor.generic.title_file', copy\GetFilename() or '%ERRNAME%')
PPM2.EditorCreateTopButtons(@, true, true)
@saves = @modelPanel.saves
@savesOld = @modelPanel.savesOld
@DoUpdate = -> @modelPanel\DoUpdate()
@OnClose = ->
net.Start('PPM2.EditorStatus')
net.WriteBool(false)
net.SendToServer()
net.Start('PPM2.EditorStatus')
net.WriteBool(true)
net.SendToServer()
if not file.Exists('ppm2_intro.txt', 'DATA')
file.Write('ppm2_intro.txt', '')
Derma_Message('gui.ppm2.editor.intro.text', 'gui.ppm2.editor.intro.title', 'gui.ppm2.editor.intro.okay')
concommand.Add 'ppm2_editor3', ppm2_editor3
IconData3 =
title: 'PPM/2 Editor/3',
icon: 'gui/ppm2_icon.png',
width: 960,
height: 700,
onewindow: true,
init: (icon, window) ->
window\Remove()
ppm2_editor3()
list.Set('DesktopWindows', 'PPM2_E3', IconData3)
CreateContextMenu() if IsValid(g_ContextMenu)
| 31.900801 | 163 | 0.646779 |
cc946db557e79beaf809f12f47c450bd33108f14 | 782 | ----------------------------------------------------------------
-- A module with helper functions related to strings.
--
-- @module String
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
-- {{ TBSHTEMPLATE:BEGIN }}
----------------------------------------------------------------
-- Duplicates the given string n times and returns a new string.
--
-- @tparam string s The string to duplicate.
-- @tparam integer n The amount of times to duplicate the
-- string.
-- @treturn string The duplicated string.
----------------------------------------------------------------
StringNTimes = (s, n) ->
buffer = ""
for i=1,n
buffer ..= s
return buffer
String = { :StringNTimes }
-- {{ TBSHTEMPLATE:END }}
return String
| 26.066667 | 64 | 0.455243 |
06fcb13c93fcd03df4f3fe89413ebcf5f7440660 | 1,825 | package.path = '?/init.lua;?.lua;'..package.path
moonxml = require 'moonxml'
describe 'moonxml', ->
setup ->
--print = stub.new()
for language in *{'html', 'xml'}
describe "#{language} language", ->
it 'should exist and be a table', ->
assert.is.table moonxml[language]
setup ->
export lang = moonxml[language]
lang.environment.print = stub.new()
it 'should have a loadmoon function', ->
assert.is.function lang.loadmoon
assert.is.function lang.loadlua
it 'should have a loadmoonfile function', ->
assert.is.function lang.loadmoonfile
assert.is.function lang.loadluafile
it 'should load templates from strings', ->
assert.is.function lang\loadmoon '-> "test"'
it 'should fail on invalid moonscript', ->
res, err = lang\loadmoon '->-><- yolo#'
assert.is.nil res
assert.is.string err
it 'should load templates from files', ->
assert.is.function lang\loadmoonfile 'example.moonxml'
it 'should fail to load non-existant files', ->
assert.has.errors (-> lang\loadmoonfile 'foo.bar'),
'foo.bar: No such file or directory'
it 'should escape text', ->
lang\loadlua('p "<b>"')()
with assert.stub(lang.environment.print)
.was_not_called_with('<b>')
.was_called_with('<b>')
describe 'derived languages', ->
setup ->
export lang = moonxml[language]
export lang = lang\derive!
lang.environment.print = stub.new!
it 'should escape text', ->
lang\loadlua('p "<b>"')()
with assert.stub(lang.environment.print)
.was_not_called_with('<b>')
.was_called_with('<b>')
describe 'buffered languages', ->
it 'should buffer text', ->
buffered = lang\buffered!
buffered\loadlua('h1("foo")')()
assert.equal "<h1>foo</h1>", buffered.buffer\concat!
| 28.968254 | 58 | 0.642192 |
2c6f73001135696d3d31d1fc22de6f661d97c644 | 7,876 |
util = require "lapis.util"
json = require "cjson"
tests = {
{
-> util.parse_query_string "field1=value1&field2=value2&field3=value3"
{
{"field1", "value1"}
{"field2", "value2"}
{"field3", "value3"}
field1: "value1"
field2: "value2"
field3: "value3"
}
}
{
-> util.parse_query_string "blahblah"
{
{ "blahblah"}
blahblah: true
}
}
{
-> util.parse_query_string "hello=wo%22rld&thing"
{
{ "hello", 'wo"rld' }
{ "thing" }
hello: 'wo"rld'
thing: true
}
}
{
-> util.parse_query_string "hello=&thing=123&world="
{
{"hello", ""}
{"thing", "123"}
{"world", ""}
hello: ""
thing: "123"
world: ""
}
}
{
-> util.underscore "ManifestRocks"
"manifest_rocks"
}
{
-> util.underscore "ABTestPlatform"
"abtest_platform"
}
{
-> util.underscore "HELLO_WORLD"
"" -- TODO: fix
}
{
-> util.underscore "whats_up"
"whats__up" -- TODO: fix
}
{
-> util.camelize "hello"
"Hello"
}
{
-> util.camelize "world_wide_i_web"
"WorldWideIWeb"
}
{
-> util.camelize util.underscore "ManifestRocks"
"ManifestRocks"
}
{
->
util.encode_query_string {
{"dad", "day"}
"hello[hole]": "wor=ld"
}
"dad=day&hello%5bhole%5d=wor%3dld"
}
{ -- stripping invalid types
->
json.decode util.to_json {
color: "blue"
data: {
height: 10
fn: =>
}
}
{
color: "blue", data: { height: 10}
}
}
{
->
util.build_url {
path: "/test"
scheme: "http"
host: "localhost.com"
port: "8080"
fragment: "cool_thing"
query: "dad=days"
}
"http://localhost.com:8080/test?dad=days#cool_thing"
}
{
->
util.build_url {
host: "dad.com"
path: "/test"
fragment: "cool_thing"
}
"//dad.com/test#cool_thing"
}
{
->
util.build_url {
scheme: ""
host: "leafo.net"
}
"//leafo.net"
}
{
-> util.time_ago os.time! - 34234349
{
{"years", 1}
{"days", 31}
{"hours", 5}
{"minutes", 32}
{"seconds", 29}
years: 1
days: 31
hours: 5
minutes: 32
seconds: 29
}
}
{
-> util.time_ago os.time! + 34234349
{
{"years", 1}
{"days", 31}
{"hours", 5}
{"minutes", 32}
{"seconds", 29}
years: 1
days: 31
hours: 5
minutes: 32
seconds: 29
}
}
{
-> util.time_ago_in_words os.time! - 34234349
"1 year ago"
}
{
-> util.time_ago_in_words os.time! - 34234349, 2
"1 year, 31 days ago"
}
{
-> util.time_ago_in_words os.time! - 34234349, 10
"1 year, 31 days, 5 hours, 32 minutes, 29 seconds ago"
}
{
-> util.time_ago_in_words os.time!
"0 seconds ago"
}
{
-> util.parse_cookie_string "__utma=54729783.634507326.1355638425.1366820216.1367111186.43; __utmc=54729783; __utmz=54729783.1364225235.36.12.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/Q95kO2iEje; __utma=163024063.1111023767.1355638932.1367297108.1367341173.42; __utmb=163024063.1.10.1367341173; __utmc=163024063; __utmz=163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo"
{
__utma: '163024063.1111023767.1355638932.1367297108.1367341173.42'
__utmz: '163024063.1366693549.37.11.utmcsr=t.co|utmccn=(referral)|utmcmd=referral|utmcct=/UYMGwvGJNo'
__utmb: '163024063.1.10.1367341173'
__utmc: '163024063'
}
}
{
-> util.slugify "What is going on right now?"
"what-is-going-on-right-now"
}
{
-> util.slugify "whhaa $%#$ hooo"
"whhaa-hooo"
}
{
-> util.slugify "what-about-now"
"what-about-now"
}
{
-> util.slugify "hello - me"
"hello-me"
}
{
-> util.slugify "cow _ dogs"
"cow-dogs"
}
{
-> util.uniquify { "hello", "hello", "world", "another", "world" }
{ "hello", "world", "another" }
}
{
-> util.trim "what the heck"
"what the heck"
}
{
-> util.trim "
blah blah "
"blah blah"
}
{
-> util.trim_filter {
" ", " thing ",
yes: " "
okay: " no "
}
{ -- TODO: fix indexing?
nil, "thing", okay: "no"
}
}
{
-> util.trim_filter {
hello: " hi"
world: " hi"
yeah: " "
}, {"hello", "yeah"}, 0
{ hello: "hi", yeah: 0 }
}
{
->
util.key_filter {
hello: "world"
foo: "bar"
}, "hello", "yeah"
{ hello: "world" }
}
{
-> "^%()[12332]+$"\match(util.escape_pattern "^%()[12332]+$") and true
true
}
{
-> util.title_case "hello"
"Hello"
}
{
-> util.title_case "hello world"
"Hello World"
}
{
-> util.title_case "hello-world"
"Hello-world"
}
{
-> util.title_case "What my 200 Dollar thing You love to eat"
"What My 200 Dollar Thing You Love To Eat"
}
}
describe "lapis.util", ->
for group in *tests
it "should match", ->
input = group[1]!
if #group > 2
assert.one_of input, { unpack group, 2 }
else
assert.same input, group[2]
it "should autoload", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
mod = util.autoload "things"
assert.equal "yeah", mod.HelloWorld
assert.equal "cool", mod.cool_thing
assert.equal nil, mod.not_here
assert.equal nil, mod.not_here
assert.equal "cool", mod.cool_thing
it "should autoload with starting table", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
mod = util.autoload "things", { dad: "world" }
assert.equal "yeah", mod.HelloWorld
assert.equal "cool", mod.cool_thing
assert.equal "world", mod.dad
it "should autoload with multiple prefixes", ->
package.loaded["things.hello_world"] = "yeah"
package.loaded["things.cool_thing"] = "cool"
package.loaded["wings.cool_thing"] = "very cool"
package.loaded["wings.hats"] = "off to you"
mod = util.autoload "wings", "things"
assert.equal "off to you", mod.hats
assert.equal "very cool", mod.CoolThing
assert.equal "yeah", mod.hello_world
assert.equal "yeah", mod.HelloWorld
it "should singularize words", ->
words = {
{"banks", "bank"}
{"chemists", "chemist"}
{"hospitals", "hospital"}
{"letters", "letter"}
{"vallys", "vally"}
{"keys", "key"}
{"industries", "industry"}
{"ladies", "lady"}
{"heroes", "hero"}
{"torpedoes", "torpedo"}
-- these will never work
-- {"halves", "half"}
-- {"leaves", "leaf"}
-- {"wives", "wife"}
}
for {plural, single} in *words
assert.same single, util.singularize plural
describe "lapis.util.mixin", ->
it "should mixin mixins", ->
import insert from table
log = {}
class Mixin
new: =>
insert log, "initializing Mixin"
@thing = { "hello" }
pop: =>
add_one: (num) =>
insert log, "Before add_one (Mixin), #{num}"
class Mixin2
new: =>
insert log, "initializing Mixin2"
add_one: (num) =>
insert log, "Before add_one (Mixin2), #{num}"
class One
util.mixin Mixin
util.mixin Mixin2
add_one: (num) =>
num + 1
new: =>
insert log, "initializing One"
o = One!
assert.equal 13, o\add_one(12)
assert.same {
"initializing One"
"initializing Mixin"
"initializing Mixin2"
"Before add_one (Mixin2), 12"
"Before add_one (Mixin), 12"
}, log
| 18.575472 | 430 | 0.53352 |
0481ecb073649b8840a7a430bbf72f9004ba442b | 976 | #!/usr/bin/env moon
-- vim: ts=2 sw=2 et :
package.moonpath = '../src/?.moon;' .. package.moonpath
import Rand,sorted,fmt,said from require "fun"
import cat,sum,csv,cli,eg from require "fun"
import Num from require "col"
import Cols from require "data"
eg={}
eg.rand= ->
eqs=(a1,a2) ->
for j,x in pairs a1 do return false if a2[j]!=x
return true
n = 10^4
Rand.seed=1
r=Rand!
a1= sorted [r\any(10,20) for _=1,n]
Rand.seed=1
r=Rand!
a2= sorted [r\any(10,20) for _=1,n]
for i=1,10 do print(r\any())
assert eqs(a1,a2)
eg.csv= ->
a2=[a1 for a1 in csv "../etc/data/auto93.csv"]
assert 399==#a2
assert "number"==type(a2[#a2][1])
eg.say= ->
c = Cols {"A?", "B","C-"}
print #c.all
print c.xs[1].txt
said(c.all)
said(true)
said({1,2,3,4})
eg.cat= -> assert "10, 20, 30" == cat({10,20,30})
eg.fmt= ->
x=3
assert "1.111 2.22 3.33" ==fmt("%5.#{x}f %5.2f %5.2f", 1.1111,2.2222,3.333)
eg.sum= -> assert 10==sum( {1,2,3,4})
cli eg
| 21.217391 | 79 | 0.584016 |
95adc287cdccc511a44a9d97edc86484fc04f0e2 | 589 | import config from require "lazuli.config"
config {"development","test","production"},->
set "appname", "<EDIT THIS>"
config {"development","test"}, ->
postgres ->
database "<EDIT THIS>"
password "<EDIT THIS>"
session_name "<EDIT THIS>"
secret "<EDIT THIS>"
port 8089
modules ->
user_management ->
providers ->
set "lazuli.modules.user_management.providers.example_false", true
config "production", ->
postgres ->
database "<EDIT THIS>"
password "<EDIT THIS>"
port 8081 -- EDIT THIS
session_name "<EDIT THIS>"
secret "<EDIT THIS>"
| 22.653846 | 74 | 0.646859 |
cff089b9da8e4b43b109394d479bf58a49bcdb92 | 729 | state = {
current: {}
global: {
update: {}
draw: {}
}
}
setmetatable state, state
state.new = => {}
state.set = (path, args) =>
@current.unload! if @current.unload
matches = {}
for match in string.gmatch path, "[^;]+"
matches[#matches + 1] = match
path = matches[1]
package.loaded[path] = false
@current = require path
@
state.load = =>
@current\load! if @current.load
@
state.update = (dt) =>
@current\update dt if @current.update
@
state.draw = =>
@current\draw! if @current.update
@
state.press = (key, isrepeat) =>
@current\press key, isrepeat if @current.press
@
state.release = (key, isrepeat) =>
@current\release key, isrepeat if @current.release
@
state
| 14.58 | 52 | 0.610425 |
3eb467a580d976f002e283e9c24470dca1070634 | 850 | -- support module for interfacing with bzext
Module = require("module")
rx = require("rx")
class NetSocketModule extends Module
new: (parent, serviceManager) =>
super(parent, serviceManager)
@serviceManager = serviceManager
@sockets = {}
@nextId = 1
@subscriptions = {}
update: () =>
for i, v in pairs(@sockets)
if not v\isClosed()
v\_update()
else
@unregSocket(i)
unregSocket: (id) =>
if @subscriptions[id]
@subscriptions[id]\unsubscribe()
@sockets[id] = nil
handleSocket: (socket) =>
id = @nextId
@nextId += 1
@sockets[id] = socket
if socket.mode == "ACCEPT"
sub = socket\accept()\subscribe(@\handleSocket, nil, nil)
@subscriptions[id] = sub
return {
:NetSocketModule,
:getUserId,
:getAppInfo,
:readString,
:writeString,
} | 20.238095 | 63 | 0.611765 |
6126c79dccae3a148deb4b3dc0340c7d63e07841 | 3,386 |
--
-- Copyright (C) 2017-2019 DBot
-- 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.
doPatch = =>
return if not @IsValid()
local target
for _, child in ipairs @GetChildren()
if child\GetName() == 'DIconLayout'
target = child
break
return if not target
local buttonTarget
for _, button in ipairs target\GetChildren()
buttonChilds = button\GetChildren()
cond1 = buttonChilds[1] and buttonChilds[1]\GetName() == 'DLabel'
cond2 = buttonChilds[2] and buttonChilds[2]\GetName() == 'DLabel'
if cond1 and buttonChilds[1]\GetText() == 'Player Model'
buttonTarget = button
break
elseif cond2 and buttonChilds[2]\GetText() == 'Player Model'
buttonTarget = button
break
return if not buttonTarget
{:title, :init, :icon, :width, :height, :onewindow} = list.Get('DesktopWindows').PlayerEditor
buttonTarget.DoClick = ->
return buttonTarget.Window\Center() if onewindow and IsValid(buttonTarget.Window)
buttonTarget.Window = @Add('DFrame')
with buttonTarget.Window
\SetSize(width, height)
\SetTitle(title)
\Center()
init(buttonTarget, buttonTarget.Window)
local targetModel
for _, child in ipairs buttonTarget.Window\GetChildren()
if child\GetName() == 'DModelPanel'
targetModel = child
break
return if not targetModel
targetModel.oldSetModel = targetModel.SetModel
targetModel.SetModel = (model) =>
oldModel = @Entity\GetModel()
oldPonyData = @Entity\GetPonyData()
@oldSetModel(model)
if IsValid(@Entity) and oldPonyData
oldPonyData\SetupEntity(@Entity)
oldPonyData\ModelChanges(oldModel, model)
targetModel.PreDrawModel = (ent) =>
controller = @ponyController
return if not controller
return if not ent\IsPony()
controller\SetupEntity(ent) if controller.ent ~= ent
controller\GetRenderController()\DrawModels()
controller\GetRenderController()\PreDraw(ent)
controller\GetRenderController()\HideModels(true)
bg = controller\GetBodygroupController()
bg\ApplyBodygroups() if bg
copy = PPM2.GetMainData()\Copy()
controller = copy\CreateCustomController(targetModel.Entity)
copy\SetController(controller)
controller\SetDisableTask(true)
targetModel.ponyController = controller
hook.Run 'BuildPlayerModelMenu', buttonTarget, buttonTarget.Window
hook.Add 'ContextMenuCreated', 'PPM2.PatchPlayerModelMenu', => timer.Simple 0, -> doPatch(@)
| 36.021277 | 94 | 0.746604 |
83afb252071e0c6ddd5446b5de7fe1fbc5c5e15f | 677 | class Menu
new: (@options={}, @x=0, @y=0) =>
@curr_option = 1
@key_wait = 0.2
@key_dt = @key_wait
update: (dt) =>
@key_dt += dt
if @key_dt >= @key_wait
if love.keyboard.isDown('down')
@curr_option = (@curr_option % #@options) + 1
@key_dt = 0
elseif love.keyboard.isDown('up')
@curr_option = (@curr_option - 2) % #@options + 1
@key_dt = 0
if love.keyboard.isDown('return')
@options[@curr_option].action!
draw: (x=@x, y=@y) =>
for i = 1,#@options
if i == @curr_option
love.graphics.print '>', x - 12, y + 20*(i-1)
love.graphics.print @options[i].tag, x, y + 20*(i-1)
| 26.038462 | 58 | 0.530281 |
a1942f17612cb05967e46f45cf518c73f65a8202 | 3,436 | lapis = require "lapis"
db = require "lapis.db"
import Users, Posts, Likes from require "spec_mysql.models"
assert = require "luassert"
assert_same_rows = (a, b) ->
a = {k,v for k,v in pairs a}
b = {k,v for k,v in pairs b}
a.created_at = nil
a.updated_at = nil
b.created_at = nil
b.updated_at = nil
assert.same a, b
class extends lapis.Application
@before_filter ->
Users\truncate!
Posts\truncate!
Likes\truncate!
"/": =>
json: db.query "show tables like ?", "users"
"/migrations": =>
import create_table, types from require "lapis.db.mysql.schema"
require("lapis.db.migrations").run_migrations {
=>
create_table "migrated_table", {
{"id", types.id}
{"name", types.varchar}
}
}
json: { success: true }
"/basic-model/create": =>
first = Users\create { name: "first" }
second = Users\create { name: "second" }
assert.truthy first.id
assert.same "first", first.name
assert.same first.id + 1, second.id
assert.same "second", second.name
-- TODO: looks like resty-mysql returns strings for count rows
assert.same "2", Users\count!
json: { success: true }
"/basic-model/find": =>
first = Users\create { name: "first" }
second = Users\create { name: "second" }
assert.same "2", Users\count!
assert.same first, Users\find first.id
assert.same second, Users\find second.id
assert.same second, Users\find name: "second"
assert.falsy Users\find name: "second", id: first.id
assert.same first, Users\find id: "#{first.id}"
json: { success: true }
"/basic-model/select": =>
first = Users\create { name: "first" }
second = Users\create { name: "second" }
things = Users\select!
assert.same 2, #things
things = Users\select "order by name desc"
assert "second", things[1].name
assert "first", things[2].name
things = Users\select "order by id asc", fields: "id"
assert.same {{id: first.id}, {id: second.id}}, things
things = Users\find_all {first.id, second.id + 22}
assert.same {first}, things
things = Users\find_all {first.id,second.id}, where: {
name: "second"
}
assert.same {second}, things
json: { success: true }
"/primary-key/create": =>
like = Likes\create {
user_id: 40
post_id: 22
count: 1
}
assert.same 40, like.user_id
assert.same 22, like.post_id
assert.truthy like.created_at
assert.truthy like.updated_at
assert.same like, Likes\find 40, 22
json: { success: true }
"/primary-key/delete": =>
like = Likes\create {
user_id: 1
post_id: 2
count: 1
}
other_like = Likes\create {
user_id: 4
post_id: 6
count: 2
}
like\delete!
assert.has_error ->
like\refresh!
remaining = Likes\select!
assert.same 1, #remaining
assert_same_rows other_like, remaining[1]
json: { success: true }
"/primary-key/update": =>
like = Likes\create {
user_id: 1
post_id: 2
count: 1
}
other_like = Likes\create {
user_id: 4
post_id: 6
count: 2
}
like\update {
count: 5
}
assert.same 5, like.count
assert_same_rows like, Likes\find(like.user_id, like.post_id)
assert_same_rows other_like, Likes\find(other_like.user_id, other_like.post_id)
json: { success: true }
| 21.341615 | 83 | 0.610012 |
f3368043ee0a2086d36fc811a45e1f52ed340105 | 522 | export state = {}
organism = require "src/organism"
state.load = =>
@world = {}
for i = 0, 200
@spawn organism.agent.make 5
state.spawn = (a) =>
@world[#@world + 1] = a
state.update = (dt) =>
for element in *@world
element\update dt if element.update
table.sort @world, (a, b) -> a.scale < b.scale -- n sorting lol
state.draw = =>
with love.graphics
.push!
.translate .getWidth! / 2, .getHeight! / 2
for element in *@world
element\draw! if element.draw
.pop!
state | 14.5 | 65 | 0.59387 |
071a98d8536ff117d4ef5f63aeb0f3b8d8c42232 | 29,371 | {:Buffer, :config} = howl
{:File} = howl.io
{:with_tmpfile} = File
ffi = require 'ffi'
describe 'Buffer', ->
buffer = (text) ->
with Buffer {}
.text = text
describe '.text', ->
it '.text allows setting and retrieving the buffer text', ->
b = Buffer {}
assert.equal b.text, ''
b.text = 'Ipsum'
assert.equal 'Ipsum', b.text
it 'transforms incorrect input', ->
b = Buffer {}
b.text = '|\x80|'
assert.equal '|�|', b.text
it '.size returns the size of the buffer text, in bytes', ->
assert.equal buffer('hello').size, 5
assert.equal buffer('åäö').size, 6
it '.length returns the size of the buffer text, in characters', ->
assert.equal 5, buffer('hello').length
assert.equal 3, buffer('åäö').length
it '.modified indicates and allows setting the modified status', ->
b = Buffer {}
assert.is_false b.modified
b.text = 'hello'
assert.is_true b.modified
b.modified = false
assert.is_false b.modified
b.modified = true
assert.is_true b.modified
assert.equal b.text, 'hello' -- toggling should not have changed text
describe '.last_changed', ->
sys = howl.sys
it 'is set to the current time for a new buffer', ->
b = buffer 'time'
now = math.floor sys.time!
assert.is_true math.floor(b.last_changed) > now - 1
assert.is_true math.floor(b.last_changed) <= now
it 'is updated whenever the buffer is changed in some way', ->
b = buffer 'time'
cur = b.last_changed
b\insert 'foo', 1
assert.is_true b.last_changed > cur
cur = b.last_changed
b\delete 1, 3
assert.is_true b.last_changed > cur
it '.read_only can be set to mark the buffer as read-only', ->
b = buffer 'kept'
b.read_only = true
assert.equal true, b.read_only
assert.raises 'read%-only', -> b\append 'illegal'
assert.raises 'read%-only', -> b\insert 'illegal', 1
assert.raises 'read%-only', -> b.text = 'illegal'
assert.equal 'kept', b.text
b.read_only = false
b\append ' yes'
assert.equal 'kept yes', b.text
describe '.file = <file>', ->
b = buffer ''
it 'sets the title to the basename of the file', ->
with_tmpfile (file) ->
b.file = file
assert.equal b.title, file.basename
describe 'when <file> exists', ->
describe 'and the buffer is not modified', ->
before_each ->
config.reset!
config.define name: 'buf_var', description: 'some var', default: 'def value'
b.text = 'foo'
b.modified = false
b.config.buf_var = 'orig_value'
it 'sets the buffer text to the contents of the file', ->
with_tmpfile (file) ->
file.contents = 'yes sir'
b.file = file
assert.equal b.text, 'yes sir'
it 'preserves the buffer config', ->
with_tmpfile (file) ->
b.file = file
assert.equal b.config.buf_var, 'orig_value'
it 'transforms and flags incorrect UTF-8 as input', ->
with_tmpfile (file) ->
file.contents = '|\x80|'
b.file = file
assert.equal b.text, '|�|'
assert.is_true b.modified
it 'overwrites any existing buffer text even if the buffer is modified', ->
b.text = 'foo'
with_tmpfile (file) ->
file.contents = 'yes sir'
b.file = file
assert.equal b.text, 'yes sir'
describe 'when <file> does not exist', ->
it 'set the buffer text to the empty string', ->
b.text = 'foo'
with_tmpfile (file) ->
file\delete!
b.file = file
assert.equal '', b.text
it 'marks the buffer as not modified', ->
with_tmpfile (file) ->
b.file = file
assert.is_false b.modified
it 'clears the undo history', ->
with_tmpfile (file) ->
b.file = file
assert.is_false b.can_undo
describe '.eol', ->
it 'is "\\n" by default', ->
assert.equals '\n', buffer('').eol
it 'raises an error if a assignment value is unknown', ->
assert.raises 'Unknown', -> buffer('').eol = 'foo'
it 'is adjusted automatically when a file is loaded', ->
b = buffer('')
with_tmpfile (plain_file) ->
with_tmpfile (file) ->
file.contents = 'o hai\r\nDOS'
b.file = file
assert.equals '\r\n', b.eol
b.file = plain_file
file.contents = 'o hai\nNIX'
b.file = file
assert.equals '\n', b.eol
b.file = plain_file
file.contents = 'venerable\rMac'
b.file = file
assert.equals '\r', b.eol
it '.properties is a table', ->
assert.equal 'table', type buffer('').properties
it '.data is a table', ->
assert.equal 'table', type buffer('').data
it '.showing is true if the buffer is currently referenced in any view', ->
b = buffer ''
assert.false b.showing
b\add_view_ref!
assert.true b.showing
describe '.multibyte', ->
it 'returns true if the buffer contains multibyte characters', ->
assert.is_false buffer('vanilla').multibyte
assert.is_true buffer('HƏllo').multibyte
it 'is updated whenever text is inserted', ->
b = buffer 'vanilla'
b\append 'Bačon'
assert.is_true b.multibyte
it 'is updated whenever text is deleted', ->
b = buffer 'Bačon'
b\delete 3, 5
assert.is_false b.multibyte
describe '.modified_on_disk', ->
it 'is false for a buffer with no file', ->
assert.is_false Buffer!.modified_on_disk
it "is true if the file's etag is changed after a load or save", ->
file = contents: 'foo', etag: '1', basename: 'changeable', exists: true, path: '/tmp/changeable'
b = Buffer!
b.file = file
file.etag = '2'
assert.is_true b.modified_on_disk
b\save!
assert.is_false b.modified_on_disk
describe '.config', ->
before_each ->
config.reset!
config.define_layer 'mode:config'
config.define name: 'buf_var', description: 'some var', default: 'def value'
it 'allows reading and writing (local) variables', ->
b = buffer 'config'
assert.equal 'def value', b.config.buf_var
b.config.buf_var = 123
assert.equal 123, b.config.buf_var
assert.equal 'def value', config.buf_var
it 'is chained to the mode config when available', ->
mode_config = config.proxy '', 'mode:config'
mode = config_layer: 'mode:config'
b = buffer 'config'
b.mode = mode
mode_config.buf_var = 'from_mode'
assert.equal 'from_mode', b.config.buf_var
it 'is chained to the global config when mode config is not available', ->
b = buffer 'config'
b.mode = {}
assert.equal 'def value', b.config.buf_var
it 'each new buffer gets a distinct config', ->
b1 = buffer 'config'
b2 = buffer 'config'
b1.config.buf_var = 'b1_value'
b2.config.buf_var = 'b2_value'
assert.equal 'b1_value', b1.config.buf_var
assert.equal 'b2_value', b2.config.buf_var
it 'uses a buffer scoped config for unsaved files', ->
b1 = buffer 'unsaved'
b1.config.buf_var = 'b1_value'
assert.equal 'b1_value', config.get 'buf_var', 'buffer/'..b1.id
it 'uses a file scoped config when associated with a file', ->
b1 = buffer 'saved'
with_tmpfile (file) ->
b1.file = file
b1.config.buf_var = 'f1_value'
assert.equal 'f1_value', config.get 'buf_var', 'file'..file.path
assert.equal 'def value', config.get 'buf_var', 'buffer'..b1.id
describe 'delete(start_pos, end_pos)', ->
it 'deletes the specified range, inclusive', ->
b = buffer 'ño örf'
b\delete 2, 4
assert.equal 'ñrf', b.text
it 'does nothing if end_pos is smaller than start_pos', ->
b = buffer 'hello'
b\delete 2, 1
assert.equal 'hello', b.text
describe 'insert(text, pos)', ->
it 'inserts text at pos', ->
b = buffer 'ño señor'
b\insert 'me gusta ', 4
assert.equal 'ño me gusta señor', b.text
it 'returns the position right after the inserted text', ->
b = buffer ''
assert.equal 6, b\insert 'Bačon', 1
it 'transforms incorrect input', ->
b = buffer ''
assert.equal 4, b\insert '|\x80|', 1
assert.equal '|�|', b.text
describe 'append(text)', ->
it 'appends the specified text', ->
b = buffer 'hello'
b\append ' world'
assert.equal 'hello world', b.text
it 'returns the position right after the inserted text', ->
b = buffer ''
assert.equal 6, b\append 'Bačon'
it 'transforms incorrect input', ->
b = buffer ''
assert.equal 4, b\append '|\x80|'
assert.equal '|�|', b.text
describe 'replace(pattern, replacement)', ->
it 'replaces all occurences of pattern with replacement', ->
b = buffer 'hello\nuñi©ode\nworld\n'
b\replace '[lo]', ''
assert.equal 'he\nuñi©de\nwrd\n', b.text
it 'transforms incorrect replacements', ->
b = buffer 'XX'
b\replace 'X', '\x80'
assert.equal '��', b.text
context 'when pattern contains a leading grouping', ->
it 'replaces only the match within pattern with replacement', ->
b = buffer 'hello\nworld\n'
b\replace '(hel)lo', ''
assert.equal 'lo\nworld\n', b.text
it 'returns the number of occurences replaced', ->
b = buffer 'hello\nworld\n'
assert.equal 1, b\replace('world', 'editor')
describe 'change(start_pos, end_pos, f)', ->
it 'applies all operations as one undo for the specified region', ->
b = buffer 'ño señor'
b\change 4, 6, -> -- 'señ'
b\delete 4, 6
b\insert 'minmin', 4
assert.equal 'ño minminor', b.text
b\undo!
assert.equal 'ño señor', b.text
it 'returns the return value of <f> as its own return value', ->
b = buffer '12345'
ret = b\change 1, 3, ->
'zed'
assert.equals 'zed', ret
describe 'undo', ->
it 'undoes the last operation', ->
b = buffer 'hello'
b\delete 1, 1
b\undo!
assert.equal 'hello', b.text
it 'resets the .modified flag when at last saved file revision', ->
with_tmpfile (file) ->
b = buffer ''
b.file = file
b.text = 'hello'
b\delete 1, 1
b\save!
b\delete 1, 1
assert.equal true, b.modified
b\undo!
assert.equal false, b.modified
b\undo!
assert.equal true, b.modified
it 'resets the .modified flag when at originally loaded revision', ->
with_tmpfile (file) ->
file.contents = 'hello hello'
b = buffer ''
b.file = file
b\delete 1, 1
assert.equal true, b.modified
b\undo!
assert.equal false, b.modified
describe 'redo', ->
it 'redoes the last undo operation', ->
b = buffer 'hello'
b\delete 1, 1
b\undo!
b\redo!
assert.equal 'ello', b.text
it 'resets the .modified flag when at synced file revision', ->
with_tmpfile (file) ->
b = buffer ''
b.file = file
b.text = 'hello'
b\delete 1, 1
b\save!
b\delete 1, 1
b\undo!
b\undo!
assert.equal true, b.modified
b\redo!
assert.equal false, b.modified
b\redo!
assert.equal true, b.modified
it '.can_undo returns true if undo is possible, and false otherwise', ->
b = Buffer {}
assert.is_false b.can_undo
b.text = 'bar'
assert.is_true b.can_undo
b\undo!
assert.is_false b.can_undo
describe '.can_undo = <bool>', ->
it 'setting it to false removes any undo history', ->
b = buffer 'hello'
assert.is_true b.can_undo
b.can_undo = false
assert.is_false b.can_undo
b\undo!
assert.equal b.text, 'hello'
it 'setting it to true is a no-op', ->
b = buffer 'hello'
assert.is_true b.can_undo
b.can_undo = true
assert.is_true b.can_undo
b\undo!
b.can_undo = true
assert.is_false b.can_undo
describe '.collect_revisions', ->
context 'when set to false', ->
it 'does not collect undo information', ->
b = Buffer {}
b.collect_revisions = false
b\append 'foo!'
assert.is_false b.can_undo
it 'clears existing undo information', ->
b = buffer 'zed'
assert.is_true b.can_undo
b.collect_revisions = false
assert.is_false b.can_undo
describe 'as_one_undo(f)', ->
it 'allows for grouping actions as one undo', ->
b = buffer 'hello'
b\as_one_undo ->
b\delete 1, 1
b\append 'foo'
b\undo!
assert.equal 'hello', b.text
context 'when f raises an error', ->
it 'propagates the error', ->
b = buffer 'hello'
assert.raises 'oh my', ->
b\as_one_undo -> error 'oh my'
it 'ends the undo transaction', ->
b = buffer 'hello'
assert.error -> b\as_one_undo ->
b\delete 1, 1
error 'oh noes what happened?!?'
b\append 'foo'
b\undo!
assert.equal b.text, 'ello'
describe 'save()', ->
context 'when a file is assigned', ->
it 'stores the contents of the buffer in the assigned file', ->
text = 'line1\nline2♥\nåäö\n'
b = buffer text
with_tmpfile (file) ->
b.file = file
b.text = text
b\save!
assert.equal text, file.contents
it 'clears the modified flag', ->
with_tmpfile (file) ->
b = buffer 'foo'
b.file = file
b\append ' bar'
assert.is_true b.modified
b\save!
assert.is_false b.modified
context 'when config.strip_trailing_whitespace is false', ->
it 'does not strip trailing whitespace before saving', ->
with_tmpfile (file) ->
config.strip_trailing_whitespace = false
b = buffer ''
b.file = file
b.text = 'blank \n\nfoo \n'
b\save!
assert.equal 'blank \n\nfoo \n', b.text
assert.equal file.contents, b.text
context 'when config.strip_trailing_whitespace is true', ->
it 'strips trailing whitespace at the end of lines before saving', ->
with_tmpfile (file) ->
config.strip_trailing_whitespace = true
b = buffer ''
b.file = file
b.text = 'åäö \n\nfoo \n '
b\save!
assert.equal 'åäö\n\nfoo\n', b.text
assert.equal file.contents, b.text
context 'when config.ensure_newline_at_eof is true', ->
it 'appends a newline if necessary', ->
with_tmpfile (file) ->
config.ensure_newline_at_eof = true
b = buffer ''
b.file = file
b.text = 'look mah no newline!'
b\save!
assert.equal 'look mah no newline!\n', b.text
assert.equal file.contents, b.text
context 'when config.ensure_newline_at_eof is false', ->
it 'does not appends a newline', ->
with_tmpfile (file) ->
config.ensure_newline_at_eof = false
b = buffer ''
b.file = file
b.text = 'look mah no newline!'
b\save!
assert.equal 'look mah no newline!', b.text
assert.equal file.contents, b.text
context 'when config.backup_files is true', ->
it 'backs up files before saving', ->
with_tmpfile (file) ->
mockfile = {}
setmetatable mockfile, {
__index: file
__newindex: (_, key, value) ->
assert key != 'contents', 'mock to test backup_files'
return file[key]
}
with_tmpdir (backups) ->
config.backup_files = true
config.backup_directory = backups.path
b = buffer 'hello'
b.file = file
b\save!
b.file = mockfile
pcall -> b\save!
assert.equal #backups.children, 1
assert.not_nil backups.children[1].basename\match file.basename
describe 'save_as(file)', ->
context 'when <file> does not exist', ->
it 'saves the buffer content in the newly created file', ->
with_tmpfile (file) ->
file\delete!
b = buffer 'new'
b\save_as file
assert.equal 'new', file.contents
context 'when <file> exists', ->
it 'overwrites any previous content with the buffer contents', ->
with_tmpfile (file) ->
file.contents = 'old'
b = buffer 'new'
b\save_as file
assert.equal 'new', file.contents
it 'associates the buffer with <file> henceforth', ->
with_tmpfile (file) ->
file.contents = 'orig'
b = buffer ''
b.file = file
with_tmpfile (new_file) ->
b.text = 'nuevo'
b\save_as new_file
assert.equal 'nuevo', new_file.contents
assert.equal new_file, b.file
describe 'byte_offset(char_offset)', ->
it 'returns the byte offset for the given <char_offset>', ->
b = buffer 'äåö'
for p in *{
{1, 1},
{3, 2},
{5, 3},
{7, 4},
}
assert.equal p[1], b\byte_offset p[2]
it 'adjusts out-of-bounds offsets', ->
assert.equal 7, buffer'äåö'\byte_offset 5
assert.equal 7, buffer'äåö'\byte_offset 10
assert.equal 1, buffer'äåö'\byte_offset 0
assert.equal 1, buffer'äåö'\byte_offset -1
describe 'char_offset(byte_offset)', ->
it 'returns the character offset for the given <byte_offset>', ->
b = buffer 'äåö'
for p in *{
{1, 1},
{3, 2},
{5, 3},
{7, 4},
}
assert.equal p[2], b\char_offset p[1]
it 'adjusts out-of-bounds offsets', ->
assert.equal 3, buffer'ab'\char_offset 4
assert.equal 1, buffer'äåö'\char_offset 0
assert.equal 1, buffer'a'\char_offset -1
describe 'sub(start_pos, end_pos)', ->
it 'returns the text between start_pos and end_pos, both inclusive', ->
b = buffer 'hållö\nhållö\n'
assert.equal 'h', b\sub(1, 1)
assert.equal 'å', b\sub(2, 2)
assert.equal 'hållö', b\sub(1, 5)
assert.equal 'hållö\nhållö\n', b\sub(1, 12)
assert.equal 'ållö', b\sub(8, 11)
assert.equal '\n', b\sub(12, 12)
assert.equal '\n', b\sub(12, 13)
it 'handles negative indices by counting from end', ->
b = buffer 'hållö\nhållö\n'
assert.equal '\n', b\sub(-1, -1)
assert.equal 'hållö\n', b\sub(-6, -1)
assert.equal 'hållö\nhållö\n', b\sub(-12, -1)
it 'returns empty string for start_pos > end_pos', ->
b = buffer 'abc'
assert.equal '', b\sub(2, 1)
it 'handles out-of-bounds offsets gracefully', ->
assert.equals '', buffer'abc'\sub 4, 6
assert.equals 'abc', buffer'abc'\sub 1, 6
describe 'find(pattern [, init ])', ->
it 'searches forward', ->
b = buffer 'ä öx'
assert.same { 1, 4 }, { b\find 'ä öx' }
assert.same { 2, 3 }, { b\find ' ö' }
assert.same { 3, 4 }, { b\find 'öx' }
assert.same { 4, 4 }, { b\find 'x' }
it 'searches forward from init when specified', ->
b = buffer 'öåååö'
assert.same { 2, 3 }, { b\find 'åå', 2 }
assert.same { 3, 4 }, { b\find 'åå', 3 }
assert.is_nil b\find('åå', 4)
it 'negative init specifies offset from end', ->
b = buffer 'öååååö'
assert.same { 4, 5 }, { b\find 'åå', -3 }
assert.same { 2, 3 }, { b\find 'åå', -5 }
assert.is_nil b\find('åå', -2)
it 'returns nil for out of bounds init', ->
b = buffer 'abcde'
assert.is_nil b\find('a', -6)
assert.is_nil b\find('a', 6)
describe 'rfind(pattern [, init ])', ->
it 'searches backward from end', ->
b = buffer 'äöxöx'
assert.same { 1, 3 }, { b\rfind 'äöx' }
assert.same { 4, 5 }, { b\rfind 'öx' }
assert.same { 5, 5 }, { b\rfind 'x' }
it 'searches backward from init when specified', ->
b = buffer 'öååååö'
assert.same { 4, 5 }, { b\rfind 'åå', 5 }
assert.same { 3, 4 }, { b\rfind 'åå', 4 }
assert.is_nil b\rfind('åå', 2)
it 'negative init specifies offset from end', ->
b = buffer 'öååååö'
assert.same { 4, 5 }, { b\rfind 'åå', -2 }
assert.same { 2, 3 }, { b\rfind 'åå', -4 }
assert.is_nil b\rfind('åå', -5)
it 'returns nil for out of bounds init', ->
b = buffer 'abcde'
assert.is_nil b\rfind('a', -6)
assert.is_nil b\rfind('a', 6)
describe 'mode_at(pos)', ->
it 'returns the mode at the given offset', ->
b = buffer 'abc def ghi jkl'
b.mode = { comment_syntax: '//' }
mode_at_test = { comment_syntax: '#' }
mode_reg = name: 'mode_at_test', create: -> mode_at_test
howl.mode.register mode_reg
b._buffer\style 1, {
1, 's1', 3,
5, { 1, 's3', 3 }, 'mode_at_test|s2',
9, { 1, 's3', 3 }, 'nonexistent_mode|s2',
13, 's1', 15,
}
assert.same '//', b\mode_at(1).comment_syntax
assert.same '//', b\mode_at(2).comment_syntax
assert.same '//', b\mode_at(3).comment_syntax
assert.same '//', b\mode_at(4).comment_syntax
assert.same '#', b\mode_at(5).comment_syntax
assert.same '#', b\mode_at(6).comment_syntax
assert.same '#', b\mode_at(7).comment_syntax
assert.same '//', b\mode_at(8).comment_syntax
assert.same '//', b\mode_at(9).comment_syntax
assert.same '//', b\mode_at(10).comment_syntax
assert.same '//', b\mode_at(11).comment_syntax
assert.same '//', b\mode_at(12).comment_syntax
assert.same '//', b\mode_at(13).comment_syntax
assert.same '//', b\mode_at(14).comment_syntax
assert.same '//', b\mode_at(15).comment_syntax
howl.mode.unregister 'mode_at_test'
describe 'reload(force = false)', ->
it 'reloads the buffer contents from file and returns true', ->
with_tmpfile (file) ->
b = buffer ''
file.contents = 'hello'
b.file = file
file.contents = 'there'
assert.is_true b\reload!
assert.equal 'there', b.text
it 'raises an error if the buffer is not associated with a file', ->
assert.raises 'file', -> Buffer!\reload!
context 'when the buffer is modified', ->
it 'leaves the buffer alone and returns false', ->
with_tmpfile (file) ->
b = buffer ''
file.contents = 'hello'
b.file = file
b\append ' world'
file.contents = 'there'
assert.is_false b\reload!
assert.equal 'hello world', b.text
it 'specifying <force> as true reloads the buffer anyway', ->
with_tmpfile (file) ->
b = buffer ''
file.contents = 'hello'
b.file = file
b\append ' world'
file.contents = 'there'
assert.is_true b\reload true
assert.equal 'there', b.text
it '#buffer returns the number of characters in the buffer', ->
assert.equal 5, #buffer('hello')
assert.equal 3, #buffer('åäö')
it 'tostring(buffer) returns the buffer title', ->
b = buffer 'hello'
b.title = 'foo'
assert.equal tostring(b), 'foo'
describe '.add_view_ref()', ->
it 'increments the number of viewers', ->
b = buffer ''
b\add_view_ref!
assert.equal 1, b.viewers
describe '.remove_view_ref()', ->
it 'decrements the number of viewers', ->
b = buffer ''
b\add_view_ref!
b\remove_view_ref!
assert.equal 0, b.viewers
describe 'resolve_span(span, line_nr = nil)', ->
local buf
before_each ->
buf = buffer '123åäö789'
it 'accepts .start_pos and .end_pos', ->
assert.same {4, 7}, {buf\resolve_span start_pos: 4, end_pos: 7}
it 'accepts .byte_start_pos as the start specifier', ->
assert.same {5, 7}, {buf\resolve_span byte_start_pos: 6, end_pos: 7}
it 'accepts .byte_end_pos as the end specifier', ->
assert.same {4, 5}, {buf\resolve_span start_pos: 4, byte_end_pos: 6}
it 'accepts .count as the end specifier', ->
assert.same {4, 7}, {buf\resolve_span start_pos: 4, count: 3}
it "accepts a sole line_nr argument, returning the entire line's span", ->
assert.same {1, 10}, {buf\resolve_span line_nr: 1}
context 'with a .line_nr given', ->
it "accepts .start_column as the start specifier", ->
assert.same {5, 10}, {buf\resolve_span line_nr: 1, start_column: 5}
it "accepts .byte_start_column as the start specifier", ->
assert.same {5, 10}, {buf\resolve_span line_nr: 1, byte_start_column: 6}
it "accepts .end_column as the end specifier", ->
assert.same {1, 5}, {buf\resolve_span line_nr: 1, end_column: 5}
it "accepts .byte_end_column as the end specifier", ->
assert.same {1, 5}, {buf\resolve_span line_nr: 1, byte_end_column: 6}
context 'with a line_nr parameter given', ->
it "accepts .start_column as the start specifier", ->
assert.same {5, 10}, {buf\resolve_span {start_column: 5}, 1}
it "accepts .byte_start_column as the start specifier", ->
assert.same {5, 10}, {buf\resolve_span {byte_start_column: 6}, 1}
it "accepts .end_column as the end specifier", ->
assert.same {1, 5}, {buf\resolve_span {end_column: 5}, 1}
it "accepts .byte_end_column as the end specifier", ->
assert.same {1, 5}, {buf\resolve_span {byte_end_column: 6}, 1}
describe 'get_ptr(start_pos, end_pos)', ->
assert_returns = (s, count, ...) ->
r_ptr, r_count = ...
assert.equals count, r_count
assert.equals s, ffi.string(r_ptr, r_count)
it 'returns a pointer to a char buffer for the span, and a byte count', ->
b = buffer '123456789'
assert_returns '3456', 4, b\get_ptr(3, 6)
b = buffer '1åäö8'
assert_returns 'äö', 4, b\get_ptr(3, 4)
it 'handles boundary conditions', ->
b = buffer '123'
assert_returns '123', 3, b\get_ptr(1, 3)
assert_returns '1', 1, b\get_ptr(1, 1)
it 'returns a zero pointer for an empty range', ->
b = buffer ''
assert_returns '', 0, b\get_ptr(1, 0)
it 'raises errors for illegal span values', ->
b = buffer '123'
assert.raises 'Illegal', -> b\get_ptr -1, 2
assert.raises 'Illegal', -> b\get_ptr 1, 4
assert.raises 'Illegal', -> b\get_ptr 3, 4
it 'returns a read-only pointer', ->
b = buffer '123'
ptr = b\get_ptr 1, 1
assert.raises 'constant', -> ptr[0] = 88
describe 'titles', ->
it 'uses file basename as the default title', ->
b = Buffer {}
b.file = File('/path/to/file.ext')
assert.equal b.title, 'file.ext'
it 'setting title explicitly overrides default title', ->
b = Buffer {}
b.file = File('/path/to/file.ext')
b.title = 'be something else'
assert.equal b.title, 'be something else'
describe 'signals', ->
it 'buffer-saved is fired whenever a buffer is saved', ->
with_signal_handler 'buffer-saved', nil, (handler) ->
b = buffer 'foo'
with_tmpfile (file) ->
b.file = file
b\save!
assert.spy(handler).was_called!
it 'text-inserted is fired whenever text is inserted into a buffer', ->
with_signal_handler 'text-inserted', nil, (handler) ->
b = buffer 'foo'
b\append 'bar'
assert.spy(handler).was_called!
it 'text-deleted is fired whenever text is deleted from buffer', ->
with_signal_handler 'text-inserted', nil, (handler) ->
b = buffer 'foo'
b\delete 1, 2
assert.spy(handler).was_called!
it 'text-changed is fired whenever text is change:d from buffer', ->
with_signal_handler 'text-changed', nil, (handler) ->
b = buffer 'foo'
b\change 1, 2, ->
b\delete 1, 1
assert.spy(handler).was_called!
it 'buffer-modified is fired whenever a buffer is modified', ->
with_signal_handler 'buffer-modified', nil, (handler) ->
b = buffer 'foo'
b\append 'bar'
assert.spy(handler).was_called!
it 'buffer-reloaded is fired whenever a buffer is reloaded', ->
with_signal_handler 'buffer-reloaded', nil, (handler) ->
with_tmpfile (file) ->
b = buffer 'foo'
b.file = file
b\reload!
assert.spy(handler).was_called!
it 'buffer-mode-set is fired whenever a buffer has its mode set', ->
with_signal_handler 'buffer-mode-set', nil, (handler) ->
b = buffer 'foo'
b.mode = {}
assert.spy(handler).was_called!
it 'buffer-title-set is fired whenever a buffer has its title set', ->
with_signal_handler 'buffer-title-set', nil, (handler) ->
b = buffer 'foo'
b.title = 'Sir Buffer'
assert.spy(handler).was_called!
context 'resource management', ->
it 'buffers are collected properly', ->
b = buffer 'foobar'
buffers = setmetatable { b }, __mode: 'v'
b = nil
collectgarbage!
assert.is_nil buffers[1]
| 32.134573 | 102 | 0.576487 |
ee46756a34d401d76db30011077c507b98106ce8 | 605 | -- bubble_sort.moon
-- prepare number array
-- arr = {}
-- for i = 1,#arg
-- arr[i] = (tonumber arg[i]) or 0
-- if #arr<1
-- arr = {5,8,9,7,4,1,3,2}
--
-- sort
--
swapElement = (arr,i1,i2)->
c = arr[i1]
arr[i1] = arr[i2]
arr[i2] = c
return true
bubble_sort = (arr)->
swapped = true
while swapped
swapped = false
for i = 1,#arr-1
if arr[i+1]<arr[i]
swapped = swapElement arr,i,i+1
return arr
describe "bubble sort", ->
it "test 1", ->
arr = bubble_sort {5,8,9,7,4,1,3,2}
assert.True arr[1]==1
assert.True arr[2]==2
assert.True arr[#arr]==9
| 17.285714 | 39 | 0.545455 |
1bb5b0b56c9e2abeb4a14f393269709031d97325 | 2,006 | -- Copyright 2016-2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:app, :command, :config, :mode, :inspection, :sys} = howl
{:fmt} = bundle_load 'go_fmt'
register_inspections = ->
inspection.register
name: 'golint'
factory: -> {
cmd: 'golint <file>',
type: 'warning',
is_available: -> sys.find_executable('golint'), "`golint` command not found"
}
inspection.register
name: 'gotoolvet'
factory: -> {
cmd: 'go tool vet <file>',
type: 'error',
is_available: -> sys.find_executable('go'), "`go` command not found"
}
register_mode = ->
mode_reg =
name: 'go'
aliases: 'golang'
extensions: 'go'
create: -> bundle_load('go_mode')
parent: 'curly_mode'
mode.register mode_reg
register_commands = ->
command.register
name: 'go-fmt',
description: 'Run go fmt on the current buffer and reload if reformatted'
handler: ->
buffer = app.editor.buffer
if buffer.mode.name != 'go'
log.error 'Buffer is not a go mode buffer'
return
fmt buffer
register_mode!
register_commands!
register_inspections!
with config
.define
name: 'go_fmt_on_save'
description: 'Whether to run gofmt when go files are saved'
default: true
type_of: 'boolean'
.define
name: 'go_fmt_command'
description: 'Command to run for go-fmt'
default: 'gofmt'
scope: 'global'
.define
name: 'go_complete'
description: 'Whether to use gocode completions in go mode'
default: true
type_of: 'boolean'
.define
name: 'gogetdoc_path',
description: 'Path to gogetdoc executable'
default: 'gogetdoc'
scope: 'global'
unload = ->
mode.unregister 'go'
command.unregister 'go-fmt'
inspection.unregister 'golint'
inspection.unregister 'gotoolvet'
return {
info:
author: 'Copyright 2016-2018 The Howl Developers'
description: 'Go language support'
license: 'MIT'
:unload
}
| 23.057471 | 82 | 0.653041 |
2399b8fe579dd9769fcb902f4c792f9103d8928e | 1,456 | return_v = false
value_v = 0
deep_copy = (org) ->
org_type = type org
copy
if org_type == "table"
copy = {}
for k, v in next, org, nil
copy[deep_copy k] = deep_copy org
setmetatable copy, deep_copy getmetatable org
else
copy = org
copy
gauss_random = ->
if return_v
return_v = false
return value_v
u = 2 * math.random! - 1
v = 2 * math.random! - 1
r = u^2 + v^2
if r == 0 or r > 1
return gauss_random!
c = math.sqrt -2 * (math.log r) / r
value_v = v * c
u * c
randf = (a, b) ->
(b - a) * math.random! + a
randi = (a, b) ->
math.floor (b - a) * math.random! + a
randn = (mu, sigma) ->
mu + gauss_random! * sigma
-- not really sign ... too late!
sign = (n) ->
if n < 0
return 0
if n > 1
return 1
n
is_callable = (x) ->
(nil != (getmetatable x).__call or "function" == type x)
combine = (...) ->
_error = "expected either function or nil"
n = select "#", ...
return noop if n == 0
if n == 1
fn = select 1, ...
return noop unless fn
assert (is_callable fn), _error
return fn
funcs = {}
for i = 1, n
fn = select i, ...
if fn != nil
assert (is_callable fn), _error
funcs[#funcs + 1] = fn
(...) ->
for f in *funcs
f ...
{
:is_callable
:combine
:gauss_random
:randf
:randi
:randn
:sign
:deep_copy
}
| 15.326316 | 58 | 0.508929 |
ed03c4dff51fe141b04d9e34e5294a2218d812c7 | 1,104 | #!/usr/bin/env moon
require"buildah".from "docker://docker.io/library/debian:bullseye-slim", "zeek"
SCRIPT "rmusers"
SCRIPT "rmsuid"
COPY "01_nodoc", "/etc/dpkg/dpkg.cfg.d/01_nodoc"
RUN "cp --remove-destination /usr/share/zoneinfo/UTC /etc/localtime"
APT_GET "update"
APT_GET "full-upgrade"
APT_GET "install linux-headers-5.8.0-3-amd64 build-essential cmake libpcap-dev libssl-dev swig zlib1g-dev python3-dev libmaxminddb-dev flex bison"
COPY "zeek-3.2.2.tar.gz"
RUN "tar -C / -xf /zeek-3.2.2.tar.gz"
RM "/zeek-3.2.2.tar.gz"
SCRIPT "build.sh"
RUN "strip -s /opt/zeek/bin/zeek"
COPY "zeek-af_packet-plugin"
SCRIPT "zeek-af_packet-plugin.sh"
RM "/zeek-3.2.2"
RM "/zeek-af_packet-plugin"
RUN "/opt/zeek/bin/zeek -NN Zeek::AF_Packet"
APT_GET "purge linux-headers-5.8.0-3-amd64 build-essential cmake libpcap-dev libssl-dev swig zlib1g-dev python3-dev libmaxminddb-dev flex bison"
APT_GET "install libpcap0.8 libssl1.1 zlib1g libmaxminddb0 ca-certificates libgcc1"
ENTRYPOINT "/opt/zeek/bin/zeek"
PUSH "base-zeek", "3.2.2"
| 46 | 148 | 0.692935 |
5869a327d7cbceded6d7c3d369e8f3b6df105b8e | 24 | core = {}
return core | 4.8 | 11 | 0.583333 |
48b2e39939bb33a8a46c0cc4725a64f0c00ffd49 | 1,122 | -------------------------------------------------------------------------------
-- Provides direct access to Java
-------------------------------------------------------------------------------
-- @module yae.java
---
-- Bind Java object to Lua
-- @tparam string name Java object name
-- @treturn Object a Java object converted to Lua
-- @usage
-- System = java.bind "java.lang.System"
-- print System\currentTimeMillis!
require = luajava.bindClass
---
-- Create new instance of specified Java object
-- @tparam string name Java object name
-- @param ... constructor parameters
-- @treturn Object an instance of specified Java class
-- @usage
-- Scanner = java.require "java.util.Scanner"
-- scanner = java.new Scanner, "1 fish 2 fish red fish blue fish"
-- scanner\useDelimiter "\\s*fish\\s*"
-- print scanner\next!
new = luajava.new
---
-- Extend specified Java object
-- @tparam string name Java object name
-- @tparam table options options
-- @treturn Object an extended Java object
-- @usage
-- runnable = java.extend "java.lang.Runnable",
-- run: ->
extend = luajava.createProxy
{
:require
:new
:extend
}
| 26.714286 | 79 | 0.606061 |
b4d337e3e6e6a60dc741b49b49cdf8b268b5cf23 | 1,580 | bit=require "bit"
ffi=require "ffi"
string=require "string"
_string={}
_string.wrap=(s)->
return extend copy(s),_string
_string.starts=(String,Start)->
return string.sub(String,1,string.len(Start))==Start
_string.ends=(String,End)->
return End=='' or string.sub(String,-string.len(End))==End
_string.trim=(s)->
return s\match'^()%s*$' and '' or s\match'^%s*(.*%S)'
_string.gsplit=(s, sep, plain)->
start = 1
done = false
pass=(i, j, ...)->
if i
seg = s\sub(start, i - 1)
start = j + 1
return seg, ...
else
done = true
return s\sub(start)
return ->
return if done
if sep == ''
done = true
return s
return pass s\find sep, start, plain
_string.dedent=(s)->
return _string.trim table.concat [_string.trim l for l in _string.gsplit s, "\n"], "\n"
_string.wrap_simple=(str, limit, indent, indent1)->
indent or= ""
indent1 or= indent
limit or= 72
here = 1-#indent1
return indent1..str\gsub "(%s+)()(%S+)()", (sp, st, word, fi)->
if fi-here > limit
here = st - #indent
return "\n"..indent..word
_string.wrap=(str,limit,indent,indent1)->
table.concat [_string.wrap_simple l,limit,indent,indent1 for l in _string.gsplit str,"\n"], "\n"
_io={}
socket=require 'socket'
-- i'm so terribly sorry for this one, but using ffi and syscalls for select() is even more hacky.
keyboard = socket.tcp!
keyboard\close!
keyboard\setfd 0
_io.select=(timeout=0)->
r,w,e=socket.select({keyboard}, nil , timeout)
return r[1]==keyboard and e!="timeout"
{string:_string, io:_io}
| 21.944444 | 98 | 0.627848 |
c6b0ca98f26a8e811f35a2550aab93edea70810d | 530 | require "minergirl.game.world.world"
require "minergirl.game.world.bullet"
export class Mine extends Sprite
new: (x, y) =>
super x * World.TILE_SIZE, y * World.TILE_SIZE, "resource/mine.png", 8, 8
@height = 6
@offset.y = 2
@timers\add 0.5, 1, (-> @explode!)
explode: =>
axel\state!\add_bullet Bullet @center.x, @center.y, LEFT
axel\state!\add_bullet Bullet @center.x, @center.y, RIGHT
axel\state!\add_bullet Bullet @center.x, @center.y, DOWN
axel\state!\add_bullet Bullet @center.x, @center.y, UP
@destroy! | 29.444444 | 75 | 0.688679 |
8017820e4241b0d7f98071465fa1de15b21aaf36 | 1,833 | match_compiler = require '../match_compiler'
say = require 'say'
say\set 'assertion.is_match.postitive', 'Expected %s to match %s'
say\set 'assertion.is_match.negative', 'Expected %s to not match %s'
is_match = (state, arguments) ->
pattern = match_compiler arguments[1]
return pattern\match arguments[2]
assert\register 'assertion', 'match', is_match, 'assertion.is_match.postitive',
'assertion.is_match.negative'
describe 'match compiler', ->
it 'compiles basic patterns', ->
assert.is_match 'abc', 'abc'
assert.is_not_match 'abc', 'ab'
assert.is_not_match 'abc', 'bc'
assert.is_not_match 'abc', 'a'
it 'compiles escaped characters', ->
assert.is_match '\\?\\a', '?a'
assert.is_not_match '\\?\\a', 'aa'
assert.is_not_match '\\?', 'ab'
it 'compiles sets', ->
assert.is_match '[abc]', 'a'
assert.is_match '[!abc]', 'z'
assert.is_not_match '[abc]', 'z'
assert.is_not_match '[!abc]', 'a'
it 'compiles braced sets', ->
assert.is_match '{abc,def}', 'abc'
assert.is_match '{abc,def}', 'def'
assert.is_match '{abc,}', ''
assert.is_not_match '{abc,def}', 'xyz'
assert.is_not_match '{abc,def}', 'ab'
assert.is_not_match '{abc,}', 'ab'
it 'compiles basic globs', ->
assert.is_match 'a*', 'a'
assert.is_match 'a*', 'abc'
assert.is_match 'a**', 'a'
assert.is_match 'a**', 'abc'
assert.is_not_match '*', 'ab/c'
assert.is_match '**', 'ab/c'
it 'compiles complex globs', ->
assert.is_match '*.py', '.py'
assert.is_match '*.py', 'xyz.py'
assert.is_match '*.py', 'xyz.py.py.py'
assert.is_not_match '*.py', 'xyz/abc.py.py'
assert.is_match '**.py', 'xyz/abc.py.py'
it 'compiles globs with right hand sides', ->
assert.is_match '*.py{,x}', '.py'
assert.is_match '*.py{,x}', '.pyx'
| 31.067797 | 79 | 0.613748 |
b7ebccf2670c4e80598d93d925a82da00c92ce63 | 1,867 | lapis = require "lapis"
db = require "lapis.db"
import Model from require "lapis.db.model"
import config from require "lapis.config"
import insert from table
import sort from table
import min, random from math
class Fortune extends Model
class World extends Model
class Benchmark extends lapis.Application
"/": =>
json: {message: "Hello, World!"}
"/db": =>
num_queries = tonumber(@params.queries) or 1
if num_queries < 2
w = World\find random(1, 10000)
return json: {id:w.id,randomNumber:w.randomnumber}
worlds = {}
for i = 1, num_queries
w = World\find random(1, 10000)
insert worlds, {id:w.id,randomNumber:w.randomnumber}
json: worlds
"/fortunes": =>
@fortunes = Fortune\select ""
insert @fortunes, {id:0, message:"Additional fortune added at request time."}
sort @fortunes, (a, b) -> a.message < b.message
layout:false, @html ->
raw '<!DOCTYPE HTML>'
html ->
head ->
title "Fortunes"
body ->
element "table", ->
tr ->
th ->
text "id"
th ->
text "message"
for fortune in *@fortunes
tr ->
td ->
text fortune.id
td ->
text fortune.message
"/update": =>
num_queries = tonumber(@params.queries) or 1
if num_queries == 0
num_queries = 1
worlds = {}
for i = 1, min(500, num_queries)
wid = random(1, 10000)
world = World\find wid
world.randomnumber = random(1, 10000)
world\update "randomnumber"
insert worlds, {id:world.id,randomNumber:world.randomnumber}
if num_queries < 2
return json: worlds[1]
json: worlds
"/plaintext": =>
content_type:"text/plain", layout: false, "Hello, World!"
| 26.295775 | 81 | 0.568827 |
bfab619918c7b4a2fb5be65ec1166e41b2e382ea | 1,271 | Block = require 'lib.blockchain.block'
Blockchain = require 'lib.blockchain.blockchain'
describe 'Blockchain tests', ->
it 'allows for data to be appended', ->
with Blockchain!
\append 'test data append'
assert.truthy \__tostring!\match('test data append')
it 'remains valid after appends', ->
with Blockchain!
for i = 1, 5
\append(tostring i)
\mine!
assert.True \is_valid!
it 'detects changed block data', ->
with Blockchain!
for i = 1, 5
\append(tostring i)
\mine!
assert.True \is_valid!
.blocks[3].data = '4'
assert.False \is_valid!
\mine!
assert.True \is_valid!
it 'detects changed hashes', ->
with Blockchain!
for i = 1, 5
\append(tostring i)
\mine!
assert.True \is_valid!
.blocks[3].hash = -> '4'
assert.False \is_valid!
it 'can be converted from a string', ->
bc1 = with Blockchain!
for i = 1, 5
\append(tostring i)
\mine!
bc2 = Blockchain.from_string(tostring bc1)
assert.are.same bc1, bc2
| 28.886364 | 64 | 0.508261 |
febc412b92867430ae0e9812172fd33a4dc862ae | 460 | import Widget from require "lapis.html"
class Posts extends Widget
@include require('wordpress.views.helpers')
content: =>
post = @get_post @.params.id
h1 @_("Edit") .. ' ' .. @post_name(post)
form method: "POST", action: @post_edit2_url(post), ->
@csrf_input!
input type: 'text', name: 'title', value: post.post_title
br!
@tinymce('content', post.post_content)
br!
input type: 'submit', value: @_("Save")
| 28.75 | 63 | 0.619565 |
4d0d5da9baec9ea46dc34ecc91cb93cb73f8b009 | 17,165 |
-- Copyright (C) 2018-2020 DBotThePony
-- 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.
import IsValid, table, DPP2, type, error, assert, constraint, SERVER, CLIENT, DLib from _G
import net from DLib
entMeta = FindMetaTable('Entity')
nextidP = 0
nextidP = DPP2.ContraptionHolder.NEXT_ID or 0 if DPP2.ContraptionHolder
doWalkParent = (target, root) =>
if istable(@)
for _, ent in pairs(@)
if IsValid(ent) and (root or not target[ent]) and not ent\IsPlayer()
target[ent] = ent
doWalkParent(children, target, false) for _, children in pairs(ent\GetChildren())
doWalkParent(ent\GetParent(), target, false)
return target
return target if not IsValid(@) or @IsPlayer()
return target if target[@] and not root
target[@] = @
doWalkParent(children, target, false) for _, children in pairs(@GetChildren())
doWalkParent(@GetParent(), target, false)
return target
class DPP2.ContraptionHolder
@NEXT_ID = nextidP
@OBJECTS = {}
@BLSTUFF = {}
@RSSTUFF = {}
@GetByID = (id) =>
assert(type(id) == 'number', 'Invalid ID provided')
for obj in *@OBJECTS
if obj.id == id
return obj
return false
for ent in *ents.GetAll()
if ent.__dpp2_contraption and not table.qhasValue(@OBJECTS, ent.__dpp2_contraption)
table.insert(@OBJECTS, ent.__dpp2_contraption)
obj\Invalidate(true) for obj in *@OBJECTS
@OBJECTS = [obj for obj in *@OBJECTS when obj\IsValid()]
@Invalidate = => @OBJECTS = [obj for obj in *@OBJECTS when obj\Revalidate()]
@GetAll = => @OBJECTS
@GetNextID = =>
error('ID must be specified on client realm') if CLIENT
id = @NEXT_ID
@NEXT_ID += 1
return id
new: (id = @@GetNextID()) =>
@ents = {}
@owners = {}
@ownersFull = {}
@ownersStateNotShared = {}
@types = {}
@id = id
@networked = {} if SERVER
@lastWalk = 0
table.insert(@@OBJECTS, @)
@rev = 0
@_pushing = 0
@_pushing_r = {}
for object in *@@BLSTUFF
hook.Add 'DPP2_' .. object.__class.__name .. '_' .. object.identifier .. '_EntryAdded', @, @TriggerUpdate
hook.Add 'DPP2_' .. object.__class.__name .. '_' .. object.identifier .. '_EntryRemoved', @, @TriggerUpdate
for object in *@@RSSTUFF
hook.Add 'DPP2_' .. object.identifier .. '_EntryAdded', @, @TriggerUpdate
hook.Add 'DPP2_' .. object.identifier .. '_EntryRemoved', @, @TriggerUpdate
hook.Add 'DPP2_' .. object.identifier .. '_GroupAdded', @, @TriggerUpdate
hook.Add 'DPP2_' .. object.identifier .. '_GroupRemoved', @, @TriggerUpdate
hook.Add 'DPP2_' .. object.identifier .. '_WhitelistStatusUpdated', @, @TriggerUpdate
GetID: => @id
IsValid: => #@ents > 1
GetOwners: => @owners
GetOwnersFull: => @ownersFull
GetOwnersPartial: (mode) => @ownersStateNotShared[mode] or @ownersFull
HasOwner: (owner = NULL) => table.qhasValue(@owners, owner)
CopyOwners: => [v for v in *@owners]
CopyOwnersFull: => [v for v in *@ownersFull]
EntitiesByOwner: (owner = NULL) => [ent for ent in *@ents when ent\DPP2GetOwner() == owner]
EntitiesByStringOwner: (owner = '') => [ent for ent in *@ents when ent\DPP2GetOwnerSteamID() == owner]
TriggerUpdate: =>
@rev += 1
hook.Run 'DPP2_ContraptionUpdate', @, @rev, @rev - 1
AddEntity: (ent = NULL) =>
return false if not IsValid(ent)
return false if ent.__dpp2_contraption == @
return false if ent.IsConstraint and ent\IsConstraint()
ent.__dpp2_contraption\RemoveEntity(ent) if ent.__dpp2_contraption
table.insert(@ents, ent)
@TriggerUpdate()
return true
RemoveEntity: (ent = NULL, InvalidateNow = true) =>
return false if not IsValid(ent)
hit = false
for i, ent2 in ipairs(@ents)
if ent2 == ent
table.remove(@ents, i)
hit = true
break
return false if not hit
ent.__dpp2_contraption = nil
if SERVER and ent.__dpp2_contraption_pushing
ent.__dpp2_contraption_pushing = nil
if not ent.__dpp2_pushing or ent.__dpp2_pushing == 0
ent\SetCustomCollisionCheck(@__dpp2_prev_col_check)
ent\CollisionRulesChanged()
@Invalidate() if InvalidateNow
return true
MarkForDeath: (fromMerge = false) =>
if not fromMerge
ent.__dpp2_contraption = nil for ent in *@ents when IsValid(ent) and ent.__dpp2_contraption == @
for i, obj in ipairs(@@OBJECTS)
if obj == @
table.remove(@@OBJECTS, i)
break
@ents = {}
@owners = {}
@ownersFull = {}
@ownersStateNotShared = {}
if SERVER and #@networked ~= 0
@networked = [ply for ply in *@networked when ply\IsValid()]
net.Start('dpp2_contraption_delete')
net.WriteUInt32(@id)
net.WriteBool(fromMerge)
net.Send(@networked)
DPP2.ContraptionHolder\Invalidate()
hook.Run 'DPP2_ContraptionRemove', @
return @
NetworkToPlayer: (ply) =>
error('Invalid side') if CLIENT
return false if table.qhasValue(@networked, ply)
@networked = [ply for ply in *@networked when ply\IsValid()]
table.insert(@networked, ply)
net.Start('dpp2_contraption_create')
net.WriteUInt32(@id)
net.WriteEntityArray(@ents)
net.Send(ply)
return true
ReNetworkEverything: =>
error('Invalid side') if CLIENT
@networked = [ply for ply in *@networked when ply\IsValid()]
net.Start('dpp2_contraption_create')
net.WriteUInt32(@id)
net.WriteEntityArray(@ents)
net.Send(@networked)
NetworkDiff: (previous) =>
error('Invalid side') if CLIENT
if #previous == 0
@ReNetworkEverything()
return true
removed = {}
added = {}
for ent in *@ents
if not table.qhasValue(previous, ent)
table.insert(added, ent)
for ent in *previous
if ent\IsValid() and not table.qhasValue(@ents, ent)
table.insert(removed, ent)
-- diff is not effective
if #removed + #added >= #@ents
net.Start('dpp2_contraption_create')
net.WriteUInt32(@id)
net.WriteEntityArray(@ents)
net.Send(@networked)
else -- diff is effective
net.Start('dpp2_contraption_diff')
net.WriteUInt32(@id)
net.WriteEntityArray(added)
net.WriteEntityArray(removed)
net.Send(@networked)
Walk: (frompoint = NULL, ask, _find) =>
error('Invalid side') if CLIENT
error('Tried to use a NULL entity!') if not IsValid(frompoint)
if frompoint\IsPlayer()
@Invalidate()
return false
oldEnts = @ents
for ent in *oldEnts
if ent.__dpp2_contraption_pushing
ent.__dpp2_contraption_pushing = nil
if not ent.__dpp2_pushing or ent.__dpp2_pushing == 0
ent\SetCustomCollisionCheck(@__dpp2_prev_col_check)
ent\CollisionRulesChanged()
ent.__dpp2_contraption = nil for ent in *@ents when IsValid(ent) and ent.__dpp2_contraption == @
@lastWalk = RealTime() + 0.1
@nextNetwork = RealTime() + 1
@owners = {}
@ownersFull = {}
@ownersStateNotShared = {}
find = _find or doWalkParent(constraint.GetAllConstrainedEntities(frompoint), {}, true)
find = {ent, ent for ent in pairs(find) when not ent\IsVehicle() or ent\DPP2IsOwned()} if not _find
setup = {}
for ent in pairs(find)
if ent.__dpp2_contraption and ent.__dpp2_contraption ~= @ and #ent.__dpp2_contraption.ents > #oldEnts and ent.__dpp2_contraption ~= ask
ent.__dpp2_contraption\Walk(frompoint, @, find)
ent.__dpp2_contraption._pushing = @_pushing\max(ent.__dpp2_contraption._pushing)
table.append(ent.__dpp2_contraption._pushing_r, @_pushing_r)
table.deduplicate(ent.__dpp2_contraption._pushing_r)
@MarkForDeath(true)
return false
table.insert(setup, ent)
@ents = setup
ent.__dpp2_contraption = @ for ent in *setup
if not @IsValid()
@MarkForDeath()
else
oldEnts = [ent for ent in *oldEnts]
@Invalidate()
timer.Create 'DPP2_ContraptionDiff_' .. @id, 0.2, 1, -> @NetworkDiff(oldEnts) if @IsValid()
return true
CalculateWorldAABB: =>
mins, maxs = @ents[1]\WorldSpaceAABB() if IsValid(@ents[1])
mins, maxs = Vector(), Vector() if not IsValid(@ents[1])
for ent in *@ents
if IsValid(ent)
mins2, maxs2 = ent\WorldSpaceAABB()
mins.x = mins2.x if mins2.x < mins.x
mins.y = mins2.y if mins2.y < mins.y
mins.z = mins2.z if mins2.z < mins.z
maxs.x = maxs2.x if maxs2.x > maxs.x
maxs.y = maxs2.y if maxs2.y > maxs.y
maxs.z = maxs2.z if maxs2.z > maxs.z
return mins, maxs
From: (ents = @ents) =>
for ent in *ents
if IsValid(ent)
ent.__dpp2_contraption\RemoveEntity(ent) if ent.__dpp2_contraption
ent.__dpp2_contraption = @
@ents = ents
@Invalidate()
return @
CheckUpForGrabs: (newOwner = NULL) =>
error('Invalid side CLIENT') if CLIENT
return false if not newOwner\IsValid()
fents = {}
hit = false
for ent in *@ents
if ent\IsValid() and ent\DPP2IsUpForGrabs()
hit = true
table.insert(fents, ent)
DPP2.Notify(newOwner, 'message.dpp2.owning.owned_contraption') if hit
DPP2.DoTransfer(fents, newOwner)
@TriggerUpdate()
return hit
Ghost: => ent\DPP2Ghost() for ent in *@ents when IsValid(ent)
UnGhost: => ent\DPP2UnGhost() for ent in *@ents when IsValid(ent)
Revalidate: =>
return false if not @IsValid()
@TriggerUpdate()
for ent in *@ents
if not entMeta.IsValid(ent)
@Invalidate(false, true)
return @IsValid()
return @IsValid()
InvalidateClients: =>
error('Invalid side') if CLIENT
return false if player.GetCount() == 0
net.Start('dpp2_contraption_invalidate')
net.WriteUInt32(@id)
net.Broadcast()
return true
Invalidate: (withMarkForDeath = false, networkDiff = true) =>
@TriggerUpdate()
for ent in *@ents
if not IsValid(ent)
prev = @ents
@ents = [ent for ent in *@ents when IsValid(ent)]
@NetworkDiff(prev) if SERVER and networkDiff and (#@ents > 0 or not withMarkForDeath)
break
if @_pushing > 0
for ent in *@ents
if ent.__dpp2_pushing and ent.__dpp2_pushing ~= 0
ent.__dpp2_pushing = 0
ent\SetCustomCollisionCheck(ent.__dpp2_prev_col_check)
ent\CollisionRulesChanged()
ent.__dpp2_prev_col_check = nil
if not ent.__dpp2_contraption_pushing
ent.__dpp2_contraption_pushing = true
if not ent.__dpp2_pushing or ent.__dpp2_pushing == 0
ent.__dpp2_prev_col_check = ent\GetCustomCollisionCheck()
ent\SetCustomCollisionCheck(true)
ent\CollisionRulesChanged()
@owners = {}
@ownersFull = {}
@ownersStateNotShared = {def.identifier, {} for def in *DPP2.DEF.ProtectionDefinition.OBJECTS}
@types = {}
for ent in *@ents
gtype = type(ent)
ent.__dpp2_contraption = @
owner, ownerSteamID = ent\DPP2GetOwner()
table.insert(@owners, owner) if not table.qhasValue(@owners, owner)
table.insert(@ownersFull, ownerSteamID) if not table.qhasValue(@ownersFull, ownerSteamID)
table.insert(@types, gtype) if not table.qhasValue(@types, gtype)
if ownerSteamID ~= 'world' and ownerSteamID ~= 'map'
for def in *DPP2.DEF.ProtectionDefinition.OBJECTS
if not def\IsShared(ent)
table.insert(@ownersStateNotShared[def.identifier], ownerSteamID) if not table.qhasValue(@ownersStateNotShared[def.identifier], ownerSteamID)
break
else
for def in *DPP2.DEF.ProtectionDefinition.OBJECTS
table.insert(@ownersStateNotShared[def.identifier], ownerSteamID) if not table.qhasValue(@ownersStateNotShared[def.identifier], ownerSteamID)
if withMarkForDeath and not @IsValid()
@MarkForDeath()
__tostring: => string.format('DPP2Contraption<%d>[%p]', @id, @)
entMeta.DPP2GetContraption = => @__dpp2_contraption
entMeta.DPP2HasContraption = => @__dpp2_contraption ~= nil
entMeta.DPP2InvalidateContraption = =>
@__dpp2_contraption\Invalidate() if @__dpp2_contraption
return @
entMeta.DPP2IsGhosted = => @DLibGetNWBool('dpp2_ghost', false)
DPP2.ACCESS = DPP2.ACCESS or {}
import i18n from DLib
DPP2.ALLOW_DAMAGE_NPC = DPP2.CreateConVar('allow_damage_npc', '1', DPP2.TYPE_BOOL)
DPP2.ALLOW_DAMAGE_VEHICLE = DPP2.CreateConVar('allow_damage_vehicle', '1', DPP2.TYPE_BOOL)
checksurf = (ply, ent) ->
return true if not DPP2.ENABLE_ANTIPROPKILL\GetBool() or not DPP2.ANTIPROPKILL_SURF\GetBool()
contraption = ent\DPP2GetContraption()
return true if not contraption
for ent in *contraption.ents
if ent\IsValid() and ent\IsVehicle() and ent\GetDriver() == ply
return false
return true
DPP2.ACCESS.CanPhysgun = (ply = NULL, ent = NULL) ->
return true if not ply\IsValid()
return false, i18n.localize('gui.dpp2.access.status.invalident') if not ent\IsValid()
return false, i18n.localize('gui.dpp2.access.status.no_surf'), i18n.localize('gui.dpp2.access.status.contraption_ext', ent\DPP2GetContraption()\GetID()) if not checksurf(ply, ent)
return DPP2.PhysgunProtection\CanTouch(ply, ent)
DPP2.ACCESS.CanDrive = (ply = NULL, ent = NULL) ->
return true if not ply\IsValid()
return false, i18n.localize('gui.dpp2.access.status.invalident') if not ent\IsValid()
return false, i18n.localize('gui.dpp2.access.status.no_surf'), i18n.localize('gui.dpp2.access.status.contraption_ext', ent\DPP2GetContraption()\GetID()) if not checksurf(ply, ent)
return DPP2.DriveProtection\CanTouch(ply, ent)
DPP2.ACCESS.CanToolgun = (ply = NULL, ent = NULL, toolgunMode) ->
error('Invalid toolgun mode type. It must be a string! typeof' .. type(toolgunMode)) if type(toolgunMode) ~= 'string'
return true if not ply\IsValid()
return false, i18n.localize('gui.dpp2.access.status.toolgun_mode_blocked') if not DPP2.ToolgunModeRestrictions\Ask(toolgunMode, ply)
return true, i18n.localize('gui.dpp2.access.status.invalident') if ent == Entity(0)
return false, i18n.localize('gui.dpp2.access.status.invalident') if not ent\IsValid()
if DPP2.ToolgunModeExclusions\Ask(toolgunMode, ply)
cangeneric, tstatus = DPP2.ToolgunProtection\CanGeneric(ply, ent)
return cangeneric, tstatus if cangeneric ~= nil
return true, i18n.localize('gui.dpp2.access.status.toolgun_mode_excluded')
return false, i18n.localize('gui.dpp2.access.status.toolgun_player') if ent\IsPlayer() and DPP2.NO_TOOLGUN_PLAYER\GetBool() and (not DPP2.ToolgunProtection\IsAdmin(ply) or DPP2.NO_TOOLGUN_PLAYER_ADMIN\GetBool() and DPP2.ToolgunProtection\IsAdmin(ply))
-- allow self tool
return true if ply == ent
return DPP2.ToolgunProtection\CanTouch(ply, ent)
DPP2.ACCESS.CanDamage = (ply = NULL, ent = NULL) ->
return true if not ply\IsValid()
return false, i18n.localize('gui.dpp2.access.status.invalident') if not ent\IsValid()
ALLOW_DAMAGE_NPC = DPP2.ALLOW_DAMAGE_NPC\GetBool()
ALLOW_DAMAGE_VEHICLE = DPP2.ALLOW_DAMAGE_VEHICLE\GetBool()
if contraption = ent\DPP2GetContraption()
for etype in *contraption.types
if etype == 'Vehicle' and ALLOW_DAMAGE_VEHICLE
return true, i18n.localize('gui.dpp2.access.status.damage_allowed'), i18n.localize('gui.dpp2.access.status.contraption_ext', contraption\GetID())
if (etype == 'NPC' or etype == 'NextBot') and ALLOW_DAMAGE_NPC
return true, i18n.localize('gui.dpp2.access.status.damage_allowed'), i18n.localize('gui.dpp2.access.status.contraption_ext', contraption\GetID())
if ent\IsVehicle() and ALLOW_DAMAGE_VEHICLE
return true, i18n.localize('gui.dpp2.access.status.damage_allowed')
if (ent\IsNPC() or type(ent) == 'NextBot') and ALLOW_DAMAGE_VEHICLE
return true, i18n.localize('gui.dpp2.access.status.damage_allowed')
return DPP2.DamageProtection\CanTouch(ply, ent)
DPP2.ACCESS.CanPickup = (ply = NULL, ent = NULL) ->
return true if not ply\IsValid()
return false, i18n.localize('gui.dpp2.access.status.invalident') if not ent\IsValid()
return DPP2.PickupProtection\CanTouch(ply, ent)
DPP2.ACCESS.CanUse = (ply = NULL, ent = NULL) ->
return true if not ply\IsValid()
return false, i18n.localize('gui.dpp2.access.status.invalident') if not ent\IsValid()
return DPP2.UseProtection\CanTouch(ply, ent)
DPP2.ACCESS.CanUseVehicle = (ply = NULL, ent = NULL) ->
return true if not ply\IsValid()
return false, i18n.localize('gui.dpp2.access.status.invalident') if not ent\IsValid()
return DPP2.VehicleProtection\CanTouch(ply, ent)
DPP2.ACCESS.CanGravgun = (ply = NULL, ent = NULL) ->
return true if not ply\IsValid()
return false, i18n.localize('gui.dpp2.access.status.invalident') if not ent\IsValid()
return DPP2.GravgunProtection\CanTouch(ply, ent)
DPP2.ACCESS.CanGravgunPunt = (ply = NULL, ent = NULL) ->
return true if not ply\IsValid()
return false, i18n.localize('gui.dpp2.access.status.invalident') if not ent\IsValid()
return DPP2.GravgunProtection\CanTouch(ply, ent)
| 33.590998 | 252 | 0.716924 |
c94c195b22b5e9150eb5202e3d29bca784bc8fd4 | 1,077 | import mkdirSync from require "fs"
import join from require "path"
import isfileSync, isdirSync from "novacbn/luvit-extras/fs"
import Book from "novacbn/lunarbook/api/Book"
import BOOK_HOME from "novacbn/lunarbook/lib/constants"
-- ::TEXT_COMMAND_DESCRIPTION -> string
-- Represents the description of the command
-- export
export TEXT_COMMAND_DESCRIPTION = "Builds and exports the LunarBook"
-- ::TEXT_COMMAND_SYNTAX -> string
-- Represents the syntax of the command
-- export
export TEXT_COMMAND_SYNTAX = "[book directory] [build directory]"
-- ::TEXT_COMMAND_EXAMPLES -> string
-- Represents the examples of the command
-- export
export TEXT_COMMAND_EXAMPLES = {
"./book"
}
-- ::executeCommand(Options options, string directory?, string out?) -> void
--
-- export
export executeCommand = (options, bookDirectory="book", buildDirectory="dist") ->
mkdirSync(buildDirectory) unless isdirSync(buildDirectory)
book = Book\new(bookDirectory, buildDirectory, BOOK_HOME.theme)
book\processBook()
print("LunarBook was exported to '#{buildDirectory}'")
| 30.771429 | 81 | 0.753018 |
bcddbeff6e0cc67466791618f7de06ce2e84a628 | 58 | num => bits =>
(mod (mul num (pow 2 bits)) #(pow 2 32))
| 19.333333 | 42 | 0.517241 |
feb85b64128506fa4fd1ba0c69f4c5a8eebae81a | 332 | #!/usr/bin/env moon
-- vim: ts=2 sw=2 et :
package.moonpath = '../src/?.moon;' .. package.moonpath
import cli from require "fun"
import Sym from require "sym"
eg={}
eg.sym = ->
s=Sym!
s\adds {"a", "a", "a", "a", "b", "b", "c"}
assert 4==s.all.a
e = s\ent()
print(e)
assert 1.378 <= e and e <=1.38, "bad ent"
cli eg
| 18.444444 | 55 | 0.548193 |
a63961bd1da5a7e9ed4eb676a5bfe6cc5e1ffd2e | 2,316 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
gio = require 'ljglibs.gio'
glib = require 'ljglibs.glib'
ffi = require 'ffi'
core = require 'ljglibs.core'
callbacks = require 'ljglibs.callbacks'
jit = require 'jit'
import catch_error, get_error from glib
C = ffi.C
ffi_string, ffi_new = ffi.string, ffi.new
buf_t = ffi.typeof 'unsigned char[?]'
InputStream = core.define 'GInputStream < GObject', {
properties: {
has_pending: => C.g_input_stream_has_pending(@) != 0
is_closed: => C.g_input_stream_is_closed(@) != 0
}
close: => catch_error C.g_input_stream_close, @, nil
read: (count = 4096) =>
return '' if count == 0
buf = ffi_new buf_t, count
read = catch_error C.g_input_stream_read, @, buf, count, nil
return nil if read == 0
ffi_string buf, read
read_all: (count = 4096) =>
return '' if count == 0
buf = ffi_new buf_t, count
read = ffi_new 'gsize[1]'
catch_error C.g_input_stream_read_all, @, buf, count, read, nil
return nil if read[0] == 0
ffi_string buf, read[0]
read_async: (count = 4096, priority = glib.PRIORITY_DEFAULT, callback) =>
if count == 0
callback true, ''
return
buf = ffi_new buf_t, count
local handle
handler = (source, res) ->
callbacks.unregister handle
status, ret, err_code = get_error C.g_input_stream_read_finish, @, res
if not status
callback false, ret, err_code
else
read = ret
val = read != 0 and ffi_string(buf, read) or nil
callback true, val
handle = callbacks.register handler, 'input-read-async'
C.g_input_stream_read_async @, buf, count, priority, nil, gio.async_ready_callback, callbacks.cast_arg(handle.id)
close_async: (callback) =>
local handle
handler = (source, res) ->
callbacks.unregister handle
status, ret, err_code = get_error C.g_input_stream_close_finish, @, res
if not status
callback false, ret, err_code
else
callback true
handle = callbacks.register handler, 'input-close-async'
C.g_input_stream_close_async @, 0, nil, gio.async_ready_callback, callbacks.cast_arg(handle.id)
}
jit.off InputStream.read_async
jit.off InputStream.close_async
InputStream
| 28.243902 | 117 | 0.676166 |
37f40e032971fb41a4be230768df8b1a719b5cf1 | 2,594 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
import app, bindings, interact, timer from howl
import ListWidget from howl.ui
import Matcher from howl.util
attach_list = (interactor) ->
class SelectionList
run: (@finish, @opts) =>
@command_line = app.window.command_line
if not (@opts.matcher or @opts.items) or (@opts.matcher and @opts.items)
error 'One of "matcher" or "items" required'
@command_line.prompt = @opts.prompt
@command_line.title = @opts.title
matcher = @opts.matcher or Matcher @opts.items
@list_widget = ListWidget matcher,
on_selection_change: @\_selection_changed
reverse: @opts.reverse
never_shrink: true
@list_widget.columns = @opts.columns
@list_widget.max_height = math.floor app.window.allocated_height * 0.5
@showing_list = false
if not @opts.hide_until_tab
@show_list!
if @opts.text
@command_line\write @opts.text
@on_update @opts.text
else
if @opts.selection
@list_widget\update ''
@list_widget.selection = @opts.selection
timer.asap -> @_selection_changed!
else
@on_update ''
show_list: =>
@command_line\add_widget 'completion_list', @list_widget
@showing_list = true
on_update: (text) =>
@list_widget\update text
@_selection_changed!
_selection_changed: =>
if @opts.on_selection_change
@opts.on_selection_change @list_widget.selection, @command_line.text, @list_widget.items
submit: =>
if @list_widget.selection
self.finish
selection: @list_widget.selection
text: @command_line.text
elseif @opts.allow_new_value
self.finish text: @command_line.text
else
log.error 'Invalid selection'
keymap:
ctrl_m: => @submit!
ctrl_g: => self.finish!
tab: =>
if not @showing_list
@show_list!
space: =>
return false unless @opts.submit_on_space
if @command_line.text.is_empty
@show_list!
else
@submit!
on_unhandled: (event, source, translations, self) ->
return false if not @opts.keymap
return ->
if bindings.dispatch event, source, { @opts.keymap }, {
selection: @list_widget.selection
text: @command_line.text
}
@list_widget\update @command_line.text, true
@_selection_changed!
return false
interact.register
name: 'select'
description: 'Get selection made by user from a list of items'
factory: SelectionList
| 27.020833 | 94 | 0.663069 |
f024e5bc4ae962fc607481a1504d02d77bdb25b8 | 488 | -- Copyright 2017 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
require 'ljglibs.cdefs.gdk'
core = require 'ljglibs.core'
C = ffi.C
core.define 'GtkTargetEntry', {
new: (target, flags, info) ->
flags = core.parse_flags('GTK_TARGET_', flags)
ptr = C.gtk_target_entry_new target, flags, info
ffi.gc ptr, C.gtk_target_entry_free
}, (def, target, flags = 0, info = 0) ->
def.new target, flags, info
| 28.705882 | 79 | 0.69877 |
6f9e1029a46589c52c27da042e723f7f9988b03a | 1,539 |
assert = require("vimp.util.assert")
log = require("vimp.util.log")
class CommandMapInfo
new: (id, handler, name, options) =>
@id = id
@handler = handler
@name = name
@options = options
remove_from_vim: =>
vim.api.nvim_command("delcommand #{@name}")
_get_n_args_from_handler: =>
handler_info = debug.getinfo(@handler)
if handler_info.isvararg
return '*'
if handler_info.nparams == 1
return '1'
if handler_info.nparams == 0
return '0'
return '*'
_get_options_string: =>
stringified_options = {}
if @options.complete != nil
assert.that(type(@options.complete) == 'string',
"Expected type 'string' for option 'complete' but instead found '#{type(@options.complete)}'")
table.insert stringified_options, "-complete=#{@options.complete}"
return table.concat stringified_options, ' '
_create_command_str: =>
nargs = @\_get_n_args_from_handler!
options_string = @\_get_options_string!
if nargs == '0'
return "command -nargs=0 #{options_string} #{@name} lua _vimp:_executeCommandMap(#{@id}, {})"
if nargs == '1'
return "command -nargs=1 #{options_string} #{@name} call luaeval(\"_vimp:_executeCommandMap(#{@id}, {_A})\", <q-args>)"
return "command -nargs=* #{options_string} #{@name} call luaeval(\"_vimp:_executeCommandMap(#{@id}, _A)\", [<f-args>])"
add_to_vim: =>
command_str = @\_create_command_str!
-- log.debug("Adding command: #{command_str}")
vim.api.nvim_command(command_str)
| 27.981818 | 125 | 0.647823 |
e9e24d82a080d9de122b8e1af4355a294696b356 | 255 | export modinfo = {
type: "command"
desc: "UnPunish"
alias: {"unpunish"}
func: getDoPlayersFunction (v) ->
if v.Character
v.Character.Parent = workspace
v.Character\MakeJoints()
Output2(string.format("Unpunished %s",v.Name),{Colors.Green})
} | 25.5 | 64 | 0.694118 |
e6974bd839d44603cbadc5963d720b2cff69972b | 164 | with sauce3
.draw = ->
.graphics.print "This is #{.project.name}", 10, 10
.key_pressed = (key) ->
if key == "q" or key == "escape"
.system.quit!
| 20.5 | 54 | 0.542683 |
e1095ffd9aff36bce00af9353874983e7cf83a2d | 218 | load_metadata = (name) ->
path = "/docsites/"..name.."/.data"
file = io.open(path)
if file
return file\read("*all")
-- empty json object if file is not found
return "{}"
{ :load_metadata }
| 21.8 | 45 | 0.568807 |
386b5aebbed0cea10ebbabc38f3f02a57ab9712f | 2,768 | jit.opt.start 3, '-loop', 'maxtrace=5000', 'hotloop=100'
--require "libs/autobatch"
export e, c, s = unpack (require "libs/ecs")
e.nothing = {} -- for purging entities!!
require "game/ecs/components"
require "game/ecs/entity/player"
require "game/ecs/entity/block"
require "game/ecs/entity/spike"
require "game/ecs/entity/house"
require "game/ecs/entity/cloud"
require "game/ecs/entity/door"
require "game/ecs/system/block"
require "game/ecs/system/head"
require "game/ecs/system/sprite"
require "game/ecs/system/cloud"
baton = require "libs/baton"
console = require "libs/console"
export bump = require "libs/bump"
export trail = require "libs/trail"
state = require "game"
menu = require "menu"
export input = baton.new
controls:
left: { "key:left", "axis:leftx-", "button:dpleft" }
right: { "key:right", "axis:leftx+", "button:dpright" }
up: { "key:up", "key:z", "axis:lefty-", "button:dpup" }
down: { "key:down", "axis:lefty+", "button:dpdown" }
dash: { "key:lshift", "button:rightshoulder" }
pairs:
move: { "left", "right", "up", "down" }
joystick: love.joystick.getJoysticks![1]
love.load = ->
export world = bump.newWorld!
console.load!
console.defineCommand "editor", "Toggle level-editor.", ->
console.i "Level editor: " .. tostring not state.editor
state.editor = not state.editor
state.god = state.editor
console.defineCommand "god", "Toggle god-mode.", ->
console.i "God mode!!!: " .. tostring not state.god
state.god = not state.god
love.update = (dt) ->
if menu.timer > 0
menu\update dt
else
if not menu.loaded
state\load!
menu.loaded = true
return
console.update dt
input\update dt
state\update dt
trail\update dt
love.draw = ->
with love.graphics
.setColor 0, 0, 0
.print "FPS " .. love.timer.getFPS!, 10, 10
if menu.timer > 0
menu\draw!
else
state\draw!
console.draw!
love.keypressed = (key) ->
if console.keypressed key
return
switch key
when "r"
love.load!
when "escape"
love.event.quit!
state\press key if menu.timer == 0
love.keyreleased = ->
return
love.textinput = (t) ->
console.textinput t
state\textinput t if menu.timer == 0
love.mousepressed = (x, y, button) ->
console.mousepressed x, y, button
state\mousepressed x, y, button if menu.timer == 0
-- weird shit:
math.fuzzy_eq = (a, b, eps) ->
a == b or (math.abs a - b) < eps
math.cerp = (a, b, t) ->
f = (1 - math.cos (t * math.pi)) * 0.5
a * (1 - f) + b * f
math.lerp = (a, b, t) -> a + (b - a) * t
math.dist = (pa, pb) ->
((pb.x - pa.x)^2 + (pb.y - pa.y)^2)^0.5
math.sign = (a) ->
if a < 0
-1
else if a > 0
1
else
0
| 21.625 | 68 | 0.611633 |
766a8a8c2a9a567fd773a4113c1e01a6253768fc | 469 | lapis = require "lapis"
lfs = require "lfs"
-- Load all applications
root = "applications"
all_apps = {}
for entity in lfs.dir(root) do
if entity ~= "." and entity ~= ".." and string.sub(entity, -4) == ".lua" then
app = string.sub(entity, 0, -5)
all_apps[#all_apps + 1] = app
class extends lapis.Application
@enable "etlua"
for _, app in pairs all_apps
@include "applications." .. app
[index: "/"]: =>
render: "home"
| 23.45 | 81 | 0.590618 |
14ac708edef2866b380d9ca470a1e19951c65389 | 11,121 | Dorothy!
Point = (x,y)-> -> oVec2 x or 0,y or 0
Rect = (x,y,width,height)-> -> CCRect x or 0,y or 0,width or 0,height or 0
Simulation = (level)->
switch level
when 1
1,1
when 2
4,2
when 3
8,3
Children = (parent,data)->
children = data.children
if children
for i,child in ipairs children
child = child parent,i
if child
parent\addChild child
Contact = (world,data)->
groups = data.groups
contacts = data.contacts
if groups and contacts
for contact in *contacts
world\setShouldContact unpack contact
Groups = (data)->
default = {
[0]:"Hide"
"P1","P2","P3"
"P4","P5","P6"
"P7","P8","P9"
"P10","P11","P12"
"DetectPlayer" -- 13
"Terrain" -- 14
"Detect" -- 15
}
setmetatable data or {}, {
__index: default
__tostring: =>
str = "{"
for k,v in pairs @
str ..= "["..k.."]=\""..v.."\","
str = str\sub 1,-2 if #str > 1
str ..= "}"
str
}
Contacts = (data)->
setmetatable data or {{1,1,true}},{
__tostring:=>
str = "{"
for i,contact in ipairs @
str ..= "{"
for i,item in ipairs contact
switch tolua.type item
when "boolean"
str ..= item and "t" or "f"
else
str ..= tostring item
str ..= "," unless i == #contact
str ..= "}"
str ..= "," unless i == #@
str ..= "}"
str
}
local Align
Align = {
Center:1
LeftBottom:2
LeftTop:3
RightTop:4
RightBottom:5
ToName:(align)->
switch align
when Align.Center
"Center"
when Align.LeftBottom
"Left Bottom"
when Align.LeftTop
"Left Top"
when Align.RightTop
"Right Top"
when Align.RightBottom
"Right Bottom"
else
"Center"
Get:(pos,align)->
if align == Align.Center
pos
else
{:width,:height} = CCDirector.winSize
switch align
when Align.LeftBottom
pos-oVec2 width/2,height/2
when Align.LeftTop
oVec2 pos.x-width/2,height/2-pos.y
when Align.RightTop
oVec2(width/2,height/2)-pos
when Align.RightBottom
oVec2 width/2-pos.x,pos.y-height/2
else
pos
Convert:(pos,fromAlign,toAlign)->
pos = Align.Get pos,fromAlign
if toAlign == Align.Center
pos
else
{:width,:height} = CCDirector.winSize
switch toAlign
when Align.LeftBottom
pos+oVec2 width/2,height/2
when Align.LeftTop
oVec2 pos.x+width/2,height/2-pos.y
when Align.RightTop
oVec2(width/2,height/2)-pos
when Align.RightBottom
oVec2 width/2-pos.x,pos.y+height/2
else
pos
}
Types =
PlatformWorld:1
UILayer:2
Camera:3
Layer:4
World:5
Body:6
Model:7
Sprite:8
Effect:9
SubCam:10
TypeNames = {v,k for k,v in pairs Types}
local Items
DataCreater = (dataDef)->
create = dataDef.create
dataDef.create = nil
dataMt =
__call:(parent,index)=> create @,parent,index
__newindex:(k,v)=>
if "number" == type k
rawset @,k,v
else
itemDef = dataDef[k]
if itemDef
if @[itemDef[1]] ~= v
@[itemDef[1]] = v
if k ~= "ui" and k ~= "camera"
emit "Scene.Dirty",true
if k ~= "fold" and k ~= "display"
emit "Scene.ViewArea.Frame",@
else
error "assign invalid field #{k} to data"
__index:(k)=>
itemDef = dataDef[k]
if itemDef
if itemDef[1] == 1
TypeNames[@[itemDef[1]]]
else
@[itemDef[1]]
else
nil
__tostring:=>
strs = {}
insert = table.insert
append = (str)-> insert strs,str
append "{"
for i,item in ipairs @
switch tolua.type item
when "boolean"
append item and "t" or "f"
when "oVec2"
append string.format "v(%.2f,%.2f)",item.x,item.y
when "CCSize"
append string.format "s(%d,%d)",item.width,item.height
when "CCRect"
append string.format "r(%d,%d,%d,%d)",item.origin.x,item.origin.y,item.size.width,item.size.height
when "string"
append "\""
append item
append "\""
when "table"
if getmetatable item
append tostring item
elseif #item > 0
append "{"
for i,v in ipairs item
append tostring v
append "," unless i == #item
append "}"
else
append "f"
when "number"
append string.format "%.2f",item
else
append tostring item
append "," unless i == #@
append "}"
table.concat(strs)\gsub("%.00","")
(data)->
if not data
data = {v[1],(type(v[2]) == "function" and v[2]! or v[2]) for _,v in pairs dataDef}
data.typeName = TypeNames[data[1]]
data.getItems = => {v[1],k for k,v in pairs dataDef}
setmetatable data,dataMt
data
Items =
loadData:(filename)->
setupData = (data)->
Items[TypeNames[data[1]]] data
if data.children
for child in *data.children
setupData child
data = dofile filename
setupData data
Contacts data.contacts if data.contacts
Groups data.groups if data.groups
if data.camera
camera = data.camera
Items.Camera camera
if camera.subCams
for cam in *camera.subCams
Items.SubCam cam
data
dumpData:(data,filename)->
str = "local v,r,t,f = require(\"oVec2\"),require(\"CCRect\"),true,false\nreturn "..tostring data
oContent\saveToFile filename,str
:Align
:Simulation
PlatformWorld:DataCreater
-- property
itemType:{1,Types.PlatformWorld}
gravity:{2,-10}
contacts:{3,Contacts}
groups:{4,Groups}
simulation:{5,1}
camera:{6,false}
ui:{7,false}
children:{8,false}
-- design
outline:{9,true}
-- helper
create:=>
world = with oPlatformWorld!
.gravity = oVec2 0,@gravity
.showDebug = @outline
\setIterations Simulation @simulation
world.scheduler = with CCScheduler!
.timeScale = 0
CCDirector.scheduler\schedule world.scheduler
world\slot "Cleanup",->
CCDirector.scheduler\unschedule world.scheduler
editor.items = {Scene:world}
editor.itemDefs = {[world]:@}
world.itemData = @
@.camera world if @camera
@.ui world if @ui
Contact world,@
Children world,@
world
UILayer:DataCreater
-- property
itemType:{1,Types.UILayer}
visible:{2,true}
children:{3,false}
-- design
display:{4,true}
fold:{5,false}
-- helper
create:(scene)=>
layer = scene.UILayer
editor.items.UI = layer
layer.position += editor.origin
layer.visible = @visible and @display
editor.itemDefs[layer] = @
Children layer,@
nil
Camera:DataCreater
-- property
itemType:{1,Types.Camera}
boundary:{2,false}
area:{3,Rect!}
subCams:{4,false}
-- helper
create:(scene)=>
camera = scene.camera
editor.items.Camera = camera
editor.itemDefs[camera] = @
nil
SubCam:DataCreater
-- property
itemType:{1,Types.SubCam}
name:{2,"camera"}
position:{3,Point(0,0)}
zoom:{4,1}
angle:{5,0}
-- helper
create:=>
Layer:DataCreater
-- property
itemType:{1,Types.Layer}
name:{2,"layer"}
ratioX:{3,0}
ratioY:{4,0}
offset:{5,Point(0,0)}
zoom:{6,1}
visible:{7,true}
children:{8,false}
-- design
display:{9,true}
fold:{10,false}
-- helper
create:(scene,index)=>
scene\setLayerOffset index,@offset
layer = with scene\getLayer index
.scaleX = @zoom
.scaleY = @zoom
.visible = @visible and @display
editor.items[@name] = layer
editor.itemDefs[layer] = @
Children layer,@
nil
World:DataCreater
-- property
itemType:{1,Types.World}
name:{2,"world"}
gravity:{3,Point(0,-10)}
simulation:{4,1}
ratioX:{5,0}
ratioY:{6,0}
offset:{7,Point(0,0)}
zoom:{8,1}
visible:{9,true}
children:{10,false}
-- design
outline:{11,true}
display:{12,true}
fold:{13,false}
-- helper
create:(scene,index)=>
scene\setLayerOffset index,@offset
layer = with scene\getLayer index
.scaleX = @zoom
.scaleY = @zoom
world = with oWorld!
.gravity = @gravity
.showDebug = @outline
.visible = @visible and @display
\setIterations Simulation @simulation
layer\addChild world
world.scheduler = with CCScheduler!
.timeScale = 0
CCDirector.scheduler\schedule world.scheduler
world\slot "Cleanup",->
CCDirector.scheduler\unschedule world.scheduler
oData\apply world
Contact world,editor.sceneData
editor.items[@name] = world
editor.itemDefs[world] = @
Contact world,@
Children world,@
nil
Body:DataCreater
-- property
itemType:{1,Types.Body}
name:{2,"body"}
file:{3,""}
group:{4,1}
position:{5,Point(0,0)}
angle:{6,0}
visible:{7,true}
-- design
display:{8,true}
-- helper
create:(parent)=>
world = editor.items.Scene
if "oWorld" == tolua.type parent
world = parent
body = with oBody @file,world,@position,@angle
.data\each (_,v)->
v.group = @group if "oBody" == tolua.type v
.visible = @visible and @display
editor.items[@name] = body
editor.itemDefs[body] = @
body
Model:DataCreater
-- property
itemType:{1,Types.Model}
name:{2,"model"}
file:{3,""}
position:{4,Point(0,0)}
angle:{5,0}
scale:{6,Point(1,1)}
skew:{7,Point(0,0)}
opacity:{8,1}
look:{9,""}
animation:{10,""}
speed:{11,1}
loop:{12,false}
faceRight:{13,false}
visible:{14,true}
-- design
display:{15,true}
-- ui
align:{16,Align.Center}
-- helper
create:=>
model = with oModel @file
.position = Align.Get @position,@align
.angle = @angle
.scaleX = @scale.x
.scaleY = @scale.y
.skewX = @skew.x
.skewY = @skew.y
.opacity = @opacity
.look = @look
.speed = @speed
.loop = @loop
.faceRight = @faceRight
.visible = @visible and @display
\play @animation
editor.items[@name] = model
editor.itemDefs[model] = @
model
Sprite:DataCreater
-- property
itemType:{1,Types.Sprite}
name:{2,"sprite"}
file:{3,""}
position:{4,Point(0,0)}
angle:{5,0}
scale:{6,Point(1,1)}
skew:{7,Point(0,0)}
opacity:{8,1}
visible:{9,true}
-- design
display:{10,true}
-- ui
align:{11,Align.Center}
-- helper
create:=>
sprite = with CCSprite @file
.position = Align.Get @position,@align
.angle = @angle
.scaleX = @scale.x
.scaleY = @scale.y
.skewX = @skew.x
.skewY = @skew.y
.opacity = @opacity
.visible = @visible and @display
editor.items[@name] = sprite
editor.itemDefs[sprite] = @
sprite
Effect:DataCreater
-- property
itemType:{1,Types.Effect}
name:{2,"effect"}
effect:{3,""}
position:{4,Point(0,0)}
play:{5,true}
visible:{6,true}
-- design
display:{7,true}
-- ui
align:{8,Align.Center}
-- helper
create:(parent)=>
effect = with oEffect @effect
.visible = @visible and @display
.position = Align.Get @position,@align
\addTo parent
\start! if @play
editor.items[@name] = effect
editor.itemDefs[effect] = @
nil
Items
| 22.242 | 105 | 0.589066 |
66e86ee21da9285abe1fc0476ad48fdf3c4a9435 | 1,742 | ----------------------------------------------------------------
-- The base class used for creating custom @{RomlObject}s.
-- Creating custom objects has been simplified for the purposes
-- of coding them in Lua; they only are simple tables with the
-- specific functions within them. The library creates the
-- sub-class from that (inside @{CustomObjectBuilder}).
--
-- @classmod MainRossBlock
-- @author Richard Voelker
-- @license MIT
----------------------------------------------------------------
local RomlObject
if game
RomlObject = require(game\GetService("ServerScriptService").com.blacksheepherd.roml.RomlObject)
else
RomlObject = require "com.blacksheepherd.roml.RomlObject"
-- {{ TBSHTEMPLATE:BEGIN }}
class CustomObject extends RomlObject
new: (romlDoc, objectId, classes) =>
super(romlDoc, @\Create!, objectId, classes)
@\SetProperties(@\CreateProperties!)
ObjectName: => @@__name
Create: =>
CreateProperties: =>
{}
PropertyUpdateOrder: =>
{}
UpdateProperty: (robloxObject, name, value) =>
Refresh: =>
propertyUpdateOrder = @\PropertyUpdateOrder!
if #propertyUpdateOrder > 0
for name in *propertyUpdateOrder
if @_properties[name] != nil
@\UpdateProperty @_robloxObject, name, @_properties[name]
else
for name, property in pairs @_properties
@\UpdateProperty @_robloxObject, name, property
StyleObject: (properties) =>
propertyUpdateOrder = @\PropertyUpdateOrder!
if #propertyUpdateOrder > 0
for name in *propertyUpdateOrder
if properties[name] != nil
@\UpdateProperty @_robloxObject, name, properties[name]
else
for name, property in pairs properties
@\UpdateProperty @_robloxObject, name, property
-- {{ TBSHTEMPLATE:END }}
return CustomObject
| 28.096774 | 96 | 0.679679 |
a91e0a476da6fd014fc7944b2bda44b6ebef3abe | 1,293 | howl.util.lpeg_lexer ->
expr_span = (start_pat, end_pat) ->
start_pat * ((V'sexpr' + P 1) - end_pat)^0 * (end_pat + P(-1))
comment = capture 'comment', any {
span(';', eol),
P'#|' * scan_to '|#',
P'#;' * P { 'sexpr', sexpr: expr_span('(',')') },
span('#!' * (blank^1 + '\\'), eol)
}
delimiter = any { space, P'\n', S'()[]' }
-- delimiter = any { space, S'/.,(){}[]^#' }
character = capture 'char', P'#\\' * (1 - delimiter)
string = capture 'string', span '"', '"'
number = capture 'number', word {
digit^1 * P'/' * digit^1 -- rational
P('-')^-1 * digit^1 * P'.' * digit^1 * (S'eE' * P('-')^-1 * digit^1)^-1 -- floating
P('-')^-1 * digit^1 -- decimal
P'#' * S'Bb' * S'01'^1 -- binary
P'#' * S'Oo' * R('07')^1 -- octal
P'#' * S'Xx' * R('AF','af','09')^1 -- hexadecimal
}
dorc = any { delimiter, P':' }
name = complement(dorc)^1
identifier = capture 'identifier', name
keyword = capture 'constant', any {
P':' * name,
P'#:' * name,
name * P':'
}
specials = capture 'special', any {
word { '#t', '#f' }
word { '#cs', '#ci' }
S('\'') * name
line_start * '#>' * scan_to('<#')
}
any {
string,
character,
comment,
number,
keyword,
specials,
identifier
}
| 23.089286 | 87 | 0.471771 |
ec26b166cb4cec3fcf1ba99ed0e299c1a5e38829 | 4,283 | import log from howl
-- Make the linter shut up.
spec_parsers = nil
spec_parsers =
boolean: (value) =>
switch value
when 'true'
return true
when 'false'
return false
else
return nil, 'Expected true or false'
positive_integer: (value) =>
int = tonumber value
if not value\match '^%d+$' or int < 0
return nil, 'Expected a positive integer'
return int
positive_integer_or_allowed_string: (value) =>
if value == @allowed_string
return value
int = spec_parsers.positive_integer @, value
if not int
return nil, "Expected a positive integer or #{@allowed_string}"
return int
string_choice: (value) =>
for choice in *@choices
return value if value == choice
return nil, "Expected one of #{table.concat @choices, ','}"
key_specs =
root:
parse: spec_parsers.boolean
indent_style:
parse: spec_parsers.string_choice
choices: {'tab', 'space'}
apply: (buffer, value) =>
buffer.config.use_tabs = value == 'tab'
indent_size:
parse: spec_parsers.positive_integer_or_allowed_string
allowed_string: 'tab'
apply: (buffer, value) =>
buffer.config.indent = if value == 'tab'
buffer.config.tab_width
else
value
tab_width:
parse: spec_parsers.positive_integer
apply: (buffer, value) =>
buffer.config.tab_width = value
end_of_line:
parse: spec_parsers.string_choice
choices: {'lf', 'crlf', 'cr'}
apply: (buffer, value) =>
buffer.eol = value\gsub('cr', '\r')\gsub('lf', '\n')
charset:
parse: spec_parsers.string_choice
choices: {'latin1', 'utf-8', 'utf-16be', 'utf-16le', 'utf-8-bom'}
apply: (buffer, value) =>
-- TODO (when would anyone actually use this for anything but utf-8?)
trim_trailing_whitespace:
parse: spec_parsers.boolean
apply: (buffer, value) =>
buffer.config.strip_trailing_whitespace = value
insert_final_newline:
parse: spec_parsers.boolean
apply: (buffer, value) =>
buffer.config.ensure_newline_at_eof = value
max_line_length:
parse: spec_parsers.positive_integer_or_allowed_string
allowed_string: 'off'
apply: (buffer, value) =>
if value != 'off'
buffer.config.edge_column = value
buffer.config.hard_wrap_column = value
buffer.config.auto_reflow_text = true
else
buffer.config.edge_column = nil
buffer.config.auto_reflow_text = false
class ParseContext
new: (file, match_compiler) =>
@file = file
@match_compiler = match_compiler
@line = nil
@lineno = 0
@root = false
@sections = {}
error: (message) =>
log.error "#{@file}: #{@lineno}: #{message}: #{@line}"
parse_section: =>
section_name = @line\match '^%[(.*)%]$'
if not section_name
@error "Invalid section"
else
pattern = @.match_compiler section_name
if not pattern
@error "Invalid pattern in section"
table.insert @sections,
:pattern
uncompiled: section_name
recursive: section_name\match'/' != nil
config: {}
parse_setting: =>
key, value = @line\match '^([%a_]+)%s*=%s*(.+)$'
if not key or not value
@error "Invalid setting"
return
if key == 'root'
if #@sections != 0
@error "root key must be at root"
return
elseif #@sections == 0
@error "All keys but root must be in a section"
return
spec = key_specs[key]
if not spec
return
local parsed_value
if value != 'unset' or key == 'root'
parsed_value, error = spec\parse value
if error
@error "Failed to parse value: #{error}"
return
if key == 'root'
@root = parsed_value
else
@sections[#@sections].config[key] = {:spec, value: parsed_value}
parse: =>
@file\open 'r', (fh) ->
while true
@line = fh\read!
break if not @line
@lineno += 1
@line = @line.stripped
continue if @line.is_empty or @line\match '^%s*[#;]'
if @line\match '^%['
@parse_section!
else
@parse_setting!
return @root, @sections
(...) ->
args = {...}
context = ParseContext unpack args
return context\parse!
| 24.061798 | 75 | 0.608919 |
72d17f41957a08f3cb39b4cd00040f38bb713344 | 3,697 | describe 'Regex', ->
context 'creation', ->
it 'raises an error if the pattern is invalid', ->
assert.raises 'regular expression', -> r'?\\'
it 'returns a regex for a valid pattern', ->
assert.is_not_nil r'foo()\\d+'
it 'accepts a regex as well', ->
assert.is_not_nil r r'foo()\\d+'
it 'accepts and optional table of compile flags', ->
reg = r '.', {r.DOTALL}
assert.is_truthy reg\match "\n"
it 'accepts and optional table of match flags', ->
reg = r 'x', nil, {r.MATCH_ANCHORED}
assert.is_falsy reg\match "ax"
it '.pattern holds the regex used for construction', ->
assert.equal 'foo(bar)', r('foo(bar)').pattern
it '.capture_count holds the number of captures in the pattern', ->
assert.equal 2, r('foo(bar) (\\w+)').capture_count
it 'r.is_instance(v) returns true if <v> is a regex', ->
assert.is_true r.is_instance r'foo'
assert.is_false r.is_instance 'foo'
assert.is_false r.is_instance {}
describe 'match(string [, init])', ->
it 'returns nil if the pattern does not match', ->
assert.is_nil r'foo'\match 'bar'
context 'with no captures in the pattern', ->
it 'returns the entire match', ->
assert.equal 'right', r'ri\\S+'\match 'red right hand'
context 'with captures in the pattern', ->
it 'returns the captured values', ->
assert.same { 'red', 'right' }, { r'(r\\w+)\\s+(\\S+)'\match 'red right hand' }
it 'empty captures are returned as position captures', ->
assert.same { 1, 4 }, { r'()red()'\match 'red' }
it 'position captures are character based', ->
assert.same { 2, 3 }, { r'å()ä()'\match 'åäö' }
context 'when init is specified', ->
it 'matching starts from the init position', ->
assert.equal 'right', r'r\\S+'\match 'red right hand', 2
assert.equal 6, r'r()\\S+'\match 'red right hand', 2
it 'negative values counts from the end', ->
assert.equal 'og', r'o\\w'\match 'top dog', -2
describe 'find(s, init)', ->
it 'returns nil if the pattern could not be found in <s>', ->
assert.is_nil r'foo'\find 'bar'
it 'returns the indices where the pattern match starts and end if found', ->
assert.same { 2, 2 }, { r'\\pL'\find '!äö' }
it 'returns any captures after the indices', ->
assert.same { 2, 2, 'ä' }, { r'(\\pL)'\find '!äö' }
it 'empty captures are returned as position captures', ->
assert.same { 2, 2, 3 }, { r'\\pL()'\find '!äö' }
it 'starts matching after init', ->
assert.same { 3, 5, 6 }, { r'\\w+()'\find '12ab2', 3}
describe 'gmatch(s)', ->
context 'with no captures in the pattern', ->
it 'produces each consecutive match in each call', ->
matches = [m for m in r'\\w+'\gmatch 'well hello there']
assert.same { 'well', 'hello', 'there' }, matches
context 'with captures in the pattern', ->
it 'returns empty captures as position matches', ->
matches = [p for p in r'()\\pL+'\gmatch 'well hellö there' ]
assert.same { 1, 6, 12 }, matches
it 'produces the the set of captures in each call', ->
matches = [{p,m} for p,m in r'()(\\w+)'\gmatch 'well hello there']
assert.same { {1, 'well'}, {6, 'hello'}, {12, 'there'} }, matches
it 'returns no matches when it does not match', ->
matches = [m for m in r'\\d+'\gmatch 'well hello there']
assert.same {}, matches
it 'escape(s) returns a string with all special regular expression symbols escaped', ->
assert.equal 'a\\.b\\*c', r.escape 'a.b*c'
it 'tostring(regex) returns the pattern', ->
assert.equal '\\s*(foo)', tostring r'\\s*(foo)'
| 38.113402 | 89 | 0.590749 |
9b39b7f7418ee84bec87a667f54b48fc009a33de | 102 | from => til =>
val => end =>
(for from til end i =>
(val (sub (add from til) (add i 1))))
| 20.4 | 43 | 0.470588 |
a265366751f9d6867473549e6543306e543a4ef6 | 18,338 | return (ASS, ASSFInst, yutilsMissingMsg, createASSClass, Functional, LineCollection, Line, logger, SubInspector, Yutils) ->
{:list, :math, :string, :table, :unicode, :util, :re } = Functional
msgs = {
new: {
badInput: "argument #%d is not a valid drawing object, contour or table, got a %s."
invalidObject: "argument #%d is not a valid drawing object or contour, got a %s."
badCommandsInTable: "argument #%d to %s contains invalid drawing objects (#%d is a %s)."
}
modCommands: {
badCommandType: "argument #2 must be either a table of command classes or names, a single command class or a single command name, got a %s."
}
insertContours: {
badContours: "argument #1 (contours) must be either a single contour object or a table of contours, got a %s."
badContour: "can only insert objects of class %s, got a %s."
}
insertCommand: {
badIndex: "argument #2 (index) must be an integer != 0, got '%s' of type %s."
badCommands: "argument #1 (cmds) must be either a drawing command object or a table of drawing commands, got a %s."
noContourAtIndex: "can't insert command: no contour at index %d"
badCommand: "command #%d must be a drawing command object, got a %s"
}
getCommandAtLength: {
missingLength: "Unexpected Error: command at length not found in target contour."
}
removeContours: {
badContours: "argument #1 must be either an %s object, an index, nil or a table of contours/indexes; got a %s."
}
rotate: {
badAngle: "argument #1 (angle) must be either a number or a %s object, got a %s."
}
}
DrawingBase = createASSClass "Draw.DrawingBase", ASS.Tag.Base, {"contours"}, {"table"}
-- TODO: check if these can be remapped/implemented in a way that makes sense, maybe work on strings
DrawingBase.set, DrawingBase.mod = nil, nil
local cmdMap, cmdSet, Close, Draw, Move, Contour, Bezier
DrawingBase.new = (args = {}) =>
unless cmdMap -- import often accessed information into local scope
cmdMap, cmdSet = ASS.Draw.commandMapping, ASS.Draw.commands
Close, Move, Contour, Bezier = ASS.Draw.Close, ASS.Draw.Move, ASS.Draw.Contour, ASS.Draw.Bezier
-- construct from a raw string of drawing commands
if args.raw or args.str
scale = args.scale or 1
str = if args.raw and args.tagProps.signature == "scale"
scale = args.raw[1]
args.raw[2]
elseif args.raw
args.raw[1]
else args.str
@contours, @junk = ASS.Parser.Drawing\getContours str, @, args.splitContours
@scale = ASS\createTag "drawing", scale
if @scale > 1
@div 2^(@scale-1), 2^(@scale-1)
-- construct by deep-copying a compatible object
elseif ASS\instanceOf args[1], DrawingBase, nil, true
copy = args[1]\copy!
@contours, @scale = copy.contours, copy.scale
@__tag.inverse = copy.__tag.inverse
-- construct from valid drawing commands, contours and tables of drawing commands
else
@contours, c = {}, 1
@scale = ASS\createTag "drawing", args.scale or 1
contour, d = {}, 1
for i, arg in ipairs args
argType = type arg
logger\assert argType == "table", msgs.new.badInput, i, argType
-- a new contour causes the already open contour to be closed
if arg.class == Contour
if #contour > 0
@contours[c] = Contour contour
@contours[c].parent, c = @, c+1
@contours[c], c = arg, c+1
contour, d = {}, 1
-- a move creates a new contour, unless otherwise requested
elseif arg.class == Move and i > 1 and args.splitContours != false
@contours[c], c = Contour(contour), c+1
contour, d = {arg}, 2
-- any other valid command is added to the currently open contour
elseif ASS\instanceOf arg, cmdSet
contour[d] = arg
d += 1
else
logger\assert not arg.class, msgs.new.invalidObject, i, arg.typeName
-- a table of drawing commands is also supported
for j, cmd in ipairs arg
logger\assert ASS\instanceOf(cmd, cmdSet), msgs.new.badCommandsInTable,
i, @typeName, j, cmd.class or type cmd
if cmd.instanceOf[Move]
@contours[c] = Contour contour
@contours[c].parent = @
contour, d = {cmd}, 2
c += 1
else
contour[d] = cmd
d += 1
-- commit last open contour if it contains any drawing commands
if #contour > 0
@contours[c] = Contour contour
@contours[c].parent = @
@readProps args
return @
DrawingBase.callback = (callback, first = 1, last = #@contours, includeCW = true, includeCCW = true, a1, a2, a3, a4, a5, a6) =>
j, rmCnt, removed = 1, 0
for i = first, last
cnt = @contours[i]
if (includeCW or not cnt.isCW) and (includeCCW or cnt.isCW)
res = callback cnt, @contours, i, j, @toRemove, a1, a2, a3, a4, a5, a6
j += 1
if res == false
@toRemove or= {}
@toRemove[cnt], @toRemove[rmCnt+1] = true, i
rmCnt += 1
elseif res != nil and res != true
@contours[i], @length = res
-- delay removal of contours until the all contours have been processed
if rmCnt > 0
removed = list.removeIndices @contours, @toRemove
@length = nil
@toRemove = nil
return removed, rmCnt
mapCommandTypes = (cmdType, cmdSet = {}) ->
switch type cmdType
when "string"
if cmdClass = cmdMap[cmdType]
cmdSet[cmdClass] = true
when "table"
if cmdType.class
cmdSet[cmdType.class] = true
else
for cmd in *cmdType
res, err = mapCommandTypes cmd, cmdSet
return nil, err unless res
else return nil, cmdType
return true
DrawingBase.modCommands = (callback, commandTypes, start, end_, includeCW = true, includeCCW = true, args) =>
cmdSet, err = mapCommandTypes commandTypes if commandTypes
logger\error msgs.modCommands.badCommandType, err if err
matchedCmdCnt, matchedCntsCnt, rmCntsCnt, rmCmdsCnt = 1, 1, 0, 0
for i, cnt in @contours
if (includeCW or not cnt.isCW) and (includeCCW or cnt.isCW)
rmCmdsCnt = 0
for j, cmd in cnt.commands
if not cmdSet or cmdSet[cmd.class]
res = callback cmd, cnt.commands, j, matchedCmdCnt, i, matchedCntsCnt, cnt.toRemove, @toRemove, args
matchedCmdCnt += 1
if res == false
cnt.toRemove or= {}
cnt.toRemove[cmd], cnt.toRemove[rmCmdsCnt+1] = true, j
rmCmdsCnt += 1
elseif res != nil and res != true
cnt.commands[j] = res
cnt.length, cnt.isCW, @length = nil
matchedCntsCnt += 1
if rmCmdsCnt > 0
list.removeIndices cnt.commands, cnt.toRemove
cnt.length, cnt.isCW, @length, cnt.toRemove = nil
if #cnt.commands == 0
@toRemove or= {}
@toRemove[cnt], @toRemove[rmCntsCnt+1] = true, i
rmCntsCnt += 1
-- delay removal of contours until the all contours have been processed
if rmCntsCnt > 0
list.removeIndices @contours, @toRemove
@length, @toRemove = nil
DrawingBase.insertCommands = (cmds, index) =>
prevCnt = #@contours
index or= math.max prevCnt, 1
unless math.isInt(index) and index != 0
logger\error msgs.insertCommands.badIndex, tostring(index), type index
if type(cmds) != "table"
logger\error msgs.insertCommands.badCommands, type cmds
index += prevCnt + 1 if index < 0
currentContour = @contours[index]
unless currentContour
logger\assert index == 1 and prevCnt == 0, msgs.insertCommands.noContourAtIndex, index
@contours[1] = Contour! -- create a contour if none exists and index is 1
currentContour = @contours[1]
c = #currentContour.commands + 1
-- insert a single drawing command
if cmds.class
unless cmdSet[cmds.class]
logger\error msgs.insertCommands.badCommand, cmds.typeName
if cmds.class == Move
@insertContours Contour({cmds}), index
else
currentContour.commands[c] = cmds
currentContour.length, currentContour.isCW = nil
@length = nil
return
-- insert any number of drawing commands
for i, cmd in ipairs cmds
if type(cmd) != "table" or not cmdSet[cmd.class]
logger\error msgs.insertCommands.badCommand, type(cmd) == "table" and cmd.typeName or type cmd
if cmd.class == Move
unless currentContour.class
@insertContours Contour(currentContour), index
currentContour, c = {cmd}, 1
index += 1
elseif currentContour.class
currentContour.commands[c] = cmd
currentContour.length, currentContour.isCW = nil
else currentContour[c] = cmd
c += 1
@insertContours Contour(currentContour), index unless currentContour.class
@length = nil
DrawingBase.insertContours = (cnts, index = #@contours + 1) =>
if type(cnts) != "table"
logger\error msgs.insertContours.badContours, type cnts
if cnts.class
if cnts.compatible[DrawingBase]
-- copy all contours from another drawing
cnts = cnts\copy!.contours
elseif cnts.class == Contour
-- insert a single contour
table.insert @contours, index, cnts
@length = nil
return cnts
else logger\error msgs.insertContours.badContour, Contour.typeName, cnts.typeName
-- insert a table of contours
for i, cnt in ipairs cnts
if type(cnt) != "table" or cnt.class != Contour
logger\error msgs.insertContours.badContour, Contour.typeName,
type(cnt) == "table" and cnt.typeName or type cnt
table.insert @contours, index + i-1, cnt
cnt.parent = @
@length = nil if #cnts > 0
return cnts
DrawingBase.toString = =>
cmds, c = {}, 1
for i, cnt in ipairs @contours
unless cnt.disabled or @toRemove and @toRemove[cnt]
-- make disabled contours and contours subject to delayed deletion disappear
cmds[c] = cnt\getTagParams @scale
c += 1
return table.concat cmds, " "
DrawingBase.__tostring = DrawingBase.__tostring
DrawingBase.getTagParams = =>
if @scale\equal 1
return DrawingBase.toString @
return @scale\getTagParams!, DrawingBase.toString @
DrawingBase.commonOp = (method, callback, default, x, y) => -- drawing commands only have x and y in common
for cnt in *@contours
cnt\commonOp method, callback, default, x, y
return @
DrawingBase.drawRect = (tl, br) => -- TODO: contour direction
rect = ASS.Draw.Contour{ASS.Draw.Move(tl), ASS.Draw.Line(br.x, tl.y),
ASS.Draw.Line(br), ASS.Draw.Line(tl.x, br.y)}
@insertContours rect
return @, rect
DrawingBase.expand = (x, y) =>
holes, others, covered = @getHoles!
@removeContours covered
hole\expand -x, -y for hole in *holes
other\expand x, y for other in *others
return @
DrawingBase.flatten = =>
flatStr = {}
for i, cnt in *@contours
_, flatStr[i] = cnt\flatten!
return @, table.concat flatStr, " "
DrawingBase.getLength = (includeContourLengths) =>
totalLen = 0
lens = includeContourLengths and {} or nil
for cnt in *@contours
len, lenParts = cnt\getLength!
table.joinInto(lens, lenParts) if includeContourLengths
totalLen += len
@length = totalLen
return totalLen, lens
DrawingBase.getCommandAtLength = (len, useCachedLength) =>
@getLength! unless useCachedLength and @length
currTotalLen, contourCnt = 0, #@contours
for i, contour in ipairs @contours
if currTotalLen+contour.length-len > -0.001 and contour.length > 0
cmd, remLen = contour\getCommandAtLength len, useCachedLength
if i != contourCnt and not cmd
logger\error msgs.getCommandAtLength.missingLength
return cmd, remLen, contour, i
else currTotalLen += contour.length - len
return false
-- error(string.format("Error: length requested (%02f) is exceeding the total length of the shape (%02f)",len,currTotalLen))
DrawingBase.getPositionAtLength = (len, useCachedLength, useCurveTime) =>
@getLength! unless useCachedLength and @length
cmd, remLen, cnt = @getCommandAtLength len, true
return false unless cmd
return cmd\getPositionAtLength(remLen, true, useCurveTime), cmd, cnt
DrawingBase.getAngleAtLength = (len, useCachedLength) =>
@getLength! unless useCachedLength and @length
cmd, remLen, cnt = @getCommandAtLength len, true
return false unless cmd
fCmd = cmd.class == Bezier and cmd.flattened\getCommandAtLength(remLen, true) or cmd
return fCmd\getAngle(nil, false, true), cmd, cnt
DrawingBase.getExtremePoints = (allowCompatible) =>
return {w: 0, h: 0} if #@contours == 0
ext = @contours[1]\getExtremePoints allowCompatible
for i=2, #@contours
pts = @contours[i]\getExtremePoints allowCompatible
ext.top = pts.top if ext.top.y > pts.top.y
ext.left = pts.left if ext.left.x > pts.left.x
ext.bottom = pts.bottom if ext.bottom.y < pts.bottom.y
ext.right=pts.right if ext.right.x < pts.right.x
ext.w, ext.h = ext.right.x - ext.left.x, ext.bottom.y - ext.top.y
return ext
DrawingBase.getBounds = =>
logger\assert Yutils, yutilsMissingMsg
l, t, r, b = Yutils.shape.bounding Yutils.shape.flatten DrawingBase.toString @
return {ASS.Point(l, t), ASS.Point(r, b), w: r-l, h: b-t}
DrawingBase.outline = (x, y, mode) =>
@contours = @getOutline(x, y, mode).contours
@length = nil
DrawingBase.getOutline = (x, y = x, mode = "round") =>
logger\assert Yutils, yutilsMissingMsg
outline = Yutils.shape.to_outline Yutils.shape.flatten(DrawingBase.toString @), x, y, mode
return @class {str: outline}
DrawingBase.removeContours = (cnts, first = 1, last, includeCW = true, includeCCW = true) =>
-- calling this without any arguments removes all contours
if not cnts and first == 1 and not last and includeCW and includeCCW
removed, @contours, @length = @contours, {}
cnt.parent = nil for cnt in *removed
return removed
cntsType = type cnts
-- remove a single contour by index or reference
if not cnts or cntsType == "number" or cntsType == "table" and cnts.class == Contour
return @callback ((cnt, _, i) -> cnts and cnts != i and cnts != cnt), first, last, includeCW, includeCCW
if cntsType == "table" and cnts.class or cntsType != "table"
logger\error msgs.removeContours.badContours, Contour.typeName, cntsType == "table" and cnts.typeName or cntsType
-- remove a list of contours or indices
cntsSet = list.makeSet cnts
@callback((cnt,_,i) -> not cntsSet[cnt] and not cntsSet[i]), first, last, includeCW, includeCCW
DrawingBase.getFullyCoveredContours = =>
scriptInfo, parentContents = ASS\getScriptInfo @
parentCollection = parentContents and parentContents.line.parentCollection or LineCollection ASSFInst.cache.lastSub
covCnts, c = {}, 0
@callback (cnt, cnts, i) ->
return if covCnts[cnt]
for j = i+1, #cnts
if not (covCnts[cnt] or covCnts[cnts[j]]) and cnts[j].isCW == cnt.isCW
if covered = cnt\getFullyCovered cnts[j], scriptInfo, parentCollection
covCnts[covered], c = true, c+1
covCnts[c] = covered == cnt and i or j
return covCnts
DrawingBase.getHoles = =>
scriptInfo, parentContents = ASS\getScriptInfo @
parentCollection = parentContents and parentContents.line.parentCollection or LineCollection ASSFInst.cache.lastSub
bounds, safe = @getExtremePoints!, 1.05
scaleFac = math.max bounds.w*safe / scriptInfo.PlayResX, bounds.h*safe / scriptInfo.PlayResY
testDrawing = ASS.Section.Drawing{@}
testDrawing\modCommands (cmd) ->
cmd\sub bounds.left.x, bounds.top.y
cmd\div scaleFac, scaleFac if scaleFac > 1
-- snap drawing commands to the pixel grid to avoid false positives
-- when using the absence of opaque pixels in the clipped drawing to determine
-- whether the contour is a hole
cmd\ceil 0, 0
testLineCnts = ASS\createLine({{ASS.Section.Tag(ASS.defaults.drawingTestTags), testDrawing}, parentCollection}).ASS
testTagCnt = #testLineCnts.sections[1].tags
covered, holes, other, h, o = @getFullyCoveredContours!, {}, {}, 1, 1
coveredSet = list.makeSet covered
testDrawing\callback (cnt, _, i) ->
unless coveredSet[@contours[i]]
testLineCnts.sections[1].tags[testTagCnt+1] = ASS\createTag "clip_vect", cnt
if not testLineCnts\getLineBounds!.firstFrameIsSolid
-- clipping the drawing to the contour produced no solid pixels (only subpixel residue)
-- most likely means the contour is a hole
holes[h] = @contours[i]
h += 1
else
other[o] = @contours[i]
o += 1
return holes, other, covered
DrawingBase.rotate = (angle = 0) =>
if ASS\instanceOf angle, ASS.Number
angle = angle\getTagParams!
else logger\assert type(angle) == "number", msgs.rotate.badAngle,ASS.Number.typeName,
type(angle) == "table" and angle.typeName or type angle
if angle % 360 != 0
logger\assert Yutils, yutilsMissingMsg
shape = DrawingBase.toString @
bnd = {Yutils.shape.bounding shape }
rotMatrix = with Yutils.math.create_matrix!
.translate((bnd[3]-bnd[1])/2,(bnd[4]-bnd[2])/2,0)
.rotate("z",angle)
.translate(-bnd[3]+bnd[1]/2,(-bnd[4]+bnd[2])/2,0)
shape = Yutils.shape.transform shape, rotMatrix
@contours = DrawingBase({raw: shape}).contours
return @
DrawingBase.get = =>
if #@contours == 1
return @contours[1]\get!, @scale\get!
commands, c = {}, 1
for cnt in *@contours
commands[c], c = cmd, c + 1 for cmd in *cnt\get!
return commands, @scale\get!
DrawingBase.getSection = =>
section = ASS.Section.Drawing!
section.contours, section.scale = @contours, @scale
return section
return DrawingBase
| 36.602794 | 146 | 0.639328 |
42ba3fb8b2eb0bfee168bb513bfef77a66196c21 | 1,041 | class WebmVP8 extends Format
new: =>
@displayName = "WebM"
@supportsTwopass = true
@videoCodec = "libvpx"
@audioCodec = "libvorbis"
@outputExtension = "webm"
@acceptsBitrate = true
getPreFilters: =>
-- colormatrix filter
colormatrixFilter =
"bt.709": "bt709"
"bt.2020": "bt2020"
"smpte-240m": "smpte240m"
ret = {}
-- vp8 only supports bt.601, so add a conversion filter
-- thanks anon
colormatrix = mp.get_property_native("video-params/colormatrix")
if colormatrixFilter[colormatrix]
append(ret, {
"lavfi-colormatrix=#{colormatrixFilter[colormatrix]}:bt601"
})
return ret
getFlags: =>
{
"--ovcopts-add=threads=#{options.libvpx_threads}"
}
formats["webm-vp8"] = WebmVP8!
class WebmVP9 extends Format
new: =>
@displayName = "WebM (VP9)"
@supportsTwopass = true
@videoCodec = "libvpx-vp9"
@audioCodec = "libopus"
@outputExtension = "webm"
@acceptsBitrate = true
getFlags: =>
{
"--ovcopts-add=threads=#{options.libvpx_threads}"
}
formats["webm-vp9"] = WebmVP9!
| 21.6875 | 66 | 0.67147 |
a97b273eebd584ec5a23efe0b34e946d648fad32 | 358 | class ProgressBarBackground extends BarBase
reconfigure: =>
super!
if settings['bar-background-adaptive']
for bar in *@@instantiatedBars
@minHeight = math.max @minHeight, bar.minHeight
@maxHeight = math.max @maxHeight, bar.maxHeight
@_updateBarVisibility!
@line[6] = 100
@line[8] = @line[8]\format settings['bar-background-style']
| 23.866667 | 61 | 0.712291 |
b8cdfda73332d9441a14a7ce1a1cfb7ee2293e23 | 304 | class MATH
-- returns the distance between two points
distance: (x1 = 0, y1 = 0, x2 = 0, y2 = 0) => @round sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2), 3
-- rounds numerical values
round: (x, dec = 2) => dec >= 1 and floor(x * 10 ^ floor(dec) + 0.5) / 10 ^ floor(dec) or floor(x + 0.5)
{:MATH} | 33.777778 | 108 | 0.536184 |
bb848ec7fd9257114b6ad85a2bb402ae8b45a22c | 3,094 | class EventLoop
new: =>
@script = { }
@uiElements = Stack!
@activityZones = Stack!
@displayRequested = false
@needsRedraw = false
@updateTimer = mp.add_periodic_timer settings['redraw-period'], @\redraw
@updateTimer\stop!
mp.register_event 'shutdown', ->
@updateTimer\kill!
local displayRequestTimer
displayDuration = settings['request-display-duration']
mp.add_key_binding "tab", "request-display",
( event ) ->
-- Complex bindings will always fire repeat events and the best we can
-- do is to quickly return.
if event.event == "repeat"
return
-- The "press" event happens when a simulated keypress happens through
-- the JSON IPC, the client API and through the mpv command interface. I
-- don't know if it will ever happen with an actual key event.
if event.event == "down" or event.event == "press"
if displayRequestTimer
displayRequestTimer\kill!
@displayRequested = true
if event.event == "up" or event.event == "press"
if displayDuration == 0
@displayRequested = false
else
displayRequestTimer = mp.add_timeout displayDuration, ->
@displayRequested = false,
{ complex: true }
mp.add_key_binding 'ctrl+r', 'reconfigure', @\reconfigure, { repeatable: false }
reconfigure: =>
settings\_reload!
AnimationQueue.destroyAnimationStack!
for _, zone in ipairs @activityZones
zone\reconfigure!
for _, element in ipairs @uiElements
element\reconfigure!
addZone: ( zone ) =>
if zone == nil
return
@activityZones\insert zone
removeZone: ( zone ) =>
if zone == nil
return
@activityZones\remove zone
generateUIFromZones: =>
seenUIElements = { }
@script = { }
@uiElements\clear!
AnimationQueue.destroyAnimationStack!
for _, zone in ipairs @activityZones
for _, uiElement in ipairs zone.elements
unless seenUIElements[uiElement]
@addUIElement uiElement
seenUIElements[uiElement] = true
@updateTimer\resume!
addUIElement: ( uiElement ) =>
if uiElement == nil
error 'nil UIElement added.'
@uiElements\insert uiElement
table.insert @script, ''
removeUIElement: ( uiElement ) =>
if uiElement == nil
error 'nil UIElement removed.'
-- this is kind of janky as it relies on an implementation detail of Stack
-- (i.e. that it stores the element index in the under the hashtable key of
-- the stack instance itself)
table.remove @script, uiElement[@uiElements]
@uiElements\remove uiElement
@needsRedraw = true
resize: =>
for _, zone in ipairs @activityZones
zone\resize!
for _, uiElement in ipairs @uiElements
uiElement\resize!
redraw: ( forceRedraw ) =>
clickPending = Mouse\update!
if Window\update!
@resize!
for index, zone in ipairs @activityZones
zone\update @displayRequested, clickPending
AnimationQueue.animate!
for index, uiElement in ipairs @uiElements
if uiElement\redraw!
@script[index] = uiElement\stringify!
@needsRedraw = true
if @needsRedraw
mp.set_osd_ass Window.w, Window.h, table.concat @script, '\n'
@needsRedraw = false
| 27.380531 | 82 | 0.698449 |
10394a7c865f85f92b724fa1877cdb5bbe79b05b | 2,029 | Caste = require('vendor/caste/lib/caste')
EventEmitter = req(..., 'lib.event-emitter')
class Secs extends Caste
new: () =>
@events = EventEmitter()
@entities = {}
@systems = {}
@events\on('entity.component.add', @updateComponent, @)
@events\on('entity.component.remove', @updateComponent, @)
addSystem: (system) =>
@systems[system\getCriteria()] = system
if system.active then @startSystem(system)
for entity in *@entities
if system\matches(entity) then system\add(entity)
system\init()
return @
removeSystem: (system) =>
@stopSystem(system)
@systems[system\getCriteria()] = nil
return @
getSystem: (system) => return @systems[system] or @systems[system\getCriteria()]
startSystem: (system) =>
@toggleSystem(system, true)
return @
stopSystem: (system) =>
@toggleSystem(system, false)
return @
toggleSystem: (system, active) =>
@getSystem(system)\toggle(active)
return @
addEntity: (entity) =>
entity.events = @events
table.insert(@entities, entity)
@events\emit('secs.entity.add', entity)
for criteria, system in pairs(@systems)
if criteria\matches(entity) then system\add(entity)
entity\init()
return @
removeEntity: (entity) =>
for e = 1, #@entities
ent = @entities[e]
if ent == entity or ent.id == entity
ent.events = nil
table.remove(@entities, e)
@events\emit('secs.entity.remove', ent)
break
for criteria, system in pairs(@systems)
if system\has(entity) then system\remove(entity)
return @
-- Sync entities/systems as components change
updateComponent: (entity, component) =>
for criteria, system in pairs(@systems)
if criteria\involves(component) then system\sync(entity)
return @
update: (dt) =>
for criteria, system in pairs(@systems)
if not system.update or not system.active or #system.entities == 0 then continue
system\update(dt)
draw: () =>
for criteria, system in pairs(@systems)
if not system.draw or not system.active or #system.entities == 0 then continue
system\draw()
| 25.049383 | 83 | 0.685067 |
4c9952adaec94dbe1ad5e765baa1ea77a80a8eb6 | 3,525 | import format from string
import concat, insert from table
import Template from gmodproj.api
-- ::TEMPLATE_GAMEMODE_MANIFEST(string projectName) -> string
-- Template for creating a Garry's Mod gamemode manifest file
--
TEMPLATE_GAMEMODE_MANIFEST = (projectName) ->
-- HACK: would rather use MoonScript's templating, but it only works with double quotes
return format([["%s"
{
"base" "base"
"title" "%s"
"maps" ""
"menusystem" "1"
"settings" {}
}]], projectName, projectName)
-- ::TEMPLATE_PROJECT_BOOTLOADER(table clientFiles, table includeFiles) -> string
-- Template for creating Lua project bootloader scripts
--
TEMPLATE_PROJECT_BOOTLOADER = (clientFiles, includeFiles) ->
bootloaderLines = {}
-- If there are scripts to send to the client, template them
if clientFiles
insert(bootloaderLines, "-- These scripts are sent to the client")
insert(bootloaderLines, "AddCSLuaFile('#{file}')") for file in *clientFiles
-- If there are scripts to bootload, template them
if includeFiles
insert(bootloaderLines, "-- These scripts are bootloaded by this script")
insert(bootloaderLines, "include('#{file}')") for file in *includeFiles
-- Combine lines via newline
return concat(bootloaderLines, "\n")
-- GamemodeTemplate::GamemodeTemplate()
-- Represents the project template to create new Garry's Mod gamemodes
-- export
export GamemodeTemplate = Template\extend {
-- GamemodeTemplate::createProject() -> void
-- Event called to construct the new project
-- event
createProject: () =>
-- Create the project directories
@createDirectory("gamemodes")
@createDirectory("gamemodes/#{@projectName}")
@createDirectory("gamemodes/#{@projectName}/gamemode")
@createDirectory("src")
-- Create the Garry's Mod gamemode manifest
@write("gamemodes/#{@projectName}/#{@projectName}.txt", TEMPLATE_GAMEMODE_MANIFEST(
@projectName
))
-- Create the Garry's Mod bootloader scripts
@write("gamemodes/#{@projectName}/gamemode/cl_init.lua", TEMPLATE_PROJECT_BOOTLOADER(
nil, {"#{@projectName}_client.lua"}
))
@write("gamemodes/#{@projectName}/gamemode/init.lua", TEMPLATE_PROJECT_BOOTLOADER(
{"cl_init.lua", "#{@projectName}_client.lua"},
{"#{@projectName}_server.lua"}
))
-- Format a header prefix for brevity
moduleHeader = @projectAuthor.."/"..@projectName
-- Create the project's entry points
-- HACK: gmodproj currently doesn't do lexical lookup of import/dependency statements...
@write("src/client.lua", "imp".."ort('#{moduleHeader}/shared').sharedFunc()\nprint('I was called on the client!')")
@write("src/server.lua", "imp".."ort('#{moduleHeader}/shared').sharedFunc()\nprint('I was called on the server!')")
@write("src/shared.lua", "function sharedFunc()\n\tprint('I was called on the client and server!')\nend")
-- Create the project's manifest
@writeProperties(".gmodmanifest", {
name: @projectName
author: @projectAuthor
version: "0.0.0"
repository: "unknown://unknown"
buildDirectory: "gamemodes/#{@projectName}/gamemode"
projectBuilds: {
"#{moduleHeader}/client": "#{@projectName}_client"
"#{moduleHeader}/server": "#{@projectName}_server"
}
})
} | 38.315217 | 123 | 0.645674 |
d51e5d882611c89d1a2b97dc6b45b2ac410a9448 | 275 |
noop = ->
defaults =
JSON: ->
load = -> require 'json'
select 2, xpcall load, noop
return setmetatable {}, __index: (key) =>
val = rawget self, key
if val == nil
load = defaults[key]
if load
val = load!
rawset self, key, val
return val
| 16.176471 | 41 | 0.570909 |
27c359989f79edea783f08266d822a5ad66d8598 | 2,497 | -- typekit.prelude
-- Basic types, functions and typeclasses
-- To be imported in most projects
-- By daelvn
import DEBUG from require "typekit.config"
import inspect, log from (require "typekit.debug") DEBUG
import sign from require "typekit.sign"
import kindof from require "typekit.type"
import Type from require "typekit.type.data"
unpack or= table.unpack
--# Maybe #--
-- typedef
Maybe = Type "Maybe a",
Nothing: ""
Just: "a"
Option = Maybe
import Nothing, Just from Maybe.constructor
-- maybe
maybe = sign "b -> (a -> b) -> Maybe a -> b"
maybe (d) -> (f) -> (x) -> switch x
when Nothing then return d
else return f x[1]
--# Either #--
Either = Type "Either l r",
Left: "l"
Right: "r"
import Left, Right from Either.constructor
-- either
either = sign "(l -> c) -> (r -> c) -> Either l r -> c"
either (fl) -> (fr) -> (e) -> switch kindof e
when "Left" then return fl e[1]
when "Right" then return fr e[1]
--# Ordering #--
Ordering = Type "Ordering",
LT: "", EQ: "", GT: ""
import LT, EQ, GT from Ordering.constructor
--# Pair #--
Pair = Type "Pair a b", Tuple: "a b"
import Tuple from Pair.constructor
-- fst
fst = sign "Pair a b -> a"
fst (p) -> p[1]
-- snd
snd = sign "Pair a b -> b"
snd (p) -> p[2]
--# miscellaneous functions #--
id = sign "a -> a"
id (x) -> x
const = sign "a -> b -> a"
const (c) -> -> c
compose = sign "(b -> c) -> (a -> b) -> a -> c"
compose (fa) -> (fb) -> (x) -> fa fb x
flip = sign "(a -> b -> c) -> b -> a -> c"
flip (f) -> (b) -> (a) -> (f a) b
until_ = sign "(a -> Boolean) -> (a -> a) -> a -> a"
until_ (p) -> (f) -> (v) -> if p! then return f v else return v
asTypeOf = sign "a -> a -> a"
asTypeOf (c) -> -> c
--# list operations #--
map = sign "(a -> b) -> [a] -> [b]"
map = (f) -> (t) -> [f v for v in *t]
append = sign "[a] -> [a] -> [a]"
append (tg) -> (fr) ->
table.insert tg, v for v in *fr
tg
filter = sign "(a -> Bool) -> [a] -> [a]"
filter (p) -> (xs) -> [x for x in *xs when p x]
head = sign "[a] -> a"
head (xs) -> xs[1]
last = sign "[a] -> a"
last (xs) -> xs[#xs]
tail = sign "[a] -> [a]"
tail (xs) -> {select 2, unpack xs}
init = sign "[a] -> [a]"
init (xs) -> [v for i, v in ipairs xs when i != #xs]
reverse = sign "[a] -> [a]"
reverse (xs) -> [xs[i] for i=#xs,1,-1]
take = sign "Number -> [a] -> [a]"
take (n) -> (xs) -> [v for i, v in ipairs xs when i <= n]
drop = sign "Number -> [a] -> [a]"
drop (n) -> (xs) -> {select n, unpack xs} | 23.12037 | 63 | 0.531037 |
dba72cf617c386f1c909658319d5c005f287a1ae | 4,215 | import Widget from require "lapis.html"
date = require "date"
i18n = require "i18n"
class MTAResourceManageAuthors extends Widget
@include "widgets.utils"
name: "Authors"
breadcrumb: =>
li @author.name if @author
content: =>
unless @active_user.id == @resource.creator
div class: "alert alert-warning", role: "alert", ->
strong "#{i18n 'warning'} "
text i18n "resources.manage.author.delete_self"
@output_errors!
if @author
div class: "card", ->
div class: "card-header", ->
text i18n "resources.manage.author.own_permissions", name: @author.username
small class: "text-muted", " #{i18n 'resources.manage.author.perm_dashboard_note'}"
div class: "card-block", ->
rights = @author_rights
form class: "mta-inline-form form-inline", method: "POST", action: @url_for("resources.manage.update_author_rights", resource_slug: @resource), ->
element "table", class: "table table-hover table-bordered table-sm mta-card-table", ->
thead ->
th i18n "resources.manage.author.right"
th i18n "resources.manage.author.right_value"
tbody ->
for right in *@right_names
right_value = rights[right]
tr ->
td ->
input type: "checkbox", class: "checkbox", checked: right_value, disabled: true
text " #{right}"
td -> input type: "checkbox", class: "checkbox", name: right, value: "true", checked: right_value
br!
@write_csrf_input!
input type: "hidden", name: "author", value: @author.slug, ["aria-hidden"]: "true"
button type: "submit", class: "btn btn-primary", onclick: "return confirm(\"#{i18n 'are_you_sure'}\")", ->
text i18n "resources.manage.author.update_perms_button"
raw " "
form class: "mta-inline-form", method: "POST", action: @url_for("resources.manage.delete_author", resource_slug: @resource), ->
@write_csrf_input!
input type: "hidden", name: "author", value: @author.slug, ["aria-hidden"]: "true"
button type: "submit", class: "btn btn-secondary btn-danger", onclick: "return confirm(\"#{i18n 'resources.manage.author.delete_confirm'}\")", ->
text i18n "resources.manage.author.delete_button"
else
list_authors = (headerText, missingText, rows) ->
div class: "card", ->
div class: "card-header", headerText
div class: "card-block", ->
return text missingText if #rows == 0
element "table", class: "table table-href table-hover table-bordered mta-card-table", ->
thead ->
th i18n "settings.username"
th i18n "since"
tbody ->
for manager in *rows
url = @url_for "resources.manage.authors", resource_slug: @resource, author: manager.slug
tr ["data-href"]: url, ->
td ->
a href: @url_for(manager), manager.username
td ->
text date(manager.created_at)\fmt "${rfc1123} "
a class: "btn btn-sm btn-secondary pull-xs-right", href: url, -> i class: "fa fa-cogs"
list_authors i18n("resources.manage.author.authors_list"), i18n("resources.manage.author.authors_list_empty"), @resource\get_authors include_creator: false, is_confirmed: true
list_authors i18n("resources.manage.author.authors_invited"), i18n("resources.manage.author.authors_invited_empty"), @resource\get_authors include_creator: false, is_confirmed: false
div class: "card", ->
div class: "card-header", i18n("resources.manage.author.make_invite")
div class: "card-block", -> form action: @url_for("resources.manage.invite_author", resource_slug: @resource), method: "POST", ->
@write_csrf_input!
fieldset class: "form-group row", ->
label class: "col-sm-2", for: "inviteAuthor", i18n "settings.username"
div class: "col-sm-10", ->
input type: "text", class: "form-control", id: "inviteAuthor", name: "author"
div class: "form-group row", ->
div class: "col-sm-offset-2 col-sm-10", ->
button type: "submit", class: "btn btn-secondary", onclick: "return confirm('Are you sure?')", i18n "resources.manage.author.invite_button"
| 45.815217 | 186 | 0.637248 |
673451b1e1bf415c48a2464c4487a7b309d7fb7a | 6,195 | {:delegate_to} = howl.util.table
light_grey = '#E1EEF6'
dark_blue = '#003A4c'
dark_blue_off = '#336170'
deep_dark_blue = '#002F3D'
orange = '#FF5F2E'
yellow = '#FCBE32'
grey = '#888'
blue = '#738DFC'
red = '#B23610'
light_red = '#FF9F8F'
magenta = '#D33682'
cyan = '#2AA198'
green = '#00B284'
purple = '#C687FF'
background = dark_blue
current = grey
selection = lightblue
string = green
number = green
operator = yellow
keyword = yellow
class_name = blue
special = green
key = orange
-- General styling for context boxes (editor)
content_box = {
background:
color: deep_dark_blue
border:
radius: 5
color: deep_dark_blue
header:
background: color: deep_dark_blue
color: white
padding: 4
border_bottom:
width: 0.5
color: dark_blue_off
footer:
background: color: deep_dark_blue
color: white
padding: 4
}
return {
window:
outer_padding: 6
background:
image: theme_file('circle.png')
status:
font: bold: true
color: blue
info: color: white
warning: color: yellow
error: color: light_red
:content_box
popup: {
background:
color: deep_dark_blue
border:
color: dark_blue_off
width: 0.5
}
editor: delegate_to content_box, {
scrollbars:
slider:
color: keyword
alpha: 0.8
background: color: dark_blue
indicators:
default:
color: yellow
header:
background:
gradient:
type: 'linear'
direction: 'vertical'
stops: { deep_dark_blue, deep_dark_blue, deep_dark_blue, dark_blue}
padding_bottom: 10
border_bottom: width: 0
footer:
background:
gradient:
type: 'linear'
direction: 'vertical'
stops: { dark_blue, deep_dark_blue, deep_dark_blue}
padding_top: 10
current_line:
background: current
gutter:
color: dark_blue_off
background:
color: dark_blue
}
flairs:
indentation_guide_1:
type: flair.PIPE,
foreground: yellow,
foreground_alpha: 0.3
line_width: 1
line_type: 'solid'
indentation_guide_2:
type: flair.PIPE,
foreground: yellow,
foreground_alpha: 0.2
line_width: 1
line_type: 'solid'
indentation_guide_3:
type: flair.PIPE,
foreground: yellow,
foreground_alpha: 0.1
line_width: 1
line_type: 'solid'
indentation_guide:
type: flair.PIPE,
foreground: yellow,
foreground_alpha: 0.1
line_width: 1
line_type: 'solid'
edge_line:
type: flair.PIPE,
foreground: white,
foreground_alpha: 0.2,
line_type: 'solid'
line_width: 0.5
search:
type: highlight.ROUNDED_RECTANGLE
foreground: white
background: yellow
text_color: dark_blue
height: 'text'
search_secondary:
line_width: 1
type: highlight.ROUNDED_RECTANGLE
background: yellow
background_alpha: 0.4
text_color: light_grey
height: 'text'
replace_strikeout:
type: highlight.ROUNDED_RECTANGLE
foreground: white
background: red
text_color: lightgray
background_alpha: 0.7
height: 'text'
brace_highlight:
type: highlight.ROUNDED_RECTANGLE
text_color: background
background: yellow
height: 'text'
brace_highlight_secondary:
type: highlight.RECTANGLE
foreground: orange
line_width: 1
height: 'text'
list_selection:
type: highlight.ROUNDED_RECTANGLE
background: white
background_alpha: 0.1
list_highlight:
type: highlight.UNDERLINE
text_color: yellow
line_width: 2
foreground: yellow
cursor:
type: highlight.RECTANGLE
background: white
width: 2
height: 'text'
block_cursor:
type: highlight.RECTANGLE,
background: white
text_color: background
height: 'text',
min_width: 'letter'
selection:
type: highlight.ROUNDED_RECTANGLE
background: selection
background_alpha: 0.3
min_width: 'letter'
styles:
default:
color: light_grey
red: color: red
green: color: green
yellow: color: yellow
blue: color: blue
magenta: color: magenta
cyan: color: cyan
comment:
color: grey
font: italic: true
variable: color: yellow
label:
color: orange
font: italic: true
key:
color: key
char: color: green
wrap_indicator: 'blue'
fdecl:
color: orange
font:
bold: true
keyword:
color: keyword
font: bold: true
class:
color: class_name
font:
bold: true
type_def:
color: class_name
font:
bold: true
size: 'large'
definition: color: yellow
function: color: light_grey
number:
color: number
font: bold: true
operator:
color: operator
font: bold: true
preproc:
color: yellow
font: italic: true
special:
color: special
font: bold: true, italic: true
tag: color: purple
type: color: class_name
member:
color: light_grey
font: bold: true
info: color: light_grey
constant: color: orange
string: color: string
regex:
color: green
embedded:
background: white
background_alpha: 0.1
css_unit:
color: green
font: italic: true
-- Markup and visual styles
error:
font:
bold: true
color: red
warning:
font: italic: true
color: orange
h1:
color: yellow
font:
bold: true
size: 'xx-large'
h2:
color: white
color: yellow
font: size: 'x-large'
h3:
color: yellow
emphasis:
font:
bold: true
italic: true
strong: font: italic: true
link_label:
color: orange
underline: true
link_url:
color: grey
font: italic: true
table:
underline: true
addition: color: green
deletion: color: red
change: color: yellow
}
| 17.401685 | 77 | 0.599516 |
d2f0d12a1c696b190f01e44f5931cfd73b8b8964 | 1,309 | cqueues = require 'cqueues'
import IRCClient from require 'lib.irc'
unpack = unpack or table.unpack
for tmp_cmd in *{'422', '376'}
IRCClient\add_handler tmp_cmd, => @fire_hook 'READY'
IRCClient\add_hook 'READY', =>
if @config.autojoin
-- ::TODO:: properly
for channel in *@config.autojoin
@send_raw "JOIN", channel
IRCClient\add_handler 'PING', (prefix, args)=>
@send_raw "PONG", unpack args
IRCClient\add_handler 'ERROR', =>
time = os.time()
if time > @data.last_connect + 30
@connect!
else
cqueues.sleep(@data.last_connect + 30 - time)
IRCClient\add_handler '433', =>
@data.nick_test = 0 if not @data.nick_test
@data.nick_test += 1
cqueues.sleep 0.5
if @data.nick_test >= 30
@disconnect!
else
@send_raw 'NICK', "#{@config.nick}[#{@data.nick_test}]"
IRCClient\add_handler '354', (prefix, args)=>
table.remove(args, 1)
query_type = table.remove(args, 1)
@fire_hook "WHOX_#{query_type}", unpack(args)
IRCClient\add_sender 'PRIVMSG', (target, message, tags={})=>
for line in message\gmatch("[^\r\n]+")
@send_raw 'PRIVMSG', target, line, tags: tags
unless @server.ircv3_caps["echo-message"]
@process_line ":#{@config.nick}!local@localhost PRIVMSG #{target} :(local) #{line}"
IRCClient\add_sender 'TAGMSG', (target, tags={})=>
@send_raw 'TAGMSG', target, tags: tags
| 27.851064 | 86 | 0.690604 |
853cf19b970faeeef86bd954892a5409518f3f5e | 2,174 |
require "alt_getopt"
moonscript = require "moonscript.base"
util = require "moonscript.util"
errors = require "moonscript.errors"
unpack = util.unpack
opts, ind = alt_getopt.get_opts arg, "cvhd", {
version: "v"
help: "h"
}
help = [=[Usage: %s [options] [script [args]]
-h Print this message
-d Disable stack trace rewriting
-c Collect and print code coverage
-v Print version
]=]
print_err = (...) ->
msg = table.concat [tostring v for v in *{...}], "\t"
io.stderr\write msg .. "\n"
print_help = (err) ->
help = help\format arg[0]
if err
print_err err
print_err help
else
print help
os.exit!
run = ->
if opts.h
print_help!
if opts.v
require("moonscript.version").print_version!
os.exit!
script_fname = arg[ind]
unless script_fname
print_help "repl not yet supported"
new_arg = {
[-1]: arg[0],
[0]: arg[ind],
select ind + 1, unpack arg
}
local moonscript_chunk, lua_parse_error
passed, err = pcall ->
moonscript_chunk, lua_parse_error = moonscript.loadfile script_fname, {
implicitly_return_root: false
}
unless passed
print_err err
os.exit 1
unless moonscript_chunk
if lua_parse_error
print_err lua_parse_error
else
print_err "Can't file file: #{script_fname}"
os.exit 1
util.getfenv(moonscript_chunk).arg = new_arg
run_chunk = ->
moonscript.insert_loader!
moonscript_chunk unpack new_arg
moonscript.remove_loader!
if opts.d
return run_chunk!
local err, trace, cov
if opts.c
print "starting coverage"
coverage = require "moonscript.cmd.coverage"
cov = coverage.CodeCoverage!
cov\start!
xpcall run_chunk, (_err) ->
err = _err
trace = debug.traceback "", 2
if err
truncated = errors.truncate_traceback util.trim trace
rewritten = errors.rewrite_traceback truncated, err
if rewritten
print_err rewritten
else
-- failed to rewrite, show original
print_err table.concat {
err,
util.trim trace
}, "\n"
else
if cov
cov\stop!
cov\print_results!
run!
| 18.581197 | 75 | 0.637994 |
30c5802e780d07da30a022864366ed4a965f5e20 | 172 | [[local lapis = require "lapis"
local app = lapis.Application()
app:get("/", function()
return "Welcome to Lapis " .. require("lapis.version")
end)
lapis.serve(app)
]]
| 17.2 | 56 | 0.668605 |
e262ff2ff69848600a36f3916a13bf03fed22561 | 4,122 | assert = require "luassert"
say = require "say"
useDistMode = ->
flag = false
for i, v in pairs arg
if v == "-Xhelper=--use-dist"
flag = true
break
return flag
-- UTILITY FUNCTIONS
export use = (path) ->
switch string.match path, ".*(%..*)$"
when ".lua"
(assert loadfile path)!
when ".moon"
(assert (require "moonscript").loadfile path)!
export dist = (dists) ->
if useDistMode!
dists!
export source = (sources) ->
if not useDistMode!
sources!
export inspect = (table, indent) ->
if not table
print "<nil>"
return
indent = indent or 0
padLength = indent * 2
if indent == 0 then print "{"
for k, v in pairs table
t = type v
if t == "table" and not v.__class
print (string.rep " ", padLength + 2) .. k .. ": {"
inspect v, indent + 1
print (string.rep " ", padLength + 2) .. "}"
else
val = nil
switch t
when "table"
val = "<object> " .. v.__class.__name
when "function"
val = "<function>"
when "boolean"
val = v and "true" or "false"
when "string"
val = "\"" .. v .. "\""
else
val = v
print (string.rep " ", padLength + 2) .. k .. ": " .. val
if indent == 0 then print "}"
addAssertion = (name, definition, failPositive, failNegative) ->
positiveKey = "assertion." .. name .. ".positive"
negativeKey = "assertion." .. name .. ".negative"
say\set positiveKey, failPositive
say\set negativeKey, failNegative
assert\register "assertion", name, definition, positiveKey, negativeKey
-- CUSTOM ASSERTIONS
-- "assert.is.of.class (class, object)"
is_of_class = (state, arguments) ->
arguments[1] == arguments[2].__class
addAssertion "of_class", is_of_class,
"Expected %s to be the class of %s.",
"Expected %s not to be the class of %s."
-- "assert.are.about.equal (value1, value2)"
round = (number, place) ->
multiplier = 10^(place or 0)
math.floor(number * multiplier + 0.5) / multiplier
about_equal = (state, arguments) ->
roundedArg1 = round(arguments[1], 8)
roundedArg2 = round(arguments[2], 8)
return roundedArg1 == roundedArg2
addAssertion "about_equal", about_equal,
"Expected %s to be approximately equal to %s.",
"Expected %s not to be approximately equal to %s."
-- "assert.is.a.table (reference)"
is_a_table = (state, arguments) ->
(type arguments[1]) == "table"
addAssertion "a_table", is_a_table,
"Expected %s to be a table, but it was not.",
"Expected %s not to be a table, but it was one."
-- "assert.is.a.function (reference)"
is_a_function = (state, arguments) ->
(type arguments[1]) == "function"
addAssertion "a_function", is_a_function,
"Expected %s to be a function, but it was not.",
"Expected %s not to be a function, but it was one."
-- "assert.is.inherited (object, property)"
is_inherited = (state, arguments) ->
arguments[1][arguments[2]] == arguments[1].__class[arguments[2]]
addAssertion "inherited", is_inherited,
"Expected %s to have inherited property %s from its class, but it did not.",
"Expected %s not to have inherited property %s from its class, but it did."
-- "assert.contains.key (table)"
contains_key = (state, arguments) ->
(type arguments[2]) == "table" and (type arguments[2][arguments[1]]) != nil
addAssertion "contains_key", contains_key,
"Expected to find key %s in: \n%s",
"Expected not to find key %s in: \n%s"
-- "assert.contains.value (table)"
contains_value = (state, arguments) ->
if (type arguments[2]) != "table"
return false
for key, value in pairs arguments[2]
if value == arguments[1]
return true
return false
addAssertion "contains_value", contains_value,
"Expected to find value %s in: \n%s",
"Expected not to find value %s in: \n%s"
-- "assert.has.method (name, object)"
has_method = (state, arguments) ->
(type arguments[2]) == "table" and (type arguments[2][arguments[1]]) != "function"
addAssertion "method", has_method,
"Expected to find a method called %s, but there was not one.",
"Expected not to find a method called %s, but there was one."
| 29.442857 | 84 | 0.637555 |
4a94da159c44f8625bdbfc886f41dbdd76b8bab6 | 8,807 | brain = require "src/agent/brain"
radius = 10
speed = 0.5
boost_speed = 2
rep = 2
rep_rate = (herb, c=rep, h=rep) ->
herb * (util.randf c - 0.1, h + 0.1) + (1 - herb) * util.randf c - 0.1, h + 0.1
random = (w, h, z) ->
agent = {
pos: {
[1]: math.random 0, w
[2]: math.random 0, h
[3]: 0 -- gross
}
color: {
[1]: math.random 0, 255
[2]: math.random 0, 255
[3]: math.random 0, 255
}
:radius
}
with agent
.brain = brain.dwraonn.make!
.w1 = 0 -- wheel1
.w2 = 0 -- wheel2
.boosting = false
.health = 1 + util.randf 0, 0.1
.herb = util.randf 0, 1
.sound_mul = 0
.gen_count = 0
.fur = util.randf -1, 1
.rep_count = rep_rate .herb
.clock_f1 = util.randf 5, 100
.clock_f2 = util.randf 5, 100
.mut_rate1 = 0.003
.mut_rate2 = 0.05
.spike_len = 0
.angle = util.randf -math.pi, math.pi
.out = {}
for i = 0, brain.settings.outputs
.out[i] = 0
.inp = {}
for i = 0, brain.settings.inputs
.inp[i] = 0
.tick = =>
@brain\tick @inp, @out
.update = (plane) =>
@input plane
@tick!
@output!
if plane.count % 2 == 0
for i = 1, #plane.env.agents
other = plane.env.agents[i]
continue if other == @
d = util.distance @pos, other.pos
if d < 2 * @radius
diff = math.atan2 other.pos[2] - @pos[2], other.pos[1] - @pos[1]
if math.pi / 8 > math.abs diff
mult = 1
mult = 2 if @boosting
dmg = 0.5 * @spike_len * 2 * math.max (math.abs @w1), math.abs @w2
other.health -= dmg
@spike_len = 0
-- rep
if @rep_count < 0 and @health > 0.65
plane.env\spawn @make_baby @mut_rate1, @mut_rate2
@rep_count = rep_rate .herb
-- movement
whp1 = { -- wheel position
radius * (math.cos @angle - math.pi / 4) + @pos[1]
radius * (math.sin @angle - math.pi / 4) + @pos[2]
}
whp2 = { -- wheel position
radius * (math.cos @angle + math.pi / 4) + @pos[1]
radius * (math.sin @angle + math.pi / 4) + @pos[2]
}
boost1 = speed * @w1
boost2 = speed * @w2
if @boosting
boost1 *= boost_speed
boost2 *= boost_speed
vv1 = {
boost1 * (math.cos math.atan2 whp1[2] - @pos[2], whp1[1] - @pos[1])
boost1 * (math.sin math.atan2 whp1[2] - @pos[2], whp1[1] - @pos[1])
}
vv2 = {
boost2 * (math.cos math.atan2 whp2[2] - @pos[2], whp2[1] - @pos[1])
boost2 * (math.sin math.atan2 whp2[2] - @pos[2], whp2[1] - @pos[1])
}
@angle = math.atan2 vv1[2] + vv2[2], vv1[1] + vv2[1]
@pos[1] += vv1[1]
@pos[2] += vv1[2]
@pos[1] += vv2[1]
@pos[2] += vv2[2]
@pos[1] %= w
@pos[2] %= h
@eat plane
.eat = (plane) =>
cx = math.floor @pos[1] / (plane.w / #plane.env.food)
cy = math.floor @pos[2] / (plane.h / #plane.env.food)
food = plane.env.food[cx][cy]
if food > 0 and @health < 2 -- 2 is maxima
itk = math.min food, 0.0325 -- intake constant
speed_mul = (1 - (math.abs @w1 + math.abs @w2) / 2) / 2 + 0.5
itk *= @herb^2 * speed_mul
@health += itk
@rep_count -= 3 * itk
plane.env.food[cx][cy] -= math.min food, 0.003 -- food waste constant
.input = (plane) =>
pi8 = math.pi / 8 / 2
pi38 = pi8 * 3
-- health
@inp[11] = util.cap @health / 2
-- food
cx = math.floor @pos[1] / (plane.w / #plane.env.food)
cy = math.floor @pos[2] / (plane.h / #plane.env.food)
@inp[9] = plane.env.food[cx][cy] / 0.5 -- food maxima is 0.5
-- sound, smell and eyes
p1, r1, g1, b1 = 0, 0, 0, 0
p2, r2, g2, b2 = 0, 0, 0, 0
p3, r3, g3, b3 = 0, 0, 0, 0
sound_acc = 0
smell_acc = 0
hear_acc = 0
blood = 0
for i = 0, #plane.env.agents
agent = plane.env.agents[i]
continue if agent == @
x1 = @pos[1] < agent.pos[1] - 150
x2 = @pos[1] > agent.pos[1] + 150
y1 = @pos[2] > agent.pos[2] + 150
y2 = @pos[2] < agent.pos[2] - 150
continue if x1 or x2 or y1 or y2
d = util.distance @pos, agent.pos
if d < 150
smell_acc += 0.3 * (150 - d) / 150
sound_acc += 0.4 * (150 - d) / 150
hear_acc += agent.sound_mul * (150 - d) / 150
angle = math.atan2 (@pos[2] - agent.pos[2]), (@pos[1] - agent.pos[1])
-- completely unreadable madness
l_eye_ang = @angle - pi8
r_eye_ang = @angle + pi8
back_angle = @angle + math.pi
forw_angle = @angle
l_eye_ang += 2 * math.pi if l_eye_ang < -math.pi
r_eye_ang -= 2 * math.pi if r_eye_ang > math.pi
back_angle -= 2 * math.pi if back_angle > math.pi
diff1 = l_eye_ang - angle
diff1 = 2 * math.pi - math.abs diff1 if math.pi < math.abs diff1
diff1 = math.abs diff1
diff2 = r_eye_ang - angle
diff2 = 2 * math.pi - math.abs diff2 if math.pi < math.abs diff2
diff2 = math.abs diff2
diff3 = back_angle - angle
diff3 = 2 * math.pi - math.abs diff3 if math.pi < math.abs diff3
diff3 = math.abs diff3
diff4 = forw_angle - angle
diff4 = 2 * math.pi - math.abs forw_angle if math.pi < math.abs forw_angle
diff4 = math.abs diff4
if diff1 < pi38
mul1 = 2 *((pi38 - diff1) / pi38) * ((150 - d) / 150)
p1 += mul1 * (d / 150)
r1 += mul1 * agent.color[1]
g1 += mul1 * agent.color[2]
b1 += mul1 * agent.color[3]
if diff2 < pi38
mul2 = 2 *((pi38 - diff1) / pi38) * ((150 - d) / 150)
p2 += mul2 * (d / 150)
r2 += mul2 * agent.color[1]
g2 += mul2 * agent.color[2]
b2 += mul2 * agent.color[3]
if diff3 < pi38
mul3 = 2 *((pi38 - diff1) / pi38) * ((150 - d) / 150)
p3 += mul3 * (d / 150)
r3 += mul3 * agent.color[1]
g3 += mul3 * agent.color[2]
b3 += mul3 * agent.color[3]
if diff4 < pi38
mul4 = 2 *((pi38 - diff1) / pi38) * ((150 - d) / 150) -- 2 == blood_sens
blood += mul4 * (1 - agent.health / 2)
@inp[1] = util.cap p1
@inp[2] = util.cap r1
@inp[3] = util.cap g1
@inp[4] = util.cap b1
@inp[5] = util.cap p2
@inp[6] = util.cap r2
@inp[7] = util.cap g2
@inp[8] = util.cap b2
@inp[10] = util.cap sound_acc
@inp[12] = util.cap smell_acc
@inp[13] = util.cap p3
@inp[14] = util.cap r3
@inp[15] = util.cap g3
@inp[16] = util.cap b3
@inp[17] = math.abs math.sin plane.count / @clock_f1
@inp[18] = math.abs math.sin plane.count / @clock_f2
@inp[19] = util.cap hear_acc
@inp[20] = util.cap blood
.output = =>
@w1 = @out[1]
@w2 = @out[2]
@color[1] = @out[3] * 255
@color[2] = @out[4] * 255
@color[2] = @out[5] * 255
g = @out[6]
if @spike_len < g
@spike_len += 0.05
else
@spike_len = g
@boosting = @out[7] > .5
@sound_mul = @out[8]
.make_baby = (mr, mr2) =>
baby = random w, h, z
-- behind
baby.pos = {
@pos[1] + radius + util.randf -radius * 2, radius * 2
@pos[2] + util.randf -radius * 2, radius * 2
@pos[3]
}
baby.pos[1] %= w
baby.pos[2] %= h
baby.gen_count = @gen_count + 1
baby.rep_count = rep_rate baby.herb
baby.mut_rate1 = @mut_rate1
baby.mut_rate2 = @mut_rate2
if .2 > util.randf 0, 1
baby.mut_rate1 = util.randn @mut_rate1, 0.002
if .2 > util.randf 0, 1
baby.mut_rate2 = util.randn @mut_rate2, 0.05
@mut_rate1 = 0.001 if @mut_rate1 < 0.001
@mut_rate1 = 0.025 if @mut_rate1 < 0.025
baby.herb = util.cap @herb, mr2 * 4
baby.fur = @fur
if mr * 5 > util.randf 0, 1
baby.fur = util.randf baby.fur, mr2
baby.clock_f1 = @clock_f1
baby.clock_f2 = @clock_f2
if mr * 5 > util.randf 0, 1
baby.clock_f1 = util.randf baby.clock_f1, mr2
if mr * 5 > util.randf 0, 1
baby.clock_f2 = util.randf baby.clock_f2, mr2
baby.clock_f1 = 2 if baby.clock_f1 < 2
baby.clock_f2 = 2 if baby.clock_f2 < 2
baby.brain = brain.dwraonn.from @brain
baby.brain\mutate mr, mr2
baby
agent
{
:random
}
| 24.808451 | 86 | 0.481549 |
df2e4508e35f6148c04c128c925d660ebc65f03f | 4,894 | db = require "lapis.db.mysql"
import escape_literal, escape_identifier from db
import concat from table
import gen_index_name from require "lapis.db.base"
append_all = (t, ...) ->
for i=1, select "#", ...
t[#t + 1] = select i, ...
extract_options = (cols) ->
options = {}
cols = for col in *cols
if type(col) == "table" and col[1] != "raw"
for k,v in pairs col
options[k] = v
continue
col
cols, options
entity_exists = (name) ->
config = require("lapis.config").get!
mysql_config = assert config.mysql, "missing mysql configuration"
database = escape_literal assert mysql_config.database
name = escape_literal name
res = unpack db.select "COUNT(*) as c from information_schema.tables where
table_schema = #{database} and table_name = #{name} LIMIT 1"
tonumber(res.c) > 0
create_table = (name, columns, opts={}) ->
prefix = if opts.if_not_exists
"CREATE TABLE IF NOT EXISTS "
else
"CREATE TABLE "
buffer = {prefix, escape_identifier(name), " ("}
add = (...) -> append_all buffer, ...
for i, c in ipairs columns
add "\n "
if type(c) == "table"
name, kind = unpack c
add escape_identifier(name), " ", tostring kind
else
add c
add "," unless i == #columns
add "\n" if #columns > 0
add ")"
add " ENGINE=", opts.engine if opts.engine
add " CHARSET=", opts.charset or "UTF8"
add ";"
db.query concat buffer
drop_table = (tname) ->
db.query "DROP TABLE IF EXISTS #{escape_identifier tname};"
create_index = (tname, ...) ->
index_name = gen_index_name tname, ...
columns, options = extract_options {...}
buffer = {"CREATE"}
append_all buffer, " UNIQUE" if options.unique
append_all buffer, " INDEX ", escape_identifier index_name
if options.using
append_all buffer, " USING ", options.using
append_all buffer, " ON ", escape_identifier tname
append_all buffer, " ("
for i, col in ipairs columns
append_all buffer, escape_identifier(col)
append_all buffer, ", " unless i == #columns
append_all buffer, ")"
append_all buffer, ";"
db.query concat buffer
drop_index = (tname, ...) ->
index_name = gen_index_name tname, ...
tname = escape_identifier tname
db.query "DROP INDEX #{escape_identifier index_name} on #{tname};"
add_column = (tname, col_name, col_type) ->
tname = escape_identifier tname
col_name = escape_identifier col_name
db.query "ALTER TABLE #{tname} ADD COLUMN #{col_name} #{col_type}"
drop_column = (tname, col_name) ->
tname = escape_identifier tname
col_name = escape_identifier col_name
db.query "ALTER TABLE #{tname} DROP COLUMN #{col_name}"
rename_column = (tname, col_from, col_to, col_type)->
assert col_type, "A column type is required when renaming a column"
tname = escape_identifier tname
col_from = escape_identifier col_from
col_to = escape_identifier col_to
db.query "ALTER TABLE #{tname} CHANGE COLUMN #{col_from} #{col_to} #{col_type}"
rename_table = (tname_from, tname_to) ->
tname_from = escape_identifier tname_from
tname_to = escape_identifier tname_to
db.query "RENAME TABLE #{tname_from} TO #{tname_to}"
class ColumnType
default_options: { null: false }
new: (@base, @default_options) =>
__call: (length, opts={}) =>
out = @base
if type(length) == "table"
opts = length
length = nil
for k,v in pairs @default_options
opts[k] = v unless opts[k] != nil
if l = length or opts.length
out ..= "(#{l}"
if d = opts.decimals
out ..= ",#{d})"
else
out ..= ")"
-- type mods
if opts.unsigned
out ..= " UNSIGNED"
if opts.binary
out ..= " BINARY"
-- column mods
unless opts.null
out ..= " NOT NULL"
if opts.default != nil
out ..= " DEFAULT " .. escape_literal opts.default
if opts.auto_increment
out ..= " AUTO_INCREMENT"
if opts.unique
out ..= " UNIQUE"
if opts.primary_key
out ..= " PRIMARY KEY"
out
__tostring: => @__call {}
C = ColumnType
types = setmetatable {
id: C "INT", auto_increment: true, primary_key: true
varchar: C "VARCHAR", length: 255
char: C "CHAR"
text: C "TEXT"
blob: C "BLOB"
bit: C "BIT"
tinyint: C "TINYINT"
smallint: C "SMALLINT"
mediumint: C "MEDIUMINT"
integer: C "INT"
bigint: C "BIGINT"
float: C "FLOAT"
double: C "DOUBLE"
date: C "DATE"
time: C "TIME"
timestamp: C "TIMESTAMP"
datetime: C "DATETIME"
boolean: C "TINYINT", length: 1
enum: C "TINYINT UNSIGNED"
}, __index: (key) =>
error "Don't know column type `#{key}`"
{
:entity_exists
:gen_index_name
:types
:create_table
:drop_table
:create_index
:drop_index
:add_column
:drop_column
:rename_column
:rename_table
}
| 23.757282 | 81 | 0.629342 |
ba9d196ab3e920d51f9d35554190ba7d0322d8f9 | 2,118 | finder = require "libs.pathfinding"
System = require "src.systems.system"
class Grid extends System
onCreate: (orientation, width, height=width, cellW=8, cellH=8) =>
@orientation = orientation
@width = width
@height = height
@cellWidth = cellW
@cellHeight = cellH
@cells = {}
cellId: (x,y) => x + (@height * y)
inside: (x,y) => x >= 1 and x <= @width and y >= 1 and y <= @height
init: ([email protected], cellSystem="GridCell", ...) =>
z = 1
cellArgs = {...}
functional.generate_2d @width, @height, (x,y) ->
cellEntityName = string.format "%s_cell_%d_%d", @entity.name, x, y
@cells[@\cellId x,y] = with @entity.scene\newEntity cellEntityName, 0, 0, z, defaultLayer
\addSystem cellSystem, @, x, y, unpack cellArgs
z += 1
getCell: (x,y) => if @\inside x,y then @cells[@cellId x,y]
foreachCell: (func) => func cell for _,cell in pairs @cells
getOnePath: (start, goal, isWalkableFunc, getCostFunc, searchDirectionMode="normal") =>
getDistance: (cell1, cell2) => math.abs(node1.x - node2.x) + math.abs(node1.y - node2.y)
getAdj = (cell) ->
cells = {}
checkCell = (x,y) ->
thisCell = @\getCell x,y
if @\inside(x,y) and isWalkableFunc thisCell
table.insert cells, thisCell
checkCell x-1,y
checkCell x+1,y
checkCell x,y-1
checkCell x,y+1
if searchDirectionMode == "diagonal"
checkCell x-1,y-1
checkCell x+1,y+1
checkCell x+1,y-1
checkCell x-1,y+1
return cells
finder "one", start, goal, getAdj, getCostFunc, getDistance
getManyPath: (start, goals, isWalkableFunc, getCostFunc, searchDirectionMode="normal") =>
getAdj = (cell) ->
cells = {}
checkCell = (x,y) ->
thisCell = @\getCell x,y
if @\inside(x,y) and isWalkableFunc thisCell
table.insert cells, thisCell
x,y = cell.tile.x, cell.tile.y
checkCell x-1,y
checkCell x+1,y
checkCell x,y-1
checkCell x,y+1
if searchDirectionMode == "diagonal"
checkCell x-1,y-1
checkCell x+1,y+1
checkCell x+1,y-1
checkCell x-1,y+1
return cells
finder "many", start, goals, getAdj, getCostFunc
| 23.533333 | 92 | 0.641643 |
424d298203041eb54602764162a8f8fda112880f | 1,335 |
{graphics: g} = love
import WaterEmitter, DirtEmitter from require "particles"
class Object extends Entity
lazy sprite: => Spriter "images/tile.png", 16, 16
w: 16
h: 16
color: C.stone
solid: true
held_by: nil
update: (...) =>
if o = @held_by
@move_center o\head_pos!
return true
super ...
true
pickup: (thing, world) =>
world\remove @
@held_by = thing
thing.holding = @
drop: (thing, world) =>
@held_by = nil
thing.holding = nil
world\add @
__tostring: => "<Object #{Box.__tostring @}>"
draw: =>
@sprite\draw "48,16,16,16", @x, @y
class WateringCan extends Object
name: "watering can"
use: (player, world) =>
print "using watering can"
if tile = player\active_tile!
world.particles\add WaterEmitter tile, world
tile_state = world.ground_tiles[tile]
return unless tile_state
tile_state.wet = true
draw: =>
@sprite\draw "48,16,16,16", @x, @y
class Hoe extends Object
name: "hoe"
use: (player, world) =>
print "using hoe"
if tile = player\active_tile!
world.particles\add DirtEmitter tile, world
tile_state = world.ground_tiles[tile]
return unless tile_state
tile_state.tilled = true
draw: =>
@sprite\draw "64,16,16,16", @x, @y
{ :Object, :WateringCan, :Hoe }
| 19.071429 | 57 | 0.620225 |
b82f9a8321ddc3057775819d60ba8c60092cc5dd | 624 | -- Copyright 2018 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
howl.interact.register
name: 'explore'
description: 'Generic explorer interaction'
handler: (opts={}) ->
error 'path required' unless opts.path
explorer_view = howl.ui.ExplorerView path: opts.path, prompt: opts.prompt, title: opts.title, auto_trim: opts.auto_trim, editor: opts.editor
item = howl.app.window.command_panel\run explorer_view, text: opts.text, help: opts.help
return unless item != nil
return item unless opts.transform_result
return opts.transform_result item
| 44.571429 | 144 | 0.748397 |
cf75ea337f95399a65d6c1b7e3fdab3075dc38f3 | 9,210 | -- Copyright 2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
{:RGBA} = require 'ljglibs.gdk'
require 'ljglibs.cairo.context'
{:SCALE, :Layout, :Attribute, :Color, :cairo} = require 'ljglibs.pango'
styles = require 'aullar.styles'
Styling = require 'aullar.styling'
{:min, :max, :floor, :pi} = math
copy = moon.copy
flairs = {}
parse_color = (color) ->
return color and RGBA(color)
set_source_from_color = (cr, name, opts) ->
color = opts["_#{name}"]
alpha = opts["#{name}_alpha"]
if color
if alpha
cr\set_source_rgba color.red, color.green, color.blue, alpha
else
cr\set_source_rgb color.red, color.green, color.blue
else
cr\set_source_rgba 0, 0, 0, 0, 0
set_line_type_from_flair = (cr, flair) ->
cr.line_width = flair._line_width
switch flair.line_type
when 'dotted'
cr.dash = {0.5, 1}
when 'dashed'
cr.dash = {6, 3}
draw_ops = {
custom: (flair, x, y, width, height, cr) ->
local ok, err
if flair.custom_draw
ok, err = pcall flair.custom_draw, flair, x, y, width, height, cr
else
ok ,err = false, "'custom_draw' function missing"
if not ok
-- Something went wrong in custom_draw, so draw an intensely red "missing"
-- cross, for visual attention and to maintain functioning of the editor.
io.stderr\write err ..'\n'
cr\set_source_rgba 1, 0, 0, 1
cr.line_width = 2
cr\move_to x, y
cr\line_to x + width, y + height
cr\move_to x, y + height
cr\line_to x + width, y
cr\stroke!
rectangle: (flair, x, y, width, height, cr) ->
if flair.background
set_source_from_color cr, 'background', flair
cr\rectangle x, y, width, height
cr\fill!
if flair.foreground
set_source_from_color cr, 'foreground', flair
set_line_type_from_flair cr, flair
line_width = flair._line_width
cr\rectangle x, y + (line_width / 2), width, height - line_width
cr\stroke!
rounded_rectangle: (flair, x, y, width, height, cr) ->
radius = flair.corner_radius or 3
if width < radius * 3 or height < radius * 3
radius = min(width, height) / 3
quadrant = pi / 2
right, bottom, left, top = 0, quadrant - 0.5, quadrant * 2, (quadrant * 3) + 0.5
cr\move_to x, y + radius
cr\arc x + radius, y + radius, radius, left, top
cr\arc x + width - radius, y + radius, radius, top, right
cr\arc x + width - radius, y + height - radius, radius, right, bottom
cr\arc x + radius, y + height - radius, radius, bottom, left
cr\close_path!
set_source_from_color cr, 'background', flair
cr\fill_preserve!
set_source_from_color cr, 'foreground', flair
set_line_type_from_flair cr, flair
cr\stroke!
sandwich: (flair, x, y, width, height, cr) ->
set_source_from_color cr, 'foreground', flair
set_line_type_from_flair cr, flair
cr\move_to x, y + 0.5
cr\rel_line_to width, 0
cr\stroke!
cr\move_to x, y + height - 0.5
cr\rel_line_to width, 0
cr\stroke!
underline: (flair, x, y, width, height, cr) ->
set_source_from_color cr, 'foreground', flair
set_line_type_from_flair cr, flair
cr\move_to x, y + height - 0.5
cr\rel_line_to width, 0
cr\stroke!
wavy_underline: (flair, x, y, width, height, cr) ->
wave_height = flair.wave_height or 2
line_run = (flair.wave_width or 8) / 2
runs = math.floor (width / line_run)
cr\move_to x, y + height - 0.5
set_source_from_color cr, 'foreground', flair
set_line_type_from_flair cr, flair
direction = -1
for _ = 1, runs
cr\rel_line_to line_run, direction * wave_height
direction *= -1
partial_run = width - (runs * line_run)
if partial_run > 0
cr\rel_line_to partial_run, (direction * wave_height * partial_run / line_run)
cr\stroke!
pipe: (flair, x, y, width, height, cr) ->
if flair.foreground
set_source_from_color cr, 'foreground', flair
set_line_type_from_flair cr, flair
cr\move_to x + 0.5, y
cr\rel_line_to 0, height
cr\stroke!
strike_through: (flair, x, y, width, height, cr) ->
set_source_from_color cr, 'foreground', flair
set_line_type_from_flair cr, flair
cr\move_to x, y + (height / 2)
cr\rel_line_to width, 0
cr\stroke!
}
build = (params) ->
flair = copy params
flair.draw = draw_ops[params.type]
error "Invalid flair type '#{params.type}'", 2 unless flair.draw
flair._background = parse_color params.background
flair._foreground = parse_color params.foreground
flair._line_width = params.line_width or 0.5
flair
define = (name, opts) ->
flair = build opts
flairs[name] = flair
get_text_object = (display_line, start_offset, end_offset, flair) ->
layout = Layout display_line.pango_context
dline_layout = display_line.layout
text_size = end_offset - start_offset
t_ptr = dline_layout\get_text!
layout\set_text t_ptr + start_offset - 1, text_size
layout.tabs = dline_layout.tabs
-- need to set the correct attributes when we have a different text color
-- or need to determine the height of the text object correctly
if flair.text_color or flair.height == 'text'
styling = Styling.sub display_line.styling, start_offset, end_offset
exclude = flair.text_color and {color: true} or {}
attributes = styles.get_attributes styling, text_size, :exclude
if flair.text_color
color = Color flair.text_color
attributes\insert_before Attribute.Foreground(color.red, color.green, color.blue)
layout.attributes = attributes
width, height = layout\get_pixel_size!
:layout, :width, :height
need_text_object = (flair) ->
flair.text_color or flair.height == 'text'
{
CUSTOM: 'custom'
RECTANGLE: 'rectangle'
ROUNDED_RECTANGLE: 'rounded_rectangle'
SANDWICH: 'sandwich'
UNDERLINE: 'underline'
WAVY_UNDERLINE: 'wavy_underline'
PIPE: 'pipe'
STRIKE_TROUGH: 'strike_through'
:build
:define
define_default: (name, flair_type, opts) ->
unless flairs[name]
define name, flair_type, opts
get: (name) -> flairs[name]
clear: (name) ->
if name
flairs[name] = nil
else
flairs = {}
compile: (flair, start_offset, end_offset, display_line) ->
flair = flairs[flair] if type(flair) == 'string'
return nil unless flair
if need_text_object(flair) and not display_line.is_wrapped
flair = moon.copy flair
flair.text_object = get_text_object display_line, start_offset, end_offset, flair
flair
draw: (flair, display_line, start_offset, end_offset, x, y, cr) ->
get_defined_width = (at_x, f, clip) ->
return f.width if type(f.width) == 'number'
if f.width == 'full'
clip.x2 - at_x
flair = flairs[flair] if type(flair) == 'string'
return unless flair
{:layout, :view, :lines} = display_line
clip = cr.clip_extents
base_x = view.base_x
width_of_space = display_line.width_of_space
line_y_offset = 0
for nr = 1, #lines
line = lines[nr]
off_line = start_offset > line.line_end or end_offset < line.line_start
if off_line or end_offset == line.line_start and (start_offset != end_offset)
line_y_offset += line.height
continue -- flair not within this layout line
f_start_offset = max start_offset, line.line_start
f_end_offset = min line.line_end, end_offset
start_rect = layout\index_to_pos f_start_offset - 1
flair_y = y + start_rect.y / SCALE
text_start_x = x + max((start_rect.x / SCALE), 0) - base_x
start_x = max(text_start_x, view.edit_area_x)
width = get_defined_width(start_x, flair, clip)
unless width
end_rect = layout\index_to_pos f_end_offset - 1
end_x = end_rect.x / SCALE
width = x + end_x - start_x - base_x
if flair.min_width
flair_min_width = flair.min_width
if flair_min_width == 'letter'
width = max(width_of_space, width)
else
width = max(flair_min_width - base_x, width)
-- why draw a zero-width flair?
return if width <= 0
text_object = flair.text_object
if not text_object and need_text_object(flair)
ft_end_offset = min line.line_end + 1, end_offset
text_object = get_text_object display_line, f_start_offset, ft_end_offset, flair
-- height calculations
height = type(flair.height) == 'number' and flair.height or line.height
if (flair.height == 'text' or flair.text_color) and height > text_object.height
flair_y += display_line.y_offset
height = text_object.height
l_baseline = line.baseline - line_y_offset
bl_diff = floor (l_baseline - (text_object.layout.baseline / SCALE))
if bl_diff > 0
flair_y += bl_diff
cr\save!
flair.draw flair, start_x, flair_y, width, height, cr
cr\restore!
if flair.text_color
cr\save!
if base_x > 0
cr\rectangle x, flair_y, clip.x2 - x, clip.y2
cr\clip!
cr\move_to text_start_x, flair_y
cairo.show_layout cr, text_object.layout
cr\restore!
line_y_offset += line.height
}
| 29.805825 | 88 | 0.661672 |
b4775b3af2bf2158638c0d393a64c247bd7a1e7d | 764 | class Inventory
new: =>
@items = {}
@items["t"]=100
add_item: (name) =>
if @items[name]
@items[name] += 1
else
@items[name] = 1
inv = Inventory!
inv\add_item "tshirt"
inv\add_item "tshirt"
inv\add_item "pants"
inv\add_item "pants"
inv\add_item "pants"
print inv.items["pants"]
sum2 = (x, y) ->
x + 2*y
-- export sum2
print sum2 1, 2
some_values = {
name: "Bill",
age: 200,
["favorite food"]: "rice"
}
-- print some_values
hello = (name) ->
print "Hello #{name}!"
pl = require "pl.pretty"
pprint = pl.dump
-- pprint inv
moon = require "moon"
moon.p inv
t = require 'pl.text'
t.format_operator()
print "test %s %s"%{1,2}
{:hello,:sum2,:Inventory,:some_values}
-- ORM https://github.com/itdxer/4DaysORM | 13.642857 | 41 | 0.60733 |
76e05a4ba7c699e1bf9085313d41fa8523a3af50 | 41 | extra = () -> "Hello from extra"
:extra
| 10.25 | 32 | 0.585366 |
e516d02047b9f9d247200d1e8cd3506b71fe8875 | 17,594 | [[
==README==
Frame-by-Frame Transform Automation Script
Smoothly transforms various parameters across multi-line, frame-by-frame typesets.
Useful for adding smooth transitions to frame-by-frame typesets that cannot be tracked with mocha,
or as a substitute for the stepped \t transforms generated by the Aegisub-Motion.lua script, which
may cause more lag than hard-coded values.
First generate the frame-by-frame typeset that you will be adding the effect to. Find the lines where
you want the effect to begin and the effect to end, and visually typeset them until they look the way
you want them to.
These lines will act as "keyframes", and the automation will modify all the lines in between so that
the appearance of the first line smoothly transitions into the appearance of the last line. Simply
highlight the first line, the last line, and all the lines in between, and run the automation.
It will only affect the tags that are checked in the popup menu when you run the automation. If you wish
to save specific sets of parameters that you would like to run together, you can use the presets manager.
For example, you can go to the presets manager, check all the color tags, and save a preset named "Colors".
The next time you want to transform all the colors, just select "Colors" from the preset dropdown menu.
The "All" preset is included by default and cannot be deleted. If you want a specific preset to be loaded
when you start the script, name it "Default" when you define the preset.
This may be obvious, but this automation only works on one layer or one component of a frame-by-frame
typeset at a time. If you have a frame-by-frame typeset that has two lines per frame, which looks like:
A1
B1
A2
B2
A3
B3
etc.
Then this automation will not work. The lines must be organized as:
A1
A2
A3
etc.
B1
B2
B3
etc.
And you would have to run the automation twice, once on A and once on B. Furthermore, the text of each
line must be exactly the same once all tags are removed. You can have as many tag blocks as you want
in whatever positions you want for the "keyframe" lines (the first and the last). But once the tags are
taken out, the text of the lines must be identical, down to the last space. If you are using ctrl-D or
copy-pasting, this should be a given, but it's worth a warning.
The lines in between can have any tags you want in them. So long as the automation is not transforming
those particular tags, they will be left untouched. If you need the typeset to suddenly turn huge for one
frame, simply uncheck "fscx" and "fscy" when you run the automation, and the size of the line won't be
touched.
If you are transforming rotations, there is something to watch out for. If you want a line to start
with \frz10 and rotate to \frz350, then with default options, the line will rotate 340 degrees around the
circle until it gets to 350. You probably wanted it to rotate only 20 degrees, passing through 0. The
solution is to check the "Rotate in shortest direction" checkbox from the popup window. This will cause
the line to always pick the rotation direction that has a total rotation of less than 180 degrees.
New feature: ignore text. Requires you to only have one tag block in each line, at the beginning.
Comes with an extra automation "Remove tags" that utilizes functions that were written for the main
automation. You can comment out (two dashes) the line at the bottom that adds this automation if you don't
want it.
TODO:
Check that all lines text match
iclip support
]]
export script_name = "Frame-by-frame transform"
export script_description = "Smoothly transforms between the first and last selected lines."
export script_version = "2.0.0"
export script_namespace = "lyger.FbfTransform"
DependencyControl = require "l0.DependencyControl"
rec = DependencyControl{
feed: "https://raw.githubusercontent.com/TypesettingTools/lyger-Aegisub-Scripts/master/DependencyControl.json",
{
"aegisub.util",
{"lyger.LibLyger", version: "2.0.0", url: "http://github.com/TypesettingTools/lyger-Aegisub-Scripts"},
{"l0.ASSFoundation.Common", version: "0.2.0", url: "https://github.com/TypesettingTools/ASSFoundation",
feed: "https://raw.githubusercontent.com/TypesettingTools/ASSFoundation/master/DependencyControl.json"}
}
}
util, LibLyger, Common = rec\requireModules!
have_SubInspector = rec\checkOptionalModules "SubInspector.Inspector"
logger, libLyger = rec\getLogger!, LibLyger!
-- tag list, grouped by dialog layout
tags_grouped = {
{"c", "2c", "3c", "4c"},
{"alpha", "1a", "2a", "3a", "4a"},
{"fscx", "fscy", "fax", "fay"},
{"frx", "fry", "frz"},
{"bord", "shad", "fs", "fsp"},
{"xbord", "ybord", "xshad", "yshad"},
{"blur", "be"},
{"pos", "org", "clip"}
}
tags_flat = table.join unpack tags_grouped
-- default settings for every preset
preset_defaults = { skiptext: false, flip_rot: false, accel: 1.0,
tags: {tag, false for tag in *tags_flat }
}
-- the default preset must always be available and cannot be deleted
config = rec\getConfigHandler {
presets: {
Default: {}
"[Last Settings]": {description: "Repeats the last #{script_name} operation"}
}
startupPreset: "Default"
}
unless config\load!
-- write example preset on first time load
config.c.presets["All"] = tags: {tag, true for tag in *tags_flat}
config\write!
create_dialog = (preset) ->
config\load!
preset_names = [preset for preset, _ in pairs config.c.presets]
table.sort preset_names
dlg = {
-- Flip rotation
{ name: "flip_rot", class: "checkbox", x: 0, y: 9, width: 3, height: 1,
label: "Rotate in shortest direction", value: preset.c.flip_rot },
{ name: "skiptext", class: "checkbox", x: 3, y: 9, width: 2, height: 1,
label: "Ignore text", value: preset.c.skiptext },
-- Acceleration
{ class: "label", x: 0, y: 10, width: 2, height: 1,
label: "Acceleration: ", },
{ name: "accel", class:"floatedit", x: 2, y: 10, width: 3, height: 1,
value: preset.c.accel, hint: "1 means no acceleration, >1 starts slow and ends fast, <1 starts fast and ends slow" },
{ class: "label", x: 0, y: 11, width: 2, height: 1,
label: "Preset: " },
{ name: "preset_select", class: "dropdown", x: 2, y: 11, width: 2, height: 1,
items: preset_names, value: preset.section[#preset.section] },
{ name: "preset_modify", class: "dropdown", x: 4, y: 11, width: 2, height: 1,
items: {"Load", "Save", "Delete", "Rename"}, value: "Load" }
}
-- generate tag checkboxes
for y, group in ipairs tags_grouped
dlg[#dlg+1] = { name: tag, class: "checkbox", x: x-1, y: y, width: 1, height: 1,
label: "\\#{tag}", value: preset.c.tags[tag] } for x, tag in ipairs group
btn, res = aegisub.dialog.display dlg, {"OK", "Cancel", "Mod Preset", "Create Preset"}
return btn, res, preset
save_preset = (preset, res) ->
preset\import res, nil, true
if res.__class != DependencyControl.ConfigHandler
preset.c.tags[k] = res[k] for k in *tags_flat
preset\write!
create_preset = (settings, name) ->
msg = if not name
"Onii-chan, what name would you like your preset to listen to?"
elseif name == ""
"Onii-chan, did you forget to name the preset?"
elseif config.c.presets[name]
"Onii-chan, it's not good to name a preset the same thing as another one~"
if msg
btn, res = aegisub.dialog.display {
{ class: "label", x: 0, y: 0, width: 2, height: 1, label: msg }
{ class: "label", x: 0, y: 1, width: 1, height: 1, label: "Preset Name: " },
{ class: "edit", x: 1, y: 1, width: 1, height: 1, name: "name", text: name }
}
return btn and create_preset settings, res.name
preset = config\getSectionHandler {"presets", name}, preset_defaults
save_preset preset, settings
return name
prepare_line = (i, preset) ->
line = libLyger.lines[i]
-- Figure out the correct position and origin values
posx, posy = libLyger\get_pos line
orgx, orgy = libLyger\get_org line
-- Look for clips
clip = {line.text\match "\\clip%(([%d%.%-]*),([%d%.%-]*),([%d%.%-]*),([%d%.%-]*)%)"}
-- Make sure each line starts with tags
line.text = "{}#{line.text}" unless line.text\find "^{"
-- Turn all \1c tags into \c tags, just for convenience
line.text = line.text\gsub "\\1c", "\\c"
--Separate line into a table of tags and text
line_table = if preset.c.skiptext
while not line.text\match "^{[^}]+}[^{]"
line.text = line.text\gsub "}{", "", 1
tag, text = line.text\match "^({[^}]+})(.+)$"
{{:tag, :text}}
else [{:tag, :text} for tag, text in line.text\gmatch "({[^}]*})([^{]*)"]
return line, line_table, posx, posy, orgx, orgy, #clip > 0 and clip
--The main body of code that runs the frame transform
frame_transform = (sub, sel, res) ->
-- save last settings
preset = config\getSectionHandler {"presets", "[Last Settings]"}, preset_defaults
save_preset preset, res
libLyger\set_sub sub
-- Set the first and last lines in the selection
first_line, start_table, sposx, sposy, sorgx, sorgy, sclip = prepare_line sel[1], preset
last_line, end_table, eposx, eposy, eorgx, eorgy, eclip = prepare_line sel[#sel], preset
-- If either the first or last line do not contain a rectangular clip,
-- you will not be clipping today
preset.c.tags.clip = false unless sclip and eclip
-- These are the tags to transform
transform_tags = [tag for tag in *tags_flat when preset.c.tags[tag]]
-- Make sure both lines have the same splits
LibLyger.match_splits start_table, end_table
-- Tables that store tables for each tag block, consisting of the state of all relevant tags
-- that are in the transform_tags table
start_state_table = LibLyger.make_state_table start_table, transform_tags
end_state_table = LibLyger.make_state_table end_table, transform_tags
-- Insert default values when not included for the state of each tag block,
-- or inherit values from previous tag block
start_style = libLyger\style_lookup first_line
end_style = libLyger\style_lookup last_line
current_end_state, current_start_state = {}, {}
for k, sval in ipairs start_state_table
-- build current state tables
for skey, sparam in pairs sval
current_start_state[skey] = sparam
for ekey, eparam in pairs end_state_table[k]
current_end_state[ekey] = eparam
-- check if end is missing any tags that start has
for skey, sparam in pairs sval
end_state_table[k][skey] or= current_end_state[skey] or end_style[skey]
-- check if start is missing any tags that end has
for ekey, eparam in pairs end_state_table[ k]
start_state_table[k][ekey] or= current_start_state[ekey] or start_style[ekey]
-- Insert proper state into each intervening line
for i = 2, #sel-1
aegisub.progress.set 100 * (i-1) / (#sel-1)
this_line = libLyger.lines[sel[i]]
-- Turn all \1c tags into \c tags, just for convenience
this_line.text = this_line.text\gsub "\\1c","\\c"
-- Remove all the relevant tags so they can be replaced with their proper interpolated values
this_line.text = LibLyger.time_exclude this_line.text, transform_tags
this_line.text = LibLyger.line_exclude this_line.text, transform_tags
this_line.text = this_line.text\gsub "{}",""
-- Make sure this line starts with tags
this_line.text = "{}#{this_line.text}" unless this_line.text\find "^{"
-- The interpolation factor for this particular line
factor = (i-1)^preset.c.accel / (#sel-1)^preset.c.accel
-- Handle pos transform
if preset.c.tags.pos then
x = LibLyger.float2str util.interpolate factor, sposx, eposx
y = LibLyger.float2str util.interpolate factor, sposy, eposy
this_line.text = this_line.text\gsub "^{", "{\\pos(#{x},#{y})"
-- Handle org transform
if preset.c.tags.org then
x = LibLyger.float2str util.interpolate factor, sorgx, eorgx
y = LibLyger.float2str util.interpolate factor, sorgy, eorgy
this_line.text = this_line.text\gsub "^{", "{\\org(#{x},#{y})"
-- Handle clip transform
if preset.c.tags.clip then
clip = [util.interpolate factor, ord, eclip[i] for i, ord in ipairs sclip]
logger\dump{clip, sclip, eclip}
this_line.text = this_line.text\gsub "^{", "{\\clip(%d,%d,%d,%d)"\format unpack clip
-- Break the line into a table
local this_table
if preset.c.skiptext
while not this_line.text\match "^{[^}]+}[^{]"
this_line.text = this_line.text\gsub "}{", "", 1
tag, text = line.text\match "^({[^}]+})(.+)$"
this_table = {{:tag, :text}}
else
this_table = [{:tag, :text} for tag, text in this_line.text\gmatch "({[^}]*})([^{]*)"]
-- Make sure it has the same splits
j = 1
while j <= #start_table
stext, stag = start_table[j].text, start_table[j].tag
ttext, ttag = this_table[j].text, this_table[j].tag
-- ttext might contain miscellaneous tags that are not being checked for,
-- so remove them temporarily
ttext_temp = ttext\gsub "{[^{}]*}", ""
-- If this table item has longer text, break it in two based on
-- the text of the start table
if #ttext_temp > #stext
newtext = ttext_temp\match "#{LibLyger.esc stext}(.*)"
for i = #this_table, j+1,-1
this_table[i+1] = this_table[i]
this_table[j] = tag: ttag, text: ttext\gsub "#{LibLyger.esc newtext}$",""
this_table[j+1] = tag: "{}", text: newtext
-- If the start table has longer text, then perhaps ttext was split
-- at a tag that's not being transformed
if #ttext < #stext
-- It should be impossible for this to happen at the end, but check anyway
assert this_table[j+1], "You fucked up big time somewhere. Sorry."
this_table[j].text = table.concat {ttext, this_table[j+1].tag, this_table[j+1].text}
if this_table[j+2]
this_table[i] = this_table[i+1] for i = j+1, #this_table-1
this_table[#this_table] = nil
j -= 1
j += 1
--Interpolate all the relevant parameters and insert
this_line.text = LibLyger.interpolate this_table, start_state_table, end_state_table,
factor, preset
sub[sel[i]] = this_line
validate_fbf = (sub, sel) -> #sel >= 3
load_tags_remove = (sub, sel) ->
pressed, res = aegisub.dialog.display {
{ class: "label", label: "Enter the tags you would like to remove: ",
x: 0, y: 0, width: 1,height: 1 },
{ class: "textbox", name: "tag_list", text: "",
x: 0, y: 1,width: 1, height: 1 },
{ class: "checkbox", label: "Remove all EXCEPT", name: "do_except", value: false,
x: 0,y: 2, width: 1, height: 1 }
}, {"Remove","Cancel"}, {ok: "Remove", cancel: "Cancel"}
return if pressed == "Cancel"
tag_list = [tag for tag in res.tag_list\gmatch "\\?(%w+)[%s\\n,;]*"]
--Remove or remove except the tags in the table
for li in *sel
line = sub[li]
f = res.do_except and LibLyger.line_exclude_except or LibLyger.line_exclude
line.text = f(line.text, tag_list)\gsub "{}", ""
sub[li] = line
fbf_gui = (sub, sel, _, preset_name = config.c.startupPreset) ->
preset = config\getSectionHandler {"presets", preset_name}, preset_defaults
btn, res = create_dialog preset
switch btn
when "OK" do frame_transform sub, sel, res
when "Create Preset" do fbf_gui sub, sel, nil, create_preset res
when "Mod Preset"
if preset_name != res.preset_select
preset = config\getSectionHandler {"presets", res.preset_select}, preset_defaults
preset_name = res.preset_select
switch res.preset_modify
when "Delete"
preset\delete!
preset_name = nil
when "Save" do save_preset preset, res
when "Rename"
preset_name = create_preset preset.userConfig, preset_name
preset\delete!
fbf_gui sub, sel, nil, preset_name
-- register macros
rec\registerMacros {
{script_name, nil, fbf_gui, validate_fbf},
{"Remove tags", "Remove or remove all except the input tags.", load_tags_remove}
}
for name, preset in pairs config.c.presets
f = (sub, sel) -> frame_transform sub, sel, config\getSectionHandler {"presets", name}
rec\registerMacro "Presets/#{name}", preset.description, f, validate_fbf, nil, true | 44.095238 | 127 | 0.631238 |
4564d8571033dac910af8a404703ce650d6c2268 | 115 | cond => list =>
(list
x => xs => i =>
(if (cond x)
1
(xs (add i 1)))
i => 0
0)
| 12.777778 | 23 | 0.295652 |
b6fc465bb6d1d714ac5a63ffb11df676df968a45 | 3,444 | state = bundle_load 'state'
import apply from state
import bindings, config from howl
with config
.define
name: 'vi_command_cursor_blink_interval'
description: 'The rate at which the cursor blinks while in command mode (ms, 0 disables)'
default: 0
type_of: 'number'
cursor_home = (editor) -> apply editor, (editor) -> editor.cursor\home!
forward_to_char = (event, source, translations, editor) ->
if event.character
apply editor, (editor) -> editor\forward_to_match event.character
else
return false
back_to_char = (event, source, translations, editor) ->
if event.character
apply editor, (editor) -> editor\backward_to_match event.character
else
return false
end_of_word = (cursor) ->
with cursor
current_pos = .pos
\word_right_end!
\word_right_end! if .pos == current_pos + 1
\left!
cursor_properties = {
style: 'block'
blink_interval: config.vi_command_cursor_blink_interval
}
map = {
__meta: {
:cursor_properties
}
editor: {
j: (editor) -> apply editor, (editor) -> editor.cursor\down!
k: (editor) -> apply editor, (editor) -> editor.cursor\up!
h: (editor) ->
if editor.cursor.at_start_of_line
state.reset!
else
apply editor, (editor) -> editor.cursor\left!
H: (editor) -> apply editor, (editor) ->
editor.cursor.line = editor.line_at_top
l: (editor) ->
if editor.cursor.at_end_of_line
state.reset!
else
apply editor, (editor) -> editor.cursor\right!
e: (editor) -> apply editor, (editor) -> end_of_word editor.cursor
w: (editor) -> apply editor, (editor, _state) ->
if _state.change or _state.yank then end_of_word editor.cursor
elseif _state.delete
for i = 1,_state.count or 1 do editor.cursor\word_right!
editor.cursor\left!
true
else
editor.cursor\word_right!
b: (editor) -> apply editor, (editor) -> editor.cursor\word_left!
g: (editor) ->
if state.go
editor.cursor\start!
state.reset!
else
state.go = true
G: (editor) -> apply editor, (editor, _state) ->
if _state.count then editor.cursor.line = _state.count
else editor.cursor\eof!
L: (editor) -> apply editor, (editor) ->
editor.cursor.line = editor.line_at_bottom
f: (editor) -> bindings.capture forward_to_char
F: (editor) -> bindings.capture back_to_char
'/': 'buffer-search-forward'
'?': 'buffer-search-backward'
n: 'buffer-repeat-search'
M: (editor) -> apply editor, (editor) ->
editor.cursor.line = editor.line_at_center
'$': (editor) -> apply editor, (editor) ->
editor.cursor.column_index = math.max(1, #editor.current_line)
'^': (editor) -> apply editor, (editor) ->
editor.cursor\home_indent!
}
on_unhandled: (event, source, translations) ->
char = event.character
modifiers = event.control or event.alt
if char and not modifiers
if char\match '^%d$'
-- we need to special case '0' here as that's a valid command in its own
-- right, unless it's part of a numerical prefix
if char == '0' and not state.count then return cursor_home
else state.add_number tonumber char
elseif char\match '^%w$'
state.reset!
return -> true
}
config.watch 'vi_command_cursor_blink_interval', (_, value) ->
cursor_properties.blink_interval = value
return map
| 27.774194 | 93 | 0.647213 |
7af864ceaf0736fe0d7d1a1ff5f2c80b224f7e0a | 7,541 | bold = (text) ->
"{\\b1}#{text}{\\b0}"
-- OSD message, using ass.
message = (text, duration) ->
ass = mp.get_property_osd("osd-ass-cc/0")
-- wanted to set font size here, but it's completely unrelated to the font
-- size in set_osd_ass.
ass ..= text
mp.osd_message(ass, duration or options.message_duration)
append = (a, b) ->
for _, val in ipairs b
a[#a+1] = val
return a
seconds_to_time_string = (seconds, no_ms, full) ->
if seconds < 0
return "unknown"
ret = ""
ret = string.format(".%03d", seconds * 1000 % 1000) unless no_ms
ret = string.format("%02d:%02d%s", math.floor(seconds / 60) % 60, math.floor(seconds) % 60, ret)
if full or seconds > 3600
ret = string.format("%d:%s", math.floor(seconds / 3600), ret)
ret
seconds_to_path_element = (seconds, no_ms, full) ->
time_string = seconds_to_time_string(seconds, no_ms, full)
-- Needed for Windows (and maybe for Linux? idk)
time_string, _ = time_string\gsub(":", ".")
return time_string
file_exists = (name) ->
info, err = utils.file_info(name)
if info ~= nil
return true
return false
expand_properties = (text, magic="$") ->
for prefix, raw, prop, colon, fallback, closing in text\gmatch("%" .. magic .. "{([?!]?)(=?)([^}:]*)(:?)([^}]*)(}*)}")
local err
local prop_value
local compare_value
original_prop = prop
get_property = mp.get_property_osd
if raw == "="
get_property = mp.get_property
if prefix ~= ""
for actual_prop, compare in prop\gmatch("(.-)==(.*)")
prop = actual_prop
compare_value = compare
if colon == ":"
prop_value, err = get_property(prop, fallback)
else
prop_value, err = get_property(prop, "(error)")
prop_value = tostring(prop_value)
if prefix == "?"
if compare_value == nil
prop_value = err == nil and fallback .. closing or ""
else
prop_value = prop_value == compare_value and fallback .. closing or ""
prefix = "%" .. prefix
elseif prefix == "!"
if compare_value == nil
prop_value = err ~= nil and fallback .. closing or ""
else
prop_value = prop_value ~= compare_value and fallback .. closing or ""
else
prop_value = prop_value .. closing
if colon == ":"
text, _ = text\gsub("%" .. magic .. "{" .. prefix .. raw .. original_prop\gsub("%W", "%%%1") .. ":" .. fallback\gsub("%W", "%%%1") .. closing .. "}", expand_properties(prop_value))
else
text, _ = text\gsub("%" .. magic .. "{" .. prefix .. raw .. original_prop\gsub("%W", "%%%1") .. closing .. "}", prop_value)
return text
format_filename = (startTime, endTime, videoFormat) ->
hasAudioCodec = videoFormat.audioCodec != ""
replaceFirst =
"%%mp": "%%mH.%%mM.%%mS"
"%%mP": "%%mH.%%mM.%%mS.%%mT"
"%%p": "%%wH.%%wM.%%wS"
"%%P": "%%wH.%%wM.%%wS.%%wT"
replaceTable =
"%%wH": string.format("%02d", math.floor(startTime/(60*60)))
"%%wh": string.format("%d", math.floor(startTime/(60*60)))
"%%wM": string.format("%02d", math.floor(startTime/60%60))
"%%wm": string.format("%d", math.floor(startTime/60))
"%%wS": string.format("%02d", math.floor(startTime%60))
"%%ws": string.format("%d", math.floor(startTime))
"%%wf": string.format("%s", startTime)
"%%wT": string.sub(string.format("%.3f", startTime%1), 3)
"%%mH": string.format("%02d", math.floor(endTime/(60*60)))
"%%mh": string.format("%d", math.floor(endTime/(60*60)))
"%%mM": string.format("%02d", math.floor(endTime/60%60))
"%%mm": string.format("%d", math.floor(endTime/60))
"%%mS": string.format("%02d", math.floor(endTime%60))
"%%ms": string.format("%d", math.floor(endTime))
"%%mf": string.format("%s", endTime)
"%%mT": string.sub(string.format("%.3f", endTime%1), 3)
"%%f": mp.get_property("filename")
"%%F": mp.get_property("filename/no-ext")
"%%s": seconds_to_path_element(startTime)
"%%S": seconds_to_path_element(startTime, true)
"%%e": seconds_to_path_element(endTime)
"%%E": seconds_to_path_element(endTime, true)
"%%T": mp.get_property("media-title")
"%%M": (mp.get_property_native('aid') and not mp.get_property_native('mute') and hasAudioCodec) and '-audio' or ''
"%%R": (options.scale_height != -1) and "-#{options.scale_height}p" or "-#{mp.get_property_native('height')}p"
"%%t%%": "%%"
filename = options.output_template
for format, value in pairs replaceFirst
filename, _ = filename\gsub(format, value)
for format, value in pairs replaceTable
filename, _ = filename\gsub(format, value)
if mp.get_property_bool("demuxer-via-network", false)
filename, _ = filename\gsub("%%X{([^}]*)}", "%1")
filename, _ = filename\gsub("%%x", "")
else
x = string.gsub(mp.get_property("stream-open-filename", ""), string.gsub(mp.get_property("filename", ""), "%W", "%%%1") .. "$", "")
filename, _ = filename\gsub("%%X{[^}]*}", x)
filename, _ = filename\gsub("%%x", x)
filename = expand_properties(filename, "%")
for format in filename\gmatch("%%t([aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ])")
filename, _ = filename\gsub("%%t" .. format, os.date("%" .. format))
-- Remove invalid chars
-- Windows: < > : " / \ | ? *
-- Linux: /
filename, _ = filename\gsub("[<>:\"/\\|?*]", "")
return "#{filename}.#{videoFormat.outputExtension}"
parse_directory = (dir) ->
home_dir = os.getenv("HOME")
if not home_dir
-- Windows home dir is obtained by USERPROFILE, or, if it fails, HOMEDRIVE + HOMEPATH
home_dir = os.getenv("USERPROFILE")
if not home_dir
drive = os.getenv("HOMEDRIVE")
path = os.getenv("HOMEPATH")
if drive and path
home_dir = utils.join_path(drive, path)
else
msg.warn("Couldn't find home dir.")
home_dir = ""
dir, _ = dir\gsub("^~", home_dir)
return dir
-- from stats.lua
is_windows = type(package) == "table" and type(package.config) == "string" and package.config\sub(1, 1) == "\\"
trim = (s) ->
return s\match("^%s*(.-)%s*$")
get_null_path = ->
if file_exists("/dev/null")
return "/dev/null"
return "NUL"
run_subprocess = (params) ->
res = utils.subprocess(params)
msg.verbose("Command stdout: ")
msg.verbose(res.stdout)
if res.status != 0
msg.verbose("Command failed! Reason: ", res.error, " Killed by us? ", res.killed_by_us and "yes" or "no")
return false
return true
shell_escape = (args) ->
ret = {}
for i,a in ipairs(args)
s = tostring(a)
if string.match(s, "[^A-Za-z0-9_/:=-]")
-- Single quotes for UNIX, double quotes for Windows.
if is_windows
s = '"'..string.gsub(s, '"', '"\\""')..'"'
else
s = "'"..string.gsub(s, "'", "'\\''").."'"
table.insert(ret,s)
concat = table.concat(ret, " ")
if is_windows
-- Add a second set of double-quotes because idk it works
concat = '"' .. concat .. '"'
return concat
run_subprocess_popen = (command_line) ->
command_line_string = shell_escape(command_line)
-- Redirect stderr to stdout, because for some reason
-- the progress is outputted to stderr???
command_line_string ..= " 2>&1"
msg.verbose("run_subprocess_popen: running #{command_line_string}")
return io.popen(command_line_string)
calculate_scale_factor = () ->
baseResY = 720
osd_w, osd_h = mp.get_osd_size()
return osd_h / baseResY
should_display_progress = () ->
if options.display_progress == "auto"
return not is_windows
return options.display_progress
reverse = (list) ->
[element for element in *list[#list, 1, -1]]
get_pass_logfile_path = (encode_out_path) ->
"#{encode_out_path}-video-pass1.log"
| 34.277273 | 184 | 0.619546 |
046f80f5ad9ea2150306ffd6ccf5ef31840660b4 | 1,491 | json = require("json")
default_file = "bundle.pvdf"
class VdfPart
new: (name, pos, relpos) =>
@name = name
@pos = pos
@relpos = relpos
setParent: (parent) =>
@parent = parent
getName: () =>
return @name
getPosition: () =>
return @pos
getRelativePos: () =>
return @relpos
getParent: () =>
return @parent
class VehicleDefinition
new: (name) =>
@name = name
@parts = {}
return
getName: () =>
return @name
addPart: (shortname, part) =>
@parts[shortname] = part
hasPart: (name) =>
return @parts[name] ~= nil
getPart: (name) =>
if @hasPart(name)
return @parts[name]
getPartList: () =>
return @parts
bundleCache = {}
loadBundle = (file=default_file) ->
if bundleCache[file]
return bundleCache[file]
bundle = {}
vdfs = json.decode(UseItem(file))
for vdfName, struct in pairs(vdfs)
vdf = VehicleDefinition(vdfName)
for shortname, p in pairs(struct)
part = VdfPart(p["fullname"], SetVector(unpack(p["pos"])), SetVector(unpack(p["relpos"])))
part\setParent(p["parent"])
vdf\addPart(shortname, part)
for shortname, part in pairs(vdf\getPartList())
parent = vdf\getPart(part\getParent())
part\setParent(parent)
bundle[vdfName] = vdf
bundleCache[file] = bundle
return bundle
return {
:VdfPart,
:VehicleDefinition,
:loadBundle
} | 18.182927 | 97 | 0.576123 |
1dcdea6d530fee770c97755e0d08f291ddd3fc66 | 151 | M = {}
M.main = (...) ->
output = {}
for i in *{...}
output[#output+1] = string.format "hello %d", i
return unpack output
return M | 21.571429 | 55 | 0.496689 |
8c139290c3c140ac8dd277c23a64e1d838930a32 | 598 | export ^
require "states/transitions/fadefrom"
class SlapScreen extends GameState
new: (@slapLevel, @updatePrevious=false) =>
@slapped = false
previousState: =>
statestack\peek(1)
update: (dt) =>
if @updatePrevious
@previousState()\update(dt)
if not @slapped
soundmanager\playSlap(@slapLevel)
statestack\pop()
-- statestack\push FadeToBlack(10)
statestack\push FadeFrom({255, 255, 255}, 0.5)
@slapped = true
draw: =>
@previousState()\draw()
| 24.916667 | 58 | 0.553512 |
c0d931c4804cac84bb63be727f0c671693ddeafd | 966 | Navigation = include "Navigation"
Omnibar = include "Omnibar"
Style (env) ->
div.container {
overflow: "hidden"
}
Layout (env, state) ->
html ->
head ->
title env.title
if env.styles
for stylesheet in *env.styles
link rel: "stylesheet", href: env.basePath..stylesheet
if env.scripts
for scriptsrc in *env.scripts
script type: "application/javascript", src: env.basePath..scriptsrc
link rel: "stylesheet", href: env.basePath..env.stylePath
script type: "application/javascript", src: env.basePath..env.scriptPath
body class: "cover col", ->
Omnibar env.omnibar if #env.omnibar > 0
div class: "row container fill-5", id: "container", ->
Navigation fragments: state.navigation, link: state.link if state.navigation
raw state.fragment | 32.2 | 92 | 0.568323 |
b84a951771521aeb43a23fa4456f8d3fb6d9fb80 | 3,341 | import hmac_sha1, encode_base64 from require "lapis.util.encoding"
UsersApplication=require "lib.lazuli.src.lazuli.modules.user_management"
Profiles = require "models.profiles"
ACLs = require "models.acls"
ACL_Entries = require "models.acl_entries"
config = (require "lapis.config").get!
csrf = require "lapis.csrf"
Users = require "lazuli.modules.user_management.models.users"
import hash_password, verify_password from require "lazuli.modules.user_management.crypto"
prepareUserProfile=(user)->
profile=Profiles\getOrCreateByUser user
nobodyACL=ACLs\create {
user_id: user.id
name: "nobody"
default_policy: false
}
everyoneACL=ACLs\create {
user_id: user.id
name: "everyone"
default_policy: true
}
usersACL=ACLs\create {
user_id: user.id
name: "logged in users"
default_policy: false
}
ACL_Entries\create {
acl_id: usersACL.id
target_type: ACL_Entries.target_types.include
target_id: ACL_Entries.special_targets.include_logged_in
policy: true
}
-- TODO: default ACLs, etc.
class CustomUsersApplication extends UsersApplication
@before_filter =>
if config.projectStage=="alpha" or config.projectStage=="beta"
if @req.parsed_url.path=="/users/register/do" and Users\count! > 0 and @req.params_post.key~=encode_base64 hmac_sha1 config.secret, @req.params_post.username
@write redirect_to: @url_for "index"
@modules.user_management or={}
@session.modules.user_management or={}
if not @modules.user_management.providers
if type(config.modules.user_management)=="table" and type(config.modules.user_management.providers)=="table"
@modules.user_management.providers={k,require(k)(@,k,v) for k,v in pairs config.modules.user_management.providers}
else
@modules.user_management.providers={}
@modules.user_management.csrf_token = csrf.generate_token @, "lazuli_modules_usermanagement"
if @session.modules.user_management.currentuser and not @modules.user_management.currentuser
@modules.user_management.currentuser = Users\find @session.modules.user_management.currentuser
@superroute logout: "/logout"
@superroute login: "/login"
@superroute register: "/register"
@superroute register_do: "/register/do", (ret)=>
if (ret.status ~= 403) and @modules.user_management.currentuser
prepareUserProfile @modules.user_management.currentuser
ret
@superroute login_do: "/login/do", (ret)=>
if @modules.user_management.currentuser
if @session.login_redirect
[email protected]_redirect
@session.login_redirect=nil
redirect_to: red
else
redirect_to: @url_for "profile_show", id: @modules.user_management.currentuser.id
else
ret
@change_user_name: (user, newname, password)->
if type(user)=="number"
user=Users\find user
return nil, "user not found" unless user
newhash=hash_password newname, password
return nil, "wrong password" unless verify_password user.username, password, user.pwHash
user\update{
username: newname
pwHash: newhash
}
@change_password: (user, newpassword)->
if type(user)=="number"
user=Users\find user
return nil, "user not found" unless user
newhash=hash_password user.username, newpassword
user\update{
pwHash: newhash
}
| 35.924731 | 163 | 0.728225 |
20be60e0048f9d3cce2cb1172fa739f1f248d785 | 1,753 | #!/bin/env moon
import read, Reader from require'opeth.bytecode.reader'
import mkcfg from require'opeth.common.blockrealm'
import map from require'opeth.common.utils'
Graph = require'graphviz'
ptr_to_idx = (cfg, to_lua) ->
indexed_cfg = [{succ: {}, pred: {}, start: b.start, end: b.end} for b in *cfg]
for i = 1, #cfg
if to_lua
indexed_cfg[i].ed = cfg[i].end
indexed_cfg[i].end = nil
if instr = cfg[i].instr
indexed_cfg[i].instr = instr
for predidx = 1, #(cfg[i].pred)
for j = 1, #cfg
if (tostring cfg[i].pred[predidx]) == (tostring cfg[j])
indexed_cfg[i].pred[predidx] = j
break
for toidx = 1, #(cfg[i].succ)
for j = 1, #cfg
if (tostring cfg[i].succ[toidx]) == (tostring cfg[j])
indexed_cfg[i].succ[toidx] = j
break
indexed_cfg
process_proto = (fn, dot, lprefix, idx = 1) ->
cfg = ptr_to_idx mkcfg fn.instruction
for i = 1, #cfg
cfg[i].instr = ""
for j = cfg[i].start, cfg[i].end
cfg[i].instr ..= "%4d: %-8s %-14s\n"\format j, fn.instruction[j].op, table.concat (map (=> "%4d"\format math.tointeger @), fn.instruction[j]), " "
dot\node("#{lprefix}_b#{i}", "\\N: [#{cfg[i].start} ~ #{cfg[i].end}]\n#{cfg[i].instr}")
for i = 1, #cfg
for j = 1, #cfg[i].succ
dot\edge("#{lprefix}_b#{i}", "#{lprefix}_b#{cfg[i].succ[j]}")
for pi = 1, #fn.prototype
process_proto fn.prototype[pi], dot, lprefix .. "→clos#{idx}_#{pi}", idx + 1
vmfmt = do
rd = Reader arg[1]
with rd\read!
rd\close!
dot = Graph!
fontname = "Inconsolata Regular"
styles = {
graph: {
}
nodes: {
:fontname
shape: "rectangle"
}
edges: {
:fontname
}
}
dot.nodes.style\update styles.nodes
dot.edges.style\update styles.edges
process_proto vmfmt.fnblock, dot, "main"
dot\render "drawngraph"
| 22.766234 | 150 | 0.621221 |
c75e0137c23b28b490087b9a727e6b0028078bac | 243 | io.stderr\write "WARNING: The module `lapis.nginx.postgres` has moved to `lapis.db.postgres`
Please update your require statements as the old path will no longer be
available in future versions of lapis.\n\n"
require "lapis.db.postgres"
| 34.714286 | 92 | 0.769547 |
d893660233032e1c5484eb52f7d5ac7cbe61bbc2 | 1,036 | import format from string
import gettime from require "gettime"
import Object from "novacbn/novautils/utilities/Object"
-- ::getSeconds() -> number
-- Returns the current time as seconds
getSeconds = () ->
return gettime() / 1000
-- ElapsedTimer::ElapsedTimer()
-- Represents a basic timer for timing tasks
export ElapsedTimer = Object\extend {
-- ElapsedTimer::startTime -> number
-- Represents the time in seconds since the an ElapsedTimer object was initiated
startTime: 0
-- ElapsedTimer::constructor()
-- Constructor for ElapsedTimer
constructor: () =>
-- Store the creation timestamp
@startTime = getSeconds()
-- ElapsedTimer::getElapsed() -> number
-- Returns the elapsed time as a number delta
getElapsed: () =>
return getSeconds() - @startTime
-- ElapsedTimer::getFormattedElapsed() -> string
-- Returns the elapsed time formatted as a string, e.g. "0.0341"
getFormattedElapsed: () =>
return format("%.4fs", getSeconds() - @startTime)
} | 30.470588 | 84 | 0.678571 |
c6444ace360038212f20ff7cbe36953cf10f9ef3 | 8,922 | class Config
new: (str) =>
assert(type(str) == 'string' and str ~= '', 'shared.utility.Config')
@active = tonumber(str\match('Active=(%d+)')) or 0
@windowX = tonumber(str\match('WindowX=(%d+)')) or 0
@windowY = tonumber(str\match('WindowY=(%d+)')) or 0
@clickThrough = tonumber(str\match('ClickThrough=(%d+)')) or 0
@draggable = tonumber(str\match('Draggable=(%d+)')) or 0
@snapEdges = tonumber(str\match('SnapEdges=(%d+)')) or 0
@keepOnScreen = tonumber(str\match('KeepOnScreen=(%d+)')) or 0
@alwaysOnTop = tonumber(str\match('AlwaysOnTop=(%d+)')) or 0
@loadOrder = tonumber(str\match('LoadOrder=(%d+)')) or 0
isActive: () => return @active == 1
getX: () => return @windowX
getY: () => return @windowY
getZ: () => return @alwaysOnTop
isClickThrough: () => return @clickThrough == 1
isDraggable: () => return @draggable == 1
snapsToEdges: () => return @snapEdges == 1
isKeptOnScreen: () => return @keepOnScreen == 1
getLoadOrder: () => return @loadOrder
-- May have to look into selective loading of lookup tables for various character sets.
lookup = {
[195]: {
[96]: {' ', '\160'}
[97]: {'¡', '\161'}
[98]: {'¢', '\162'}
[99]: {'£', '\163'}
[100]: {'¤', '\164'}
[101]: {'¥', '\165'}
[102]: {'¦', '\166'}
[103]: {'§', '\167'}
[104]: {'¨', '\168'}
[105]: {'©', '\169'}
[106]: {'ª', '\170'}
[107]: {'«', '\171'}
[108]: {'¬', '\172'}
[110]: {'®', '\174'}
[111]: {'¯', '\175'}
[112]: {'°', '\176'}
[113]: {'±', '\177'}
[114]: {'²', '\178'}
[115]: {'³', '\179'}
[116]: {'´', '\180'}
[117]: {'µ', '\181'}
[118]: {'¶', '\182'}
[119]: {'·', '\183'}
[120]: {'¸', '\184'}
[121]: {'¹', '\185'}
[122]: {'º', '\186'}
[123]: {'»', '\187'}
[124]: {'¼', '\188'}
[125]: {'½', '\189'}
[126]: {'¾', '\190'}
[127]: {'¿', '\191'}
[128]: {'À', '\192'}
[129]: {'Á', '\193'}
[130]: {'Â', '\194'}
[131]: {'Ã', '\195'}
[132]: {'Ä', '\196'}
[133]: {'Å', '\197'}
[134]: {'Æ', '\198'}
[135]: {'Ç', '\199'}
[136]: {'È', '\200'}
[137]: {'É', '\201'}
[138]: {'Ê', '\202'}
[139]: {'Ë', '\203'}
[140]: {'Ì', '\204'}
[141]: {'Í', '\205'}
[142]: {'Î', '\206'}
[143]: {'Ï', '\207'}
[144]: {'Ð', '\208'}
[145]: {'Ñ', '\209'}
[146]: {'Ò', '\210'}
[147]: {'Ó', '\211'}
[148]: {'Ô', '\212'}
[149]: {'Õ', '\213'}
[150]: {'Ö', '\214'}
[151]: {'×', '\215'}
[152]: {'Ø', '\216'}
[153]: {'Ù', '\217'}
[154]: {'Ú', '\218'}
[155]: {'Û', '\219'}
[156]: {'Ü', '\220'}
[157]: {'Ý', '\221'}
[158]: {'Þ', '\222'}
[159]: {'ß', '\223'}
[160]: {'à', '\224'}
[161]: {'á', '\225'}
[162]: {'â', '\226'}
[163]: {'ã', '\227'}
[164]: {'ä', '\228'}
[165]: {'å', '\229'}
[166]: {'æ', '\230'}
[167]: {'ç', '\231'}
[168]: {'è', '\232'}
[169]: {'é', '\233'}
[170]: {'ê', '\234'}
[171]: {'ë', '\235'}
[172]: {'ì', '\236'}
[173]: {'í', '\237'}
[174]: {'î', '\238'}
[175]: {'ï', '\239'}
[176]: {'ð', '\240'}
[177]: {'ñ', '\241'}
[178]: {'ò', '\242'}
[179]: {'ó', '\243'}
[180]: {'ô', '\244'}
[181]: {'õ', '\245'}
[182]: {'ö', '\246'}
[183]: {'÷', '\247'}
[184]: {'ø', '\248'}
[185]: {'ù', '\249'}
[186]: {'ú', '\250'}
[187]: {'û', '\251'}
[188]: {'ü', '\252'}
[189]: {'ý', '\253'}
[190]: {'þ', '\254'}
[191]: {'ÿ', '\255'}
}
}
parseVDF = (lines, start = 1) ->
result = {}
i = start - 1
while i < #lines
i += 1
key = lines[i]\match('^%s*"([^"]+)"%s*$') -- Start of a dictionary
if key ~= nil
assert(lines[i + 1]\match('^%s*{%s*$') ~= nil, '"parseVDF" expected "{".')
tbl, i = parseVDF(lines, i + 2)
result[key\lower()] = tbl
else
key, value = lines[i]\match('^%s*"([^"]+)"%s*"(.-)"%s*$') -- Key-value pair
if key ~= nil and value ~= nil
result[key\lower()] = value
else
if lines[i]\match('^%s*}%s*$') -- End of a dictionary
return result, i
elseif lines[i]\match('^%s*//.*$') -- Comment
continue
elseif lines[i]\match('^%s*"#base"%s*"([^"]+)"%s*$')
continue
else
assert(nil, ('"parseVDF" encountered unexpected input on line %d: %s.')\format(i, lines[i]))
return result, i
return {
createJSONHelpers: () ->
json = require('lib.json')
assert(type(json) == 'table', 'shared.utility.createJSONHelpers')
io.readJSON = (path, pathIsRelative = true) -> return json.decode(io.readFile(path, pathIsRelative))
io.writeJSON = (relativePath, tbl) ->
assert(type(tbl) == 'table', 'io.writeJSON')
return io.writeFile(relativePath, json.encode(tbl))
runCommand: (parameter, output, callback, callbackArgs = {}, state = 'Hide', outputType = 'UTF16') ->
assert(type(parameter) == 'string', 'shared.utility.runCommand')
assert(type(output) == 'string', 'shared.utility.runCommand')
assert(type(callback) == 'string', 'shared.utility.runCommand')
SKIN\Bang(('[!SetOption "Command" "Parameter" "%s"]')\format(parameter))
SKIN\Bang(('[!SetOption "Command" "OutputFile" "%s"]')\format(output))
SKIN\Bang(('[!SetOption "Command" "OutputType" "%s"]')\format(outputType))
SKIN\Bang(('[!SetOption "Command" "State" "%s"]')\format(state))
SKIN\Bang(('[!SetOption "Command" "FinishAction" "[!CommandMeasure Script %s(%s)]"]')\format(callback, table.concat(callbackArgs, ', ')))
SKIN\Bang('[!UpdateMeasure "Command"]')
SKIN\Bang('[!CommandMeasure "Command" "Run"]')
runLastCommand: () -> SKIN\Bang('[!CommandMeasure "Command" "Run"]')
waitCommand: 'ping -n 2 127.0.0.1 > nul'
parseVDF: (file) ->
switch type(file)
when 'string'
return parseVDF(file\splitIntoLines())
when 'table'
return parseVDF(file)
else
assert(nil, ('"parseVDF" does not support the "%s" type as its argument.')\format(type(file)))
replaceUnsupportedChars: (str) ->
assert(type(str) == 'string', 'shared.utility.replaceUnsupportedChars')
result = ''
charsToReplace = {}
hasCharsToDrop = false
hasCharsToReplace = false
for char in str\gmatch('[%z\1-\127\194-\255][\128-\191]*')
lookupValue = nil
-- TODO: Have a look at this again. Seems like this would cause an excessive amount of allocations.
-- TODO: Any way to reduce the amount of allocations?
bytes = {char\byte(1, -1)}
if #bytes > 1
lookupValue = lookup
for byte in *bytes
continue if lookupValue == nil
lookupValue = lookupValue[byte]
--assert(lookupValue ~= nil,
-- ('Encountered unsupported variable-width character: %s %s')\format(char, table.concat(bytes, '|'))
--) -- Leave here for testing purposes, but comment out for releases
if lookupValue == nil
hasCharsToDrop = true
continue
charsToReplace[lookupValue[1]] = lookupValue[2]
hasCharsToReplace = true
result ..= char
if hasCharsToReplace
for find, replace in pairs(charsToReplace)
result = result\gsub(find, replace)
elseif not hasCharsToDrop or #result == 0
result = str
return result
getConfig: (name) ->
assert(type(name) == 'string', 'shared.utility.getConfig')
path = io.joinPaths(SKIN\GetVariable('SETTINGSPATH'), 'Rainmeter.ini')
rainmeterINI = io.readFile(path, false)
pattern = '%[' .. name .. '%][^%[]+'
starts, ends = rainmeterINI\find(pattern)
return nil if starts == nil or ends == nil
return Config(rainmeterINI\sub(starts, ends))
getConfigs: (names) ->
path = io.joinPaths(SKIN\GetVariable('SETTINGSPATH'), 'Rainmeter.ini')
rainmeterINI = io.readFile(path, false)
configs = {}
for name in *names
pattern = '%[' .. name .. '%][^%[]+'
starts, ends = rainmeterINI\find(pattern)
continue if starts == nil or ends == nil
table.insert(configs, Config(rainmeterINI\sub(starts, ends)))
return configs
getConfigMonitor: (config) ->
assert(config.__class == Config, 'shared.utility.getConfigMonitor')
x = config\getX()
y = config\getY()
for i = 1, 8
monitorX = tonumber(SKIN\GetVariable(('SCREENAREAX@%d')\format(i)))
monitorY = tonumber(SKIN\GetVariable(('SCREENAREAY@%d')\format(i)))
monitorWidth = tonumber(SKIN\GetVariable(('SCREENAREAWIDTH@%d')\format(i)))
monitorHeight = tonumber(SKIN\GetVariable(('SCREENAREAHEIGHT@%d')\format(i)))
continue if x < monitorX or x > (monitorX + monitorWidth - 1)
continue if y < monitorY or y > (monitorY + monitorHeight - 1)
return i
return nil
centerOnMonitor: (width, height, screen = 1) ->
assert(type(width) == 'number', 'shared.utility.centerOnMonitor')
assert(type(height) == 'number', 'shared.utility.centerOnMonitor')
assert(type(screen) == 'number', 'shared.utility.centerOnMonitor')
monitorX = tonumber(SKIN\GetVariable(('SCREENAREAX@%d')\format(screen)))
monitorY = tonumber(SKIN\GetVariable(('SCREENAREAY@%d')\format(screen)))
monitorWidth = tonumber(SKIN\GetVariable(('SCREENAREAWIDTH@%d')\format(screen)))
monitorHeight = tonumber(SKIN\GetVariable(('SCREENAREAHEIGHT@%d')\format(screen)))
x = math.round(monitorX + (monitorWidth - width) / 2)
y = math.round(monitorY + (monitorHeight - height) / 2)
return x, y
}
| 33.923954 | 139 | 0.567249 |
3ad05c4a32682f0856e6619a9fa6896619e83155 | 6,123 | import java, Font, Image, Quad from sauce3
Constants = require "sauce3/wrappers"
Color = java.require "com.badlogic.gdx.graphics.Color"
Gdx = java.require "com.badlogic.gdx.Gdx"
GL20 = java.require "com.badlogic.gdx.graphics.GL20"
Matrix4 = java.require "com.badlogic.gdx.math.Matrix4"
Sauce3VM = java.require "sauce3.Sauce3VM"
OrthographicCamera = java.require "com.badlogic.gdx.graphics.OrthographicCamera"
ShapeRender = java.require "com.badlogic.gdx.graphics.glutils.ShapeRenderer"
SpriteBatch = java.require "com.badlogic.gdx.graphics.g2d.SpriteBatch"
shader = SpriteBatch\createDefaultShader!
batch = java.new SpriteBatch, 1000, shader
shapes = java.new ShapeRender
font = Font!
shapes\setAutoShapeType true
matrix = java.new Matrix4
color = java.new Color, 1, 1, 1, 1
background = java.new Color, 0, 0, 0, 1
blending = "alpha"
batch\setColor color
shapes\setColor color
font.font\setColor color
camera = java.new OrthographicCamera
camera\setToOrtho true
batch\setProjectionMatrix camera.combined
shapes\setProjectionMatrix camera.combined
matrix_dirty = false
check = (texture_based) ->
if texture_based
if matrix_dirty
batch\setTransformMatrix matrix
matrix_dirty = false
if shapes\isDrawing!
Sauce3VM.util\endShapes shapes
unless batch\isDrawing!
batch\begin!
else
if matrix_dirty
shapes\setTransformMatrix matrix
matrix_dirty = false
if batch\isDrawing!
Sauce3VM.util\endBatch batch
unless shapes\isDrawing!
shapes\begin!
arc = (mode, x, y, radius, a1, a2) ->
check false
shapes\set Constants.shapes[mode]
shapes\arc x, y, radius, (math.deg a1), math.deg a2
circle = (mode, x, y, radius) ->
check false
shapes\set Constants.shapes[mode]
shapes\circle x, y, radius
clear = ->
Gdx.gl\glClearColor background.r, background.g, background.b
Gdx.gl\glClear GL20.GL_COLOR_BUFFER_BIT
draw = (image, x = 0, y = 0, r = 0, sx = 1, sy = 1, ox = 0, oy = 0) ->
check true
w = image\get_width!
h = image\get_height!
src_x = 0
src_y = 0
src_w = w
src_h = h
x -= ox
y -= oy
batch\draw image.texture, x, y, ox, oy, w, h, sx, sy, r, srx_x, srx_y, src_w, src_h, false, true
draw_q = (image, quad, x = 0, y = 0, r = 0, sx = 1, sy = 1, ox = 0, oy = 0) ->
check true
w = quad.w
h = quad.h
src_x = quad.x
src_y = quad.y
src_w = quad.sw
src_h = quad.sh
x -= ox
y -= oy
batch\draw image.texture, x, y, ox, oy, w, h, sx, sy, r, src_x, src_y, src_w, src_h, false, true
ellipse = (mode, x, y, width, height) ->
check false
shapes\set Constants.shapes[mode]
shapes\ellipse x, y, width, height
line = (x1, y1, x2, y2) ->
check false
shapes\line x1, y1, x2, y2
origin = ->
matrix\idt!
matrix_dirty = true
point = (x, y) ->
check false
shapes\point x, y, 0
polygon = (mode, ...) ->
check false
shapes\set Constants.shapes[mode]
args = table.pack ...
if type args[1] == "table"
shapes\polygon args[1]
else
shapes\polygon args
present = ->
if shapes\isDrawing!
Sauce3VM.util\endShapes shapes
if batch\isDrawing!
Sauce3VM.util\endBatch batch
print = (text, x = 0, y = 0, r = 0, sx = 1, sy = 1, ox = 0, oy = 0) ->
check true
local tmp
unless r == 0
tmp = batch\getTransformMatrix!
translate x, y
rotate r
translate -x, -y
batch\setTransformMatrix matrix
matrix_dirty = false
font.font\getData!\setScale sx, -sy
font.font\draw batch, text, x - ox * sx, y - oy * sy
unless r == 0
translate x, y
rotate -r
translate -x, -y
batch\setTransformMatrix tmp
matrix_dirty = false
print_f = (text, width = 0, align = "left", x = 0, y = 0, r = 0, sx = 1, sy = 1, ox = 0, oy = 0) ->
check true
tmp = nil
unless r == 0
tmp = batch\getTransformMatrix!
translate x, y
rotate r
translate -x, -y
batch\setTransformMatrix matrix
matrix_dirty = false
font.font\getData!\setScale sx, -sy
font.font\draw batch, text, x - ox * sx, y - oy * sy, width, Constants.aligns[align], true
unless r == 0
translate x, y
rotate -r
translate -x, -y
batch\setTransformMatrix tmp
matrix_dirty = false
rectangle = (mode, x, y, width, height) ->
check false
shapes\set Constants.shapes[mode]
shapes\rect x, y, width, height
reset = ->
shader = SpriteBatch\createDefaultShader!
batch\setShader shader
background\set 0, 0, 0, 1
color\set 1, 1, 1, 1
batch\setColor color
shapes\setColor color
font.font\setColor color
matrix\idt!
matrix_dirty = true
translate = (x, y) ->
matrix\translate x, y
matrix_dirty = true
rotate = (radians) ->
matrix\rotate 0, 0, 1, math.deg radians
matrix_dirty = true
scale = (sx, sy) ->
matrix\scale sx, sy, 1
matrix_dirty = true
get_background_color = ->
background.r * 255, background.g * 255, background.b * 255
get_blend_mode = ->
blending
get_color = ->
color.r * 255, color.g * 255, color.b * 255, color.a * 255
get_font = ->
font
set_background_color = (r, g, b, a = 255) ->
background\set r / 255, g / 255, b / 255, a / 255
set_blend_mode = (mode) ->
blending = mode
blend_mode = Constants[blending]
batch\setBlendFunction blend_mode[1], blend_mode[2]
set_color = (r, g, b, a = 255) ->
color\set r / 255, g / 255, b / 255, a / 255
batch\setColor color
shapes\setColor color
font.font\setColor color
set_font = (v) ->
font = v
set_new_font = (path, size, f_type) ->
font = new_font path, size, f_type
new_font = (path, size, f_type) ->
(Font path, size, f_type)
new_image = (path, format, f_type) ->
(Image path, format, f_type)
new_quad = (x, y, width, height, sx, sy) ->
(Quad x, y, width, height, sx, sy)
{
:arc
:circle
:clear
:draw
:draw_q
:ellipse
:get_background_color
:get_blendMode
:get_color
:get_font
:line
:origin
:point
:polygon
:present
:print
:print_f
:rectangle
:reset
:translate
:rotate
:scale
:set_background_color
:set_blend_mode
:set_color
:set_font
:set_new_font
:new_font
:new_image
:new_quad
}
| 20.141447 | 99 | 0.654581 |
3e91e57bbc8c1c6615c5c1334ac64c34a37ad42e | 1,018 | import type from _G
import insert, remove from table
import index_of, noop from "novacbn/reactive-moon/util"
READABLE_TYPE = {"Readable"}
export Readable = (start, value) ->
subscribers = {}
get = () ->
return value
set = (new_value) ->
return if new_value == value
value = new_value
subscriber[2]() for subscriber in *subscribers
subscriber[1](value) for subscriber in *subscribers
subscribe = (callback, invalidate=noop) ->
stop = start(get, set) if #subscribers < 1
subscriber = {callback, invalidate}
insert(subscribers, subscriber)
callback(value)
return () ->
index = index_of(subscribers, callback)
remove(subscribers, index) if index
if stop and #subscribers < 0
stop()
stop = nil
return {:READABLE_TYPE, :get, :subscribe}
export is_readable = (value) ->
return type(value) == "table" and value.READABLE_TYPE == READABLE_TYPE | 25.45 | 74 | 0.608055 |
0e9b2e1cd358b4a98e7b041623ed89c251917dee | 17,825 | utility = require('shared.utility')
Page = require('settings.pages.page')
Settings = require('settings.types')
state = {
languages: {}
}
-- Localization
updateLanguages = () ->
path = 'cache\\languages.txt'
state.languages = {}
if io.fileExists(path)
file = io.readFile(path)
for line in *file\splitIntoLines()
continue unless line\endsWith('%.txt')
continue if line == 'languages.txt'
language = line\match('([^%.]+)')
table.insert(state.languages, {
displayValue: language
})
englishListed = false
for language in *state.languages
if language.displayValue == 'English'
englishListed = true
break
unless englishListed
table.insert(state.languages, {
displayValue: 'English'
})
table.sort(state.languages, (a, b) ->
return true if a.displayValue\lower() < b.displayValue\lower()
return false
)
getLanguageIndex = () ->
currentLanguage = COMPONENTS.SETTINGS\getLocalization()
for i, language in ipairs(state.languages)
if language.displayValue == currentLanguage
return i
return 1
-- Slot hover animations
state.slotHoverAnimations = {
{displayValue: LOCALIZATION\get('setting_animation_label_none', 'None')}
{displayValue: LOCALIZATION\get('setting_animation_label_zoom_in', 'Zoom in')}
{displayValue: LOCALIZATION\get('setting_animation_label_jiggle', 'Jiggle')}
{displayValue: LOCALIZATION\get('setting_animation_label_shake_left_right', 'Shake left and right')}
{displayValue: LOCALIZATION\get('setting_animation_label_shake_up_down', 'Shake up and down')}
}
-- Slot click animations
state.slotClickAnimations = {
{displayValue: LOCALIZATION\get('setting_animation_label_none', 'None')}
{displayValue: LOCALIZATION\get('setting_animation_label_slide_up', 'Slide upwards')}
{displayValue: LOCALIZATION\get('setting_animation_label_slide_right', 'Slide to the right')}
{displayValue: LOCALIZATION\get('setting_animation_label_slide_down', 'Slide downwards')}
{displayValue: LOCALIZATION\get('setting_animation_label_slide_left', 'Slide to the left')}
{displayValue: LOCALIZATION\get('setting_animation_label_shrink', 'Shrink')}
}
-- Skin animations
state.skinAnimations = {
{displayValue: LOCALIZATION\get('setting_animation_label_none', 'None')}
{displayValue: LOCALIZATION\get('setting_animation_label_slide_up', 'Slide upwards')}
{displayValue: LOCALIZATION\get('setting_animation_label_slide_right', 'Slide to the right')}
{displayValue: LOCALIZATION\get('setting_animation_label_slide_down', 'Slide downwards')}
{displayValue: LOCALIZATION\get('setting_animation_label_slide_left', 'Slide to the left')}
}
-- Game detection frequencies
state.gameDetectionFrequencies = {
{displayValue: LOCALIZATION\get('setting_game_detection_frequency_never', 'Never')}
{displayValue: LOCALIZATION\get('setting_game_detection_frequency_always', 'Always')}
{displayValue: LOCALIZATION\get('setting_game_detection_frequency_once_per_day', 'Once per day')}
}
-- Slot overlay text options
state.slotsOverlayTextOptions = {
{displayValue: LOCALIZATION\get('setting_slots_overlay_text_option_none', 'Nothing')}
{displayValue: LOCALIZATION\get('setting_slots_overlay_text_option_game_title', 'Title')}
{displayValue: LOCALIZATION\get('setting_slots_overlay_text_option_game_platform', 'Platform')}
{displayValue: LOCALIZATION\get('setting_slots_overlay_text_option_time_played_hours', 'Hours played')}
{displayValue: LOCALIZATION\get('setting_slots_overlay_text_option_time_played_hours_and_minutes', 'Hours and minutes played')}
{displayValue: LOCALIZATION\get('setting_slots_overlay_text_option_time_played_hours_or_minutes', 'Hours or minutes played')}
{displayValue: LOCALIZATION\get('setting_slots_overlay_text_option_last_played_yyyymmdd', 'Last played (YYYY-MM-DD)')}
{displayValue: LOCALIZATION\get('setting_slots_overlay_text_option_notes', 'Notes')}
}
class Skin extends Page
new: () =>
super()
@title = LOCALIZATION\get('setting_skin_title', 'Skin')
updateLanguages()
@settings = {
Settings.Boolean({
title: LOCALIZATION\get('setting_slots_horizontal_orientation_title', 'Horizontal orientation')
tooltip: LOCALIZATION\get('setting_slots_horizontal_orientation_description', 'If enabled, then slots are placed from left to right. If disabled, then slots are placed from the top to the bottom.')
toggle: () ->
COMPONENTS.SETTINGS\toggleLayoutHorizontal()
return true
getState: () ->
return COMPONENTS.SETTINGS\getLayoutHorizontal()
})
Settings.Integer({
title: LOCALIZATION\get('setting_slots_rows_title', 'Number of rows')
tooltip: LOCALIZATION\get('setting_slots_rows_description', 'The number of rows of slots.')
defaultValue: COMPONENTS.SETTINGS\getLayoutRows()
minValue: 1
maxValue: 16
onValueChanged: (value) =>
COMPONENTS.SETTINGS\setLayoutRows(value)
})
Settings.Integer({
title: LOCALIZATION\get('setting_slots_columns_title', 'Number of columns')
tooltip: LOCALIZATION\get('setting_slots_columns_description', 'The number of columns of slots.')
defaultValue: COMPONENTS.SETTINGS\getLayoutColumns()
minValue: 1
maxValue: 16
onValueChanged: (value) =>
COMPONENTS.SETTINGS\setLayoutColumns(value)
})
Settings.Integer({
title: LOCALIZATION\get('setting_slots_width_title', 'Slot width')
tooltip: LOCALIZATION\get('setting_slots_width_description', 'The width of each slot in pixels.')
defaultValue: COMPONENTS.SETTINGS\getLayoutWidth()
minValue: 144
maxValue: 1280
onValueChanged: (value) =>
COMPONENTS.SETTINGS\setLayoutWidth(value)
})
Settings.Integer({
title: LOCALIZATION\get('setting_slots_height_title', 'Slot height')
tooltip: LOCALIZATION\get('setting_slots_height_description', 'The height of each slot in pixels.')
defaultValue: COMPONENTS.SETTINGS\getLayoutHeight()
minValue: 48
maxValue: 600
onValueChanged: (value) =>
COMPONENTS.SETTINGS\setLayoutHeight(value)
})
Settings.Boolean({
title: LOCALIZATION\get('setting_slots_overlay_enabled_title', 'Show overlays on slots')
tooltip: LOCALIZATION\get('setting_slots_overlay_enabled_description', 'If enabled, then an overlay with contextual information is displayed when the mouse is on a slot.')
toggle: () ->
COMPONENTS.SETTINGS\toggleSlotsOverlayEnabled()
return true
getState: () ->
return COMPONENTS.SETTINGS\getSlotsOverlayEnabled()
})
Settings.Boolean({
title: LOCALIZATION\get('setting_slots_overlay_images_enabled_title', 'Show images on slot overlays')
tooltip: LOCALIZATION\get('setting_slots_overlay_images_enabled_description', 'If enabled, then context-sensitive images are used in the slot overlays.')
toggle: () ->
COMPONENTS.SETTINGS\toggleSlotsOverlayImagesEnabled()
return true
getState: () ->
return COMPONENTS.SETTINGS\getSlotsOverlayImagesEnabled()
})
Settings.Spinner({
title: LOCALIZATION\get('setting_slots_overlay_upper_text_title', 'Slot overlay upper text')
tooltip: LOCALIZATION\get('setting_slots_overlay_upper_text_description', 'The text that is shown on the upper half of the slot overlay.')
index: COMPONENTS.SETTINGS\getSlotsOverlayUpperText()
setIndex: (index) =>
if index < 1
index = #@getValues()
elseif index > #@getValues()
index = 1
@index = index
COMPONENTS.SETTINGS\setSlotsOverlayUpperText(index)
getValues: () =>
return state.slotsOverlayTextOptions
setValues: () =>
return
})
Settings.Spinner({
title: LOCALIZATION\get('setting_slots_overlay_lower_text_title', 'Slot overlay lower text')
tooltip: LOCALIZATION\get('setting_slots_overlay_lower_text_description', 'The text that is shown on the lower half of the slot overlay.')
index: COMPONENTS.SETTINGS\getSlotsOverlayLowerText()
setIndex: (index) =>
if index < 1
index = #@getValues()
elseif index > #@getValues()
index = 1
@index = index
COMPONENTS.SETTINGS\setSlotsOverlayLowerText(index)
getValues: () =>
return state.slotsOverlayTextOptions
setValues: () =>
return
})
Settings.Spinner({
title: LOCALIZATION\get('setting_slots_hover_animation_title', 'Slot hover animation')
tooltip: LOCALIZATION\get('setting_slots_hover_animation_description', 'The animation that plays when the mouse is on a slot.')
index: COMPONENTS.SETTINGS\getSlotsHoverAnimation()
setIndex: (index) =>
if index < 1
index = #@getValues()
elseif index > #@getValues()
index = 1
@index = index
COMPONENTS.SETTINGS\setSlotsHoverAnimation(index)
getValues: () =>
return state.slotHoverAnimations
setValues: () =>
return
})
Settings.Spinner({
title: LOCALIZATION\get('setting_slots_click_animation_title', 'Slot click animation')
tooltip: LOCALIZATION\get('setting_slots_click_animation_description', 'The animation that plays when a slot is clicked.')
index: COMPONENTS.SETTINGS\getSlotsClickAnimation()
setIndex: (index) =>
if index < 1
index = #@getValues()
elseif index > #@getValues()
index = 1
@index = index
COMPONENTS.SETTINGS\setSlotsClickAnimation(index)
getValues: () =>
return state.slotClickAnimations
setValues: () =>
return
})
Settings.Boolean({
title: LOCALIZATION\get('setting_slots_double_click_to_launch_title', 'Double-click to launch.')
tooltip: LOCALIZATION\get('setting_slots_double_click_to_launch_description', 'If enabled, then a game has to be double-clicked to launched.')
toggle: () ->
COMPONENTS.SETTINGS\toggleDoubleClickToLaunch()
return true
getState: () ->
return COMPONENTS.SETTINGS\getDoubleClickToLaunch()
})
Settings.Spinner({
title: LOCALIZATION\get('setting_skin_animation_title', 'Skin animation')
tooltip: LOCALIZATION\get('setting_skin_animation_description', 'The animation that is played when the mouse leaves the skin. The animation is played in reverse when the mouse enters the skin\'s enabler edge.')
index: COMPONENTS.SETTINGS\getSkinSlideAnimation()
setIndex: (index) =>
if index < 1
index = #@getValues()
elseif index > #@getValues()
index = 1
@index = index
COMPONENTS.SETTINGS\setSkinSlideAnimation(index)
getValues: () =>
return state.skinAnimations
setValues: () =>
return
})
Settings.Integer({
title: LOCALIZATION\get('setting_skin_revealing_delay_title', 'Revealing delay')
tooltip: LOCALIZATION\get('setting_skin_revealing_delay_description', 'The duration (in milliseconds) before the skin animation is played in order to reveal the skin.')
defaultValue: COMPONENTS.SETTINGS\getSkinRevealingDelay()
minValue: 0
maxValue: 10000
stepValue: 16
onValueChanged: (value) =>
COMPONENTS.SETTINGS\setSkinRevealingDelay(value)
})
Settings.Integer({
title: LOCALIZATION\get('setting_skin_scroll_step_title', 'Scroll step')
tooltip: LOCALIZATION\get('setting_skin_scroll_step_description', 'The number of games that are scrolled at each scroll event.')
defaultValue: COMPONENTS.SETTINGS\getScrollStep()
minValue: 1
maxValue: 100
onValueChanged: (value) =>
COMPONENTS.SETTINGS\setScrollStep(value)
})
Settings.Boolean({
title: LOCALIZATION\get('setting_slots_toolbar_at_top_title', 'Toolbar at the top')
tooltip: LOCALIZATION\get('setting_slots_toolbar_at_top_description', 'If enabled, then the toolbar is at the top of the skin.')
toggle: () ->
COMPONENTS.SETTINGS\toggleLayoutToolbarAtTop()
return true
getState: () ->
return COMPONENTS.SETTINGS\getLayoutToolbarAtTop()
})
Settings.Boolean({
title: LOCALIZATION\get('setting_slots_center_on_monitor_title', 'Center windows on the current monitor')
tooltip: LOCALIZATION\get('setting_slots_center_on_monitor_description', 'If enabled, then some windows (e.g. sort, filter) are centered on the monitor that the main window of this skin is on.')
toggle: () ->
COMPONENTS.SETTINGS\toggleCenterOnMonitor()
return true
getState: () ->
return COMPONENTS.SETTINGS\getCenterOnMonitor()
})
Settings.Boolean({
title: LOCALIZATION\get('setting_skin_hide_skin_title', 'Hide skin while playing')
tooltip: LOCALIZATION\get('setting_skin_hide_skin_description', 'If enabled, then the skin is hidden while playing a game.')
toggle: () ->
COMPONENTS.SETTINGS\toggleHideSkin()
return true
getState: () ->
return COMPONENTS.SETTINGS\getHideSkin()
})
Settings.Boolean({
title: LOCALIZATION\get('setting_skin_show_session_title', 'Show session skin')
tooltip: LOCALIZATION\get('setting_skin_show_session_description', 'If enabled, then a small skin that shows the current system time and session duration in HH:MM format is loaded for the duration of the game.')
toggle: () ->
COMPONENTS.SETTINGS\toggleShowSession()
return true
getState: () ->
return COMPONENTS.SETTINGS\getShowSession()
})
Settings.Boolean({
title: LOCALIZATION\get('setting_bangs_enabled_title', 'Execute bangs')
tooltip: LOCALIZATION\get('setting_bangs_enabled_description', 'If enabled, then the specified Rainmeter bangs are executed when a game starts or terminates.')
toggle: () =>
COMPONENTS.SETTINGS\toggleBangsEnabled()
return true
getState: () =>
return COMPONENTS.SETTINGS\getBangsEnabled()
})
Settings.Action({
title: LOCALIZATION\get('button_label_starting_bangs', 'Starting bangs')
tooltip: LOCALIZATION\get('setting_bangs_starting_description', 'These Rainmeter bangs are executed just before any game launches.')
label: LOCALIZATION\get('button_label_edit', 'Edit')
perform:() =>
path = 'cache\\bangs.txt'
bangs = COMPONENTS.SETTINGS\getGlobalStartingBangs()
io.writeFile(path, table.concat(bangs, '\n'))
utility.runCommand(('""%s""')\format(io.joinPaths(STATE.PATHS.RESOURCES, path)), '', 'OnEditedGlobalStartingBangs')
})
Settings.Action({
title: LOCALIZATION\get('button_label_stopping_bangs', 'Stopping bangs')
tooltip: LOCALIZATION\get('setting_bangs_stopping_description', 'These Rainmeter bangs are executed just after any game terminates.')
label: LOCALIZATION\get('button_label_edit', 'Edit')
perform:() =>
path = 'cache\\bangs.txt'
bangs = COMPONENTS.SETTINGS\getGlobalStoppingBangs()
io.writeFile(path, table.concat(bangs, '\n'))
utility.runCommand(('""%s""')\format(io.joinPaths(STATE.PATHS.RESOURCES, path)), '', 'OnEditedGlobalStoppingBangs')
})
Settings.Boolean({
title: LOCALIZATION\get('setting_search_uninstalled_games_enabled_title', 'Include uninstalled games in search results')
tooltip: LOCALIZATION\get('setting_search_uninstalled_games_enabled_description', 'If enabled, then uninstalled games are included in the results when searching by name among all games.')
toggle: () ->
COMPONENTS.SETTINGS\toggleSearchUninstalledGamesEnabled()
return true
getState: () ->
return COMPONENTS.SETTINGS\getSearchUninstalledGamesEnabled()
})
Settings.Boolean({
title: LOCALIZATION\get('setting_search_hidden_games_enabled_title', 'Include hidden games in search results')
tooltip: LOCALIZATION\get('setting_search_hidden_games_enabled_description', 'If enabled, then hidden games are included in the results when searching by name among all games.')
toggle: () ->
COMPONENTS.SETTINGS\toggleSearchHiddenGamesEnabled()
return true
getState: () ->
return COMPONENTS.SETTINGS\getSearchHiddenGamesEnabled()
})
Settings.Spinner({
title: LOCALIZATION\get('setting_localization_language_title', 'Language')
tooltip: LOCALIZATION\get('setting_localization_language_description', 'Select a language.')
index: getLanguageIndex()
setIndex: (index) =>
if index < 1
index = #@getValues()
elseif index > #@getValues()
index = 1
@index = index
language = @getValues()[@index]
COMPONENTS.SETTINGS\setLocalization(language.displayValue)
setValues: () =>
updateLanguages()
@setIndex(getLanguageIndex())
getValues: () =>
return state.languages
})
Settings.Integer({
title: LOCALIZATION\get('setting_number_of_backups_title', 'Number of backups')
tooltip: LOCALIZATION\get('setting_number_of_backups_description', 'The number of daily backups to keep of the list of games.')
defaultValue: COMPONENTS.SETTINGS\getNumberOfBackups()
minValue: 0
maxValue: 100
onValueChanged: (value) =>
COMPONENTS.SETTINGS\setNumberOfBackups(value)
})
Settings.Spinner({
title: LOCALIZATION\get('setting_game_detection_frequency_title', 'Game detection frequency')
tooltip: LOCALIZATION\get('setting_game_detection_frequency_description', 'How often the skin should attempt to detect games when the skin is loaded. Game detection can also be triggered manually via the context menu.')
index: COMPONENTS.SETTINGS\getGameDetectionFrequency()
setIndex: (index) =>
if index < 1
index = #@getValues()
elseif index > #@getValues()
index = 1
@index = index
COMPONENTS.SETTINGS\setGameDetectionFrequency(index)
getValues: () =>
return state.gameDetectionFrequencies
setValues: () =>
return
})
Settings.Boolean({
title: LOCALIZATION\get('setting_logging_title', 'Log')
tooltip: LOCALIZATION\get('setting_logging_description', 'If enabled, then a bunch of messages are printed to the Rainmeter log. Useful when troubleshooting issues.')
toggle: () =>
COMPONENTS.SETTINGS\toggleLogging()
return true
getState: () =>
return COMPONENTS.SETTINGS\getLogging()
})
}
return Skin
| 44.012346 | 223 | 0.734811 |
d8bd9bbb6aa989ac4675e551585a4aafe98463d3 | 1,863 | import Signal from require "lib/core/signal"
import Scheduler from require "lib/core/scheduler"
class Object
new: (t = {}) =>
@type = "Object"
@name
@scheduler = @_opt t.scheduler, Scheduler!
@signals = {}
@getters = {}
@setters = {}
if t.properties
for prop in *t.properties
@property prop[1], prop[2], prop[3]
if t.signals
for signals in *t.signals
@add_signal signal
_opt: (v, def) =>
if v == nil
return def
v
property: (name, getter, setter) =>
@getters[name] = @[getter]
@setters[name] = @[setter]
get: (name) =>
if @getters[name]
return @getters[name] @
@[name]
set: (name, value) =>
if @setters[name]
return @setters[name] @, value
@[name] = value
value
add_signal: (name) =>
unless @signals[name] == nil
error "Why would you add #{name} more than once?"
@signals[name] = Signal @scheduler
connect: (name, event, one_shot = false, differed = false) =>
if @signals[name] == nil
error "Why would you connect non-existent signal - #{name}?"
@signals[name]\connect event, one_shot, differed
_connect: (name, event, one_shot = false, differed = false) =>
if @signals[name] == nil
error "Why would you connect non-existent signal - #{name}?"
obj = @
event = (...) ->
obj[method] obj, ...
@signals[name]\connect event, one_shot, differed
event
disconnect: (name, event) =>
if @signals[name] == nil
error "Why would you disconnect non-existent signal - #{name}?"
@signals[name]\disconnect event
emit: (name, ...) =>
if @signals[name] != nil
error "Why would you emit non-existent signal - #{name}?"
@signals[name] ...
{
:Object
}
| 23 | 71 | 0.557703 |
44af9df483c44ca79e06d1159dde25b617ee78c6 | 7,347 | -- Copyright 2012-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
_G = _G
import table, coroutine, pairs from _G
import pcall, callable, setmetatable, typeof, tostring from _G
import signal, command, sys from howl
append = table.insert
signal.register 'key-press',
description: [[Signaled right after a key is pressed.
If any handler returns true, the key press is considered to be handled, and any subsequent
processing is skipped.
]]
parameters:
event: 'The event for the key press'
translations: 'A list of readable translations for the key event'
source: 'The source of the key press (e.g. "editor")'
parameters: 'Other source specific parameters (e.g. an editor for source = "editor")'
_ENV = {}
setfenv(1, _ENV) if setfenv
capture_handler = nil
keymap_options = setmetatable {}, __mode: 'k'
export keymaps = {}
export is_capturing = false
alternate_names = {
kp_up: 'up'
kp_down: 'down'
kp_left: 'left'
kp_right: 'right'
kp_page_up: 'page_up'
kp_page_down: 'page_down'
kp_home: 'home'
kp_end: 'end'
kp_insert: 'insert'
kp_delete: 'delete'
kp_enter: { 'return', 'enter' }
iso_left_tab: 'tab'
return: 'enter'
enter: 'return'
altL: 'alt'
altR: 'alt'
shiftL: 'shift'
shiftR: 'shift'
ctrlL: 'ctrl'
ctrlR: 'ctrl'
metaL: 'meta'
metaR: 'meta'
superL: 'super'
superR: 'super'
hyperL: 'hyper'
hyperR: 'hyper'
}
substituted_names = {
meta_l: 'metaL'
meta_r: 'metaR'
alt_l: 'altL'
alt_r: 'altR'
shift_l: 'shiftL'
shift_r: 'shiftR'
control_l: 'ctrlL'
control_r: 'ctrlR'
super_l: 'superL'
super_r: 'superR'
kp_prior: 'kp_page_up'
kp_next: 'kp_page_down'
hyper_l: 'hyperL'
hyper_r: 'hyperR'
}
modifier_keys = {
'alt',
'shift',
'ctrl',
'meta',
'super',
'hyper',
'iso_level3_shift',
'iso_level5_shift',
}
substitute_keyname = (event) ->
key_name = substituted_names[event.key_name]
return event unless key_name
copy = {k,v for k,v in pairs event}
copy.key_name = key_name
copy
export action_for = (tr, source='editor') ->
os = sys.info.os
empty = {}
for i = #keymaps, 1, -1
km = keymaps[i]
continue unless km
source_km = km[source] or empty
os_map = km.for_os and km.for_os[os] or empty
os_source_map = os_map[source] or empty
handler = os_source_map[tr] or os_map[tr] or source_km[tr] or km[tr]
return handler if handler
nil
find_handlers = (event, source, translations, maps_to_search, ...) ->
handlers = {}
empty = {}
os = sys.info.os
for map in *maps_to_search
continue unless map
source_map = map[source] or empty
handler = nil
map_binding_for = map.binding_for
source_map_binding_for = source_map.binding_for
os_map = map.for_os and map.for_os[os] or empty
os_source_map = os_map[source] or empty
for t in *translations
handler = os_source_map[t] or source_map[t] or os_map[t] or map[t]
break if handler
if source_map_binding_for or map_binding_for
cmd = action_for t
if typeof(cmd) == 'string'
handler = source_map_binding_for and source_map_binding_for[cmd]
break if handler
handler = map_binding_for and map_binding_for[cmd]
break if handler
if not handler and callable map.on_unhandled
handler = map.on_unhandled event, source, translations, ...
append handlers, handler if handler
opts = keymap_options[map] or {}
return handlers, map, opts if opts.block or opts.pop
handlers
export cancel_capture = ->
capture_handler = nil
is_capturing = false
process_capture = (event, source, translations, ...) ->
if capture_handler
status, ret = pcall capture_handler, event, source, translations, ...
if not status or ret != false
cancel_capture!
_G.log.error ret unless status
return true
export push = (km, options = {}) ->
append keymaps, km
keymap_options[km] = options
export remove = (map) ->
error "No bindings in stack" unless #keymaps > 0
for i = 1, #keymaps
if keymaps[i] == map
keymap_options[map] = nil
table.remove keymaps, i
return true
false
export pop = ->
remove keymaps[#keymaps]
export translate_key = (event) ->
ctrl = (event.control and 'ctrl_') or ''
shift = (event.shift and 'shift_') or ''
alt = (event.alt and 'alt_') or ''
meta = (event.meta and 'meta_') or ''
super = (event.super and 'super_') or ''
event = substitute_keyname event
alternate = alternate_names[event.key_name]
translations = {}
character = event.character
if event.lock and character
if event.shift
character = character.uupper
else
character = character.ulower
append translations, ctrl .. meta .. super .. alt .. character if character
modifiers = ctrl .. meta .. super .. shift .. alt
if event.key_name and event.key_name != character
append translations, modifiers .. event.key_name
if typeof(alternate) == 'table'
for a in *alternate
append translations, modifiers .. a
elseif alternate
append translations, modifiers .. alternate
append translations, modifiers .. event.key_code
translations
export is_modifier = (translations) ->
for translation in *translations
for modifier in *modifier_keys
if translation == modifier
return true
return false
export dispatch = (event, source, maps_to_search, ...) ->
event = substitute_keyname event
translations = translate_key event
handlers, halt_map, map_opts = find_handlers event, source, translations, maps_to_search, ...
remove halt_map if halt_map and map_opts.pop
for handler in *handlers
status, ret = true, true
htype = typeof handler
f = if htype == 'string'
-> command.run handler
elseif callable handler
(...) -> handler ...
if f
co = coroutine.create f
status, ret = coroutine.resume co, ...
elseif htype == 'table'
push handler, pop: true
else
_G.log.error "Illegal handler: type #{htype}"
_G.log.error ret unless status
return true if not status or (status and ret != false)
false
export can_dispatch = (event, source, maps_to_search) ->
event = substitute_keyname event
translations = translate_key event
handlers = find_handlers event, source, translations, maps_to_search
return #handlers > 0
export process = (event, source, extra_keymaps = {}, ...) ->
event = substitute_keyname event
translations = translate_key event
return true if process_capture event, source, translations, ...
emit_result = signal.emit 'key-press', :event, :source, :translations, parameters: {...}
return true if emit_result == signal.abort
maps = {}
append maps, map for map in *extra_keymaps
for i = #keymaps, 1, -1
append maps, keymaps[i]
dispatch event, source, maps, ...
export capture = (handler) ->
capture_handler = handler
is_capturing = true
export keystrokes_for = (handler, source = nil) ->
keystrokes = {}
for i = #keymaps, 1, -1
km = keymaps[i]
source_km = km[source]
if source_km
for keystroke, h in pairs source_km
if h == handler
append keystrokes, keystroke
for keystroke, h in pairs km
if h == handler
append keystrokes, keystroke
keystrokes
return _ENV
| 25.510417 | 95 | 0.67565 |
8f31c2a9e3d1007c9e093e2f95062fd17241f4ec | 320 | make = (x, y, key) ->
block = {
:x, :y
w: 20
h: 20
:key
}
block.draw = =>
with love.graphics
.setColor 0, 0, 0
if @key == "jump"
.setColor 0, 1, 0
if @key == "die"
.setColor 1, 0, 0
.rectangle "fill", @x, @y, @w, @h
block
{
:make
} | 10 | 39 | 0.39375 |
902e0840faa43629ea0306f2b58f4b0fb8ecb564 | 31 | require "lapis.db.mysql.schema" | 31 | 31 | 0.806452 |
d88f5e703a314068f89302ef34bb624adc68b37b | 8,355 |
logger = require "lapis.logging"
lapis_config = require "lapis.config"
import Router from require "lapis.router"
import insert from table
json = require "cjson"
local capture_errors, capture_errors_json, respond_to
run_before_filter = (filter, r) ->
_write = r.write
written = false
r.write = (...) ->
written = true
_write ...
filter r
r.write = nil
written
class Application
Request: require "lapis.request"
layout: require "lapis.views.layout"
error_page: require "lapis.views.error"
views_prefix: "views"
flows_prefix: "flows"
-- find action for named route in this application
@find_action: (name) =>
@_named_route_cache or= {}
route = @_named_route_cache[name]
-- update the cache
unless route
for app_route in pairs @__base
if type(app_route) == "table"
app_route_name = next app_route
@_named_route_cache[app_route_name] = app_route
route = app_route if app_route_name == name
route and @[route], route
new: =>
@build_router!
enable: (feature) =>
fn = require "lapis.features.#{feature}"
if type(fn) == "function"
fn @
match: (route_name, path, handler) =>
if handler == nil
handler = path
path = route_name
route_name = nil
@ordered_routes or= {}
key = if route_name
tuple = @ordered_routes[route_name]
if old_path = tuple and tuple[next(tuple)]
if old_path != path
error "named route mismatch (#{old_path} != #{path})"
if tuple
tuple
else
tuple = {[route_name]: path}
@ordered_routes[route_name] = tuple
tuple
else
path
unless @[key]
insert @ordered_routes, key
@[key] = handler
@router = nil
handler
for meth in *{"get", "post", "delete", "put"}
upper_meth = meth\upper!
@__base[meth] = (route_name, path, handler) =>
if handler == nil
handler = path
path = route_name
route_name = nil
@responders or= {}
existing = @responders[route_name or path]
tbl = { [upper_meth]: handler }
if existing
setmetatable tbl, __index: (key) =>
existing if key\match "%u"
responder = respond_to tbl
@responders[route_name or path] = responder
@match route_name, path, responder
build_router: =>
@router = Router!
@router.default_route = => false
add_route = (path, handler) ->
t = type path
if t == "table" or t == "string" and path\match "^/"
@router\add_route path, @wrap_handler handler
add_routes = (cls) ->
for path, handler in pairs cls.__base
add_route path, handler
if ordered = @ordered_routes
for path in *ordered
add_route path, @[path]
else
for path, handler in pairs @
add_route path, handler
if parent = cls.__parent
add_routes parent
add_routes @@
wrap_handler: (handler) =>
(params, path, name, r) ->
support = r.__class.support
with r
.route_name = name
support.add_params r, r.req.params_get, "GET"
support.add_params r, r.req.params_post, "POST"
support.add_params r, params, "url_params"
if @before_filters
for filter in *@before_filters
return r if run_before_filter filter, r
\write handler r
render_request: (r) =>
r.__class.support.render r
logger.request r
render_error_request: (r, err, trace) =>
config = lapis_config.get!
r\write @.handle_error r, err, trace
if config._name == "test"
r.options.headers or= {}
param_dump = logger.flatten_params r.original_request.url_params
error_payload = {
summary: "[#{r.original_request.req.cmd_mth}] #{r.original_request.req.cmd_url} #{param_dump}"
:err, :trace
}
import to_json from require "lapis.util"
r.options.headers["X-Lapis-Error"] = to_json error_payload
r.__class.support.render r
logger.request r
dispatch: (req, res) =>
local err, trace, r
success = xpcall (->
r = @.Request @, req, res
unless @router\resolve req.parsed_url.path, r
-- run default route if nothing matched
handler = @wrap_handler @default_route
handler {}, nil, "default_route", r
@render_request r),
(_err) ->
err = _err
trace = debug.traceback "", 2
unless success
-- create a new request to handle the rendering the error
error_request = @.Request @, req, res
error_request.original_request = r
@render_error_request error_request, err, trace
success, r
@before_filter: (...) =>
@__base.before_filter @__base, ...
before_filter: (fn) =>
unless rawget @, "before_filters"
@before_filters = {}
insert @before_filters, fn
-- copies all actions into this application, preserves before filters
-- @include other_app, path: "/hello", name: "hello_"
@include: (other_app, opts, into=@__base) =>
if type(other_app) == "string"
other_app = require other_app
path_prefix = opts and opts.path or other_app.path
name_prefix = opts and opts.name or other_app.name
for path, action in pairs other_app.__base
t = type path
if t == "table"
if path_prefix
name = next path
path[name] = path_prefix .. path[name]
if name_prefix
name = next path
path[name_prefix .. name] = path[name]
path[name] = nil
elseif t == "string" and path\match "^/"
if path_prefix
path = path_prefix .. path
else
continue
if before_filters = other_app.before_filters
fn = action
action = (r) ->
for filter in *before_filters
return if run_before_filter filter, r
fn r
into[path] = action
-- Callbacks
-- run with Request as self, instead of application
default_route: =>
-- strip trailing /
if @req.parsed_url.path\match "./$"
stripped = @req.parsed_url.path\match "^(.+)/+$"
redirect_to: @build_url(stripped, query: @req.parsed_url.query), status: 301
else
@app.handle_404 @
handle_404: =>
error "Failed to find route: #{@req.cmd_url}"
handle_error: (err, trace) =>
@status = 500
@err = err
@trace = trace
{
status: 500
layout: false
render: @app.error_page
}
cookie_attributes: (name, value) =>
"Path=/; HttpOnly"
respond_to = do
default_head = -> layout: false -- render nothing
(tbl) ->
tbl.HEAD = default_head unless tbl.HEAD
out = =>
fn = tbl[@req.cmd_mth]
if fn
if before = tbl.before
return if run_before_filter before, @
fn @
else
error "don't know how to respond to #{@req.cmd_mth}"
if error_response = tbl.on_error
out = capture_errors out, error_response
out
default_error_response = -> { render: true }
capture_errors = (fn, error_response=default_error_response) ->
if type(fn) == "table"
error_response = fn.on_error or error_response
fn = fn[1]
(...) =>
co = coroutine.create fn
out = { coroutine.resume co, @ }
unless out[1] -- error
error debug.traceback co, out[2]
-- { status, "error", error_msgs }
if coroutine.status(co) == "suspended"
if out[2] == "error"
@errors = out[3]
error_response @
else -- yield to someone else
error "Unknown yield"
else
unpack out, 2
capture_errors_json = (fn) ->
capture_errors fn, => {
json: { errors: @errors }
}
yield_error = (msg) ->
coroutine.yield "error", {msg}
assert_error = (thing, msg, ...) ->
yield_error msg unless thing
thing, msg, ...
json_params = (fn) ->
(...) =>
if content_type = @req.headers["content-type"]
-- Header often ends with ;UTF-8
if string.find content_type\lower!, "application/json", nil, true
ngx.req.read_body!
local obj
pcall -> obj, err = json.decode ngx.req.get_body_data!
@@support.add_params @, obj, "json" if obj
fn @, ...
{
Request: Application.Request
:Application, :respond_to
:capture_errors, :capture_errors_json
:json_params, :assert_error, :yield_error
}
| 24.287791 | 102 | 0.60766 |
73ca5735efe8946cf80f43dacbb8fc51d7a31d3d | 21,336 | -- Downloaded from github.com/leafo/tableshape on 22 Aug 2019
-- Original was modified to load into the global space, since Garry's Mod doesn't support Lua best practices
local OptionalType, TaggedType, types
-- metatable to identify arrays for merging
FailedTransform = {}
unpack = unpack or table.unpack
-- make a clone of state for insertion
clone_state = (state_obj) ->
-- uninitialized state
if type(state_obj) != "table"
return {}
-- shallow copy
out = {k, v for k, v in pairs state_obj}
if mt = getmetatable state_obj
setmetatable out, mt
out
local BaseType, TransformNode, SequenceNode, FirstOfNode, DescribeNode, NotType
describe_literal = (val) ->
switch type(val)
when "string"
if not val\match '"'
"\"#{val}\""
elseif not val\match "'"
"'#{val}'"
else
"`#{val}`"
else
if BaseType\is_base_type val
val\_describe!
else
tostring val
join_names = (items, sep=", ", last_sep) ->
count = #items
chunks = {}
for idx, name in ipairs items
if idx > 1
current_sep = if idx == count
last_sep or sep
else
sep
table.insert chunks, current_sep
table.insert chunks, name
table.concat chunks
class BaseType
@is_base_type: (val) =>
return false unless type(val) == "table"
cls = val and val.__class
return false unless cls
return true if BaseType == cls
@is_base_type cls.__parent
@__inherited: (cls) =>
cls.__base.__call = cls.__call
cls.__base.__eq = @__eq
cls.__base.__div = @__div
cls.__base.__mod = @__mod
cls.__base.__mul = @__mul
cls.__base.__add = @__add
cls.__base.__unm = @__unm
mt = getmetatable cls
create = mt.__call
mt.__call = (cls, ...) ->
ret = create cls, ...
if ret.opts and ret.opts.optional
ret\is_optional!
else
ret
__eq: (other) =>
if BaseType\is_base_type other
other @
else
@ other[1]
__div: (fn) =>
TransformNode @, fn
__mod: (fn) =>
with TransformNode @, fn
.with_state = true
__mul: (right) =>
SequenceNode @, right
__add: (right) =>
if @__class == FirstOfNode
options = { unpack @options }
table.insert options, right
FirstOfNode unpack options
else
FirstOfNode @, right
__unm: (right) =>
NotType right
_describe: =>
error "Node missing _describe: #{@@__name}"
new: =>
if @opts
@_describe = @opts.describe
-- like repair but only returns true or false
check_value: (...) =>
value, state_or_err = @_transform ...
if value == FailedTransform
return nil, state_or_err
if type(state_or_err) == "table"
state_or_err
else
true
transform: (...) =>
value, state_or_err = @_transform ...
if value == FailedTransform
return nil, state_or_err
if type(state_or_err) == "table"
value, state_or_err
else
value
-- alias for transform
repair: (...) => @transform ...
on_repair: (fn) =>
(@ + types.any / fn * @)\describe -> @_describe!
is_optional: =>
OptionalType @
describe: (...) =>
DescribeNode @, ...
tag: (name) =>
TaggedType @, {
tag: name
}
clone_opts: (merge) =>
opts = if @opts
{k,v for k,v in pairs @opts}
else
{}
if merge
for k, v in pairs merge
opts[k] = v
opts
__call: (...) =>
@check_value ...
-- done with the division operator
class TransformNode extends BaseType
@transformer: true
new: (@node, @t_fn) =>
assert @node, "missing node for transform"
_describe: =>
@.node\_describe!
_transform: (value, state) =>
value, state_or_err = @.node\_transform value, state
if value == FailedTransform
FailedTransform, state_or_err
else
out = switch type @.t_fn
when "function"
if @with_state
@.t_fn(value, state_or_err)
else
@.t_fn(value)
else
@.t_fn
out, state_or_err
class SequenceNode extends BaseType
@transformer: true
new: (...) =>
@sequence = {...}
_describe: =>
item_names = for i in *@sequence
if type(i) == "table" and i._describe
i\_describe!
else
describe_literal i
join_names item_names, " then "
_transform: (value, state) =>
for node in *@sequence
value, state = node\_transform value, state
if value == FailedTransform
break
value, state
class FirstOfNode extends BaseType
@transformer: true
new: (...) =>
@options = {...}
_describe: =>
item_names = for i in *@options
if type(i) == "table" and i._describe
i\_describe!
else
describe_literal i
join_names item_names, ", ", ", or "
_transform: (value, state) =>
unless @options[1]
return FailedTransform, "no options for node"
for node in *@options
new_val, new_state = node\_transform value, state
unless new_val == FailedTransform
return new_val, new_state
FailedTransform, "expected #{@_describe!}"
class DescribeNode extends BaseType
new: (@node, describe) =>
local err_message
if type(describe) == "table"
{type: describe, error: err_message} = describe
@_describe = if type(describe) == "string"
-> describe
else
describe
@err_handler = if err_message
if type(err_message) == "string"
-> err_message
else
err_message
_transform: (input, ...) =>
value, state = @node\_transform input, ...
if value == FailedTransform
err = if @err_handler
@.err_handler input, state
else
"expected #{@_describe!}"
return FailedTransform, err
value, state
describe: (...) =>
DescribeNode @node, ...
class TaggedType extends BaseType
new: (@base_type, opts) =>
@tag_name = assert opts.tag, "tagged type missing tag"
@tag_type = type @tag_name
if @tag_type == "string"
if @tag_name\match "%[%]$"
@tag_name = @tag_name\sub 1, -3
@tag_array = true
update_state: (state, value, ...) =>
out = clone_state state
if @tag_type == "function"
if select("#", ...) > 0
@.tag_name out, ..., value
else
@.tag_name out, value
else
if @tag_array
existing = out[@tag_name]
if type(existing) == "table"
copy = {k,v for k,v in pairs existing}
table.insert copy, value
out[@tag_name] = copy
else
out[@tag_name] = { value }
else
out[@tag_name] = value
out
_transform: (value, state) =>
value, state = @base_type\_transform value, state
if value == FailedTransform
return FailedTransform, state
state = @update_state state, value
value, state
_describe: =>
base_description = @base_type\_describe!
"#{base_description} tagged #{describe_literal @tag}"
class TagScopeType extends TaggedType
new: (base_type, opts) =>
if opts
super base_type, opts
else
@base_type = base_type
-- override to control how empty state is created for existing state
create_scope_state: (state) =>
nil
_transform: (value, state) =>
value, scope = @base_type\_transform value, @create_scope_state(state)
if value == FailedTransform
return FailedTransform, scope
if @tag_name
state = @update_state state, scope, value
value, state
class OptionalType extends BaseType
new: (@base_type, @opts) =>
super!
assert BaseType\is_base_type(@base_type), "expected a type checker"
_transform: (value, state) =>
return value, state if value == nil
@base_type\_transform value, state
is_optional: => @
_describe: =>
if @base_type._describe
base_description = @base_type\_describe!
"optional #{base_description}"
class AnyType extends BaseType
_transform: (v, state) => v, state
_describe: => "anything"
-- any type is already optional (accepts nil)
is_optional: => @
-- basic type check
class Type extends BaseType
new: (@t, @opts) =>
if @opts
@length_type = @opts.length
super!
_transform: (value, state) =>
got = type(value)
if @t != got
return FailedTransform, "expected type #{describe_literal @t}, got #{describe_literal got}"
if @length_type
len = #value
res, state = @length_type\_transform len, state
if res == FailedTransform
return FailedTransform, "#{@t} length #{state}, got #{len}"
value, state
length: (left, right) =>
l = if BaseType\is_base_type left
left
else
types.range left, right
Type @t, @clone_opts length: l
_describe: =>
t = "type #{describe_literal @t}"
if @length_type
t ..= " length_type #{@length_type\_describe!}"
t
class ArrayType extends BaseType
new: (@opts) =>
super!
_describe: => "an array"
_transform: (value, state) =>
return FailedTransform, "expecting table" unless type(value) == "table"
k = 1
for i,v in pairs value
unless type(i) == "number"
return FailedTransform, "non number field: #{i}"
unless i == k
return FailedTransform, "non array index, got #{describe_literal i} but expected #{describe_literal k}"
k += 1
value, state
class OneOf extends BaseType
new: (@options, @opts) =>
super!
assert type(@options) == "table",
"expected table for options in one_of"
-- optimize types
fast_opts = types.array_of types.number + types.string
if fast_opts @options
@options_hash = {v, true for v in *@options}
_describe: =>
item_names = for i in *@options
if type(i) == "table" and i._describe
i\_describe!
else
describe_literal i
"#{join_names item_names, ", ", ", or "}"
_transform: (value, state) =>
if @options_hash
if @options_hash[value]
return value, state
else
for item in *@options
return value, state if item == value
if BaseType\is_base_type item
new_value, new_state = item\_transform value, state
continue if new_value == FailedTransform
return new_value, new_state
FailedTransform, "expected #{@_describe!}"
class AllOf extends BaseType
new: (@types, @opts) =>
super!
assert type(@types) == "table", "expected table for first argument"
for checker in *@types
assert BaseType\is_base_type(checker), "all_of expects all type checkers"
_describe: =>
item_names = for i in *@types
if type(i) == "table" and i._describe
i\_describe!
else
describe_literal i
join_names item_names, " and "
_transform: (value, state) =>
for t in *@types
value, state = t\_transform value, state
if value == FailedTransform
return FailedTransform, state
value, state
class ArrayOf extends BaseType
@type_err_message: "expecting table"
new: (@expected, @opts) =>
if @opts
@keep_nils = @opts.keep_nils
@length_type = @opts.length
super!
_describe: =>
"array of #{describe_literal @expected}"
_transform: (value, state) =>
pass, err = types.table value
unless pass
return FailedTransform, err
if @length_type
len = #value
res, state = @length_type\_transform len, state
if res == FailedTransform
return FailedTransform, "array length #{state}, got #{len}"
is_literal = not BaseType\is_base_type @expected
local copy, k
for idx, item in ipairs value
skip_item = false
transformed_item = if is_literal
if @expected != item
return FailedTransform, "array item #{idx}: expected #{describe_literal @expected}"
else
item
else
item_val, state = @expected\_transform item, state
if item_val == FailedTransform
return FailedTransform, "array item #{idx}: #{state}"
if item_val == nil and not @keep_nils
skip_item = true
else
item_val
if transformed_item != item or skip_item
unless copy
copy = [i for i in *value[1, idx - 1]]
k = idx
if copy and not skip_item
copy[k] = transformed_item
k += 1
copy or value, state
class MapOf extends BaseType
new: (@expected_key, @expected_value, @opts) =>
super!
_transform: (value, state) =>
pass, err = types.table value
unless pass
return FailedTransform, err
key_literal = not BaseType\is_base_type @expected_key
value_literal = not BaseType\is_base_type @expected_value
transformed = false
out = {}
for k,v in pairs value
new_k = k
new_v = v
if key_literal
if k != @expected_key
return FailedTransform, "map key expected #{describe_literal @expected_key}"
else
new_k, state = @expected_key\_transform k, state
if new_k == FailedTransform
return FailedTransform, "map key #{state}"
if value_literal
if v != @expected_value
return FailedTransform, "map value expected #{describe_literal @expected_value}"
else
new_v, state = @expected_value\_transform v, state
if new_v == FailedTransform
return FailedTransform, "map value #{state}"
if new_k != k or new_v != v
transformed = true
continue if new_k == nil
out[new_k] = new_v
transformed and out or value, state
class Shape extends BaseType
@type_err_message: "expecting table"
new: (@shape, @opts) =>
super!
assert type(@shape) == "table", "expected table for shape"
if @opts
@extra_fields_type = @opts.extra_fields
@open = @opts.open
@check_all = @opts.check_all
if @open
assert not @extra_fields_type, "open can not be combined with extra_fields"
if @extra_fields_type
assert not @open, "extra_fields can not be combined with open"
-- allow extra fields
is_open: =>
Shape @shape, @clone_opts open: true
_describe: =>
parts = for k, v in pairs @shape
"#{describe_literal k} = #{describe_literal v}"
"{ #{table.concat parts, ", "} }"
_transform: (value, state) =>
pass, err = types.table value
unless pass
return FailedTransform, err
check_all = @check_all
remaining_keys = {key, true for key in pairs value}
local errors
dirty = false
out = {}
for shape_key, shape_val in pairs @shape
item_value = value[shape_key]
if remaining_keys
remaining_keys[shape_key] = nil
new_val, state = if BaseType\is_base_type shape_val
shape_val\_transform item_value, state
else
if shape_val == item_value
item_value, state
else
FailedTransform, "expected #{describe_literal shape_val}"
if new_val == FailedTransform
err = "field #{describe_literal shape_key}: #{state}"
if check_all
if errors
table.insert errors, err
else
errors = {err}
else
return FailedTransform, err
else
if new_val != item_value
dirty = true
out[shape_key] = new_val
if remaining_keys and next remaining_keys
if @open
-- copy the remaining keys to out
for k in pairs remaining_keys
out[k] = value[k]
elseif @extra_fields_type
for k in pairs remaining_keys
item_value = value[k]
tuple, state = @.extra_fields_type\_transform {[k]: item_value}, state
if tuple == FailedTransform
err = "field #{describe_literal k}: #{state}"
if check_all
if errors
table.insert errors, err
else
errors = {err}
else
return FailedTransform, err
else
if nk = tuple and next tuple
-- the tuple key changed
if nk != k
dirty = true
-- the value changed
elseif tuple[nk] != item_value
dirty = true
out[nk] = tuple[nk]
else
-- value was removed, dirty
dirty = true
else
names = for key in pairs remaining_keys
describe_literal key
err = "extra fields: #{table.concat names, ", "}"
if check_all
if errors
table.insert errors, err
else
errors = {err}
else
return FailedTransform, err
if errors and next errors
return FailedTransform, table.concat errors, "; "
dirty and out or value, state
class Pattern extends BaseType
new: (@pattern, @opts) =>
super!
_describe: =>
"pattern #{describe_literal @pattern}"
-- TODO: remove coerce, can be done with operators
_transform: (value, state) =>
if initial = @opts and @opts.initial_type
return FailedTransform, "expected #{describe_literal initial}" unless type(value) == initial
value = tostring value if @opts and @opts.coerce
t_res, err = types.string value
unless t_res
return FailedTransform, err
if value\match @pattern
value, state
else
FailedTransform, "doesn't match #{@_describe!}"
class Literal extends BaseType
new: (@value, @opts) =>
super!
_describe: =>
describe_literal @value
_transform: (value, state) =>
if @value != value
return FailedTransform, "expected #{@_describe!}"
value, state
class Custom extends BaseType
new: (@fn, @opts) =>
super!
_describe: =>
@opts and @opts.describe or "custom checker #{@fn}"
_transform: (value, state) =>
pass, err = @.fn value, state
unless pass
return FailedTransform, err or "failed custom check"
value, state
class Equivalent extends BaseType
values_equivalent = (a,b) ->
return true if a == b
if type(a) == "table" and type(b) == "table"
seen_keys = {}
for k,v in pairs a
seen_keys[k] = true
return false unless values_equivalent v, b[k]
for k,v in pairs b
continue if seen_keys[k]
return false unless values_equivalent v, a[k]
true
else
false
new: (@val, @opts) =>
super!
_transform: (value, state) =>
if values_equivalent @val, value
value, state
else
FailedTransform, "not equivalent to #{@val}"
class Range extends BaseType
new: (@left, @right, @opts) =>
super!
assert @left <= @right, "left range value should be less than right range value"
@value_type = assert types[type(@left)], "couldn't figure out type of range boundary"
_transform: (value, state) =>
res, state = @.value_type\_transform value, state
if res == FailedTransform
return FailedTransform, "range #{state}"
if value < @left
return FailedTransform, "not in #{@_describe!}"
if value > @right
return FailedTransform, "not in #{@_describe!}"
value, state
_describe: =>
"range from #{@left} to #{@right}"
class Proxy extends BaseType
new: (@fn, @opts) =>
_transform: (...) =>
assert(@.fn!, "proxy missing transformer")\_transform ...
_describe: (...) =>
assert(@.fn!, "proxy missing transformer")\_describe ...
class AssertType extends BaseType
new: (@base_type, @opts) =>
super!
assert BaseType\is_base_type(@base_type), "expected a type checker"
_transform: (value, state) =>
value, state_or_err = @base_type\_transform value, state
assert value != FailedTransform, state_or_err
value, state_or_err
_describe: =>
if @base_type._describe
base_description = @base_type\_describe!
"assert #{base_description}"
class NotType extends BaseType
new: (@base_type, @opts) =>
super!
assert BaseType\is_base_type(@base_type), "expected a type checker"
_transform: (value, state) =>
out, _ = @base_type\_transform value, state
if out == FailedTransform
value, state
else
FailedTransform, "expected #{@_describe!}"
_describe: =>
if @base_type._describe
base_description = @base_type\_describe!
"not #{base_description}"
types = setmetatable {
any: AnyType!
string: Type "string"
number: Type "number"
function: Type "function"
func: Type "function"
boolean: Type "boolean"
userdata: Type "userdata"
nil: Type "nil"
table: Type "table"
array: ArrayType!
-- compound
integer: Pattern "^%d+$", coerce: true, initial_type: "number"
-- type constructors
one_of: OneOf
all_of: AllOf
shape: Shape
pattern: Pattern
array_of: ArrayOf
map_of: MapOf
literal: Literal
range: Range
equivalent: Equivalent
custom: Custom
scope: TagScopeType
proxy: Proxy
assert: AssertType
}, __index: (fn_name) =>
error "Type checker does not exist: `#{fn_name}`"
check_shape = (value, shape) ->
assert shape.check_value, "missing check_value method from shape"
shape\check_value value
is_type = (val) ->
BaseType\is_base_type val
type_switch = (val) ->
setmetatable { val }, { __eq: BaseType.__eq }
export tableshape = { :check_shape, :types, :is_type, :type_switch, :BaseType, :FailedTransform, VERSION: "2.0.0" }
| 23.654102 | 115 | 0.613798 |
3a957b343733e25c205aba52cfeb53d68b265bde | 2,309 | -- Copyright 2014-2015 The Howl Developers
-- License: MIT (see LICENSE.md at the top-level directory of the distribution)
ffi = require 'ffi'
jit = require 'jit'
require 'ljglibs.cdefs.gobject'
callbacks = require 'ljglibs.callbacks'
C, ffi_string = ffi.C, ffi.string
signal = {
-- GConnectFlags
CONNECT_AFTER: C.G_CONNECT_AFTER,
CONNECT_SWAPPED: C.G_CONNECT_SWAPPED
-- GSignalFlags
RUN_FIRST: C.G_SIGNAL_RUN_FIRST
RUN_LAST: C.G_SIGNAL_RUN_LAST
RUN_CLEANUP: C.G_SIGNAL_RUN_CLEANUP
NO_RECURSE: C.G_SIGNAL_NO_RECURSE
DETAILED: C.G_SIGNAL_DETAILED
ACTION: C.G_SIGNAL_ACTION
NO_HOOKS: C.G_SIGNAL_NO_HOOKS
MUST_COLLECT: C.G_SIGNAL_MUST_COLLECT
DEPRECATED: C.G_SIGNAL_DEPRECATED
connect: (cb_type, instance, signal, handler, ...) ->
cb = callbacks[cb_type]
error "Unknown callback type '#{cb_type}'" unless cb
handle = callbacks.register handler, "signal #{signal}", ...
handler_id = C.g_signal_connect_data(instance, signal, cb, callbacks.cast_arg(handle.id), nil, 0)
handle.signal_handler_id = handler_id
handle.signal_object_instance = instance
handle
disconnect: (handle) ->
callbacks.unregister handle
C.g_signal_handler_disconnect handle.signal_object_instance, handle.signal_handler_id
unref_handle: (handle) ->
callbacks.unref_handle handle
emit_by_name: (instance, signal, ...) ->
C.g_signal_emit_by_name ffi.cast('gpointer', instance), signal, ..., nil
lookup: (name, gtype) ->
C.g_signal_lookup name, gtype
list_ids: (gtype) ->
error 'Undefined gtype passed in (zero)', 2 if gtype == 0 or gtype == nil
n_ids = ffi.new 'guint [1]'
id_ptr = C.g_signal_list_ids gtype, n_ids
ids = {}
for i = 0, n_ids[0] - 1
ids[#ids + 1] = (id_ptr + i)[0]
ids
query: (signal_id) ->
query = ffi.new 'GSignalQuery'
C.g_signal_query signal_id, query
return nil if query.signal_id == 0
param_types = {}
for i = 0, query.n_params - 1
param_types[#param_types + 1] = (query.param_types + i)[0]
info = {
:signal_id,
signal_name: ffi_string query.signal_name
itype: query.itype
signal_flags: query.signal_flags
return_type: query.return_type
n_params: query.n_params
:param_types
}
info
}
jit.off signal.connect
signal
| 28.8625 | 101 | 0.698571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.