lib: Trim .nim files trailing whitespace

via OSX: find . -name '*.nim' -exec sed -i '' -E 's/[[:space:]]+$//' {} +
This commit is contained in:
Adam Strzelecki 2015-09-04 23:03:56 +02:00
commit 43bddf62dd
67 changed files with 2435 additions and 2435 deletions

View file

@ -7,7 +7,7 @@
# distribution, for details about the copyright.
#
## A higher level `mySQL`:idx: database wrapper. The same interface is
## A higher level `mySQL`:idx: database wrapper. The same interface is
## implemented for other databases too.
import strutils, mysql
@ -29,22 +29,22 @@ type
{.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn].}
proc sql*(query: string): SqlQuery {.noSideEffect, inline.} =
## constructs a SqlQuery from the string `query`. This is supposed to be
## constructs a SqlQuery from the string `query`. This is supposed to be
## used as a raw-string-literal modifier:
## ``sql"update user set counter = counter + 1"``
##
## If assertions are turned off, it does nothing. If assertions are turned
## If assertions are turned off, it does nothing. If assertions are turned
## on, later versions will check the string for valid syntax.
result = SqlQuery(query)
proc dbError(db: DbConn) {.noreturn.} =
proc dbError(db: DbConn) {.noreturn.} =
## raises an EDb exception.
var e: ref EDb
new(e)
e.msg = $mysql.error(db)
raise e
proc dbError*(msg: string) {.noreturn.} =
proc dbError*(msg: string) {.noreturn.} =
## raises an EDb exception with message `msg`.
var e: ref EDb
new(e)
@ -55,9 +55,9 @@ when false:
proc dbQueryOpt*(db: DbConn, query: string, args: varargs[string, `$`]) =
var stmt = mysql_stmt_init(db)
if stmt == nil: dbError(db)
if mysql_stmt_prepare(stmt, query, len(query)) != 0:
if mysql_stmt_prepare(stmt, query, len(query)) != 0:
dbError(db)
var
var
binding: seq[MYSQL_BIND]
discard mysql_stmt_close(stmt)
@ -79,9 +79,9 @@ proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
else:
add(result, dbQuote(args[a]))
inc(a)
else:
else:
add(result, c)
proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.
tags: [FReadDB, FWriteDb].} =
## tries to execute the query and returns true if successful, false otherwise.
@ -97,19 +97,19 @@ proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
## executes the query and raises EDB if not successful.
var q = dbFormat(query, args)
if mysql.realQuery(db, q, q.len) != 0'i32: dbError(db)
proc newRow(L: int): Row =
proc newRow(L: int): Row =
newSeq(result, L)
for i in 0..L-1: result[i] = ""
proc properFreeResult(sqlres: mysql.PRES, row: cstringArray) =
proc properFreeResult(sqlres: mysql.PRES, row: cstringArray) =
if row != nil:
while mysql.fetchRow(sqlres) != nil: discard
mysql.freeResult(sqlres)
iterator fastRows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
## executes the query and iterates over the result dataset. This is very
## executes the query and iterates over the result dataset. This is very
## fast, but potenially dangerous: If the for-loop-body executes another
## query, the results can be undefined. For MySQL this is the case!.
rawExec(db, query, args)
@ -121,7 +121,7 @@ iterator fastRows*(db: DbConn, query: SqlQuery,
while true:
row = mysql.fetchRow(sqlres)
if row == nil: break
for i in 0..L-1:
for i in 0..L-1:
setLen(result[i], 0)
if row[i] == nil:
result[i] = nil
@ -164,8 +164,8 @@ proc getRow*(db: DbConn, query: SqlQuery,
var L = int(mysql.numFields(sqlres))
result = newRow(L)
var row = mysql.fetchRow(sqlres)
if row != nil:
for i in 0..L-1:
if row != nil:
for i in 0..L-1:
setLen(result[i], 0)
if row[i] == nil:
result[i] = nil
@ -173,7 +173,7 @@ proc getRow*(db: DbConn, query: SqlQuery,
add(result[i], row[i])
properFreeResult(sqlres, row)
proc getAllRows*(db: DbConn, query: SqlQuery,
proc getAllRows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): seq[Row] {.tags: [FReadDB].} =
## executes the query and returns the whole result dataset.
result = @[]
@ -196,44 +196,44 @@ proc getAllRows*(db: DbConn, query: SqlQuery,
inc(j)
mysql.freeResult(sqlres)
iterator rows*(db: DbConn, query: SqlQuery,
iterator rows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
## same as `fastRows`, but slower and safe.
for r in items(getAllRows(db, query, args)): yield r
proc getValue*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): string {.tags: [FReadDB].} =
proc getValue*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): string {.tags: [FReadDB].} =
## executes the query and returns the first column of the first row of the
## result dataset. Returns "" if the dataset contains no rows or the database
## value is NULL.
result = getRow(db, query, args)[0]
proc tryInsertId*(db: DbConn, query: SqlQuery,
proc tryInsertId*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
## executes the query (typically "INSERT") and returns the
## executes the query (typically "INSERT") and returns the
## generated ID for the row or -1 in case of an error.
var q = dbFormat(query, args)
if mysql.realQuery(db, q, q.len) != 0'i32:
if mysql.realQuery(db, q, q.len) != 0'i32:
result = -1'i64
else:
result = mysql.insertId(db)
proc insertId*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
## executes the query (typically "INSERT") and returns the
proc insertId*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
## executes the query (typically "INSERT") and returns the
## generated ID for the row.
result = tryInsertID(db, query, args)
if result < 0: dbError(db)
proc execAffectedRows*(db: DbConn, query: SqlQuery,
proc execAffectedRows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.
tags: [FReadDB, FWriteDb].} =
tags: [FReadDB, FWriteDb].} =
## runs the query (typically "UPDATE") and returns the
## number of affected rows
rawExec(db, query, args)
result = mysql.affectedRows(db)
proc close*(db: DbConn) {.tags: [FDb].} =
proc close*(db: DbConn) {.tags: [FDb].} =
## closes the database connection.
if db != nil: mysql.close(db)
@ -242,14 +242,14 @@ proc open*(connection, user, password, database: string): DbConn {.
## opens a database connection. Raises `EDb` if the connection could not
## be established.
result = mysql.init(nil)
if result == nil: dbError("could not open database connection")
if result == nil: dbError("could not open database connection")
let
colonPos = connection.find(':')
host = if colonPos < 0: connection
else: substr(connection, 0, colonPos-1)
port: int32 = if colonPos < 0: 0'i32
else: substr(connection, colonPos+1).parseInt.int32
if mysql.realConnect(result, host, user, password, database,
if mysql.realConnect(result, host, user, password, database,
port, nil, 0) == nil:
var errmsg = $mysql.error(result)
db_mysql.close(result)
@ -257,6 +257,6 @@ proc open*(connection, user, password, database: string): DbConn {.
proc setEncoding*(connection: DbConn, encoding: string): bool {.
tags: [FDb].} =
## sets the encoding of a database connection, returns true for
## sets the encoding of a database connection, returns true for
## success, false for failure.
result = mysql.set_character_set(connection, encoding) == 0

View file

@ -7,7 +7,7 @@
# distribution, for details about the copyright.
#
## A higher level `PostgreSQL`:idx: database wrapper. This interface
## A higher level `PostgreSQL`:idx: database wrapper. This interface
## is implemented for other databases too.
import strutils, postgres
@ -20,7 +20,7 @@ type
## used to get a row's
## column text on demand
EDb* = object of IOError ## exception that is raised if a database error occurs
SqlQuery* = distinct string ## an SQL query string
SqlPrepared* = distinct string ## a identifier for the prepared queries
@ -30,15 +30,15 @@ type
{.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn,
TSqlPrepared: SqlPrepared].}
proc sql*(query: string): SqlQuery {.noSideEffect, inline.} =
## constructs a SqlQuery from the string `query`. This is supposed to be
proc sql*(query: string): SqlQuery {.noSideEffect, inline.} =
## constructs a SqlQuery from the string `query`. This is supposed to be
## used as a raw-string-literal modifier:
## ``sql"update user set counter = counter + 1"``
##
## If assertions are turned off, it does nothing. If assertions are turned
## If assertions are turned off, it does nothing. If assertions are turned
## on, later versions will check the string for valid syntax.
result = SqlQuery(query)
proc dbError*(db: DbConn) {.noreturn.} =
## raises an EDb exception.
var e: ref EDb
@ -73,7 +73,7 @@ proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
inc(a)
else:
add(result, c)
proc tryExec*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): bool {.tags: [FReadDB, FWriteDb].} =
## tries to execute the query and returns true if successful, false otherwise.
@ -106,7 +106,7 @@ proc exec*(db: DbConn, stmtName: SqlPrepared,
proc newRow(L: int): Row =
newSeq(result, L)
for i in 0..L-1: result[i] = ""
proc setupQuery(db: DbConn, query: SqlQuery,
args: varargs[string]): PPGresult =
var arr = allocCStringArray(args)
@ -128,7 +128,7 @@ proc prepare*(db: DbConn; stmtName: string, query: SqlQuery;
var res = pqprepare(db, stmtName, query.string, int32(nParams), nil)
if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db)
return SqlPrepared(stmtName)
proc setRow(res: PPGresult, r: var Row, line, cols: int32) =
for col in 0..cols-1:
setLen(r[col], 0)
@ -140,7 +140,7 @@ proc setRow(res: PPGresult, r: var Row, line, cols: int32) =
iterator fastRows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): Row {.tags: [FReadDB].} =
## executes the query and iterates over the result dataset. This is very
## executes the query and iterates over the result dataset. This is very
## fast, but potenially dangerous: If the for-loop-body executes another
## query, the results can be undefined. For Postgres it is safe though.
var res = setupQuery(db, query, args)
@ -224,14 +224,14 @@ proc getValue*(db: DbConn, query: SqlQuery,
## value is NULL.
var x = pqgetvalue(setupQuery(db, query, args), 0, 0)
result = if isNil(x): "" else: $x
proc tryInsertID*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].}=
## executes the query (typically "INSERT") and returns the
## executes the query (typically "INSERT") and returns the
## generated ID for the row or -1 in case of an error. For Postgre this adds
## ``RETURNING id`` to the query, so it only works if your primary key is
## named ``id``.
var x = pqgetvalue(setupQuery(db, SqlQuery(string(query) & " RETURNING id"),
## named ``id``.
var x = pqgetvalue(setupQuery(db, SqlQuery(string(query) & " RETURNING id"),
args), 0, 0)
if not isNil(x):
result = parseBiggestInt($x)
@ -240,13 +240,13 @@ proc tryInsertID*(db: DbConn, query: SqlQuery,
proc insertID*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
## executes the query (typically "INSERT") and returns the
## executes the query (typically "INSERT") and returns the
## generated ID for the row. For Postgre this adds
## ``RETURNING id`` to the query, so it only works if your primary key is
## named ``id``.
## named ``id``.
result = tryInsertID(db, query, args)
if result < 0: dbError(db)
proc execAffectedRows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.tags: [
FReadDB, FWriteDb].} =
@ -286,6 +286,6 @@ proc open*(connection, user, password, database: string): DbConn {.
proc setEncoding*(connection: DbConn, encoding: string): bool {.
tags: [FDb].} =
## sets the encoding of a database connection, returns true for
## sets the encoding of a database connection, returns true for
## success, false for failure.
return pqsetClientEncoding(connection, encoding) == 0

View file

@ -7,7 +7,7 @@
# distribution, for details about the copyright.
#
## A higher level `SQLite`:idx: database wrapper. This interface
## A higher level `SQLite`:idx: database wrapper. This interface
## is implemented for other databases too.
import strutils, sqlite3
@ -19,31 +19,31 @@ type
InstantRow* = Pstmt ## a handle that can be used to get a row's column
## text on demand
EDb* = object of IOError ## exception that is raised if a database error occurs
SqlQuery* = distinct string ## an SQL query string
FDb* = object of IOEffect ## effect that denotes a database operation
FReadDb* = object of FDb ## effect that denotes a read operation
FWriteDb* = object of FDb ## effect that denotes a write operation
{.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn].}
proc sql*(query: string): SqlQuery {.noSideEffect, inline.} =
## constructs a SqlQuery from the string `query`. This is supposed to be
proc sql*(query: string): SqlQuery {.noSideEffect, inline.} =
## constructs a SqlQuery from the string `query`. This is supposed to be
## used as a raw-string-literal modifier:
## ``sql"update user set counter = counter + 1"``
##
## If assertions are turned off, it does nothing. If assertions are turned
## If assertions are turned off, it does nothing. If assertions are turned
## on, later versions will check the string for valid syntax.
result = SqlQuery(query)
proc dbError(db: DbConn) {.noreturn.} =
proc dbError(db: DbConn) {.noreturn.} =
## raises an EDb exception.
var e: ref EDb
new(e)
e.msg = $sqlite3.errmsg(db)
raise e
proc dbError*(msg: string) {.noreturn.} =
proc dbError*(msg: string) {.noreturn.} =
## raises an EDb exception with message `msg`.
var e: ref EDb
new(e)
@ -67,8 +67,8 @@ proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string =
inc(a)
else:
add(result, c)
proc tryExec*(db: DbConn, query: SqlQuery,
proc tryExec*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): bool {.tags: [FReadDb, FWriteDb].} =
## tries to execute the query and returns true if successful, false otherwise.
var q = dbFormat(query, args)
@ -81,32 +81,32 @@ proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {.
tags: [FReadDb, FWriteDb].} =
## executes the query and raises EDB if not successful.
if not tryExec(db, query, args): dbError(db)
proc newRow(L: int): Row =
newSeq(result, L)
for i in 0..L-1: result[i] = ""
proc setupQuery(db: DbConn, query: SqlQuery,
args: varargs[string]): Pstmt =
proc setupQuery(db: DbConn, query: SqlQuery,
args: varargs[string]): Pstmt =
var q = dbFormat(query, args)
if prepare_v2(db, q, q.len.cint, result, nil) != SQLITE_OK: dbError(db)
proc setRow(stmt: Pstmt, r: var Row, cols: cint) =
for col in 0..cols-1:
setLen(r[col], column_bytes(stmt, col)) # set capacity
setLen(r[col], 0)
let x = column_text(stmt, col)
if not isNil(x): add(r[col], x)
iterator fastRows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): Row {.tags: [FReadDb].} =
## executes the query and iterates over the result dataset. This is very
## executes the query and iterates over the result dataset. This is very
## fast, but potenially dangerous: If the for-loop-body executes another
## query, the results can be undefined. For Sqlite it is safe though.
var stmt = setupQuery(db, query, args)
var L = (column_count(stmt))
var result = newRow(L)
while step(stmt) == SQLITE_ROW:
while step(stmt) == SQLITE_ROW:
setRow(stmt, result, L)
yield result
if finalize(stmt) != SQLITE_OK: dbError(db)
@ -136,31 +136,31 @@ proc getRow*(db: DbConn, query: SqlQuery,
var stmt = setupQuery(db, query, args)
var L = (column_count(stmt))
result = newRow(L)
if step(stmt) == SQLITE_ROW:
if step(stmt) == SQLITE_ROW:
setRow(stmt, result, L)
if finalize(stmt) != SQLITE_OK: dbError(db)
proc getAllRows*(db: DbConn, query: SqlQuery,
proc getAllRows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): seq[Row] {.tags: [FReadDb].} =
## executes the query and returns the whole result dataset.
result = @[]
for r in fastRows(db, query, args):
result.add(r)
iterator rows*(db: DbConn, query: SqlQuery,
iterator rows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): Row {.tags: [FReadDb].} =
## same as `FastRows`, but slower and safe.
for r in fastRows(db, query, args): yield r
proc getValue*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): string {.tags: [FReadDb].} =
proc getValue*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): string {.tags: [FReadDb].} =
## executes the query and returns the first column of the first row of the
## result dataset. Returns "" if the dataset contains no rows or the database
## value is NULL.
var stmt = setupQuery(db, query, args)
if step(stmt) == SQLITE_ROW:
let cb = column_bytes(stmt, 0)
if cb == 0:
if cb == 0:
result = ""
else:
result = newStringOfCap(cb)
@ -168,12 +168,12 @@ proc getValue*(db: DbConn, query: SqlQuery,
else:
result = ""
if finalize(stmt) != SQLITE_OK: dbError(db)
proc tryInsertID*(db: DbConn, query: SqlQuery,
proc tryInsertID*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64
{.tags: [FWriteDb], raises: [].} =
## executes the query (typically "INSERT") and returns the
## generated ID for the row or -1 in case of an error.
## executes the query (typically "INSERT") and returns the
## generated ID for the row or -1 in case of an error.
var q = dbFormat(query, args)
var stmt: sqlite3.Pstmt
result = -1
@ -183,27 +183,27 @@ proc tryInsertID*(db: DbConn, query: SqlQuery,
if finalize(stmt) != SQLITE_OK:
result = -1
proc insertID*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
## executes the query (typically "INSERT") and returns the
proc insertID*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} =
## executes the query (typically "INSERT") and returns the
## generated ID for the row. For Postgre this adds
## ``RETURNING id`` to the query, so it only works if your primary key is
## named ``id``.
## named ``id``.
result = tryInsertID(db, query, args)
if result < 0: dbError(db)
proc execAffectedRows*(db: DbConn, query: SqlQuery,
proc execAffectedRows*(db: DbConn, query: SqlQuery,
args: varargs[string, `$`]): int64 {.
tags: [FReadDb, FWriteDb].} =
tags: [FReadDb, FWriteDb].} =
## executes the query (typically "UPDATE") and returns the
## number of affected rows.
exec(db, query, args)
result = changes(db)
proc close*(db: DbConn) {.tags: [FDb].} =
proc close*(db: DbConn) {.tags: [FDb].} =
## closes the database connection.
if sqlite3.close(db) != SQLITE_OK: dbError(db)
proc open*(connection, user, password, database: string): DbConn {.
tags: [FDb].} =
## opens a database connection. Raises `EDb` if the connection could not
@ -216,12 +216,12 @@ proc open*(connection, user, password, database: string): DbConn {.
proc setEncoding*(connection: DbConn, encoding: string): bool {.
tags: [FDb].} =
## sets the encoding of a database connection, returns true for
## sets the encoding of a database connection, returns true for
## success, false for failure.
##
## Note that the encoding cannot be changed once it's been set.
## According to SQLite3 documentation, any attempt to change
## the encoding after the database is created will be silently
## According to SQLite3 documentation, any attempt to change
## the encoding after the database is created will be silently
## ignored.
exec(connection, sql"PRAGMA encoding = ?", [encoding])
result = connection.getValue(sql"PRAGMA encoding") == encoding

View file

@ -9,7 +9,7 @@
## This module implements graphical output for Nim; the current
## implementation uses SDL but the interface is meant to support multiple
## backends some day. There is no need to init SDL as this module does that
## backends some day. There is no need to init SDL as this module does that
## implicitly.
import colors, math
@ -24,7 +24,7 @@ type
Surface* {.pure, final.} = object
w*, h*: Natural
s*: sdl.PSurface
EGraphics* = object of IOError
Font {.pure, final.} = object
@ -35,7 +35,7 @@ type
proc toSdlColor*(c: Color): sdl.Color =
## Convert colors.Color to sdl.Color
var x = c.extractRGB
var x = c.extractRGB
result.r = x.r and 0xff
result.g = x.g and 0xff
result.b = x.b and 0xff
@ -43,7 +43,7 @@ proc toSdlColor*(c: Color): sdl.Color =
proc createSdlColor*(sur: PSurface, c: Color, alpha: int = 0): int32 =
## Creates a color using ``sdl.MapRGBA``.
var x = c.extractRGB
return sdl.mapRGBA(sur.s.format, x.r and 0xff, x.g and 0xff,
return sdl.mapRGBA(sur.s.format, x.r and 0xff, x.g and 0xff,
x.b and 0xff, alpha and 0xff)
proc toSdlRect*(r: Rect): sdl.Rect =
@ -53,26 +53,26 @@ proc toSdlRect*(r: Rect): sdl.Rect =
result.w = uint16(r.width)
result.h = uint16(r.height)
proc raiseEGraphics =
proc raiseEGraphics =
raise newException(EGraphics, $sdl.getError())
proc surfaceFinalizer(s: PSurface) = sdl.freeSurface(s.s)
proc newSurface*(width, height: int): PSurface =
## creates a new surface.
new(result, surfaceFinalizer)
result.w = width
result.h = height
result.s = sdl.createRGBSurface(sdl.SWSURFACE, width, height,
result.s = sdl.createRGBSurface(sdl.SWSURFACE, width, height,
32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0)
if result.s == nil:
raiseEGraphics()
assert(not sdl.mustLock(result.s))
proc fontFinalizer(f: PFont) = closeFont(f.f)
proc newFont*(name = "VeraMono.ttf", size = 9, color = colBlack): PFont =
proc newFont*(name = "VeraMono.ttf", size = 9, color = colBlack): PFont =
## Creates a new font object. Raises ``EIO`` if the font cannot be loaded.
new(result, fontFinalizer)
result.f = openFont(name, size.cint)
@ -84,7 +84,7 @@ var
defaultFont*: PFont ## default font that is used; this needs to initialized
## by the client!
proc initDefaultFont*(name = "VeraMono.ttf", size = 9, color = colBlack) =
proc initDefaultFont*(name = "VeraMono.ttf", size = 9, color = colBlack) =
## initializes the `defaultFont` var.
defaultFont = newFont(name, size, color)
@ -98,7 +98,7 @@ proc newScreenSurface*(width, height: int): PSurface =
raiseEGraphics()
proc writeToBMP*(sur: PSurface, filename: string) =
## Saves the contents of the surface `sur` to the file `filename` as a
## Saves the contents of the surface `sur` to the file `filename` as a
## BMP file.
if sdl.saveBMP(sur.s, filename) != 0:
raise newException(IOError, "cannot write: " & filename)
@ -111,7 +111,7 @@ type
template setPix(video, pitch, x, y, col: expr): stmt =
video[y * pitch + x] = int32(col)
template getPix(video, pitch, x, y: expr): expr =
template getPix(video, pitch, x, y: expr): expr =
colors.Color(video[y * pitch + x])
const
@ -120,7 +120,7 @@ const
proc getPixel(sur: PSurface, x, y: Natural): colors.Color {.inline.} =
assert x <% sur.w
assert y <% sur.h
result = getPix(cast[PPixels](sur.s.pixels), sur.s.pitch.int div ColSize,
result = getPix(cast[PPixels](sur.s.pixels), sur.s.pitch.int div ColSize,
x, y)
proc setPixel(sur: PSurface, x, y: Natural, col: colors.Color) {.inline.} =
@ -146,7 +146,7 @@ proc `[]=`*(sur: PSurface, x, y: int, col: Color) =
## set the pixel at position ``(x, y)``. No range checking is done!
setPixel(sur, x, y, col)
proc blit*(destSurf: PSurface, destRect: Rect, srcSurf: PSurface,
proc blit*(destSurf: PSurface, destRect: Rect, srcSurf: PSurface,
srcRect: Rect) =
## Copies ``srcSurf`` into ``destSurf``
var destTRect, srcTRect: sdl.Rect
@ -175,7 +175,7 @@ proc drawText*(sur: PSurface, p: Point, text: string, font = defaultFont) =
## font.
var textSur: PSurface # This surface will have the text drawn on it
new(textSur, surfaceFinalizer)
# Render the text
textSur.s = sdl_ttf.renderTextBlended(font.f, text, font.color)
# Merge the text surface with sur
@ -183,14 +183,14 @@ proc drawText*(sur: PSurface, p: Point, text: string, font = defaultFont) =
proc drawText*(sur: PSurface, p: Point, text: string,
bg: Color, font = defaultFont) =
## Draws text, at location ``p`` with font ``font``. ``bg``
## Draws text, at location ``p`` with font ``font``. ``bg``
## is the background color.
var textSur: PSurface # This surface will have the text drawn on it
new(textSur, surfaceFinalizer)
textSur.s = sdl_ttf.renderTextShaded(font.f, text, font.color, toSdlColor(bg))
# Merge the text surface with sur
sur.blit((p.x, p.y, sur.w, sur.h), textSur, (0, 0, sur.w, sur.h))
proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) =
## draws a circle with center `p` and radius `r` with the given color
## onto the surface `sur`.
@ -205,7 +205,7 @@ proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) =
if x+px <% sur.w:
if y+py <% sur.h: setPix(video, pitch, x+px, y+py, color)
if y-py <% sur.h: setPix(video, pitch, x+px, y-py, color)
if x-px <% sur.w:
if y+py <% sur.h: setPix(video, pitch, x-px, y+py, color)
if y-py <% sur.h: setPix(video, pitch, x-px, y-py, color)
@ -213,7 +213,7 @@ proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) =
if x+py <% sur.w:
if y+px <% sur.h: setPix(video, pitch, x+py, y+px, color)
if y-px <% sur.h: setPix(video, pitch, x+py, y-px, color)
if x-py <% sur.w:
if y+px <% sur.h: setPix(video, pitch, x-py, y+px, color)
if y-px <% sur.h: setPix(video, pitch, x-py, y-px, color)
@ -225,10 +225,10 @@ proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) =
py = py - 1
px = px + 1
proc `>-<`(val: int, s: PSurface): int {.inline.} =
proc `>-<`(val: int, s: PSurface): int {.inline.} =
return if val < 0: 0 elif val >= s.w: s.w-1 else: val
proc `>|<`(val: int, s: PSurface): int {.inline.} =
proc `>|<`(val: int, s: PSurface): int {.inline.} =
return if val < 0: 0 elif val >= s.h: s.h-1 else: val
proc drawLine*(sur: PSurface, p1, p2: Point, color: Color) =
@ -242,7 +242,7 @@ proc drawLine*(sur: PSurface, p1, p2: Point, color: Color) =
var dy = y1 - y0
var dx = x1 - x0
if dy < 0:
dy = -dy
dy = -dy
stepy = -1
else:
stepy = 1
@ -251,7 +251,7 @@ proc drawLine*(sur: PSurface, p1, p2: Point, color: Color) =
stepx = -1
else:
stepx = 1
dy = dy * 2
dy = dy * 2
dx = dx * 2
var video = cast[PPixels](sur.s.pixels)
var pitch = sur.s.pitch.int div ColSize
@ -328,17 +328,17 @@ proc drawRect*(sur: PSurface, r: Rect, color: Color) =
if (r.x >= 0 and r.x <= sur.s.w) and (r.y >= 0 and r.y <= sur.s.h):
var minW = min(sur.s.w - r.x, r.width)
var minH = min(sur.s.h - r.y, r.height)
# Draw Top
for i in 0 .. minW - 1:
setPix(video, pitch, r.x + i, r.y, color)
setPix(video, pitch, r.x + i, r.y + minH - 1, color) # Draw bottom
# Draw left side
for i in 0 .. minH - 1:
setPix(video, pitch, r.x, r.y + i, color)
setPix(video, pitch, r.x + minW - 1, r.y + i, color) # Draw right side
proc fillRect*(sur: PSurface, r: Rect, col: Color) =
## Fills a rectangle using sdl's ``FillRect`` function.
var rect = toSdlRect(r)
@ -350,23 +350,23 @@ proc plot4EllipsePoints(sur: PSurface, cx, cy, x, y: Natural, col: Color) =
var pitch = sur.s.pitch.int div ColSize
if cx+x <= sur.s.w-1:
if cy+y <= sur.s.h-1: setPix(video, pitch, cx+x, cy+y, col)
if cy-y <= sur.s.h-1: setPix(video, pitch, cx+x, cy-y, col)
if cy-y <= sur.s.h-1: setPix(video, pitch, cx+x, cy-y, col)
if cx-x <= sur.s.w-1:
if cy+y <= sur.s.h-1: setPix(video, pitch, cx-x, cy+y, col)
if cy-y <= sur.s.h-1: setPix(video, pitch, cx-x, cy-y, col)
proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural,
proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural,
col: Color) =
## Draws an ellipse, ``CX`` and ``CY`` specify the center X and Y of the
## Draws an ellipse, ``CX`` and ``CY`` specify the center X and Y of the
## ellipse, ``XRadius`` and ``YRadius`` specify half the width and height
## of the ellipse.
var
var
x, y: Natural
xChange, yChange: int
ellipseError: Natural
twoASquare, twoBSquare: Natural
stoppingX, stoppingY: Natural
twoASquare = 2 * xRadius * xRadius
twoBSquare = 2 * yRadius * yRadius
x = xRadius
@ -376,7 +376,7 @@ proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural,
ellipseError = 0
stoppingX = twoBSquare * xRadius
stoppingY = 0
while stoppingX >= stoppingY: # 1st set of points, y` > - 1
sur.plot4EllipsePoints(cx, cy, x, y, col)
inc(y)
@ -388,7 +388,7 @@ proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural,
dec(stoppingX, twoBSquare)
inc(ellipseError, xChange)
inc(xChange, twoBSquare)
# 1st point set is done; start the 2nd set of points
x = 0
y = yRadius
@ -408,7 +408,7 @@ proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural,
dec(stoppingY, twoASquare)
inc(ellipseError, yChange)
inc(yChange,twoASquare)
proc plotAA(sur: PSurface, x, y: int, c: float, color: Color) =
if (x > 0 and x < sur.s.w) and (y > 0 and y < sur.s.h):
@ -419,43 +419,43 @@ proc plotAA(sur: PSurface, x, y: int, c: float, color: Color) =
setPix(video, pitch, x, y,
pixColor.intensity(1.0 - c) + color.intensity(c))
template ipart(x: expr): expr = floor(x)
template ipart(x: expr): expr = floor(x)
template cround(x: expr): expr = ipart(x + 0.5)
template fpart(x: expr): expr = x - ipart(x)
template rfpart(x: expr): expr = 1.0 - fpart(x)
proc drawLineAA*(sur: PSurface, p1, p2: Point, color: Color) =
## Draws a anti-aliased line from ``p1`` to ``p2``, using Xiaolin Wu's
## Draws a anti-aliased line from ``p1`` to ``p2``, using Xiaolin Wu's
## line algorithm
var (x1, x2, y1, y2) = (p1.x.toFloat(), p2.x.toFloat(),
var (x1, x2, y1, y2) = (p1.x.toFloat(), p2.x.toFloat(),
p1.y.toFloat(), p2.y.toFloat())
var dx = x2 - x1
var dy = y2 - y1
var ax = dx
if ax < 0'f64:
ax = 0'f64 - ax
var ay = dy
if ay < 0'f64:
ay = 0'f64 - ay
if ax < ay:
swap(x1, y1)
swap(x2, y2)
swap(dx, dy)
template doPlot(x, y: int, c: float, color: Color): stmt =
if ax < ay:
sur.plotAA(y, x, c, color)
else:
sur.plotAA(x, y, c, color)
if x2 < x1:
swap(x1, x2)
swap(y1, y2)
var gradient = dy / dx
# handle first endpoint
var xend = cround(x1)
@ -509,19 +509,19 @@ when not defined(testing) and isMainModule:
# Draw the shapes
surf.drawLineAA((150, 170), (400, 471), colTan)
surf.drawLine((100, 170), (400, 471), colRed)
surf.drawEllipse(200, 300, 200, 30, colSeaGreen)
surf.drawHorLine(1, 300, 400, colViolet)
surf.drawHorLine(1, 300, 400, colViolet)
# Check if the ellipse is the size it's suppose to be.
surf.drawVerLine(200, 300 - 30 + 1, 60, colViolet) # ^^ | i suppose it is
surf.drawEllipse(400, 300, 300, 300, colOrange)
surf.drawEllipse(5, 5, 5, 5, colGreen)
surf.drawHorLine(5, 5, 900, colRed)
surf.drawVerLine(5, 60, 800, colRed)
surf.drawCircle((600, 500), 60, colRed)
surf.fillRect((50, 50, 100, 100), colFuchsia)
surf.fillRect((150, 50, 100, 100), colGreen)
surf.drawRect((50, 150, 100, 100), colGreen)
@ -530,12 +530,12 @@ when not defined(testing) and isMainModule:
surf.drawHorLine(250, 150, 100, colRed)
surf.drawLineAA((592, 160), (592, 280), colPurple)
#surf.drawText((300, 300), "TEST", colMidnightBlue)
#var textSize = textBounds("TEST")
#surf.drawText((300, 300 + textSize.height), $textSize.width & ", " &
# $textSize.height, colDarkGreen)
var mouseStartX = -1
var mouseStartY = -1
withEvents(surf, event):
@ -561,17 +561,17 @@ when not defined(testing) and isMainModule:
surf.drawLineAA((mouseStartX, mouseStartY), (int(mbd.x), int(mbd.y)), colPurple)
mouseStartX = -1
mouseStartY = -1
of sdl.MOUSEMOTION:
var mm = sdl.evMouseMotion(eventp)
if mouseStartX != -1 and mouseStartY != -1:
surf.drawLineAA((mouseStartX, mouseStartY), (int(mm.x), int(mm.y)), colPurple)
#echo(mm.x, " ", mm.y, " ", mm.yrel)
else:
discard "echo(event.kind)"
sdl.updateRect(surf.s, 0, 0, 800, 600)
surf.writeToBMP("test.bmp")
sdl.quit()

View file

@ -41,11 +41,11 @@ type
reExtended = 3, ## ignore whitespace and ``#`` comments
reStudy = 4 ## study the expression (may be omitted if the
## expression will be used only once)
RegexDesc = object
RegexDesc = object
h: ptr Pcre
e: ptr ExtraData
Regex* {.deprecated.} = ref RegexDesc ## a compiled regular expression
RegexError* = object of ValueError

View file

@ -7,7 +7,7 @@
# distribution, for details about the copyright.
#
## This module provides an easy to use sockets-style
## This module provides an easy to use sockets-style
## nim interface to the OpenSSL library.
{.deprecated.}
@ -20,37 +20,37 @@ type
bio: BIO
{.deprecated: [TSecureSocket: SecureSocket].}
proc connect*(sock: var SecureSocket, address: string,
proc connect*(sock: var SecureSocket, address: string,
port: int): int =
## Connects to the specified `address` on the specified `port`.
## Returns the result of the certificate validation.
SslLoadErrorStrings()
ERR_load_BIO_strings()
if SSL_library_init() != 1:
raiseOSError(osLastError())
var ctx = SSL_CTX_new(SSLv23_client_method())
if ctx == nil:
ERR_print_errors_fp(stderr)
raiseOSError(osLastError())
#if SSL_CTX_load_verify_locations(ctx,
#if SSL_CTX_load_verify_locations(ctx,
# "/tmp/openssl-0.9.8e/certs/vsign1.pem", NIL) == 0:
# echo("Failed load verify locations")
# ERR_print_errors_fp(stderr)
sock.bio = BIO_new_ssl_connect(ctx)
if BIO_get_ssl(sock.bio, addr(sock.ssl)) == 0:
raiseOSError(osLastError())
if BIO_set_conn_hostname(sock.bio, address & ":" & $port) != 1:
raiseOSError(osLastError())
if BIO_do_connect(sock.bio) <= 0:
ERR_print_errors_fp(stderr)
raiseOSError(osLastError())
result = SSL_get_verify_result(sock.ssl)
proc recvLine*(sock: SecureSocket, line: var TaintedString): bool =
@ -86,12 +86,12 @@ proc close*(sock: SecureSocket) =
when not defined(testing) and isMainModule:
var s: SecureSocket
echo connect(s, "smtp.gmail.com", 465)
#var buffer: array[0..255, char]
#echo BIO_read(bio, buffer, buffer.len)
var buffer: string = ""
echo s.recvLine(buffer)
echo buffer
echo buffer
echo buffer.len