Rewrite to static site

With a complete reorganisation of the directory structure and most of
the content converted to pandoc-flavoured markdown.

Some TODO's left before this can go live:
- Main page
- Atom feeds
- Bug tracker
This commit is contained in:
Yorhel 2019-03-23 11:52:08 +01:00
parent 5c85a7d32f
commit 6242b2ee9c
291 changed files with 4346 additions and 6141 deletions

166
pub/download/code/awshrink Normal file
View file

@ -0,0 +1,166 @@
#!/usr/bin/perl
# awshrink v0.1
# 2007-01-15
# Yoran Heling
# License: MIT
use strict;
use warnings;
use bytes;
# hash for easy lookup
my %shrinkable = ( map { $_ => 1 } qw|
DOMAIN LOGIN ROBOT WORMS EMAILSENDER EMAILRECEIVER
BROWSER UNKNOWNREFERER UNKOWNREFERERBROWSER SEREFERRALS
PAGEREFS SEARCHWORDS KEYWORDS SIDER_404 SIDER VISITOR
UNKNOWNREFERERBROWSER
|);
sub getstats { # read
my $fl = shift;
my @l;
seek($fl, 0, 0);
# get positions
while(<$fl>) {
last if /^END_MAP/;
next if !/^POS_([A-Z0-9_]+)\s+([0-9]+)\s+$/;
push(@l, [ $1, $2, 0, 0 ]);
}
# get sizes (bytes)
@l = sort { $a->[1] <=> $b->[1] } @l;
$l[$_][2] = ($l[$_+1] ? $l[$_+1][1] : -s $fl) - $l[$_][1]
for (0..$#l);
# get lines
for (0..$#l) {
seek $fl, $l[$_][1], 0;
<$fl> =~ /BEGIN_[A-Z0-9_]+\s+([0-9]+)/;
$l[$_][3] = $1;
}
print " Section Size (Bytes) Lines\n";
printf "%22s %12d %7d\n", $_->[0].($shrinkable{$_->[0]}?' ':'*'), $_->[2], $_->[3]
for (sort { $a->[2] <=> $b->[2] } @l);
print "* = not shrinkable\n";
}
sub fixmap { # read, write
my($fl, $FL) = @_;
my $map = '';
my @l;
seek $fl, 0, 0;
while(<$fl>) {
next if !/^BEGIN_([A-Z0-9_]+)/ || $1 eq 'MAP';
$map .= sprintf "POS_%s %-20d\n", $1, tell($fl)-length($_);
}
seek $fl, 0, 0;
seek $FL, 0, 0;
my $inmap = 0;
while(<$fl>) {
if(!$inmap && !/^BEGIN_MAP/) {
print $FL $_;
next;
}
$inmap = 1;
if(/^END_MAP/) {
printf $FL "BEGIN_MAP 27\n%sEND_MAP\n", $map;
$inmap = 0;
}
}
}
sub shrink { # read, write, %sections->{ key = section, value = lines }
my($fh, $FH, %sec) = @_;
seek $fh, 0, 0;
seek $FH, 0, 0;
while(<$fh>) {
if(!/^BEGIN_([A-Z0-9_]+)\s+([0-9]+)/ || !$sec{$1} || $sec{$1} >= $2) {
print $FH $_;
next;
}
my $sec = $1;
# read entire section
my @l;
while(<$fh>) {
last if /^END_/;
s/^[\s\r\n]+//;
s/[\s\r\n]+$//;
push @l, [ split / / ];
}
# sort section
# DOMAIN, LOGIN, ROBOT, WORMS, EMAILSENDER. EMAILRECEIVER,
# BROWSER, UNKNOWNREFERER, UNKOWNREFERERBROWSER, SEREFERRALS,
# PAGEREFS, SEARCHWORDS, KEYWORDS, SIDER_404, SIDER -> 1
# VISITOR -> 2
if($sec{$sec} > 10) { # assume sorted if we only want the first ten
@l = sort { $b->[1] <=> $a->[1] } @l if $sec ne 'VISITOR';
@l = sort { $b->[2] <=> $a->[2] } @l if $sec eq 'VISITOR';
}
# write section
printf $FH "BEGIN_%s %d\n", $sec, $sec{$sec};
print $FH join(' ', @{$l[$_]})."\n"
for (0..($sec{$sec}-1));
printf $FH "END_%s\n", $sec;
}
1;
}
sub run {
print "Usage: $@ [options] filename\n" and exit if !@ARGV;
my $file = pop;
my $ci = 0;
my $st = 0;
my %options;
while(local $_ = shift) {
/^-c$/ ? $ci++ :
/^-s$/ ? $st++ :
/^-([A-Za-z0-9_]+)$/ && $shrinkable{ uc($1) } ? $options{ uc($1) } = shift :
printf("Unknown option: %s\n", $_) && exit;
}
(!$options{$_} || $options{$_} !~ /^[0-9]+$/) && printf("Invalid value for -%s\n", $_) && exit
for keys %options;
print "Nothing to do...\n" and exit if !keys %options && !$st;
open(my $fl, '<', $file) || die $!;
my $tmpfile;
open(my $TMP, '+>', \$tmpfile);
open(my $FL, '+>', "$file~") || die $! if keys %options;
shrink($fl, $TMP, %options) && fixmap($TMP, $FL) if keys %options;
getstats(keys %options ? $FL : $fl) if $st;
close $fl;
close $TMP;
close $FL if keys %options;
rename "$file~", $file if $ci;
}
run @ARGV;

330
pub/download/code/bbcode.c Normal file
View file

@ -0,0 +1,330 @@
/*
* BBCode 2 HTML converter by //YorHel
* Copyright 2006 Y.Heling,
* License: MIT
*
* Created just to learn C, probably very ugly piece of code
* and probably with a _LOT_ of bugs... But the only way to
* learn a programming language is to code something yourself :)
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_ARGH_SIZE 500
#define MAX_TAG_SIZE 10
#define MAX_NESTED_TAGS 100
#define TAGCHARS 28
#define NUMBER_OF_TAGS 16
#define TRUE 1
#define FALSE 0
/* typedefs */
typedef enum {
B,
I,
U,
SIZE,
COLOR,
URL,
QUOTE,
QUOTE2,
IMG,
IMG2,
EMAIL,
LIST,
LIST2,
CODE,
HTML,
UNDEF, /* hack */
} TAGNAME;
typedef struct {
TAGNAME intags[MAX_NESTED_TAGS];
int curtag;
char tag[MAX_TAG_SIZE];
char argh[MAX_ARGH_SIZE];
FILE *dest;
int inlist;
int liststart;
} PARSEINFO; /* just a hack to prevent the use of global variables */
typedef struct {
char *bb;
char *html_s;
char *html_e;
char arg;
} TAGINFO; /* store global information about the tags */
/* functions */
void parsebbcode(FILE *, FILE *);
void converttag(PARSEINFO *);
void formattag(PARSEINFO *);
char endtags(PARSEINFO *, TAGNAME);
void convertchars(PARSEINFO *, const char *);
void convertchar(PARSEINFO *, const int);
void convertchararg(char *, int);
char istagchar(const int);
void err(const char *);
/* global vars (only consts!) */
const char tagchars[TAGCHARS] = "abcdefghijklmnopqrstuvwxyz/*";
const TAGINFO taglist[NUMBER_OF_TAGS] = { /* same order as TAGNAME! */
{ "b", "<b>", "</b>", FALSE },
{ "i", "<i>", "</i>", FALSE },
{ "u", "<span style=\"text-decoration: underline\">", "</span>", FALSE },
{ "size", "<span style=\"font-size: %spx\">", "</span>", TRUE },
{ "color", "<span style=\"color: %s\">", "</span>", TRUE },
{ "url", "<a href=\"%s\">", "</a>", TRUE },
{ "quote", "<span class=\"bbcode_quote_header\">Quote: <span class=\"bbcode_quote_body\">", "</span></span>", FALSE },
{ "quote", "<span class=\"bbcode_quote_header\">%s wrote: <span class=\"bbcode_quote_body\">", "</span></span>", TRUE },
{ "img", "<img src=\"", "\" alt=\"\" />", FALSE },
{ "img", "<img src=\"%s\" alt=\"", "\" />", TRUE },
{ "email", "<a href=\"mailto:%s\">", "</a>", TRUE },
{ "list", "<ul>", "</li></ul>", FALSE },
{ "list", "<ul style=\"list-style-type: %s\">", "</li></ul>", TRUE },
{ "code", "<span class=\"bbcode_code_header\">Code: <span class=\"bbcode_code_body\">", "</span></span>", FALSE },
{ "html", "", "", FALSE },
{ "", "", "", FALSE },
}; /* NOTE: not all characteristics of the BBCodes are defined above, there is also a lot of hard-coded stuff below for a few tags */
int main() {
/* printf("BBCode to HTML converter by //YorHel\n");
printf("Copyright 2006 Y. Heling\n\n");
printf("* Reading & parsing bbcode...\n");
while(1) {
FILE *file;
if((file = fopen(BBFILE, "r")) == NULL) err("Couldn't open BBFILE");
parsebbcode(file, stdout);
fclose(file);
}
printf("\n");*/
parsebbcode(stdin, stdout);
return 0;
}
void parsebbcode(FILE *file, FILE *dest) {
PARSEINFO pitemp; /* make sure we allocate the memory */
PARSEINFO *pi = &pitemp; /* but we are still going to use a pointer */
char intag = pi->inlist = pi->liststart = 0;
pi->curtag = 1;
pi->intags[0] = UNDEF;
sprintf(pi->tag, "");
sprintf(pi->argh, "");
pi->dest = dest;
int c;
char tmp[MAX_TAG_SIZE+MAX_ARGH_SIZE+4]; /* temp string, should be able to hold anything necessary */
while((c = fgetc(file)) && c != EOF) {
if(intag == 0 && c == '[') {
intag = 1;
}
else if(intag == 1 && c == '=')
intag = -1;
else if(intag != 0 && c == ']') {
intag = 0;
converttag(pi);
sprintf(pi->tag, "");
sprintf(pi->argh, "");
}
else if(intag == 1 && strlen(pi->tag) < sizeof(pi->tag)) {
if(istagchar(c)) {
sprintf(tmp, "%c", tolower(c));
strcat(pi->tag, tmp);
} else {
sprintf(tmp, "[%s", pi->tag);
convertchars(pi, tmp);
sprintf(pi->tag, "");
}
}
else if(intag == 1) {
intag = 0;
sprintf(tmp, "[%s", pi->tag);
convertchars(pi, tmp);
sprintf(pi->tag, "");
}
else if(intag == -1 && (strlen(pi->argh)+10) < sizeof(pi->argh)) {
convertchararg(tmp, c);
strcat(pi->argh, tmp);
}
else if(intag == -1) {
sprintf(tmp, "[%s=%s", pi->tag, pi->argh);
convertchars(pi, tmp);
sprintf(pi->tag, "");
sprintf(pi->argh, "");
intag = 0;
}
else
convertchar(pi, c);
}
/* some stuff left in the buffer */
if(strlen(pi->tag) > 0 && strlen(pi->argh) == 0)
fprintf(dest, "[%s", pi->tag);
else if(strlen(pi->tag) > 0 && strlen(pi->argh) > 0)
fprintf(dest, "[%s=%s", pi->tag, pi->argh);
/* automatically close opened tags */
endtags(pi, UNDEF);
}
void converttag(PARSEINFO *pi) {
/* ignore tag if we're not allowed to nest */
if((pi->intags[pi->curtag] == CODE && strcmp(pi->tag, "/code") != 0)
|| (pi->intags[pi->curtag] == HTML && strcmp(pi->tag, "/html") != 0)
|| ((pi->intags[pi->curtag] == IMG || pi->intags[pi->curtag] == IMG2) && strcmp(pi->tag, "/img"))) {
formattag(pi);
return;
}
/* parse list items */
if(!strcmp(pi->tag, "*") && pi->inlist) {
endtags(pi, LIST);
if(pi->inlist == pi->liststart)
fprintf(pi->dest, "</li>");
else
pi->liststart = pi->inlist;
fprintf(pi->dest, "<li>");
return; /* no need to parse more */
}
/* begin a tag */
if(*pi->tag != '/') {
int i; int got = -1;
for(i=0 ; i<NUMBER_OF_TAGS && got == -1 ; i++)
if(!strcmp(pi->tag, taglist[i].bb)) {
got = i;
if(strlen(pi->argh) == 0 && !taglist[i].arg)
fprintf(pi->dest, "%s", taglist[i].html_s);
else if(strlen(pi->argh) > 0 && taglist[i].arg) {
if(i != LIST2)
fprintf(pi->dest, taglist[i].html_s, pi->argh);
else
fprintf(pi->dest, taglist[i].html_s, strcmp(pi->argh, "1") ? "lower-roman" : "decimal");
}
else
got = -1;
};
if(got != -1) {
pi->intags[++pi->curtag] = got;
if(got == LIST || got == LIST2)
pi->inlist++;
}
else
formattag(pi);
return;
}
/* end a tag */
else {
char *tag = pi->tag+1; /* strip the '/' */
int i;
char got = FALSE;
for(i=0 ; i<NUMBER_OF_TAGS && got == FALSE ; i++)
if(!strcmp(tag, taglist[i].bb) && endtags(pi, i)) {
fprintf(pi->dest, "%s", taglist[i].html_e);
if(pi->intags[pi->curtag] == LIST || pi->intags[pi->curtag] == LIST2)
pi->liststart = --pi->inlist;
pi->curtag--;
got = TRUE;
};
if(!got)
formattag(pi);
}
}
char endtags(PARSEINFO *pi, TAGNAME to) {
char s = FALSE;
if(to == QUOTE || to == LIST || to == IMG)
s = TRUE;
else if(to == QUOTE2 || to == LIST2 || to == IMG2) {
s = TRUE;
to--;
}
int i = pi->curtag;
if(to != UNDEF)
while(pi->intags[i] != to && (!s || pi->intags[i] != to+1) && i > 0)
i--;
if(i) {
while(pi->intags[pi->curtag] != to && (!s || pi->intags[pi->curtag] != (to+1)) && pi->curtag > 0) {
if(pi->intags[pi->curtag] == LIST || pi->intags[pi->curtag] == LIST2)
pi->liststart = --pi->inlist;
fprintf(pi->dest, "%s", taglist[pi->intags[pi->curtag--]].html_e);
}
return TRUE;
}
else
return FALSE;
}
void formattag(PARSEINFO *pi) {
char tmp[MAX_TAG_SIZE+MAX_ARGH_SIZE+4];
if(strlen(pi->argh) == 0)
sprintf(tmp, "[%s]", pi->tag);
else
sprintf(tmp, "[%s=%s]", pi->tag, pi->argh);
convertchars(pi, tmp);
}
void convertchars(PARSEINFO *pi, const char *chars) {
int i;
for(i=0;i<strlen(chars);i++)
convertchar(pi, *(chars+i));
}
void convertchar(PARSEINFO *pi, const int c) {
if(pi->inlist && pi->inlist != pi->liststart)
return;
else if(pi->intags[pi->curtag] == HTML)
fprintf(pi->dest, "%c", c);
else if(pi->intags[pi->curtag] == IMG || pi->intags[pi->curtag] == IMG2) {
char tmp[10];
convertchararg(tmp, c);
fprintf(pi->dest, tmp);
}
else if(c == '\n')
fprintf(pi->dest, "<br />\n");
else if(c == '&')
fprintf(pi->dest, "&amp;");
else if(c == '<')
fprintf(pi->dest, "&lt;");
else if(c == '>')
fprintf(pi->dest, "&gt;");
else
fprintf(pi->dest, "%c", c);
}
void convertchararg(char *to, const int c) {
switch(c) {
case '\n' :
sprintf(to, ""); break;
case '&' :
sprintf(to, "&amp;"); break;
case '"' :
sprintf(to, "&quot;"); break;
default :
sprintf(to, "%c", c);
}
}
char istagchar(const int c) {
int i;
int c2 = tolower(c);
for(i=0;i<TAGCHARS;i++)
if(c2 == *(tagchars+i))
return TRUE;
return FALSE;
}
void err(const char *msg) {
fprintf(stderr, "ERROR: %s\n", msg);
exit(1);
}

View file

@ -0,0 +1,180 @@
/*
* echoserv.c - a simple single-threaded TCP server test
* by //YorHel
*
* Copyright 2006 Y. Heling,
* February 2006
* License: MIT
*
* Use it at your own risk
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
#define LISTEN_PORT 1337
#define MAX(x,y) ((x) > (y) ? (x) : (y))
;
#define MAX_CONNECTIONS 10
#define READ_BUFFER_SIZE 512
#define CST_FREE 0
#define CST_READ 1
#define CST_WRITE 2
typedef struct {
int fd;
char state;
char *buf;
} connections;
static connections *conns;
void error(const char *);
void close_and_free(int);
int main() {
printf("Simple TCP server by //YorHel\n\n");
printf("* Creating socket\n");
int l;
if((l = socket(AF_INET, SOCK_STREAM, 0)) < 0)
error("Can't create socket");
printf("* Setting SO_REUSEADDR on main socket\n");
int set = 1;
if(setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (void *) &set, sizeof(set)) < 0)
error("Can't set SO_REUSEADDR on main socket");
printf("* Binding socket\n");
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(struct sockaddr_in));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(LISTEN_PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(l, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("Can't bind socket");
printf("* Listening to socket\n");
listen(l, 5);
printf("* Creating connections table\n");
conns = (connections *) malloc( sizeof(connections) * MAX_CONNECTIONS );
if(conns == (connections *) 0)
error("Can't allocate memory for connections table");
int cnum;
for(cnum=MAX_CONNECTIONS; cnum--;)
conns[cnum].state = CST_FREE;
printf("* Accepting connections\n");
/* re-use the same vars over-and-over again
* is a little faster than defining them each time */
int n, cn, newid, clifd;
char stop = 0;
fd_set rd, wr;
struct sockaddr_in cliaddr;
unsigned int clilen;
/* main loop */
while(!stop) {
/* set FDs for select() */
FD_ZERO(&rd); FD_ZERO(&wr);
n = 0;
FD_SET(l, &rd);
n = MAX(l, n);
/* set FDs for the connections */
for(cn=MAX_CONNECTIONS;cn--;) {
if(conns[cn].state == CST_READ) {
FD_SET(conns[cn].fd, &rd);
n = MAX(n, conns[cn].fd);
} else if(conns[cn].state == CST_WRITE) {
FD_SET(conns[cn].fd, &wr);
n = MAX(n, conns[cn].fd);
}
}
n = select(n + 1, &rd, &wr, (fd_set *) NULL, (struct timeval *) 0);
if(n < 0)
error("select() failed...");
if(n == 0)
continue;
/* Something happend, handle it :) */
if(FD_ISSET(l, &rd)) { /* new connection */
/* get free slot, if one */
newid = -1;
for(cn=MAX_CONNECTIONS;cn--;)
if(conns[cn].state == CST_FREE) {
newid = cn; break;
}
if(newid < 0)
printf(" *WARNING: Too many connections\n");
else {
/* accept the connection */
clilen = sizeof(cliaddr);
memset(&cliaddr, 0, clilen);
clifd = accept(l, (struct sockaddr *) &cliaddr, &clilen);
if(clifd < 0)
error("Can't accept connection");
printf(" [%d] We have a connection!!\n", newid);
conns[newid].state = CST_WRITE;
if((conns[newid].buf = malloc(READ_BUFFER_SIZE)) < 0)
error("Can't allocate memory");
sprintf(conns[newid].buf, "Hello world!\n");
conns[newid].fd = clifd;
}
}
/* checking active sockets */
for(cn=MAX_CONNECTIONS;cn--;) {
/* we can write */
if(conns[cn].state == CST_WRITE && FD_ISSET(conns[cn].fd, &wr)) {
if(write(conns[cn].fd, conns[cn].buf, strlen(conns[cn].buf)) <= 0)
close_and_free(cn);
printf(" [%d] Sent: %s", cn, conns[cn].buf);
conns[cn].state = CST_READ;
}
/* we can read */
if(conns[cn].state == CST_READ && FD_ISSET(conns[cn].fd, &rd)) {
memset((void *) conns[cn].buf, 0, READ_BUFFER_SIZE);
if(read(conns[cn].fd, conns[cn].buf, READ_BUFFER_SIZE) <= 0)
close_and_free(cn);
printf(" [%d] G0t: %s", cn, conns[cn].buf);
conns[cn].state = CST_WRITE;
if(strstr(conns[cn].buf, "exit") == conns[cn].buf) {
printf(" [%d] Closing connection\n", cn);
close_and_free(cn);
} else if(strstr(conns[cn].buf, "die()") == conns[cn].buf) {
printf("Got die() from connection #%d, dying!\n", cn);
stop = 1;
}
}
}
}
/* close all connections before dying */
for(cnum=MAX_CONNECTIONS;cnum--;)
if(conns[cnum].state != CST_FREE)
close_and_free(cnum);
close(l);
return 0;
}
void close_and_free(int cn) {
close(conns[cn].fd);
conns[cn].state = CST_FREE;
free(conns[cn].buf);
}
void error(const char *msg) {
perror(msg);
exit(1);
}

View file

@ -0,0 +1,248 @@
#!/usr/bin/perl
# grenamr v0.1
# 2008-08-01
# Yoran Heling
# License: MIT
use warnings;
use strict;
use Gtk2 -init;
our $VERSION = '0.1';
my %w;
my $m;
use constant {
C_OLD => 0,
C_NEW => 1,
C_FLG => 2,
F_REG => 0x01,
F_MAN => 0x02, # not implemented yet...
F_CON => 0x04,
};
create();
Gtk2->main;
sub create {
$w{win} = Gtk2::Window->new('toplevel');
$w{win}->signal_connect(destroy => \&close);
$w{win}->resize(500, 500);
$w{win}->move(300, 300);
$w{win}->set(title => 'GRenamR v'.$VERSION);
$w{vbGlobal} = Gtk2::VBox->new(0, 0);
$w{win}->add($w{vbGlobal});
$w{hbDir} = Gtk2::HBox->new(0, 0);
$w{vbGlobal}->pack_start($w{hbDir}, 0, 1, 0);
$w{lbDir} = Gtk2::Label->new('_Directory');
$w{hbDir}->pack_start($w{lbDir}, 0, 0, 5);
$w{fcDir} = Gtk2::FileChooserButton->new('Select a directory', 'select-folder');
$w{fcDir}->signal_connect('current-folder-changed', \&fetchdir);
$w{hbDir}->pack_start($w{fcDir}, 1, 1, 0);
$w{lbDir}->set(mnemonic_widget => $w{fcDir}, use_underline => 1);
$w{swFiles} = Gtk2::ScrolledWindow->new;
$w{swFiles}->set_policy('automatic', 'automatic');
$w{vbGlobal}->pack_start($w{swFiles}, 1, 1, 0);
$w{tvFiles} = Gtk2::TreeView->new;
$w{swFiles}->add($w{tvFiles});
$m = $w{lsFiles} = Gtk2::ListStore->new('Glib::String', 'Glib::String', 'Glib::Int');
$w{tvFiles}->set_model($w{lsFiles});
$w{tvFiles}->insert_column_with_data_func(0, '', Gtk2::CellRendererPixbuf->new, \&column_func, 0);
my $c = Gtk2::CellRendererText->new;
$w{tvFiles}->insert_column_with_data_func(1, 'Old', $c, \&column_func, 1);
$w{tvFiles}->insert_column_with_data_func(2, 'New', $c, \&column_func, 2);
$w{tvFiles}->get_column(1)->set(sizing => 'autosize');
$w{tvFiles}->get_column(2)->set(sizing => 'autosize');
$w{hbPerl} = Gtk2::HBox->new(0, 0);
$w{vbGlobal}->pack_start($w{hbPerl}, 0, 1, 0);
$w{lbPerl} = Gtk2::Label->new('_Expression');
$w{hbPerl}->pack_start($w{lbPerl}, 0, 0, 5);
$w{enPerl} = Gtk2::Entry->new;
$w{enPerl}->signal_connect('changed', \&applyfilter);
$w{hbPerl}->pack_start($w{enPerl}, 1, 1, 0);
$w{lbPerl}->set(mnemonic_widget => $w{enPerl}, use_underline => 1);
$w{imPerl} = Gtk2::Image->new_from_stock('gtk-yes', 'menu');
$w{hbPerl}->pack_start($w{imPerl}, 0, 1, 0);
$w{hbBottom} = Gtk2::HBox->new(0, 0);
$w{vbGlobal}->pack_start($w{hbBottom}, 0, 1, 0);
$w{alStatus} = Gtk2::Alignment->new(0,0.8,0,0);
$w{hbBottom}->pack_start($w{alStatus}, 1, 1, 5);
$w{lbStatus} = Gtk2::Label->new('');
$w{alStatus}->add($w{lbStatus});
$w{alBottom} = Gtk2::Alignment->new(1,1,0,1);
$w{hbBottom}->pack_start($w{alBottom}, 0, 1, 0);
$w{bbBottom} = Gtk2::HButtonBox->new;
$w{bbBottom}->set(spacing => 5);
$w{alBottom}->add($w{bbBottom});
$w{btApply} = Gtk2::Button->new('_Rename');
$w{btApply}->signal_connect('clicked', \&dorename);
$w{bbBottom}->pack_start($w{btApply}, 0, 0, 5);
$w{btClose} = Gtk2::Button->new('_Close');
$w{btClose}->signal_connect('clicked', \&close);
$w{bbBottom}->pack_start($w{btClose}, 0, 0, 5);
$w{win}->show_all;
$w{enPerl}->grab_focus;
if($ARGV[0] && -d $ARGV[0]) {
$w{fcDir}->set_current_folder($ARGV[0]);
} else {
fetchdir();
}
}
sub column_func {
my ($column, $cell, $model, $iter, $col) = @_;
my $flags = $model->get($iter, 2);
$cell->set(
$col > 0 ? (
text => $model->get($iter, $col-1),
) : (
'stock-id' => $flags & F_CON ? 'gtk-dialog-error'
: $flags & F_REG ? 'gtk-edit'
: $flags & F_MAN ? 'gtk-apply'
: 'gtk-file',
),
$flags & F_CON ? ( cell_background => '#ffcccc' ) :
$flags & F_REG ? ( cell_background => '#ccffcc' ) :
$flags & F_MAN ? ( cell_background => '#ffffcc' ) :
( cell_background_set => 0 ),
);
}
sub close {
Gtk2->main_quit;
}
sub fetchdir {
Gtk2->main_iteration_do(0);
my $d = $w{fcDir}->get_current_folder;
$w{lbStatus}->set(label => 'Loading...');
my @lst;
opendir(my $D, $d)
|| return $w{lbStatus}->set(label => 'Unable to open the selected directory');
-f $d.'/'.$_ and push @lst, $_ for (readdir $D);
closedir $D;
$m->clear;
$m->set($m->append, C_OLD, $_, C_NEW, $_, C_FLG, 0)
for (sort @lst);
$w{lbStatus}->set(label => sprintf '%d files found.', scalar @lst);
applyfilter();
}
sub applyfilter {
my $p = $w{enPerl}->get_text;
# create a list of files
my @list;
my $i = $m->get_iter_first;
do {
push @list, $m->get($i, C_OLD)
} while ($i = $m->iter_next($i));
# eval using a for loop
$i=-1;
eval 'no strict; no warnings; for (@list) { ++$i; '.$p.' }';
my $e = $@;
$w{imPerl}->set(stock => $e ? 'gtk-no' : 'gtk-yes');
# compare and update the list
my $j=0; my $matched=0;
$i = $m->get_iter_first;
do {{
next if $m->get($i, C_FLG) & F_MAN;
my $match = $e || $m->get($i, C_OLD) eq $list[$j] ? 0 : 1;
$m->set($i, C_NEW, $list[$j++], C_FLG, $match);
$matched += $match;
}} while ($i = $m->iter_next($i));
# update status
$w{lbStatus}->set(label => $e
? 'Invalid expression'
: sprintf 'Matched %d/%d files.', $matched, scalar @list);
findconflicts();
}
sub findconflicts {
# create a list of old filenames
my @old;
my $i = $m->get_iter_first;
do {
push @old, $m->get($i, C_OLD);
} while ($i = $m->iter_next($i));
# search for modified items having a new filename in that list
my $e=0;
$i = $m->get_iter_first;
do {{
next if !$m->get($i, C_FLG);
my $new = $m->get($i, C_NEW);
my $match = $new eq '' || $new =~ /\// || grep $_ eq $new, @old;
$m->set($i, C_FLG, $m->get($i, C_FLG) | F_CON)
if $match;
$e++ if $match;
}} while ($i = $m->iter_next($i));
$w{lbStatus}->set(label => 'Errors found!') if $e;
}
sub dorename {
my $d = $w{fcDir}->get_current_folder;
# count number of renamable files
my $i = $m->get_iter_first;
my $count=0;
do {
$count++ if $m->get($i, C_FLG) && !($m->get($i, C_FLG) & F_CON);
} while ($i = $m->iter_next($i));
return $w{lbStatus}->set(label => 'Nothing to do...') if !$count;
$w{lbStatus}->set(label => 'Renaming...');
my $j=0;
$i = $m->get_iter_first;
do {{
next if !$m->get($i, C_FLG) || $m->get($i, C_FLG) & F_CON;
rename $d.'/'.$m->get($i, C_OLD), $d.'/'.$m->get($i, C_NEW);
$m->set($i, C_OLD, $m->get($i, C_NEW), C_FLG, 0);
$w{lbStatus}->set(label => sprintf 'Renaming file %d/%d...', ++$j, $count);
Gtk2->main_iteration_do(0);
}} while ($i = $m->iter_next($i));
$w{lbStatus}->set(label => sprintf 'Renamed %d files.', $j);
}

View file

@ -0,0 +1,150 @@
#!/usr/bin/perl
# mdc3-parse.pl
# June 2007
# Yoran Heling
# License: MIT
use strict;
use warnings;
use Storable 'store', 'retrieve';
use POSIX;
use POSIX::strptime;
my $log = 'log'; # the microdc2 log file
my $result = 'transferred.html'; # the resulting html file
my $cache = 'logparse.pl_cache'; # file for the Storable cache
my %ts = -s $cache ? ( %{retrieve($cache)} ) : ();
my $totalsent = 0;
# using STDIN/OUT -> lazy and ugly :-)
open(STDIN, '<', $log) || die $!;
open(STDOUT, '>', $result) || die $!;
while(<>) {
s/\r?\n//;
# 28.04.2007 20:15:25
next if !s/^([0-9]{2}\.[0-9]{2}\.[0-9]{4}\s+[0-9]{2}:[0-9]{2}:[0-9]{2})\s//;
my $date = $1;
# plesnivec: Upload of `Ghost in the Shell - Stand Alone Complex - 25.avi' succeeded (transfer complete). 1.5MiB transferred in 53s (29KiB/s).
# [Anime]Spank: Upload of `Rozen Maiden - Traumend - 07.avi' succeeded (transfer complete). 177MiB transferred in 2h46m35s (19KiB/s).
# [izms]Inkognito: Upload of `Ultra Maniac TV - 16.avi' failed (communication error). 1.7MiB transferred in 3m4s (9KiB/s).
if(/^(.+): Upload of `(.+)' (succeeded|failed) \(([^)]+)\)\. ([0-9\.]+[GMK]?i?B) transferred in ([0-9dhms]+) \(([0-9]+)KiB\/s\)/) {
my($nick, $file, $sf, $msg, $sent, $time, $speed) = ($1, $2, $3, $4, $5, $6);
$file =~ s/\\'/'/g;
my $epoch = POSIX::mktime(POSIX::strptime($date, '%d.%m.%Y %T'));
$sent = calcsize($sent);
$time = calctime($time);
$totalsent += $sent;
my $k = $nick.$file;
next if $ts{$k} && grep { +$_ == $epoch } @{$ts{$k}{epoch}};
if($ts{$k}) {
$ts{$k}{sent} += $sent;
$ts{$k}{time} += $time;
$ts{$k}{chunks}++;
$ts{$k}{failed}++ if $sf eq 'failed';
$ts{$k}{succeeded}++ if $sf eq 'succeeded';
push(@{$ts{$k}{epoch}}, $epoch);
} else {
$ts{$k} = {
file => $file,
nick => $nick,
sent => $sent,
time => $time,
date => $date,
epoch => [ $epoch ], # only used for identification and sorting
# msg => $msg, # unused
chunks => 1,
failed => $sf eq 'failed' ? 1 : 0,
succeeded => $sf eq 'succeeded' ? 1 : 0,
};
}
}
}
store \%ts, $cache;
printf "\nSent %d files and %s\n", scalar keys %ts, calcsize($totalsent);
print qq|
<html>
<head>
<style>
table { font-size: 13px; }
td { padding: 0 5px 0 5px; border: 1px solid #ccc; white-space: nowrap; }
thead td { font-weight: bold; }
.tc4, .tc5, .tc7 { text-align: right }
</style>
</head>
<body>
<table cellspacing=0 cellpadding=0>
<thead><tr>
<td class="tc1">Date/time</td>
<td class="tc4">Transfered</td>
<td class="tc5">Time</td>
<td class="tc7">Speed</td>
<td class="tc6">Chunks</td>
<td class="tc2">User</td>
<td class="tc3">Filename</td>
</tr></thead>\n|;
printf(qq|<tr>
<td class="tc1">%s</td>
<td class="tc4">%s</td>
<td class="tc5">%s</td>
<td class="tc7">%.2f KiB/s</td>
<td class="tc6">%d/%d/%d</td>
<td class="tc2">%s</td>
<td class="tc3">%s</td>
</tr>\n|,
$ts{$_}{date},
calcsize($ts{$_}{sent}),
calctime($ts{$_}{time}),
$ts{$_}{sent}/($ts{$_}{time}||1),
$ts{$_}{chunks}, $ts{$_}{succeeded}, $ts{$_}{failed},
$ts{$_}{nick},
$ts{$_}{file},
)
for (sort { $ts{$b}{epoch}[0] <=> $ts{$a}{epoch}[0] } keys %ts);
print qq|</table>
</body>
</html>|;
sub calcsize { # in KBytes by default, to avoid a 32bit int overflow
if($_[0] =~ /^([0-9\.]+)(GiB|MiB|KiB|B)$/) {
return $2 eq 'B' ? $1/1024 :
$2 eq 'KiB' ? $1 :
$2 eq 'MiB' ? $1*1024 :
$1*1024*1024;
} else {
my $r = $_[0]; my $x = 'KiB';
if($r > 1024) { $r/=1024; $x='MiB' }
if($r > 1024) { $r/=1024; $x='GiB' }
return sprintf "%.1f %s", $r, $x;
}
}
sub calctime {
if($_[0] =~ /[dhms]/) {
my @t = reverse split(/[dhms]/, $_[0]);
return ($t[3]||0)*86400 + ($t[2]||0)*3600 + ($t[1]||0)*60 + $t[0];
} else {
my $r = $_[0]; my $x = '';
if($r > 24*3600) { $x .= int($r/(24*3600)).' d '; $r%=24*3600; }
$x .= sprintf '%d:%02d:%02d',
int($r/3600),
int(($r%3600)/60),
($r%3600) % 60;
return $x;
}
}

View file

@ -0,0 +1,99 @@
/* nccolour.c - Print out some ncurses colours.
*
* Compile using:
* gcc nccolour.c -o nccolour -lncurses
*
* Written by Yoran Heling <projects@yorhel.nl>
*
* Date: 2011-06-11
* License: MIT
* Web: http://dev.yorhel.nl/dump/nccolour
*/
#include <stdlib.h>
#include <curses.h>
struct colour {
int code; char *desc;
} colours[] = {
{ -1, "default" },
{ COLOR_BLACK, "BLACK" },
{ COLOR_RED, "RED" },
{ COLOR_GREEN, "GREEN" },
{ COLOR_YELLOW, "YELLOW" },
{ COLOR_BLUE, "BLUE" },
{ COLOR_MAGENTA, "MAGENTA" },
{ COLOR_CYAN, "CYAN" },
{ COLOR_WHITE, "WHITE" },
};
void print_colourpart(int attr, int i) {
addstr(" ");
attron(attr | COLOR_PAIR(i*6+1));
addstr("FD");
addstr(" ");
attron(attr | COLOR_PAIR(i*6+2));
addstr("FB");
attroff(attr | COLOR_PAIR(i*6+2));
addstr(" ");
attron(attr | COLOR_PAIR(i*6+3));
addstr("FW");
attroff(attr | COLOR_PAIR(i*6+3));
addstr(" ");
attron(attr | COLOR_PAIR(i*6+4));
addstr("BG");
attroff(attr | COLOR_PAIR(i*6+4));
addstr(" ");
attron(attr | COLOR_PAIR(i*6+5));
addstr("BD");
attroff(attr | COLOR_PAIR(i*6+5));
}
int main(int argc, char **argv) {
if(!initscr()) {
printf("Error initializing screen.\n");
exit(1);
}
if(!has_colors()) {
printf("This terminal does not support colours.\n");
exit(1);
}
start_color();
// this prevents ncurses from forcing a white-on-black colour scheme,
// regardless of what scheme is used by the terminal.
use_default_colors();
attron(A_BOLD);
mvaddstr(0, 0, "Colour FD FB FW BG BD BFD BFB BFW BBG BBN");
attroff(A_BOLD);
int i;
for(i=0; i<sizeof(colours)/sizeof(struct colour); i++) {
init_pair(i*6+1, colours[i].code, -1);
init_pair(i*6+2, colours[i].code, COLOR_BLACK);
init_pair(i*6+3, colours[i].code, COLOR_WHITE);
init_pair(i*6+4, colours[i].code, colours[i].code);
init_pair(i*6+5, -1, colours[i].code);
mvaddstr(i+2, 1, colours[i].desc);
move(i+2, 8);
print_colourpart(0, i);
print_colourpart(A_BOLD, i);
}
mvaddstr(i+3, 2, "FD = Front colour on default background");
mvaddstr(i+4, 2, "FB = Front colour on black background");
mvaddstr(i+5, 2, "FW = Front colour on white background");
mvaddstr(i+6, 2, "BG = Front and background colour");
mvaddstr(i+7, 2, "BD = Background colour with default front colour");
mvaddstr(i+8, 2, "B?? = As above, with A_BOLD enabled");
mvaddstr(i+10, 0, "Hit any key to exit.");
refresh();
getch();
endwin();
return 0;
}

326
pub/download/code/vinfo.c Normal file
View file

@ -0,0 +1,326 @@
/* vinfo - A small commandline visual novel info display thingy
Last modified: 2009-11-16
This is just a simple example program using the public VNDB API,
this program is neither useful nor actively maintained. Feel free
to extend it to suit your needs.
Requirements:
- A POSIX-compatible system
- GNU getopt()
- json-c (http://oss.metaparadigm.com/json-c/)
Compile:
gcc vinfo.c `pkg-config --cflags --libs json` -o vinfo
Usage:
vinfo -u <username> -p <password> <vnid>
TODO:
- Giving password on the commandline is a really bad idea,
need to fix an alternative method.
- Display more info on VN info output (links/description)
- Make host/port configurable
- VN searching
- More error checking on the received JSON data
- Producers/releases?
Copyright (c) 2009 Yoran Heling
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.
*/
#define PROGRAM "vinfo"
#define VERSION 0.1
#define SERVER "81.204.242.156" /* beta, you may want to change this to whatever api.vndb.org resolves to */
#define PORT 19534
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <json.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#define WS "\011\012\015\040"
#define DIE(str) { perror(str); exit(1); }
char *user, *pass;
int sock;
/* sends command and returns reply */
char *docmd(char *cmd) {
char *res, *fmt;
unsigned int start, end, read = 0, size = 1024;
int r;
json_object *json;
if(send(sock, cmd, strlen(cmd), 0) < 0)
DIE("send");
/* receive data */
res = malloc(size);
while(memchr(res, 4, read) == NULL) {
if(read > 102400) {
printf("ERROR: Too long reply.\n");
exit(1);
}
if(size-read < 500) {
size *= 2;
res = realloc(res, size);
}
if((r = recv(sock, res+read, size-read, 0)) < 0)
DIE("recv");
read += r;
}
/* remove leading and trailing whitespace */
end = ((char *)memchr(res, 4, read))-res;
res[end--] = 0;
while(strspn(res+end, WS))
end--;
start = strspn(res, WS);
if(start == 0)
fmt = res;
else {
fmt = malloc(end-start+1);
strcpy(fmt, res+start);
free(res);
}
/* check for error response */
if(!strncmp(fmt, "error", strlen("error"))) {
res = fmt+strlen("error");
res += strspn(res, WS);
json = json_tokener_parse(res);
if(json != NULL && json_object_is_type(json, json_type_object)) {
printf("ERROR(%s): %s\n",
json_object_get_string(json_object_object_get(json, "id")),
json_object_get_string(json_object_object_get(json, "msg")));
json_object_put(json);
} else {
printf("Received something strange...\n> %s\n", fmt);
}
free(fmt);
exit(1);
}
return fmt;
}
/* opens the TCP socket and logs in */
void login() {
struct sockaddr_in addr;
json_object *arg;
const char *json;
char *cmd, *res;
/* connect */
if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
DIE("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
inet_aton(SERVER, &addr.sin_addr);
if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
DIE("connect");
/* construct login command */
arg = json_object_new_object();
json_object_object_add(arg, "protocol", json_object_new_int(1));
json_object_object_add(arg, "client", json_object_new_string(PROGRAM));
json_object_object_add(arg, "clientver", json_object_new_double(VERSION));
json_object_object_add(arg, "username", json_object_new_string(user));
json_object_object_add(arg, "password", json_object_new_string(pass));
json = json_object_to_json_string(arg);
cmd = malloc(strlen(json) + 10);
sprintf(cmd, "login %s\04", json);
json_object_put(arg);
/* login */
res = docmd(cmd);
free(cmd);
if(strncmp("ok", res, 2)) {
printf("ERROR: Received something strange.\n> %s\n", res);
free(res);
exit(1);
}
free(res);
}
void vninfo(int vid) {
char cmd[50], *res, *tmp, *tmp2;
const char *str;
int i, n;
json_object *json, *vn, *itm;
login();
sprintf(cmd, "get vn basic,details (id=%d)\04", vid);
res = docmd(cmd);
if(strncmp("results", res, 7)) {
printf("ERROR: Received something strange.\n> %s\n", res);
exit(1);
}
tmp = res+7;
tmp += strspn(tmp, WS);
if((json = json_tokener_parse(tmp)) == NULL || !json_object_is_type(json, json_type_object)) {
printf("ERROR: Received something strange.\n> %s\n", res);
exit(1);
}
/*printf("\n%s\n\n", tmp);*/
/* note: may want to put in some checks on whether the data indeed confirms to what we expect */
if(json_object_get_int(json_object_object_get(json, "num")) < 1) {
printf("No VN with that ID.\n");
exit(1);
}
vn = json_object_array_get_idx(json_object_object_get(json, "items"), 0);
/* header + titles */
printf("------------------------------ v%-5d ----------------------------\n", vid);
printf(" Title : %s\n", json_object_get_string(json_object_object_get(vn, "title")));
if((str = json_object_get_string(json_object_object_get(vn, "original"))) != NULL)
printf(" Official : %s\n", str);
/* aliases (string processing in C, meh) */
str = json_object_get_string(json_object_object_get(vn, "aliases"));
if(str != NULL) {
printf(" Aliases : ");
tmp = strdup(str);
tmp2 = tmp;
i = -1;
do {
i++;
if(!tmp[i] || tmp[i] == ',' || tmp[i] == '\n') {
if(tmp2 != tmp)
printf(" ");
tmp2 += strspn(tmp2, ", \n");
n = tmp[i];
tmp[i] = 0;
printf("%s\n", tmp2);
if(n) {
i++;
tmp2 = tmp+i;
}
}
} while(tmp[i]);
free(tmp);
}
/* release date */
str = json_object_get_string(json_object_object_get(vn, "released"));
printf(" First release : %-10s\n", str != NULL ? str : "-");
/* length */
itm = json_object_object_get(vn, "length");
if(json_object_is_type(itm, json_type_int)) {
printf(" Length : ");
switch(json_object_get_int(itm)) {
case 1: printf("Very short\n"); break;
case 2: printf("Short\n"); break;
case 3: printf("Medium\n"); break;
case 4: printf("Long\n"); break;
case 5: printf("Very long\n"); break;
}
}
/* languages */
itm = json_object_object_get(vn, "languages");
if(json_object_array_length(itm) > 0) {
printf(" Available in : ");
for(i=0; i<json_object_array_length(itm); i++) {
if(i)
printf(", ");
printf("%s", json_object_get_string(json_object_array_get_idx(itm, i)));
}
printf("\n");
}
/* platforms */
itm = json_object_object_get(vn, "platforms");
if(json_object_array_length(itm) > 0) {
printf(" ...for : ");
for(i=0; i<json_object_array_length(itm); i++) {
if(i)
printf(", ");
printf("%s", json_object_get_string(json_object_array_get_idx(itm, i)));
}
printf("\n");
}
json_object_put(json);
free(res);
}
void usage() {
printf("%s -u username -p password query\n", PROGRAM);
exit(1);
}
int main(int argc, char **argv) {
char *query;
int r;
user = pass = query = NULL;
while((r = getopt(argc, argv, "-u:p:")) >= 0) {
switch(r) {
case 'u':
user = optarg;
break;
case 'p':
pass = optarg;
break;
case '\1':
query = optarg;
break;
default:
usage();
}
}
if(!pass || !user || !query)
usage();
if(sscanf(query, "%d", &r) == 1 && r > 0) {
vninfo(r);
} else {
printf("Sorry, searching is not supported yet\n");
exit(1);
}
return 0;
}

View file

@ -0,0 +1,342 @@
/*
* YAPong.c 0.01 - Yet Another pong clone, made by //YorHel
*
* Copyright 2006 Y.Heling.
* 2006-02-22
* License: MIT
*/
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <signal.h>
#include <sys/time.h>
#define DI_UP 1
#define DI_DOWN 2
#define DI_RIGHT 3
#define DI_LEFT 4
void movepadel(char, char);
void startgame();
void drawpadels();
void updatescore();
void drawframe();
void updatedot();
void movedot(int);
int print_help(char *);
int winrows, wincols, padsize, padposL, padposR, scoreL,
scoreR, dotX, dotY, delay, padstep, dotstep;
char direX, direY, started, paused, scored, autosize;
WINDOW *win;
int main(int argc, char *argv[]) {
/* defaults */
autosize = 0;
padstep = 1;
dotstep = 1;
winrows = 25; wincols = 80;
padsize = ((winrows-3)/10);
delay = 50 * 1000;
/* args */
{
char *name = *argv++;
char *ch;
while(ch = *argv++) {
if(!strcmp(ch, "-h"))
return print_help(name);
else if(!strcmp(ch, "-l")) {
int level = atoi(*argv++);
switch(level) {
case 1 : delay = 100*1000; padsize = 6; padstep = 2; dotstep = 1; break;
case 2 : delay = 80*1000; padsize = 6; padstep = 2; dotstep = 1; break;
case 3 : delay = 65*1000; padsize = 5; padstep = 1; dotstep = 1; break;
case 4 : delay = 50*1000; padsize = 3; padstep = 1; dotstep = 1; break;
case 5 : delay = 80*1000; padsize = 3; padstep = 1; dotstep = 2; break;
default :
printf("ERROR: unknown level %d\n", level);
return 0; break;
}
}
else if(!strcmp(ch, "-d")) {
delay = atoi(*argv++) * 1000;
if(delay >= 1000*1000 || delay == 0) {
printf("ERROR: delay should be an integer between 0 and 1000\n");
return 1;
}
}
else if(!strcmp(ch, "-p")) {
padsize = atoi(*argv++);
if(padsize > wincols-3 || padsize == 0) {
printf("ERROR: padel size should at least be 1 and should not be too high\n");
return 1;
}
}
else if(!strcmp(ch, "-s")) {
if(!strcmp(*argv, "auto")) {
autosize = 1; *argv++;
} else {
wincols = atoi(*argv++);
winrows = atoi(*argv++);
autosize = 0;
if(wincols < 20 || winrows < 5) {
printf("ERROR: Window size should at least be 20x5\n");
return 1;
}
}
}
else if(!strcmp(ch, "-ps")) {
padstep = atoi(*argv++);
if(padstep > padsize || padstep <= 0) {
printf("ERROR: padstep should at least be 0 and should not be larger than padsize\n");
return 1;
}
}
else if(!strcmp(ch, "-ds")) {
dotstep = atoi(*argv++);
if(dotstep <= 0) {
printf("ERROR: dotstep should be a positive integer\n");
return 1;
}
}
else {
printf("ERROR: no such option: %s\n", ch);
return print_help(name);
}
}
}
/* initialize */
if( (win = initscr()) == NULL) {
fprintf(stderr, "ERROR: Can't initialize ncurses\n");
return(1);
}
cbreak(); /* imidiatly get input chars */
noecho(); /* don't print input chars */
keypad(stdscr, TRUE); /* also get other keys */
curs_set(0); /* hide cursor */
if(autosize)
getmaxyx(stdscr, winrows, wincols);
/* non-changable stuff */
padposL = padposR = ((winrows/2)-(padsize/2));
scoreL = scoreR = 0;
dotX = (wincols/2);
dotY = (winrows/2)-1;
direX = DI_RIGHT;
direY = DI_DOWN;
started = paused = 0;
mvaddstr(0, 0, "Initializing, please wait...");
refresh();
clear();
/* draw stuff */
drawframe();
drawpadels();
mvaddch(dotY, dotX, '0');
refresh();
/* get keyboard input */
int ch;
while(1) {
ch = getch();
switch(ch) {
case KEY_UP :
movepadel('r', 'u'); break;
case KEY_DOWN :
movepadel('r', 'd'); break;
case 'a' :
movepadel('l', 'u'); break;
case 'z' :
movepadel('l', 'd'); break;
case ' ' :
if(!started)
startgame();
else if(scored) {
scored = 0;
mvaddch(dotY, dotX, ' ');
dotX = (wincols/2);
dotY = (winrows/2)-1;
refresh();
} else if(!paused)
paused = 1;
else if(paused)
paused = 0;
break;
case 'q' :
goto end;
break;
}
}
/* cleanup */
end:
erase();
mvaddstr(0, 0, "Thank you for playing Yet Another pong game. :)\nPlease visit http://yorhel.nl/ when your bored...\n");
refresh();
delwin(win);
endwin();
refresh();
return 0;
}
void movepadel(char which, char direct) {
if(paused || scored || !started)
return;
int *pos = which == 'r' ? &padposR : &padposL;
*pos += direct == 'u' ? -1*padstep : padstep;
if(*pos < 2)
*pos = 2;
if(*pos > winrows-padsize-2)
*pos = winrows-padsize-2;
drawpadels();
move(wincols-1, 0);
refresh();
}
void startgame() {
struct itimerval t;
t.it_interval.tv_sec = t.it_value.tv_sec = 0;
t.it_interval.tv_usec = t.it_value.tv_usec = delay;
setitimer(ITIMER_REAL, &t, NULL);
struct sigaction s;
s.sa_handler = movedot;
s.sa_flags = 0;
sigemptyset(&s.sa_mask);
sigaction(SIGALRM, &s, NULL);
started = 1;
}
void drawframe() {
mvaddstr(0, 3, "left");
mvaddstr(0, wincols-8, "right");
mvaddstr(0, ((wincols/2)-7), "YAPong by //YorHel");
move(1, 0);
hline(ACS_HLINE, wincols);
move(winrows-1, 0);
hline(ACS_HLINE, wincols);
updatescore();
}
void updatescore() {
char scl[3], scr[3];
sprintf(scl, "%02d", scoreL);
sprintf(scr, "%02d", scoreR);
mvaddstr(0, 0, scl);
mvaddstr(0, wincols-2, scr);
}
void drawpadels() {
int c;
for(c=winrows; c--; ) {
if(c < 2 || c >= winrows-1)
continue;
/* left paddel */
if(c >= padposL && c <= padposL+padsize)
mvaddch(c, 0, ' ' | A_REVERSE);
else
mvaddch(c, 0, ' ');
/* right paddel */
if(c >= padposR && c <= padposR+padsize)
mvaddch(c, wincols-1, ' ' | A_REVERSE);
else
mvaddch(c, wincols-1, ' ');
}
}
/* called from signal */
void movedot(int signal) {
if(signal != SIGALRM || !started || paused || scored)
return;
mvaddch(dotY, dotX, ' ');
dotX += direX == DI_LEFT ? -1*dotstep : dotstep;
dotY += direY == DI_UP ? -1*dotstep : dotstep;
if(direY == DI_UP && dotY <= 2) {
direY = DI_DOWN;
dotY = 2;
}
if(direY == DI_DOWN && dotY >= winrows-2) {
direY = DI_UP;
dotY = winrows-2;
}
if(direX == DI_RIGHT && dotX >= wincols-2) {
direX = DI_LEFT;
dotX = wincols-2;
if(dotY < padposR || dotY > padposR + padsize) {
scored = 1;
scoreL++;
direX = DI_LEFT;
updatescore();
}
}
if(direX == DI_LEFT && dotX <= 1) {
direX = DI_RIGHT;
dotX = 1;
if(dotY < padposL || dotY > padposL + padsize) {
scored = 1;
scoreR++;
direX = DI_RIGHT;
updatescore();
}
}
mvaddch(dotY, dotX, '0');
move(wincols-1, 0);
refresh();
}
int print_help(char *name) {
printf("Usage: %s [options]\n\n", name);
printf("Options:\n");
printf(" -h This help message.\n");
printf(" -d int Specifies the interval between every move\n");
printf(" of the dot. You can speed up the game by\n");
printf(" setting this to a lower value.\n");
printf(" -p int Specifies the size of each padel in pixels\n");
printf(" -s x y Specifies the size of the window, or set\n");
printf(" to 'auto' to use the size of your current\n");
printf(" terminal. Recommended and default size is\n");
printf(" 80x25.\n");
printf(" -ps int Specifies the amount of pixels the padels\n");
printf(" move each time\n");
printf(" -ds int The amount of pixels the dot moves each\n");
printf(" time, setting this to a larger value\n");
printf(" increases game speed a lot.\n");
printf(" -l level The game-level, higher levels are more\n");
printf(" difficult. See below for more information\n\n");
printf("Levels:\n");
printf(" option equals to\n");
printf(" -l 1 -d 100 -p 6 -ps 2 -ds 1\n");
printf(" -l 2 -d 80 -p 6 -ps 2 -ds 1\n");
printf(" -l 3 -d 65 -p 5 -ps 1 -ds 1\n");
printf(" -l 4 -d 50 -p 3 -ps 1 -ds 1\n");
printf(" -l 5 -d 80 -p 3 -ps 1 -ds 2\n");
printf(" Please note that all the levels are meant for a 80x25\n");
printf(" window size, level 5 might be very easy with a higher\n");
printf(" window size. In that case you should change the\n");
printf(" the options yourself.\n\n");
printf("Ingame keys:\n");
printf(" space Start/pause/resume game\n");
printf(" key_up Move right padel up\n");
printf(" key_down Move right padel down\n");
printf(" a Move left padel up\n");
printf(" z Move left padel down\n");
printf(" q Quit game\n");
return 0;
}

335
pub/download/code/yapong.c Normal file
View file

@ -0,0 +1,335 @@
/*
* YAPong.c 0.02 - Yet Another pong clone, made by //YorHel
*
* Copyright 2006 Y.Heling.
* 2006-02-23
* License: MIT
*/
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#define DI_UP 1
#define DI_DOWN 2
#define DI_RIGHT 3
#define DI_LEFT 4
void movepadel(char, char);
void drawpadels();
void updatescore();
void drawframe();
void updatedot();
void movedot();
int print_help(char *);
int winrows, wincols, padsize, padposL, padposR, scoreL,
scoreR, dotX, dotY, delay, padstep, dotstep;
char direX, direY, started, paused, scored, autosize, autopsize;
WINDOW *win;
int main(int argc, char *argv[]) {
/* defaults */
autosize = 1;
autopsize = 1;
padstep = 1;
dotstep = 1;
winrows = 25; wincols = 80;
padsize = 0;
delay = 50;
/* args */
{
char *name = *argv++;
char *ch;
while(ch = *argv++) {
if(!strcmp(ch, "-h"))
return print_help(name);
else if(!strcmp(ch, "-l")) {
int level = atoi(*argv++);
switch(level) {
case 1 : delay = 100; padsize = 6; padstep = 2; dotstep = 1; break;
case 2 : delay = 80; padsize = 6; padstep = 2; dotstep = 1; break;
case 3 : delay = 65; padsize = 5; padstep = 1; dotstep = 1; break;
case 4 : delay = 50; padsize = 3; padstep = 1; dotstep = 1; break;
case 5 : delay = 80; padsize = 3; padstep = 1; dotstep = 2; break;
default :
printf("ERROR: unknown level %d\n", level);
return 0; break;
}
}
else if(!strcmp(ch, "-d")) {
delay = atoi(*argv++);
if(delay >= 1000 || delay == 0) {
printf("ERROR: delay should be an integer between 0 and 1000\n");
return 1;
}
}
else if(!strcmp(ch, "-p")) {
if(!strcmp(*argv, "auto")) {
autopsize = 1; *argv++;
} else {
autopsize = 0;
padsize = atoi(*argv++);
if(padsize > wincols-3 || padsize == 0) {
printf("ERROR: padel size should at least be 1 and should not be too high\n");
return 1;
}
}
}
else if(!strcmp(ch, "-s")) {
if(!strcmp(*argv, "auto")) {
autosize = 1; *argv++;
} else {
wincols = atoi(*argv++);
winrows = atoi(*argv++);
autosize = 0;
if(wincols < 20 || winrows < 5) {
printf("ERROR: Window size should at least be 20x5\n");
return 1;
}
}
}
else if(!strcmp(ch, "-ps")) {
padstep = atoi(*argv++);
if(padstep <= 0) {
printf("ERROR: padstep should at least be 1\n");
return 1;
}
}
else if(!strcmp(ch, "-ds")) {
dotstep = atoi(*argv++);
if(dotstep <= 0) {
printf("ERROR: dotstep should be a positive integer\n");
return 1;
}
}
else {
printf("ERROR: no such option: %s\n", ch);
return print_help(name);
}
}
}
/* initialize */
if( (win = initscr()) == NULL) {
fprintf(stderr, "ERROR: Can't initialize ncurses\n");
return(1);
}
cbreak(); /* imidiatly get input chars */
noecho(); /* don't print input chars */
keypad(stdscr, TRUE); /* also get other keys */
curs_set(0); /* hide cursor */
nodelay(stdscr, TRUE);
if(autosize)
getmaxyx(stdscr, winrows, wincols);
if(autopsize)
padsize = ((winrows-3)/10)*2;
/* non-changable stuff */
padposL = padposR = ((winrows/2)-(padsize/2));
scoreL = scoreR = 0;
dotX = (wincols/2);
dotY = (winrows/2)-1;
direX = DI_RIGHT;
direY = DI_DOWN;
started = paused = 0;
/* draw stuff */
drawframe();
drawpadels();
mvaddch(dotY, dotX, '0');
refresh();
/* main loop */
delay = delay/15; /* assume napms() takes 50% more time */
int ch; int d = 0;
while(1) {
ch = getch();
switch(ch) {
case ERR : break;
case KEY_UP :
movepadel('r', 'u'); break;
case KEY_DOWN :
movepadel('r', 'd'); break;
case 'a' :
movepadel('l', 'u'); break;
case 'z' :
movepadel('l', 'd'); break;
case ' ' :
if(!started)
started = 1;
else if(scored) {
scored = 0;
mvaddch(dotY, dotX, ' ');
dotX = (wincols/2);
dotY = (winrows/2)-1;
refresh();
} else if(!paused)
paused = 1;
else if(paused)
paused = 0;
break;
case 'q' :
goto end;
break;
}
if(++d == delay) {
d = 0;
movedot();
}
napms(10);
}
/* cleanup */
end:
erase();
mvaddstr(0, 0, "Thank you for playing Yet Another pong game. :)\nPlease visit http://yorhel.nl/ when your even more bored...\n");
refresh();
delwin(win);
endwin();
refresh();
return 0;
}
void movepadel(char which, char direct) {
if(paused || scored || !started)
return;
int *pos = which == 'r' ? &padposR : &padposL;
*pos += direct == 'u' ? -1*padstep : padstep;
if(*pos < 2)
*pos = 2;
if(*pos > winrows-padsize-2)
*pos = winrows-padsize-2;
drawpadels();
move(wincols-1, 0);
refresh();
}
void drawframe() {
mvaddstr(0, 3, "left");
mvaddstr(0, wincols-8, "right");
mvaddstr(0, ((wincols/2)-7), "YAPong by //YorHel");
move(1, 0);
hline(ACS_HLINE, wincols);
move(winrows-1, 0);
hline(ACS_HLINE, wincols);
updatescore();
}
void updatescore() {
char scl[3], scr[3];
sprintf(scl, "%02d", scoreL);
sprintf(scr, "%02d", scoreR);
mvaddstr(0, 0, scl);
mvaddstr(0, wincols-2, scr);
}
void drawpadels() {
int c;
for(c=winrows; c--; ) {
if(c < 2 || c >= winrows-1)
continue;
/* left paddel */
if(c >= padposL && c <= padposL+padsize)
mvaddch(c, 0, ' ' | A_REVERSE);
else
mvaddch(c, 0, ' ');
/* right paddel */
if(c >= padposR && c <= padposR+padsize)
mvaddch(c, wincols-1, ' ' | A_REVERSE);
else
mvaddch(c, wincols-1, ' ');
}
}
void movedot() {
if(!started || paused || scored)
return;
mvaddch(dotY, dotX, ' ');
dotX += direX == DI_LEFT ? -1*dotstep : dotstep;
dotY += direY == DI_UP ? -1*dotstep : dotstep;
if(direY == DI_UP && dotY <= 2) {
direY = DI_DOWN;
dotY = 2;
}
if(direY == DI_DOWN && dotY >= winrows-2) {
direY = DI_UP;
dotY = winrows-2;
}
if(direX == DI_RIGHT && dotX >= wincols-2) {
direX = DI_LEFT;
dotX = wincols-2;
if(dotY < padposR || dotY > padposR + padsize) {
scored = 1;
scoreL++;
direX = DI_LEFT;
updatescore();
}
}
if(direX == DI_LEFT && dotX <= 1) {
direX = DI_RIGHT;
dotX = 1;
if(dotY < padposL || dotY > padposL + padsize) {
scored = 1;
scoreR++;
direX = DI_RIGHT;
updatescore();
}
}
mvaddch(dotY, dotX, '0');
move(wincols-1, 0);
refresh();
}
int print_help(char *name) {
printf("Usage: %s [options]\n\n", name);
printf("Options:\n");
printf(" -h This help message.\n");
printf(" -d int Specifies the interval between every move\n");
printf(" of the dot. You can speed up the game by\n");
printf(" setting this to a lower value.\n");
printf(" -p int Specifies the size of each padel in pixels,\n");
printf(" set to auto to automatically calculate the\n");
printf(" size using the window size.\n");
printf(" -s x y Specifies the size of the window, or set\n");
printf(" to 'auto' to use the size of your current\n");
printf(" terminal. Recommended size: 80x25, default:\n");
printf(" auto.\n");
printf(" -ps int Specifies the amount of pixels the padels\n");
printf(" move each time\n");
printf(" -ds int The amount of pixels the dot moves each\n");
printf(" time, setting this to a larger value\n");
printf(" increases game speed a lot.\n");
printf(" -l level The game-level, higher levels are more\n");
printf(" difficult. See below for more information\n\n");
printf("Levels:\n");
printf(" option equals to\n");
printf(" -l 1 -d 100 -p 6 -ps 2 -ds 1\n");
printf(" -l 2 -d 80 -p 6 -ps 2 -ds 1\n");
printf(" -l 3 -d 65 -p 5 -ps 1 -ds 1\n");
printf(" -l 4 -d 50 -p 3 -ps 1 -ds 1\n");
printf(" -l 5 -d 80 -p 3 -ps 1 -ds 2\n");
printf(" Please note that all the levels are meant for a 80x25\n");
printf(" window size, level 5 might be very easy with a higher\n");
printf(" window size. In that case you should change the\n");
printf(" the options yourself.\n\n");
printf("Ingame keys:\n");
printf(" space Start/pause/resume game\n");
printf(" key_up Move right padel up\n");
printf(" key_down Move right padel down\n");
printf(" a Move left padel up\n");
printf(" z Move left padel down\n");
printf(" q Quit game\n");
return 0;
}