code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
struct _osw { int dummy; }; struct _osc { int dummy; }; struct _osg { int dummy; }; struct _osp { int dummy; };
zzywany123-libaw-1
awios.h
C
bsd
119
#if !defined __OBJC__ typedef struct _View View; typedef struct _Window Window; typedef struct _NSCursor NSCursor; typedef struct _NSOpenGLContext NSOpenGLContext; #endif struct _osg { int dummy; }; struct _osw { View * view; Window * win; NSCursor * defcur; int _vfreed; int _wfreed; }; struct _osc { NSOpenGLContext * ctx; }; struct _osp { NSCursor * cur; uint8_t rgba[CURSOR_BYTES]; };
zzywany123-libaw-1
awcocoa.h
C
bsd
459
#include <windows.h> void * awosSelf() { HMODULE ret; GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCSTR)awosSelf, &ret); return ret; } void * awosResolve(void * in, const char * name) { return GetProcAddress(in, name); } const char * awosModPath() { static char buf[256]; GetModuleFileName(awosSelf(), buf, sizeof(buf)); return buf; }
zzywany123-libaw-1
awntresolve.c
C
bsd
368
#include "awnpapios.h" #include <stdlib.h> @interface Layer : CAOpenGLLayer { @public CFTimeInterval lastdraw; } - (void)drawInCGLContext:(CGLContextObj)ct pixelFormat:(CGLPixelFormatObj)pf forLayerTime:(CFTimeInterval)lt displayTime:(const CVTimeStamp *)dt; - (BOOL)canDrawInCGLContext:(CGLContextObj)ct pixelFormat:(CGLPixelFormatObj)pf forLayerTime:(CFTimeInterval)lt displayTime:(const CVTimeStamp *)dt; @end struct _ins { insHeader h; Layer * l; }; ins * awosNew(NPNetscapeFuncs * browser, NPP i) { ins * ret = calloc(1, sizeof(ins)); ret->l = [[Layer layer] retain]; browser->setvalue(i, NPPVpluginEventModel, (void *)NPEventModelCocoa); browser->setvalue(i, NPNVpluginDrawingModel, (void *)NPDrawingModelCoreAnimation); return ret; } void awosDel(ins * o) { [o->l release]; free(o); } static void update(ins * o) { debug("update %p", o); [o->l performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:NO]; debug("/update %p", o); } void awosSetWindow(ins * o, NPWindow * win) { update(o); } int awosMakeCurrentI(ins * o) { return 1; } int awosClearCurrentI(ins * o) { return 1; } void awosUpdate(ins * o) { update(o); } static void ev(ins * o, int ev, int x, int y) { got(&o->h.w, ev, x, y); debug("event %d %d %d", ev, x, y); } NPError awosEvent(ins * o, void * ve) { extern unsigned mapkeycode(unsigned); NPCocoaEvent * e = (NPCocoaEvent *)ve; debug("event"); switch (e->type) { case NPCocoaEventDrawRect: debug("NPCocoaEventDrawRect"); break; case NPCocoaEventMouseDown: debug("NPCocoaEventMouseDown"); ev(o, AW_EVENT_DOWN, AW_KEY_MOUSELEFT + e->data.mouse.buttonNumber, 0); break; case NPCocoaEventMouseUp: debug("NPCocoaEventMouseUp"); ev(o, AW_EVENT_UP, AW_KEY_MOUSELEFT + e->data.mouse.buttonNumber, 0); break; case NPCocoaEventMouseMoved: debug("NPCocoaEventMouseMoved"); ev(o, AW_EVENT_MOTION, e->data.mouse.pluginX, e->data.mouse.pluginY); break; case NPCocoaEventMouseEntered: debug("NPCocoaEventMouseEntered"); break; case NPCocoaEventMouseExited: debug("NPCocoaEventMouseExited"); break; case NPCocoaEventMouseDragged: debug("NPCocoaEventMouseDragged"); break; case NPCocoaEventKeyDown: debug("NPCocoaEventKeyDown"); ev(o, AW_EVENT_DOWN, mapkeycode(e->data.key.keyCode), 0); break; case NPCocoaEventKeyUp: debug("NPCocoaEventKeyUp"); ev(o, AW_EVENT_UP, mapkeycode(e->data.key.keyCode), 0); break; case NPCocoaEventFlagsChanged: debug("NPCocoaEventFlagsChanged"); break; case NPCocoaEventFocusChanged: debug("NPCocoaEventFocusChanged"); break; case NPCocoaEventWindowFocusChanged: debug("NPCocoaEventWindowFocusChanged"); break; case NPCocoaEventScrollWheel: debug("NPCocoaEventScrollWheel"); break; case NPCocoaEventTextInput: debug("NPCocoaEventTextInput"); break; default: assert(0); } return NPERR_NO_ERROR; } const char * awosResourcesPath(ins * o) { return [[[NSBundle bundleForClass: [o->l class]] resourcePath] UTF8String]; } NPError awosGetValue(NPP i, NPPVariable var, void * v) { ins * o = (ins*)i->pdata; NPError ret = NPERR_NO_ERROR; debug("os getvalue"); switch(var) { case NPNVpluginDrawingModel: debug("getval drawingmodel"); *(int*)v = NPDrawingModelOpenGL; break; case NPPVpluginCoreAnimationLayer: debug("getval layer"); o->l.backgroundColor = CGColorGetConstantColor(kCGColorBlack); o->l.autoresizingMask = kCALayerWidthSizable | kCALayerHeightSizable; *(CALayer**)v = o->l; break; default: debug("os getval default"); ret = NPERR_GENERIC_ERROR; break; } return ret; } @implementation Layer - (void)drawInCGLContext:(CGLContextObj)ct pixelFormat:(CGLPixelFormatObj)pf forLayerTime:(CFTimeInterval)lt displayTime:(const CVTimeStamp *)dt { ins * o = (ins*)coData(coCurrent()); CGLSetCurrentContext(ct); debug("drawInCGLContext %p", ct); debug("aw>>main"); coSwitchTo(o->h.coaw); debug("main>>aw"); CGLSetCurrentContext(ct); debug("drawInCGLContext /cocall"); [super drawInCGLContext: ct pixelFormat: pf forLayerTime: lt displayTime: dt]; debug("/drawInCGLContext"); update(o); } - (BOOL)canDrawInCGLContext:(CGLContextObj)ct pixelFormat:(CGLPixelFormatObj)pf forLayerTime:(CFTimeInterval)lt displayTime:(const CVTimeStamp *)ts { debug("candraw %f", (float)lt); ins * o = (ins*)coData(coCurrent()); BOOL ret = lt - lastdraw > 1 / 60.; if (ret) lastdraw = lt; else update(o); return ret; } @end
zzywany123-libaw-1
awcocoanpapi.m
Objective-C
bsd
4,600
#-*-Python-*- Import('env') aw = env.ForLib() aw.UsesOpenGL() backend = { 'android' : 'awandroid.c ', 'iphone' : 'awiphone.m co.c coroutine/source/Coro.c awreportfile.c tlspthread.c', 'cocoa': 'awcocoa.m awmackeycodes.c awreportconsole.c', 'x11': 'awmain.c awx.c awx11keycodes.c awreportconsole.c', 'nt': 'awmain.c aww.c awntkeycodes.c awntevent.c awreportconsole.c', }[aw['BACKEND']] if aw['BACKEND'] == 'android': backend += aw['ANDROIDNDK'] + '/sources/android/native_app_glue/android_native_app_glue.c' if backend.find('coroutine/') >= 0: aw.Append(CPPPATH=['coroutine/source',]) aw.Append(CPPDEFINES=['USE_SETJMP',]) aw.Append(CPPDEFINES=['BUILDING_AW']) aw.Lib('aw', 'aw.c ' + backend) aw.Install('include/aw', ['aw.h', 'awtypes.h', 'sysgl.h', 'sysglu.h']) awnpapi = env.ForNPAPI() if awnpapi: awnpapi.CompileAs32Bits() awnpapi.Append(CPPPATH=['include']) awnpapi.Append(CPPDEFINES=['AWPLUGIN']) awnpapi.Append(CPPPATH=['coroutine/source',]) awnpapi.UsesOpenGL() if awnpapi['BACKEND'] == 'nt': awnpapi.Append(CPPDEFINES=['USE_FIBERS',]) elif awnpapi['BACKEND'] == 'x11': awnpapi.Append(CPPDEFINES=['USE_UCONTEXT',]) else: awnpapi.Append(CPPDEFINES=['USE_SETJMP',]) backend = { 'cocoa': ''' awposixresolve.c awmackeycodes.c awcocoanpapi.m awreportfile.c tlspthread.c ''', 'nt': ''' awntresolve.c awntkeycodes.c awntevent.c awntnpapi.c awreportfile.c ''', 'x11': ''' awposixresolve.c awx11keycodes.c awxembednpapi.c awreportconsole.c ''', }[awnpapi['BACKEND']] plg = awnpapi.ShLinkLib('awnpapi', backend + ''' aw.c awnpapi.c co.c coroutine/source/Coro.c ''') awtest = env.ForGLPrg() if awtest: awtest.Prg('awtest', 'test/awtest.c') awtest.Prg('hello', 'test/hello.c') awtest.Prg('robot', 'test/robot.c') awtest.Prg('picksquare', 'test/picksquare.c') awtest.Prg('cube', 'test/cube.c') awtest.Prg('multi', 'test/multi.c') awtest.Prg('sharing', 'test/sharing.c') awestest = env.ForGLESPrg() if awestest: awestest.Prg('awtest', 'test/awtest.c') awestest.Prg('gles', 'test/gles.c') awplugin = env.ForPlugin() if awplugin: awplugin.Plg('awplugin', 'test/awtest.c') awplugin.Plg('cubeplugin', 'test/cube.c')
zzywany123-libaw-1
SConscript
Python
bsd
2,356
#define CURSOR_WIDTH 32 #define CURSOR_HEIGHT 32 #define CURSOR_BYTES (4*CURSOR_WIDTH*CURSOR_HEIGHT) #define MAX_WINDOWS 256 #define MAX_EVENTS 1024 #define MAX_PRESSED 256 #if defined _WIN32 #include "aww.h" #elif defined __ANDROID__ #include "awandroid.h" #elif defined __IPHONE_OS_VERSION_MIN_REQUIRED #include "awios.h" #elif defined __APPLE__ #include "awcocoa.h" #else #include "awx.h" #endif struct _ae { awcell type; awcell p[2]; }; typedef struct _osw osw; struct _aw { osw osw; // must be first ag * g; ac * ctx; ap * pointer; void * user; ae * last; ae ev[MAX_EVENTS]; unsigned interval; unsigned char pressed[MAX_PRESSED/8]; unsigned char ppressed[MAX_PRESSED/8]; unsigned head, tail; unsigned width, height; int mx, my; int rx, ry, rw, rh; int maximized; int borders; int shown; }; typedef struct _osg osg; struct _ag { osg osg; // must be first }; typedef struct _osc osc; struct _ac { osc osc; // must be first ag * g; int ok; }; typedef struct _osp osp; struct _ap { osp osp; // must be first int refs; int ok; }; int osgInit(osg *, const char *); int osgTerm(osg *); int oswInit(osw *, osg *, int, int, int, int, int); int oswTerm(osw *); int oswSetTitle(osw *, const char *); int oswMakeCurrent(osw *, osc *); int oswClearCurrent(osw *); int oswSwapBuffers(osw *); int oswShow(osw *); int oswHide(osw *); void oswPollEvent(osw *); void oswThreadEvents(); int oswSetSwapInterval(osw *, int); int oswMaximize(osw *); int oswGeometry(osw *, int, int, unsigned, unsigned); void oswPointer(osw *); unsigned oswOrder(osw **); int oscInit(osc *, osg *, osc *); int oscTerm(osc *); int ospInit(osp *, const void * rgba, unsigned hotx, unsigned hoty); int ospTerm(osp *); // Defined in the frontend void got(osw * w, int, intptr_t, intptr_t); void report(const char * fmt, ...); #if defined NDEBUG static __inline void debug(const char * fmt, ...) {} #else #define debug report #endif #define wmaximized(w) (((aw*)w)->maximized) #define wgroup(w) (&(((aw*)w)->g->osg)) #define cgroup(c) (&(((ac*)c)->g->osg)) #define wpointer(w) (&(((aw*)w)->pointer->osp)) #define wcontext(w) (&(((aw*)w)->ctx->osc)) #define wmousex(w) ((((aw*)w)->mx)) #define wmousey(w) ((((aw*)w)->my)) #define prgba(p) (((ap*)p)->rgba) /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
awos.h
C
bsd
2,553
/* Copyright (c) 2008-2009, Jorge Acereda Maciá All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <ctype.h> #include <assert.h> #include "aw.h" #include "awos.h" #include "bit.h" #if !defined HANDLE_WM_MOUSEWHEEL // XXX mingw doesn't seem to define this one #define HANDLE_WM_MOUSEWHEEL(hwnd,wParam,lParam,fn) ((fn)((hwnd),(int)(short)LOWORD(lParam),(int)(short)HIWORD(lParam),(int)(short)HIWORD(wParam),(UINT)(short)LOWORD(wParam)),0L) #endif static BOOL (APIENTRY *wglSwapInterval) (int interval) = 0; static void setPF(HDC dc) { PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd 1, // version number PFD_DRAW_TO_WINDOW | // support window PFD_SUPPORT_OPENGL | // support OpenGL PFD_DOUBLEBUFFER, // double buffered PFD_TYPE_RGBA, // RGBA type 24, // 24-bit color depth 0, 0, 0, 0, 0, 0, // color bits ignored 0, // no alpha buffer 0, // shift bit ignored 0, // no accumulation buffer 0, 0, 0, 0, // accum bits ignored 32, // 32-bit z-buffer 0, // no stencil buffer 0, // no auxiliary buffer PFD_MAIN_PLANE, // main layer 0, // reserved 0, 0, 0 // layer masks ignored }; SetPixelFormat(dc, ChoosePixelFormat(dc, &pfd), &pfd); } static void wide(WCHAR * d, size_t dsz, const char * t) { MultiByteToWideChar(CP_UTF8, 0, t, -1, d, (int)dsz); } int oswSetTitle(osw * w, const char * t) { WCHAR wt[1024]; wide(wt, sizeof(wt), t); return SetWindowTextW(w->win, wt); } static int openwin(osw * w, int x, int y, int width, int height, DWORD style, DWORD exstyle, osg * g) { RECT r; HWND win; w->style = style; r.left = x; r.top = y; r.right = x + width; r.bottom = y + height; AdjustWindowRect(&r, style, FALSE); win = CreateWindowExW(exstyle, g->appname, g->appname, style, r.left, r.top, r.right - r.left, r.bottom - r.top, g->win, NULL, GetModuleHandleW(NULL), w); if (win) { HDC dc = GetDC(win); setPF(dc); ReleaseDC(win, dc); DragAcceptFiles(win, TRUE); } w->win = win; return win != 0; } static void dispatch(HWND win, unsigned type) { MSG msg; if (PeekMessageW(&msg, win, 0, 0, PM_REMOVE+type)) { TranslateMessage(&msg); DispatchMessageW(&msg); } } #define EXITMSG (WM_USER+0x1024) static DWORD __stdcall groupThread(LPVOID param) { osg * g = (osg *)param;; g->win = CreateWindowExW(0, g->appname, g->appname, WS_POPUP, 0, 0, 0, 0, 0, 0, GetModuleHandleW(NULL), 0); // ShowWindow(g->win, SW_SHOWNORMAL); SetEvent(g->ready); while (1) { MSG msg; if (GetMessageW(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessageW(&msg); } if (msg.message == EXITMSG) break; } DestroyWindow(g->win); return 0; } int osgInit(osg * g, const char * appname) { extern LRESULT CALLBACK handle(HWND win, UINT msg, WPARAM w, LPARAM l); WNDCLASSW wc; int ok; wide(g->appname, sizeof(g->appname), appname); ZeroMemory(&wc, sizeof(wc)); // wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; wc.style += CS_OWNDC; // wc.style += CS_GLOBALCLASS; wc.lpfnWndProc = handle; wc.hInstance = GetModuleHandleW(NULL); wc.lpszClassName = g->appname; ok = 0 != RegisterClassW(&wc); g->ready = CreateEvent(0,0,0,0); g->thread = CreateThread(NULL, 4096, groupThread, g, 0, NULL); WaitForSingleObject(g->ready, INFINITE); CloseHandle(g->ready); g->ready = 0; return ok; } int osgTerm(osg * g) { DWORD ret = 0; PostMessage(g->win, EXITMSG, 0, 0); ret = WaitForSingleObject(g->thread, INFINITE); assert(ret == WAIT_OBJECT_0); ret = 0 != CloseHandle(g->thread); return ret; } int oswInit(osw * w, osg * g, int x, int y, int width, int height, int bl) { DWORD style, exstyle; if (bl) { style = WS_POPUP; exstyle = WS_EX_TOPMOST; } else { style = 0 | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_SIZEBOX | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | 0; exstyle = WS_EX_APPWINDOW; } return openwin(w, x, y, width, height, style, exstyle, g); } int oswTerm(osw * w) { int ret = 1; if (w->win) ret &= 0 != DestroyWindow(w->win); return ret; } int oswSwapBuffers(osw * w) { int ret; HDC dc = GetDC(w->win); ret = SwapBuffers(dc); ReleaseDC(w->win, dc); return ret; } int oswMakeCurrent(osw * w, osc * c) { int ret; HDC dc = GetDC(w->win); ret = wglMakeCurrent(dc, c->ctx); if (!wglSwapInterval) wglSwapInterval = (void*)wglGetProcAddress("wglSwapIntervalEXT"); ReleaseDC(w->win, dc); return ret; } int oswClearCurrent(osw * w) { return wglMakeCurrent(0, 0); } int oswShow(osw * w) { ShowWindow(w->win, wmaximized(w)? SW_MAXIMIZE : SW_SHOWNORMAL); return 1; } int oswHide(osw * w) { ShowWindow(w->win, SW_HIDE); return 1; } void oswPollEvent(osw * w) { dispatch(w->win, 0); /* dispatch(w->win, PM_QS_POSTMESSAGE+PM_QS_SENDMESSAGE+PM_QS_PAINT); dispatch((HWND)-1, PM_QS_POSTMESSAGE+PM_QS_SENDMESSAGE+PM_QS_PAINT); dispatch((HWND)-1, 0); dispatch((HWND)0, PM_QS_POSTMESSAGE+PM_QS_SENDMESSAGE+PM_QS_PAINT); */ } int oswSetSwapInterval(osw * w, int si) { return wglSwapInterval? wglSwapInterval(si) : 1; } int oscInit(osc * c, osg * g, osc * share) { HGLRC ctx; HWND dummy = CreateWindowExW(0, g->appname, g->appname, 0, 0, 0, 0, 0, 0, 0, GetModuleHandleW(NULL), 0); HDC dc = GetDC(dummy); setPF(dc); ctx = wglCreateContext(dc); ReleaseDC(dummy, dc); DestroyWindow(dummy); if (ctx && share) wglShareLists(share->ctx, ctx); c->ctx = ctx; return ctx != 0; } int oscTerm(osc * c) { int ret = 0 != wglDeleteContext(c->ctx); return ret; } int oswMaximize(osw * w) { // handled in oswShow() return 1; } int oswGeometry(osw * w, int x, int y, unsigned width, unsigned height) { RECT r; r.left = x; r.top = y; r.right = x + width; r.bottom = y + height; AdjustWindowRect(&r, w->style, FALSE); return MoveWindow(w->win, r.left, r.top, r.right - r.left, r.bottom - r.top, 1); } void oswSetPointer(osw * w) { osp * p = wpointer(w); if (p) SetCursor(p->icon); else SetCursor(0); } void oswPointer(osw * w) { POINT p; GetCursorPos(&p); SetCursorPos(p.x, p.y); } int ospInit(osp * p, const void * vrgba, unsigned hotx, unsigned hoty) { HDC dc; HBITMAP bm; unsigned char * bits; int x, y; BITMAPV5HEADER bh; ICONINFO ii = {0}; int w = 32; int h = 32; ZeroMemory(&bh, sizeof(BITMAPV5HEADER)); bh.bV5Size = sizeof(bh); bh.bV5Width = w; bh.bV5Height = -h; bh.bV5Planes = 1; bh.bV5BitCount = 32; bh.bV5Compression = BI_RGB; bh.bV5AlphaMask = 0xff000000; bh.bV5BlueMask = 0x00ff0000; bh.bV5GreenMask = 0x0000ff00; bh.bV5RedMask = 0x000000ff; dc = GetDC(0); bm = CreateDIBSection(dc, (BITMAPINFO*)&bh, DIB_RGB_COLORS, (void **)&bits, 0, 0); ReleaseDC(0, dc); memcpy(bits, vrgba, w * h * 4); // Change red <-> blue for (y = 0; y < h; y++) for (x = 0; x < w; x++) { unsigned c = (y*w + x) * 4; unsigned aux = bits[c + 0]; bits[c + 0] = bits[c + 2]; bits[c + 2] = aux; } ii.fIcon = FALSE; ii.xHotspot = hotx; ii.yHotspot = hoty; ii.hbmColor = bm; ii.hbmMask = CreateBitmap(w, h, 1, 1, NULL); p->icon = CreateIconIndirect(&ii); DeleteObject(ii.hbmMask); DeleteObject(ii.hbmColor); return p->icon != 0; } int ospTerm(osp * p) { int ret; SetCursor(0); ret = DestroyIcon(p->icon); return ret; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
aww.c
C
bsd
11,184
/* Copyright (c) 2008-2009, Jorge Acereda Maciá All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <Foundation/NSAutoreleasePool.h> #include <Foundation/NSString.h> #include <Foundation/NSArray.h> #include <Foundation/NSRunLoop.h> #include <Foundation/NSNotification.h> //#include <AppKit/NSApplication.h> #include <AppKit/NSApplicationScripting.h> #include <AppKit/NSScreen.h> #include <AppKit/NSWindow.h> #include <AppKit/NSPasteboard.h> #include <AppKit/NSBitmapImageRep.h> #include <AppKit/NSImage.h> #include <AppKit/NSTrackingArea.h> #include <AppKit/NSCursor.h> #include <AppKit/NSEvent.h> #include <AppKit/NSOpenGL.h> #include <AppKit/NSTextView.h> #include <OpenGL/CGLTypes.h> #include <OpenGL/OpenGL.h> #include <OpenGL/gl.h> @class View; @class Window; #include "aw.h" #include "awos.h" @interface AppDelegate : NSObject { } @end @interface Window : NSWindow { @public osw * _w; } @end @interface View : NSTextView<NSWindowDelegate> { unsigned _prevflags; BOOL _dragging; NSTrackingArea * _currta; @public osw * _w; } - (NSPoint)toAbs: (NSPoint)p; - (void) handleMove; @end #define PROLOGUE \ NSAutoreleasePool * __arp = [[NSAutoreleasePool alloc] init] #define EPILOGUE \ [__arp release] static int reversed(int y) { NSSize ss = [[NSScreen mainScreen] frame].size; return ss.height - y - 1; } static NSRect fromQuartz(NSRect r) { NSSize ss = [[NSScreen mainScreen] frame].size; return NSMakeRect(r.origin.x, ss.height - r.origin.y - r.size.height, r.size.width, r.size.height); } static NSRect toQuartz(NSRect r) { return fromQuartz(r); } static NSCursor * currentCursor(osw * w) { osp * p = wpointer(w); return p? p->cur : w->defcur; } @implementation AppDelegate - (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSApplication *)sender { return NO; } @end @implementation View //- (void) display {} - (void) dealloc { _w->_vfreed = 1; [super dealloc]; } - (void)establishCursor { NSCursor * cur = currentCursor(_w); [cur set]; } - (void)cursorUpdate: (NSEvent*)e { [super cursorUpdate: e]; [self establishCursor]; } - (NSPoint)toAbs: (NSPoint)p { return [_w->win convertBaseToScreen: p]; } - (void)setConstrainedFrameSize:(NSSize)desiredSize{} - (BOOL) acceptsFirstResponder { return YES; } - (void) handleMove { NSSize sz = [self frame].size; NSPoint ul = NSMakePoint(0, sz.height - 1); NSPoint abs = [self toAbs: ul]; got(_w, AW_EVENT_POSITION, abs.x, reversed(abs.y)); } - (void) windowDidMove:(NSNotification *)n { [self handleMove]; } - (void) windowDidResize:(NSNotification *)n { NSRect fr = [_w->view frame]; NSSize sz = fr.size; osc * c = wcontext(_w); if (c) [c->ctx update]; got(_w, AW_EVENT_RESIZE, sz.width, sz.height); [self handleMove]; } - (void) windowDidExpose:(NSNotification *)n { got(_w, AW_EVENT_EXPOSED, 0, 0); } - (void) windowDidResignKey:(NSNotification *)n { got(_w, AW_EVENT_KILLFOCUS, 0, 0); } - (BOOL) windowShouldClose: (id)s { got(_w, AW_EVENT_CLOSE, 0, 0); return NO; } extern unsigned mapkeycode(unsigned); - (void) handleKeyEvent: (NSEvent *)ev mode: (int) mode { got(_w, mode, mapkeycode([ev keyCode]), 0); } - (void) keyUp: (NSEvent *)ev { [self handleKeyEvent: ev mode: AW_EVENT_UP]; } - (void) keyDown: (NSEvent *)ev { [self handleKeyEvent: ev mode: AW_EVENT_DOWN]; [self interpretKeyEvents: [NSArray arrayWithObject: ev]]; } - (void)deleteBackward:(id)sender { got(_w, AW_EVENT_UNICODE, AW_KEY_DELETE, 0); } - (void)insertText:(id)s { int sl = [s length]; int i; for (i = 0; i < sl; i++) got(_w, AW_EVENT_UNICODE, [s characterAtIndex: i], 0); } - (unsigned) keyFor: (unsigned)mask { unsigned ret = 0; switch (mask) { case NSShiftKeyMask: ret = AW_KEY_SHIFT; break; case NSControlKeyMask: ret = AW_KEY_CONTROL; break; case NSAlternateKeyMask: ret = AW_KEY_OPTION; break; case NSCommandKeyMask: ret = AW_KEY_COMMAND; break; default: assert(0); } return ret; } - (void) handleMod: (unsigned)mask flags: (unsigned)flags { unsigned delta = flags ^ _prevflags; unsigned pressed = delta & flags; unsigned released = delta & ~flags; if (mask & pressed) got(_w, AW_EVENT_DOWN, [self keyFor: mask], 0); if (mask & released) got(_w, AW_EVENT_UP, [self keyFor: mask], 0); } - (void) flagsChanged: (NSEvent *)ev { unsigned flags = [ev modifierFlags]; [self handleMod: NSShiftKeyMask flags: flags]; [self handleMod: NSControlKeyMask flags: flags]; [self handleMod: NSAlternateKeyMask flags: flags]; [self handleMod: NSCommandKeyMask flags: flags]; _prevflags = flags; [super flagsChanged: ev]; } - (void) handleMouseEvent: (NSEvent *)ev mode: (int)mode{ got(_w, mode, [ev buttonNumber] + AW_KEY_MOUSELEFT, 0); } - (void) mouseDown: (NSEvent*)ev { _dragging = YES; [self lockFocus]; [self handleMouseEvent: ev mode: AW_EVENT_DOWN]; [self updateTrackingAreas]; // [super mouseDown: ev]; } - (void) mouseUp: (NSEvent*)ev { _dragging = NO; [self handleMouseEvent: ev mode: AW_EVENT_UP]; [self updateTrackingAreas]; [self unlockFocus]; // [super mouseUp: ev]; } - (void) rightMouseDown: (NSEvent*)ev { [self handleMouseEvent: ev mode: AW_EVENT_DOWN]; } - (void) rightMouseUp: (NSEvent*)ev { [self handleMouseEvent: ev mode: AW_EVENT_UP]; } - (void) otherMouseDown: (NSEvent*)ev { [self handleMouseEvent: ev mode: AW_EVENT_DOWN]; } - (void) otherMouseUp: (NSEvent*)ev { [self handleMouseEvent: ev mode: AW_EVENT_UP]; } - (void)scrollWheel:(NSEvent *)ev { unsigned k = [ev deltaY] > 0? AW_KEY_MOUSEWHEELUP : AW_KEY_MOUSEWHEELDOWN; got(_w, AW_EVENT_DOWN, k, 0); got(_w, AW_EVENT_UP, k, 0); } - (void) handleMotion: (NSEvent *)ev { NSPoint l = [ev locationInWindow]; got(_w, AW_EVENT_MOTION, l.x, [self frame].size.height - l.y); } - (void) mouseDragged: (NSEvent *)ev { [self handleMotion: ev]; } - (void) mouseMoved: (NSEvent *)ev { [self handleMotion: ev]; } - (void) mouseExited: (NSEvent *)ev { } - (void) mouseEntered: (NSEvent *)ev { } - (void)updateTrackingAreas { NSRect rect; [self removeTrackingArea: _currta]; [_currta release]; _currta = 0; if (!_dragging) { rect = [self visibleRect]; _currta = [[NSTrackingArea alloc] initWithRect: rect options: 0 | NSTrackingActiveWhenFirstResponder // | NSTrackingActiveAlways | NSTrackingCursorUpdate // | NSTrackingMouseEnteredAndExited // | NSTrackingInVisibleRect // | NSTrackingEnabledDuringMouseDrag // | NSTrackingAssumeInside owner: self userInfo: nil]; [self addTrackingArea: _currta]; } [super updateTrackingAreas]; } - (BOOL) isOpaque { return YES; } - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender { NSPasteboard * pb = [sender draggingPasteboard]; NSArray * a = [pb propertyListForType:NSFilenamesPboardType]; unsigned i; for (i = 0; i < [a count]; i++) { NSString * s = [a objectAtIndex: i]; got(_w, AW_EVENT_DROP, (uintptr_t)strdup([s UTF8String]), 0); } return YES; } @end @implementation Window //- (void) display {} - (void) dealloc { _w->_wfreed = 1; [super dealloc]; } - (BOOL) canBecomeKeyWindow { return YES; } - (BOOL)isReleasedWhenClosed { return NO; } @end int oswSetTitle(osw * w, const char * t) { PROLOGUE; NSString * s = [[NSString alloc] initWithUTF8String: t]; [w->win setTitle: s]; [s release]; EPILOGUE; return 1; } static void openwin(osw * w, int x, int y, int width, int height, unsigned style) { Window * win; NSRect frm; View * view; NSRect rect = toQuartz(NSMakeRect(x, y, width, height)); win = [[Window alloc] initWithContentRect: rect styleMask: style backing: NSBackingStoreBuffered defer:NO]; frm = [Window contentRectForFrameRect: [win frame] styleMask: style]; view = [[View alloc] initWithFrame: frm]; w->view = view; w->win = win; w->view->_w = w; w->win->_w = w; w->defcur = [[NSCursor arrowCursor] retain]; [win makeFirstResponder: view]; [win setDelegate: view]; [win setContentView: view]; [view setAutoresizesSubviews:YES]; [view registerForDraggedTypes: [NSArray arrayWithObject:NSFilenamesPboardType]]; [win setAcceptsMouseMovedEvents: YES]; [win setReleasedWhenClosed: NO]; // [win setAutodisplay: NO]; [view updateTrackingAreas]; } int oswInit(osw * w, osg * g, int x, int y, int width, int height, int bl) { PROLOGUE; unsigned style = 0; if (!bl) { style += 0 | NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask ; } openwin(w, x, y, width, height, style); if (bl) [w->win setLevel: NSPopUpMenuWindowLevel]; EPILOGUE; return 1; } static NSEvent * nextEventUntil(id win, NSDate * until) { return [win nextEventMatchingMask: NSAnyEventMask untilDate: until inMode: NSDefaultRunLoopMode dequeue: YES]; } static NSEvent * pumpEvent(id win, NSDate * until) { NSEvent * ev = nextEventUntil(win, until); [NSApp sendEvent: ev]; [NSApp updateWindows]; return ev; } int oswTerm(osw * w) { PROLOGUE; [w->win makeKeyAndOrderFront: nil]; [w->win makeFirstResponder: nil]; [w->win setDelegate: nil]; [w->win setContentView: nil]; while(pumpEvent(NSApp, [NSDate distantPast])) ; [w->win close]; while(pumpEvent(NSApp, [NSDate distantPast])) ; [w->win release]; [w->view release]; while(pumpEvent(NSApp, [NSDate distantPast])) ; [w->defcur release]; EPILOGUE; // assert(w->_wfreed); // assert(w->_vfreed); return 1; } int oswSwapBuffers(osw * w) { PROLOGUE; glFlush(); [wcontext(w)->ctx flushBuffer]; EPILOGUE; return 1; } int oswShow(osw * w) { PROLOGUE; [w->win makeKeyAndOrderFront: w->view]; EPILOGUE; return 1; } int oswHide(osw * w) { PROLOGUE; [w->win orderOut: nil]; EPILOGUE; return 1; } void oswPollEvent(osw * w) { PROLOGUE; pumpEvent(w->win, [NSDate distantPast]); //pumpEvent(NSApp, [NSDate distantPast]); EPILOGUE; } int oswSetSwapInterval(osw * w, int i) { PROLOGUE; GLint param = i; [wcontext(w)->ctx setValues:&param forParameter:NSOpenGLCPSwapInterval]; EPILOGUE; return 1; } int oswClearCurrent(osw * w) { PROLOGUE; glFlush(); [wcontext(w)->ctx clearDrawable]; [NSOpenGLContext clearCurrentContext]; EPILOGUE; return 1; } int oswMakeCurrent(osw * w, osc * c) { PROLOGUE; [c->ctx setView: [w->win contentView]]; [c->ctx makeCurrentContext]; EPILOGUE; return 1; } int oswMaximize(osw * w) { NSSize scr = [[NSScreen mainScreen] frame].size; return oswGeometry(w, 0, 0, scr.width, scr.height); } int oswGeometry(osw * w, int x, int y, unsigned width, unsigned height) { PROLOGUE; NSRect r = NSMakeRect(x, reversed(y + height - 1), width, height); NSRect fr = [w->win frameRectForContentRect: r]; [w->win setFrame: fr display: YES]; EPILOGUE; return 1; } void oswPointer(osw * w) { PROLOGUE; [w->view establishCursor]; EPILOGUE; } unsigned oswOrder(osw ** order) { PROLOGUE; NSArray * wins; wins = [NSApp orderedWindows]; unsigned n = [wins count]; unsigned i; for (i = 0; i < n; i++) order[i] = ((Window*)[wins objectAtIndex: i])->_w; EPILOGUE; return n; } int oscInit(osc * c, osg * g, osc * share) { PROLOGUE; int st = 0; // XXX NSOpenGLContext *ctx = 0; CGDirectDisplayID dpy = kCGDirectMainDisplay; NSOpenGLPixelFormatAttribute attr[] = { NSOpenGLPFAFullScreen, NSOpenGLPFAScreenMask, CGDisplayIDToOpenGLDisplayMask(dpy), NSOpenGLPFAColorSize, 24, NSOpenGLPFADepthSize, 32, NSOpenGLPFAAlphaSize, 8, NSOpenGLPFADoubleBuffer, NSOpenGLPFAAccelerated, NSOpenGLPFANoRecovery, 0, 0, 0, 0, 0, 0, 0, 0, }; NSOpenGLPixelFormat * fmt; int last = sizeof(attr) / sizeof(attr[0]); while (!attr[--last]) ; last++; if (st) attr[last++] = NSOpenGLPFAStereo; fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attr]; if (fmt) ctx = [[NSOpenGLContext alloc] initWithFormat:fmt shareContext: share? share->ctx : 0]; [fmt release]; c->ctx = ctx; EPILOGUE; return ctx != 0; } void * oscContextFor(osc * c) { return c->ctx; } void * oscCurrentContext() { return [NSOpenGLContext currentContext]; } int oscTerm(osc * c) { PROLOGUE; [c->ctx release]; EPILOGUE; return 1; } int ospInit(osp * p, const void * rgba, unsigned hotx, unsigned hoty) { NSBitmapImageRep * b; NSImage * img; uint8_t * planes[1]; PROLOGUE; memcpy(p->rgba, rgba, sizeof(p->rgba)); planes[0] = p->rgba; b = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: planes pixelsWide: CURSOR_WIDTH pixelsHigh: CURSOR_HEIGHT bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES isPlanar: NO colorSpaceName: NSDeviceRGBColorSpace bytesPerRow: CURSOR_WIDTH*4 bitsPerPixel: 32]; img = [[NSImage alloc] initWithSize: NSMakeSize(CURSOR_WIDTH, CURSOR_HEIGHT)]; [img addRepresentation: b]; [b release]; p->cur = [[NSCursor alloc] initWithImage: img hotSpot: NSMakePoint(hotx, hoty)]; [img release]; EPILOGUE; return p->cur != 0; } int ospTerm(osp * p) { PROLOGUE; [p->cur release]; EPILOGUE; return 1; } int osgInit(osg * g, const char * name) { PROLOGUE; ProcessSerialNumber psn = { 0, kCurrentProcess }; TransformProcessType(&psn, kProcessTransformToForegroundApplication); SetFrontProcess(&psn); NSApp = [NSApplication sharedApplication]; [NSApp setDelegate: [[AppDelegate alloc] init]]; [NSApp finishLaunching]; [NSApp activateIgnoringOtherApps: YES]; // [NSApp setWindowsNeedUpdate: NO]; EPILOGUE; return 1; } int osgTerm(osg * g) { PROLOGUE; [NSApp release]; // ??? EPILOGUE; return 1; } int main(int argc, char **argv) { PROLOGUE; extern int fakemain(int, char**); fakemain(argc, argv); EPILOGUE; return 0; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
awcocoa.m
Objective-C
bsd
18,773
/* Copyright (c) 2008-2009, Jorge Acereda Maciá All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include "sysgl.h" #include "aw.h" #include "awos.h" #include "bit.h" #if defined(_MSC_VER) #define snprintf _snprintf #endif static int gcheck(const ag * g) { if (!g) report("Null group handle"); return g != 0; } static int ccheck(const ac * c) { if (!c) report("Null context handle"); return c != 0; } static int wcheck(const aw * w) { if (!w) report("Null window handle"); return w != 0; } static int pcheck(const ap * p) { if (!p) report("Null pointer handle"); return p != 0; } ag * agNew(const char * appname) { ag * g = calloc(1, sizeof(*g)); int ok; ok = osgInit(&g->osg, appname); if (!ok) { report("creating group %s", appname); free(g); g = 0; } return g; } void agDel(ag * g) { if (gcheck(g)) { if (!osgTerm(&g->osg)) report("deleting group"); free(g); } } void awShow(aw * w) { if (wcheck(w)) { if (!oswShow(&w->osw)) report("Unable to show window"); else w->shown = 1; } } void awHide(aw * w) { if (wcheck(w)) { if (!oswHide(&w->osw)) report("Unable to hide window"); else w->shown = 0; } } void awSetTitle(aw * w, const char * t) { if (wcheck(w) && !w->maximized && !oswSetTitle(&w->osw, t)) report("Unable to set window title"); } static void drain(aw * w) { while (awNextEvent(w)) ; } #define BADPOS 123 #define BADSIZE 17 static int wopen(ag * g, aw * w) { int ok; memset(&w->osw, 0, sizeof(w->osw)); w->g = g; w->last = w->ev; w->last->type = AW_EVENT_NONE; w->head = w->tail = 0; ok = oswInit(&w->osw, &g->osg, w->rx, w->ry, w->rw, w->rh, !w->borders); drain(w); // horrible hack to workaround lack of notifications in Cocoa oswGeometry(&w->osw, w->rx+1, w->ry+1, w->rw+1, w->rh+1); drain(w); if (!ok) report("Unable to open window"); return ok; } static void wclose(aw * w) { awPointer(w, 0); if (w->ctx) oswClearCurrent(&w->osw); oswHide(&w->osw); drain(w); if (!oswTerm(&w->osw)) report("Unable to close window"); memset(&w->osw, 0, sizeof(w->osw)); } static int wreopen(aw * w) { int ok; ac * c = w->ctx; wclose(w); w->ctx = 0; ok = wopen(w->g, w); w->ctx = c; if (w->ctx) oswMakeCurrent(&w->osw, &w->ctx->osc); drain(w); if (w->maximized) oswMaximize(&w->osw); else oswGeometry(&w->osw, w->rx, w->ry, w->rw, w->rh); if (w->shown) oswShow(&w->osw); // filterBad(w); return ok; } aw * awNew(ag * g) { aw * w = calloc(1, sizeof(*w)); int ok; w->rx = 31; w->ry = 31; w->rw = 31; w->rh = 31; w->borders = 1; ok = wopen(g, w); if (!ok) { free(w); w = 0; } return w; } void awDel(aw * w) { if (wcheck(w)) { if (w->pointer) report("Closing window with cursor established"); if (w->ctx) report("Closing window with active context"); wclose(w); } } void awShowBorders(aw * w) { if (wcheck(w)) { w->borders = 1; wreopen(w); } } void awHideBorders(aw * w) { if (wcheck(w)) { w->borders = 0; wreopen(w); } } void awMaximize(aw * w) { if (wcheck(w)) { w->maximized = 1; wreopen(w); } } void awNormalize(aw * w) { if (wcheck(w)) { w->maximized = 0; wreopen(w); } } static void setInterval(aw * w) { if (w->interval && !oswSetSwapInterval(&w->osw, w->interval)) report("Unable to set swap interval"); } void awSwapBuffers(aw * w) { if (wcheck(w)) { setInterval(w); glFlush(); if (!w->ctx) report("awSwapBuffers called without context"); else if (!oswSwapBuffers(&w->osw)) report("awSwapBuffers failed"); memcpy(w->ppressed, w->pressed, sizeof(w->ppressed)); } } void awMakeCurrent(aw * w, ac * c) { if (wcheck(w)) { if (w->ctx) glFlush(); if (w->ctx && w->ctx != c) oswClearCurrent(&w->osw); if (c && !oswMakeCurrent(&w->osw, &c->osc)) report("Unable to establish context"); w->ctx = c; } } static unsigned char * bitarrayFor(unsigned char * p, awkey * k) { int good = *k >= AW_KEY_NONE && *k < AW_KEY_MAX; assert(good); *k -= AW_KEY_NONE; return good? p : 0; } static const unsigned char * bitarrayForC(const unsigned char * p, awkey * k) { return (const unsigned char *)bitarrayFor((unsigned char *)p, k); } static int pressed(const aw * w, awkey k) { const unsigned char * ba = bitarrayForC(w->pressed, &k); return ba && bittest(ba, k); } static void press(aw * w, awkey k) { unsigned char * ba = bitarrayFor(w->pressed, &k); if (ba) bitset(ba, k); } static void release(aw * w, awkey k) { unsigned char * ba = bitarrayFor(w->pressed, &k); if (ba) bitclear(ba, k); } const ae * awNextEvent(aw * w) { const ae * e = 0; if (!wcheck(w)) return 0; assert(w->last); if (w->last->type == AW_EVENT_DROP) { ae * last = w->last; assert(last->p[0]); free((void*)last->p[0]); last->p[0] = 0; last->type = AW_EVENT_NONE; } oswPollEvent(&w->osw); if (w->head != w->tail) { e = w->ev + w->tail; w->tail++; w->tail %= MAX_EVENTS; } if (e) switch (aeType(e)) { case AW_EVENT_RESIZE: w->width = aeWidth(e); w->height = aeHeight(e); break; case AW_EVENT_MOTION: w->mx = aeX(e); w->my = aeY(e); break; case AW_EVENT_DOWN: press(w, aeWhich(e)); break; case AW_EVENT_UP: release(w, aeWhich(e)); break; default: break; } if (e) w->last = (ae*)e; return e; } unsigned awWidth(const aw * w) { return w->width; } unsigned awHeight(const aw * w) { return w->height; } int awMouseX(const aw * w) { return w->mx; } int awMouseY(const aw * w) { return w->my; } int awPressed(const aw * w, awkey k) { return pressed(w, k); } int awReleased(const aw * w, awkey k) { awkey pk = k; const unsigned char * ba = bitarrayForC(w->pressed, &k); const unsigned char * pba = bitarrayForC(w->ppressed, &pk); return ba && !bittest(ba, k) && bittest(pba, k); } void got(osw * osw, int type, intptr_t p1, intptr_t p2) { aw * w = (aw*)osw; ae * e = w->ev + w->head; w->head++; w->head %= MAX_EVENTS; e->type = type; e->p[0] = p1; e->p[1] = p2; } ac * acNew(ag * g, ac * share) { ac * c = calloc(1, sizeof(*c)); int ok; c->g = g; ok = oscInit(&c->osc, &g->osg, &share->osc); if (!ok) { report("unable to create context sharing with %p", share); free(c); c = 0; } return c; } ac * acNewStereo(ag * g, ac * share) { return 0; // XXX } void acDel(ac * c) { if (ccheck(c)) { if (!oscTerm(&c->osc)) report("unable to delete context %p", c); free(c); } } void awSetInterval(aw * w, int interval) { w->interval = interval; } void awSetUserData(aw * w, void * user) { w->user = user; } void * awUserData(const aw * w) { return w->user; } void awGeometry(aw * w, int x, int y, unsigned width, unsigned height) { if (wcheck(w)) { if (!oswGeometry(&w->osw, x, y, width, height)) report("unable to establish geometry"); else { w->rx = x; w->ry = y; w->rw = width; w->rh = height; } } } void awPointer(aw * w, ap * p) { if (w->pointer) w->pointer->refs--; w->pointer = p; if (w->pointer) w->pointer->refs++; oswPointer(&w->osw); } ap * apNew(const void * rgba, unsigned hotx, unsigned hoty) { ap * p = calloc(1, sizeof(*p)); int ok; ok = ospInit(&p->osp, rgba, hotx, hoty); if (!ok) { report("unable to create pointer"); free(p); p = 0; } return p; } void apDel(ap * p) { if (p->refs) report("destroying referenced pointer"); else if (pcheck(p)) { if (!ospTerm(&p->osp)) report("unable to destroy pointer"); free(p); } } unsigned awOrder(const aw * w) { aw * zorder[MAX_WINDOWS]; unsigned n = oswOrder((osw**)zorder); unsigned i = 0; assert(n < MAX_WINDOWS); #if !defined NDEBUG for (i = 0; i < n; i++) assert(zorder[i]); #endif for (i = 0; i < n; i++) if (w == zorder[i]) break; return i; } int aeType(const ae * e) { return e->type; } int aeWidth(const ae * e) { return e->p[0]; } int aeHeight(const ae * e) { return e->p[1]; } awkey aeWhich(const ae * e) { return e->p[0]; } int aeX(const ae * e) { return e->p[0]; } int aeY(const ae * e) { return e->p[1]; } const char * aePath(const ae * e) { return (const char *)e->p[0]; } const char * aeKeyName(const ae * e) { const char * n = 0; static char buf[32] = {0}; awkey k = aeWhich(e); switch (k) { case AW_KEY_NONE: n = "NONE"; break; case AW_KEY_MOUSEWHEELUP: n = "MOUSEWHEELUP"; break; case AW_KEY_MOUSEWHEELDOWN: n = "MOUSEWHEELDOWN"; break; case AW_KEY_MOUSELEFT: n = "MOUSELEFT"; break; case AW_KEY_MOUSEMIDDLE: n = "MOUSEMIDDLE"; break; case AW_KEY_MOUSERIGHT: n = "MOUSERIGHT"; break; case AW_KEY_A: n = "A"; break; case AW_KEY_S: n = "S"; break; case AW_KEY_D: n = "D"; break; case AW_KEY_F: n = "F"; break; case AW_KEY_H: n = "H"; break; case AW_KEY_G: n = "G"; break; case AW_KEY_Z: n = "Z"; break; case AW_KEY_X: n = "X"; break; case AW_KEY_C: n = "C"; break; case AW_KEY_V: n = "V"; break; case AW_KEY_B: n = "B"; break; case AW_KEY_Q: n = "Q"; break; case AW_KEY_W: n = "W"; break; case AW_KEY_E: n = "E"; break; case AW_KEY_R: n = "R"; break; case AW_KEY_Y: n = "Y"; break; case AW_KEY_T: n = "T"; break; case AW_KEY_1: n = "1"; break; case AW_KEY_2: n = "2"; break; case AW_KEY_3: n = "3"; break; case AW_KEY_4: n = "4"; break; case AW_KEY_6: n = "6"; break; case AW_KEY_5: n = "5"; break; case AW_KEY_EQUAL: n = "EQUAL"; break; case AW_KEY_9: n = "9"; break; case AW_KEY_7: n = "7"; break; case AW_KEY_MINUS: n = "MINUS"; break; case AW_KEY_8: n = "8"; break; case AW_KEY_0: n = "0"; break; case AW_KEY_RIGHTBRACKET: n = "RIGHTBRACKET"; break; case AW_KEY_O: n = "O"; break; case AW_KEY_U: n = "U"; break; case AW_KEY_LEFTBRACKET: n = "LEFTBRACKET"; break; case AW_KEY_I: n = "I"; break; case AW_KEY_P: n = "P"; break; case AW_KEY_L: n = "L"; break; case AW_KEY_J: n = "J"; break; case AW_KEY_QUOTE: n = "QUOTE"; break; case AW_KEY_K: n = "K"; break; case AW_KEY_SEMICOLON: n = "SEMICOLON"; break; case AW_KEY_BACKSLASH: n = "BACKSLASH"; break; case AW_KEY_COMMA: n = "COMMA"; break; case AW_KEY_SLASH: n = "SLASH"; break; case AW_KEY_N: n = "N"; break; case AW_KEY_M: n = "M"; break; case AW_KEY_PERIOD: n = "PERIOD"; break; case AW_KEY_GRAVE: n = "GRAVE"; break; case AW_KEY_KEYPADDECIMAL: n = "KEYPADDECIMAL"; break; case AW_KEY_KEYPADMULTIPLY: n = "KEYPADMULTIPLY"; break; case AW_KEY_KEYPADPLUS: n = "KEYPADPLUS"; break; case AW_KEY_KEYPADCLEAR: n = "KEYPADCLEAR"; break; case AW_KEY_KEYPADDIVIDE: n = "KEYPADDIVIDE"; break; case AW_KEY_KEYPADENTER: n = "KEYPADENTER"; break; case AW_KEY_KEYPADMINUS: n = "KEYPADMINUS"; break; case AW_KEY_KEYPADEQUALS: n = "KEYPADEQUALS"; break; case AW_KEY_KEYPAD0: n = "KEYPAD0"; break; case AW_KEY_KEYPAD1: n = "KEYPAD1"; break; case AW_KEY_KEYPAD2: n = "KEYPAD2"; break; case AW_KEY_KEYPAD3: n = "KEYPAD3"; break; case AW_KEY_KEYPAD4: n = "KEYPAD4"; break; case AW_KEY_KEYPAD5: n = "KEYPAD5"; break; case AW_KEY_KEYPAD6: n = "KEYPAD6"; break; case AW_KEY_KEYPAD7: n = "KEYPAD7"; break; case AW_KEY_KEYPAD8: n = "KEYPAD8"; break; case AW_KEY_KEYPAD9: n = "KEYPAD9"; break; case AW_KEY_RETURN: n = "RETURN"; break; case AW_KEY_TAB: n = "TAB"; break; case AW_KEY_SPACE: n = "SPACE"; break; case AW_KEY_DELETE: n = "DELETE"; break; case AW_KEY_ESCAPE: n = "ESCAPE"; break; case AW_KEY_COMMAND: n = "COMMAND"; break; case AW_KEY_SHIFT: n = "SHIFT"; break; case AW_KEY_CAPSLOCK: n = "CAPSLOCK"; break; case AW_KEY_OPTION: n = "OPTION"; break; case AW_KEY_CONTROL: n = "CONTROL"; break; case AW_KEY_RIGHTSHIFT: n = "RIGHTSHIFT"; break; case AW_KEY_RIGHTOPTION: n = "RIGHTOPTION"; break; case AW_KEY_RIGHTCONTROL: n = "RIGHTCONTROL"; break; case AW_KEY_FUNCTION: n = "FUNCTION"; break; case AW_KEY_F17: n = "F17"; break; case AW_KEY_VOLUMEUP: n = "VOLUMEUP"; break; case AW_KEY_VOLUMEDOWN: n = "VOLUMEDOWN"; break; case AW_KEY_MUTE: n = "MUTE"; break; case AW_KEY_F18: n = "F18"; break; case AW_KEY_F19: n = "F19"; break; case AW_KEY_F20: n = "F20"; break; case AW_KEY_F5: n = "F5"; break; case AW_KEY_F6: n = "F6"; break; case AW_KEY_F7: n = "F7"; break; case AW_KEY_F3: n = "F3"; break; case AW_KEY_F8: n = "F8"; break; case AW_KEY_F9: n = "F9"; break; case AW_KEY_F11: n = "F11"; break; case AW_KEY_F13: n = "F13"; break; case AW_KEY_F16: n = "F16"; break; case AW_KEY_F14: n = "F14"; break; case AW_KEY_F10: n = "F10"; break; case AW_KEY_F12: n = "F12"; break; case AW_KEY_F15: n = "F15"; break; case AW_KEY_HELP: n = "HELP"; break; case AW_KEY_HOME: n = "HOME"; break; case AW_KEY_PAGEUP: n = "PAGEUP"; break; case AW_KEY_FORWARDDELETE: n = "FORWARDDELETE"; break; case AW_KEY_F4: n = "F4"; break; case AW_KEY_END: n = "END"; break; case AW_KEY_F2: n = "F2"; break; case AW_KEY_PAGEDOWN: n = "PAGEDOWN"; break; case AW_KEY_F1: n = "F1"; break; case AW_KEY_LEFTARROW: n = "LEFTARROW"; break; case AW_KEY_RIGHTARROW: n = "RIGHTARROW"; break; case AW_KEY_DOWNARROW: n = "DOWNARROW"; break; case AW_KEY_UPARROW: n = "UPARROW"; break; case AW_KEY_SCROLL: n = "SCROLL"; break; case AW_KEY_NUMLOCK: n = "NUMLOCK"; break; case AW_KEY_CLEAR: n = "CLEAR"; break; case AW_KEY_SYSREQ: n = "SYSREQ"; break; case AW_KEY_PAUSE: n = "PAUSE"; break; case AW_KEY_CAMERA: n = "CAMERA"; break; case AW_KEY_CENTER: n = "CENTER"; break; case AW_KEY_AT: n = "AT"; break; case AW_KEY_SYM: n = "SYM"; break; default: n = 0; break; } if (n) snprintf(buf, sizeof(buf), "AW_KEY_%s", n); else if (k >= 32 && k < 127) snprintf(buf, sizeof(buf), "%c", (unsigned)k); else snprintf(buf, sizeof(buf), "0x%x", (unsigned)k); return buf; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
aw.c
C
bsd
18,209
import os import os.path import string import SCons.Action import SCons.Builder import SCons.Tool import SCons.Util def generate(env): sdkprefix = \ '/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/' gnu_tools = ['gcc', 'g++', 'applelink', 'ar', 'gas'] for tool in gnu_tools: SCons.Tool.Tool(tool)(env) env['CC'] = sdkprefix + 'gcc' env['CXX'] = sdkprefix + 'g++' env['LINK'] = sdkprefix + 'gcc' env.Append(CPPDEFINES=[['__IPHONE_OS_VERSION_MIN_REQUIRED', 30000]]) env.Append(CPPDEFINES=[['TARGET_OS_IPHONE', 1]]) env.Append(LINKFLAGS=' -arch armv6 ') env.Append(CFLAGS=' -arch armv6 ') env.Append(CFLAGS=' -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.sdk ') env.Append(LINKFLAGS=' -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.sdk ') # env.Append(CFLAGS=' -mmacosx-version-min=10.6 ') # env.Append(LINKFLAGS=' -mmacosx-version-min=10.6 ') env['AS'] = sdkprefix + 'as' def exists(env): return find(env)
zzywany123-libaw-1
iphone.py
Python
bsd
1,059
#-*-Python-*- import sys import os domain = ARGUMENTS.get('domain', 'com.example') backends = [] tools = 0 target = ARGUMENTS.get('target', 'native') if target == 'native': target = sys.platform elif target == 'iphone': tools = 'iphone' elif target == 'iphonesim': tools = 'iphonesim' elif target == 'android': tools = 'android' else: tools = 'crossmingw' if target == 'linux2': target = 'linux' if target == 'win32': comp = 'cl' else: comp = 'gcc' backends = { 'iphone' : ['iphone'], 'iphonesim' : ['iphone'], 'darwin' : ['cocoa'], 'android' : ['android'], 'linux' : ['x11'], 'win32' : ['nt'], 'mingw' : ['nt'], }[target] def filtertemplate(target, source, env): name = str(target[0]) name = name.split(os.path.sep)[-1].split('.')[0] s = open(str(source[0])) d = open(str(target[0]), 'w') c = s.read().replace('NAME', name) d.write(c) d.close() s.close() def filtermanifest(target, source, env): name = str(target[0]) name = name.split(os.path.sep)[-2] s = open(str(source[0])) d = open(str(target[0]), 'w') c = s.read().replace('{NAME}', name).replace('{DOMAIN}', domain) d.write(c) d.close() s.close() def outputfrom(cmd): p = os.popen(cmd) ret = p.read() p.close return ret class Env(Environment): def UsesOpenGL(self): if self['BACKEND'] == 'iphone': self.Append(FRAMEWORKS=['OpenGLES', 'QuartzCore', 'UIKit', 'Foundation']) # if self['BACKEND'] == 'android': # self.Append(LIBS=['EGL', 'GLESv1_CM', 'GLESv2']) if self['BACKEND'] == 'cocoa': self.Append(FRAMEWORKS=['OpenGL', 'AppKit']) if self['BACKEND'] == 'x11': self.Append(LIBPATH=['/usr/X11R6/lib']) self.Append(CPPPATH=['/usr/X11R6/include', '/usr/include/gtk-2.0/']) self.Append(LIBS=['GL', 'GLU', 'X11']) if self['BACKEND'] == 'nt': self.Append(LIBS=['opengl32', 'gdi32', 'glu32', 'user32', 'imm32', 'shell32']) def _Objects(self, bdir, sources): if self['BACKEND'] in ['android']: return self._SharedObjects(bdir, sources) return [self.Object('obj' + bdir + '/' + s + '.o', s) for s in Split(sources)] def _SharedObjects(self, bdir, sources): if self['BACKEND'] in ['iphone', 'iphonesim']: return self._Objects(bdir, sources) return [self.SharedObject('sobj' + bdir + '/' + s + '.os', s) for s in Split(sources)] def ForLib(self): return self.Clone() def Lib(self, name, sources): return self.Default(self.Library(name, self._Objects(name, sources))) def _SetCPPFlags(self): self.Append(CPPPATH=['include']) self.Append(LIBPATH='.') def ForGLPrg(self): if self['BACKEND'] in ['iphone', 'android']: return None ret = self.Clone() ret.Append(LIBS=['aw']) ret.UsesOpenGL() ret._SetCPPFlags() return ret def ForGLESPrg(self): if not self['BACKEND'] in ['iphone', 'android']: return None ret = self.Clone() ret.Append(LIBS=['aw']) ret.UsesOpenGL() ret._SetCPPFlags() return ret def App(self, name, prg): dst = '#/../Library/Application Support/' +\ 'iPhone Simulator/User/Applications/%s/%s.app/' % (name, name) plist = self.Command(name + '.plist', 'template.plist', filtertemplate) self.Default(self.Install(dst, prg)) self.Default(self.InstallAs(dst + 'Info.plist', plist)) # self.Default(self.Install(dst, name + '.png')) def Apk(self, name, prg): manifest = self.Command('%s/AndroidManifest.xml' % name, 'AndroidManifest-template.xml', filtermanifest) buildxml = self.Command( '%s/build.xml' % name, manifest, '%s update project -p ${TARGET.dir} -t 1' % self['ANDROID']) apk = self.Command( '%s/bin/%s-debug.apk' % (name, name), [buildxml, prg], 'ant debug -f ${SOURCE} && ' +\ 'mv ${TARGET.dir}/NativeActivity-debug.apk $TARGET') self.Default(self.Command( name + '-install', apk, '%s uninstall %s && %s install $SOURCE' %(env['ADB'], domain+'.'+name, env['ADB']))) def Prg(self, name, sources): if self['BACKEND'] in ['android']: prg = self.SharedLibrary( '%s/libs/armeabi/%s' % (name,name), self._SharedObjects(name, sources)) else: prg = self.Program(name, self._SharedObjects(name, sources)) self.Default(prg) if target == 'iphonesim': self.App(name, prg) if target == 'android': self.Apk(name, prg) def CompileAs32Bits(self): if comp == 'gcc': self.Append(CCFLAGS=' -m32 ') self.Append(LINKFLAGS=' -m32 ') def ForNPAPI(self): if self['BACKEND'] not in ['cocoa', 'nt', 'x11']: return None ret = self.Clone() ret.Append(CPPDEFINES=['AWPLUGIN']) ret.Append(CPPPATH=['npapi']) ret.CompileAs32Bits() if target == 'win32': ret.Append(CPPDEFINES=['XULRUNNER_SDK', 'WIN32', '_WINDOWS', 'XP_WIN32', 'MOZILLA_STRICT_API', 'XPCOM_GLUE', 'XP_WIN', '_X86_', 'NPSIMPLE_EXPORTS',]) ret.Append(LIBS=['user32']) if target == 'linux': ret.Append(CFLAGS=outputfrom( 'pkg-config --cflags gtk+-2.0')) ret.Append(LINK=outputfrom( 'pkg-config --libs gtk+-2.0')) ret.Append(CPPDEFINES=['XULRUNNER_SDK', 'XP_UNIX', 'MOZ_X11']) return ret def ForPlugin(self): if self['BACKEND'] not in ['cocoa', 'nt', 'x11']: return None ret = self.Clone() ret.UsesOpenGL() ret.CompileAs32Bits() ret._SetCPPFlags() ret.Append(LIBS=['awnpapi']) ret.Append(FRAMEWORKS=['WebKit', 'QuartzCore']) if target in ['darwin']: ret['SHLINKFLAGS'] = '$LINKFLAGS' +\ ' -bundle -flat_namespace' ret['SHLIBPREFIX'] = '' ret['SHLIBSUFFIX'] = '' return ret def ShLinkLib(self, name, sources): return self.Library(name, self._SharedObjects(name, sources)) def Plg(self, name, sources): return # XXX Broken when running as out-of-process prefix = '' platobjs = [] if target == 'win32': prefix = 'np' ress = self.Command(name + '.rc', 'template.rc', filtertemplate) res = self.Command(name + '.res', ress, 'rc /fo $TARGET $SOURCE') platobjs = ['awnpapi.def', res[0]] plg = self.SharedLibrary(prefix + name, self._SharedObjects(name, sources) +\ platobjs) self.Default(plg) home = os.environ['HOME'] + '/' if target == 'win32' and self['CONF'] == 'release': instarget = home + 'Mozilla/Plugins/' self.Default(self.Install(instarget, plg)) if target == 'linux' and self['CONF'] == 'release': instarget = home + '.mozilla/plugins/' self.Default(self.Install(instarget, plg)) if target == 'darwin' and self['CONF'] == 'release': ress = self.Command(name + '.r', 'template.r', filtertemplate) res = self.Command( name + '.rsrc', ress, '/Developer/Tools/Rez -o $TARGET' + ' -useDF $SOURCE') instarget = home + 'Library/Internet Plug-Ins/' +\ name + '.webplugin/' plist = self.Command(name + '.plist', 'webtemplate.plist', filtertemplate) self.Default( self.InstallAs(instarget +\ 'Contents/Info.plist', plist)) self.Default( self.Install(instarget + 'Contents/MacOS/', plg)) self.Default( self.Install(instarget + 'Contents/Resources/', res)) ccflags = { 'gcc': { 'debug': '-g -Wall ', 'release': '-g -O2 -Wall ', }, 'cl': { 'debug': ' /EHs-c- /MTd /DEBUG /Z7 /Od ', 'release': ' /MT /O2 ', }, } linkflags = { 'gcc': { 'debug': '-g', 'release': '-g', }, 'cl': { 'debug': ' /DEBUG ', 'release': '', }, } confcppdefines = { 'debug': [], 'release': ['NDEBUG'], } compcppdefines= { 'gcc': [], 'cl' : [['snprintf', '_snprintf']], } for backend in backends: for conf in ARGUMENTS.get('conf', 'debug,release').split(','): cf = ccflags[comp][conf] lf = linkflags[comp][conf] if not 'nt' in backends: cf += ' -fvisibility=hidden ' lf += ' -fvisibility=hidden ' cnf = Env(CCFLAGS=cf, CPPDEFINES=confcppdefines[conf]+compcppdefines[comp], LINKFLAGS=lf, ) if tools: cnf.Tool(tools, '.') dir = conf + '/' + backend cnf.SConsignFile(dir) cnf['CONF'] = conf env = cnf.Clone() env['BACKEND'] = backend env.SConscript('SConscript', variant_dir=dir, exports='env')
zzywany123-libaw-1
SConstruct
Python
bsd
8,034
#include <windows.h> #include <wingdi.h> #include <windowsx.h> #include "aw.h" #include "awos.h" #if !defined HANDLE_WM_MOUSEWHEEL #define HANDLE_WM_MOUSEWHEEL(hwnd,wParam,lParam,fn) ((fn)((hwnd),(int)(short)LOWORD(lParam),(int)(short)HIWORD(lParam),(int)(short)HIWORD(wParam),(UINT)(short)LOWORD(wParam)),0L) #endif osw * oswFor(HWND win) { return (osw*)GetWindowLongPtrW(win, GWLP_USERDATA); } unsigned oswOrder(osw ** wins) { HWND win = GetTopWindow(0); unsigned n = 0; int curr = GetCurrentProcessId(); while (win) { osw * w = oswFor(win); DWORD pid; GetWindowThreadProcessId(win, &pid); if (curr == pid && w) wins[n++] = w; win = GetNextWindow(win, GW_HWNDNEXT); }; return n; } static int wgot(HWND win, int type, intptr_t p1, intptr_t p2) { osw * w = oswFor(win); if (w) got(w, type, p1, p2); return w != 0; } static int onMOUSEMOVE(HWND win, int x, int y, UINT flags ) { return wgot(win, AW_EVENT_MOTION, x, y); } static int onMOVE(HWND win, int x, int y) { return wgot(win, AW_EVENT_POSITION, x, y); } static int onSIZE(HWND win, UINT state, int w, int h) { return wgot(win, AW_EVENT_RESIZE, w, h); } static int onCLOSE(HWND win){ return wgot(win, AW_EVENT_CLOSE, 0, 0); } static unsigned uc2aw(unsigned uc) { unsigned ret = uc; switch (uc) { case 0xd: ret = '\n'; break; } return ret; } extern unsigned mapkeycode(unsigned); static int onSYSKEYDOWN(HWND win, UINT vk, BOOL down, int repeats, UINT flags) { return wgot(win, AW_EVENT_DOWN, mapkeycode(vk), 0); } static int onSYSKEYUP(HWND win, UINT vk, BOOL down, int repeats, UINT flags) { return wgot(win, AW_EVENT_UP, mapkeycode(vk), 0); } static int onKEYDOWN(HWND win, UINT vk, BOOL down, int repeats, UINT flags) { return wgot(win, AW_EVENT_DOWN, mapkeycode(vk), 0); } static int onKEYUP(HWND win, UINT vk, BOOL down, int repeats, UINT flags) { return wgot(win, AW_EVENT_UP, mapkeycode(vk), 0); } static int mouseDown(HWND win, int which) { SetCapture(win); return wgot(win, AW_EVENT_DOWN, which, 0); } static int mouseUp(HWND win, int which) { int ret = wgot(win, AW_EVENT_UP, which, 0); ReleaseCapture(); return ret; } static int onLBUTTONDOWN(HWND win, BOOL dbl, int x, int y, UINT flags) { return mouseDown(win, AW_KEY_MOUSELEFT); } static int onMBUTTONDOWN(HWND win, BOOL dbl, int x, int y, UINT flags) { return mouseDown(win, AW_KEY_MOUSEMIDDLE); } static int onRBUTTONDOWN(HWND win, BOOL dbl, int x, int y, UINT flags) { return mouseDown(win, AW_KEY_MOUSERIGHT); } static int onLBUTTONUP(HWND win, int x, int y, UINT flags) { return mouseUp(win, AW_KEY_MOUSELEFT); } static int onMBUTTONUP(HWND win, int x, int y, UINT flags) { return mouseUp(win, AW_KEY_MOUSEMIDDLE); } static int onRBUTTONUP(HWND win, int x, int y, UINT flags) { return mouseUp(win, AW_KEY_MOUSERIGHT); } static int onMOUSEWHEEL(HWND win, int x, int y, int z, UINT keys) { int which = z >= 0? AW_KEY_MOUSEWHEELUP : AW_KEY_MOUSEWHEELDOWN; return wgot(win, AW_EVENT_DOWN, which, 0) && wgot(win, AW_EVENT_UP, which, 0); } static int onSETCURSOR(HWND win, HWND cur, UINT l, UINT h) { osw * w = oswFor(win); int handled = LOWORD(l) == HTCLIENT && w != 0; extern void oswSetPointer(osw *); if (handled) oswSetPointer(w); return handled; } static int fakeKbEvents(HWND win, unsigned type) { BYTE kbstatus[256]; UINT vk; GetKeyboardState(kbstatus); for (vk = 0; vk < sizeof(kbstatus); vk++) if (kbstatus[vk] & 0x80) wgot(win, type, mapkeycode(vk), 0); return 0; } static int onSETFOCUS(HWND win, HWND next) { wgot(win, AW_EVENT_SETFOCUS, (intptr_t)oswFor(next), 0); return fakeKbEvents(win, AW_EVENT_DOWN); } static int onKILLFOCUS(HWND win, HWND next) { wgot(win, AW_EVENT_KILLFOCUS, (intptr_t)oswFor(next), 0); return fakeKbEvents(win, AW_EVENT_UP); } static int onCHAR(HWND win, unsigned c, int repeats) { return wgot(win, AW_EVENT_UNICODE, uc2aw(c), 0); } static int onPAINT(HWND win) { return wgot(win, AW_EVENT_EXPOSED, 0, 0); } static void utf8(char * d, size_t dsz, const WCHAR * t) { WideCharToMultiByte(CP_UTF8, 0, t, -1, d, (int)dsz, 0, 0); } static int onDROPFILES(HWND win, HDROP d) { unsigned n = DragQueryFileW(d, 0xffffffff, 0, 0); unsigned i; int ret; for (i = 0; i < n; i++) { WCHAR buf[8192]; char str[8192]; DragQueryFileW(d, i, buf, sizeof(buf)); utf8(str, sizeof(str), buf); ret = wgot(win, AW_EVENT_DROP, (intptr_t)_strdup(str), 0); } DragFinish(d); return ret; } static int onNCCREATE(HWND win, CREATESTRUCT * cs) { SetWindowLongPtrW(win, GWLP_USERDATA, (LONG_PTR)cs->lpCreateParams); return 0; } LRESULT WINAPI handle(HWND win, UINT msg, WPARAM w, LPARAM l) { LRESULT r; switch (msg) { #define HANDLE(x) case WM_##x: r = HANDLE_WM_##x(win, w, l, on##x); break HANDLE(NCCREATE); HANDLE(MOUSEMOVE); HANDLE(MOVE); HANDLE(SIZE); HANDLE(CLOSE); HANDLE(KEYDOWN); HANDLE(SYSKEYDOWN); HANDLE(SYSKEYUP); HANDLE(CHAR); HANDLE(KEYUP); HANDLE(LBUTTONDOWN); HANDLE(RBUTTONDOWN); HANDLE(MBUTTONDOWN); HANDLE(LBUTTONUP); HANDLE(RBUTTONUP); HANDLE(MBUTTONUP); HANDLE(MOUSEWHEEL); HANDLE(SETFOCUS); HANDLE(KILLFOCUS); HANDLE(SETCURSOR); HANDLE(PAINT); HANDLE(DROPFILES); #undef HANDLE case WM_IME_STARTCOMPOSITION: { osw * w = oswFor(win); if (w) { HIMC imc = ImmGetContext(win); COMPOSITIONFORM cf; cf.dwStyle = CFS_POINT; cf.ptCurrentPos.x = wmousex(w); cf.ptCurrentPos.y = wmousey(w); ImmSetCompositionWindow(imc, &cf); ImmReleaseContext(win, imc); } r = w != 0; } break; case WM_IME_COMPOSITION: { osw * w = oswFor(win); if(w && (l & GCS_RESULTSTR)){ unsigned short str[4096]; unsigned len, i; HIMC imc = ImmGetContext(win); HDC dc = GetDC(win); len = ImmGetCompositionString(imc, GCS_RESULTSTR, str, sizeof(str)); len >>= 1; for (i = 0; i < len; i++) wgot(win, AW_EVENT_UNICODE, str[i], 0); ImmReleaseContext(win, imc); ReleaseDC(win, dc); } r = 0; } break; default: r = 0; } if (!r) r = DefWindowProcW(win, msg, w, l); return r; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
awntevent.c
C
bsd
7,773
#include <X11/Xlib.h> #include <GL/glx.h> struct _osg { Display * dpy; int screen; XIM xim; Atom del; int(*swapInterval)(int); int bw, bh; }; struct _osw { Window win; int lastw, lasth; int lastx, lasty; XIC xic; }; struct _osc { GLXContext ctx; }; struct _osp { int dummy; };
zzywany123-libaw-1
awx.h
C
bsd
370
#include <windows.h> #include <wingdi.h> #include <windowsx.h> struct _osg { HANDLE ready; HANDLE thread; HWND win; WCHAR appname[256]; }; struct _osw { HWND win; DWORD style; }; struct _osc { HGLRC ctx; }; struct _osp { HCURSOR icon; };
zzywany123-libaw-1
aww.h
C
bsd
306
#include "aw.h" unsigned mapkeycode(unsigned k) { unsigned ret; switch (k) { case 9: ret = AW_KEY_ESCAPE; break; case 10: ret = AW_KEY_1; break; case 11: ret = AW_KEY_2; break; case 12: ret = AW_KEY_3; break; case 13: ret = AW_KEY_4; break; case 14: ret = AW_KEY_5; break; case 15: ret = AW_KEY_6; break; case 16: ret = AW_KEY_7; break; case 17: ret = AW_KEY_8; break; case 18: ret = AW_KEY_9; break; case 19: ret = AW_KEY_0; break; case 20: ret = AW_KEY_MINUS; break; case 21: ret = AW_KEY_EQUAL; break; case 22: ret = AW_KEY_DELETE; break; case 23: ret = AW_KEY_TAB; break; case 24: ret = AW_KEY_Q; break; case 25: ret = AW_KEY_W; break; case 26: ret = AW_KEY_E; break; case 27: ret = AW_KEY_R; break; case 28: ret = AW_KEY_T; break; case 29: ret = AW_KEY_Y; break; case 30: ret = AW_KEY_U; break; case 31: ret = AW_KEY_I; break; case 32: ret = AW_KEY_O; break; case 33: ret = AW_KEY_P; break; case 34: ret = AW_KEY_LEFTBRACKET; break; case 35: ret = AW_KEY_RIGHTBRACKET; break; case 36: ret = AW_KEY_RETURN; break; case 37: ret = AW_KEY_CONTROL; break; case 38: ret = AW_KEY_A; break; case 39: ret = AW_KEY_S; break; case 40: ret = AW_KEY_D; break; case 41: ret = AW_KEY_F; break; case 42: ret = AW_KEY_G; break; case 43: ret = AW_KEY_H; break; case 44: ret = AW_KEY_J; break; case 45: ret = AW_KEY_K; break; case 46: ret = AW_KEY_L; break; case 47: ret = AW_KEY_SEMICOLON; break; case 48: ret = AW_KEY_QUOTE; break; case 49: ret = AW_KEY_GRAVE; break; case 50: ret = AW_KEY_SHIFT; break; case 51: ret = AW_KEY_BACKSLASH; break; case 52: ret = AW_KEY_Z; break; case 53: ret = AW_KEY_X; break; case 54: ret = AW_KEY_C; break; case 55: ret = AW_KEY_V; break; case 56: ret = AW_KEY_B; break; case 57: ret = AW_KEY_N; break; case 58: ret = AW_KEY_M; break; case 59: ret = AW_KEY_COMMA; break; case 60: ret = AW_KEY_PERIOD; break; case 61: ret = AW_KEY_SLASH; break; case 62: ret = AW_KEY_RIGHTSHIFT; break; case 63: ret = AW_KEY_KEYPADMULTIPLY; break; case 64: ret = AW_KEY_OPTION; break; case 65: ret = AW_KEY_SPACE; break; case 67: ret = AW_KEY_F1; break; case 68: ret = AW_KEY_F2; break; case 69: ret = AW_KEY_F3; break; case 70: ret = AW_KEY_F4; break; case 71: ret = AW_KEY_F5; break; case 72: ret = AW_KEY_F6; break; case 73: ret = AW_KEY_F7; break; case 74: ret = AW_KEY_F8; break; case 75: ret = AW_KEY_F9; break; case 76: ret = AW_KEY_F10; break; case 79: ret = AW_KEY_KEYPAD7; break; case 80: ret = AW_KEY_KEYPAD8; break; case 81: ret = AW_KEY_KEYPAD9; break; case 82: ret = AW_KEY_KEYPADMINUS; break; case 83: ret = AW_KEY_KEYPAD4; break; case 84: ret = AW_KEY_KEYPAD5; break; case 85: ret = AW_KEY_KEYPAD6; break; case 86: ret = AW_KEY_KEYPADPLUS; break; case 87: ret = AW_KEY_KEYPAD1; break; case 88: ret = AW_KEY_KEYPAD2; break; case 89: ret = AW_KEY_KEYPAD3; break; case 90: ret = AW_KEY_KEYPAD0; break; case 91: ret = AW_KEY_KEYPADDECIMAL; break; case 104: ret = AW_KEY_KEYPADENTER; break; case 106: ret = AW_KEY_KEYPADDIVIDE; break; case 110: ret = AW_KEY_HOME; break; case 113: ret = AW_KEY_LEFTARROW; break; case 114: ret = AW_KEY_RIGHTARROW; break; case 115: ret = AW_KEY_END; break; case 116: ret = AW_KEY_DOWNARROW; break; case 111: ret = AW_KEY_UPARROW; break; case 112: ret = AW_KEY_PAGEUP; break; case 117: ret = AW_KEY_PAGEDOWN; break; case 119: ret = AW_KEY_FORWARDDELETE; break; case 133: ret = AW_KEY_COMMAND; break; /* case XK_Clear: ret = AW_KEY_KEYPADCLEAR; break; case XK_KP_Equal: ret = AW_KEY_KEYPADEQUALS; break; case XK_Caps_Lock: ret = AW_KEY_CAPSLOCK; break; case XK_Alt_R: ret = AW_KEY_RIGHTOPTION; break; case XK_Control_R: ret = AW_KEY_RIGHTCONTROL; break; // case XK_function: ret = AW_KEY_FUNCTION; break; case XK_F17: ret = AW_KEY_F17; break; // case XK_VolumeUp: ret = AW_KEY_VOLUMEUP; break; // case XK_VolumeDown: ret = AW_KEY_VOLUMEDOWN; break; // case XK_Mute: ret = AW_KEY_MUTE; break; case XK_F18: ret = AW_KEY_F18; break; case XK_F19: ret = AW_KEY_F19; break; case XK_F20: ret = AW_KEY_F20; break; case XK_F11: ret = AW_KEY_F11; break; case XK_F13: ret = AW_KEY_F13; break; case XK_F16: ret = AW_KEY_F16; break; case XK_F14: ret = AW_KEY_F14; break; case XK_F12: ret = AW_KEY_F12; break; case XK_F15: ret = AW_KEY_F15; break; case XK_Help: ret = AW_KEY_HELP; break; */ default: ret = AW_KEY_NONE; } return ret; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
awx11keycodes.c
C
bsd
4,539
/* Copyright (c) 2008-2009, Jorge Acereda Maciá All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <string.h> #define GLX_GLXEXT_PROTOTYPES #include <GL/glx.h> #include <GL/glxext.h> #include <X11/keysym.h> #include "aw.h" #include "awos.h" #define EVMASK KeyPressMask | KeyReleaseMask | \ ButtonPressMask | ButtonReleaseMask | \ PointerMotionMask | StructureNotifyMask #define sync() XSync(wgroup(w)->dpy, False) static XVisualInfo * chooseVisual(Display * dpy, int screen) { int att[64]; int * p = att; *p++ = GLX_RGBA; *p++ = GLX_DOUBLEBUFFER; *p++ = GLX_RED_SIZE; *p++ = 1; *p++ = GLX_GREEN_SIZE; *p++ = 1; *p++ = GLX_BLUE_SIZE; *p++ = 1; *p++ = GLX_DEPTH_SIZE; *p++ = 1; *p++ = None; return glXChooseVisual(dpy, screen, att); } static void fillWA(unsigned long * swam, XSetWindowAttributes * swa) { *swam = 0; swa->event_mask = EVMASK; *swam |= CWEventMask; } static Window createWin(osg * g, int x, int y, int width, int height) { XSetWindowAttributes swa; unsigned long swamask; XSizeHints hints; Window w; fillWA(&swamask, &swa); w = XCreateWindow(g->dpy, XRootWindow(g->dpy, g->screen), x, y, width, height, 0, CopyFromParent, InputOutput, CopyFromParent, swamask, &swa); XSelectInput(g->dpy, w, EVMASK); XSetWMProtocols(g->dpy, w, &g->del, 1); hints.flags = USSize | USPosition; hints.x = x; hints.y = y; hints.width = width; hints.height = height; XSetWMNormalHints(g->dpy, w, &hints); return w; } static void findBorderSize(osg * g) { XEvent e; Window w = createWin(g, -100, -100, 1, 1); XMapWindow(g->dpy, w); while (g->bh < 0) { if (XCheckWindowEvent(g->dpy, w, StructureNotifyMask, &e) && e.type == ConfigureNotify && !e.xconfigure.override_redirect) { g->bw = e.xconfigure.x; g->bh = e.xconfigure.y; } } XUnmapWindow(g->dpy, w); XDestroyWindow(g->dpy, w); } int osgInit(osg * g, const char * name) { int hasExtensions = 0; g->dpy = XOpenDisplay(0); if (g->dpy) { g->screen = XDefaultScreen(g->dpy); g->del = XInternAtom(g->dpy, "WM_DELETE_WINDOW", False); findBorderSize(g); hasExtensions = 0 != glXQueryExtension(g->dpy, 0, 0); } if (hasExtensions) g->swapInterval = (int(*)(int))glXGetProcAddress( (GLubyte*)"glXSwapIntervalSGI"); if (!g->swapInterval) debug("no glXSwapIntervalSGI()"); if (g->dpy) g->xim = XOpenIM (g->dpy, 0, 0, 0); return hasExtensions && g->xim; } int osgTerm(osg * g) { int ret = 0 == XCloseDisplay(g->dpy); return ret; } int oswSetTitle(osw * w, const char * t) { return XSetStandardProperties(wgroup(w)->dpy, w->win, t, t, None, (char**)0, 0, 0); } static int openwin(osw * w, osg * g, int x, int y, int width, int height) { Window win = createWin(g, x, y, width, height); XIC xic = 0; if (win) xic = XCreateIC( g->xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, win, XNFocusWindow, win, NULL); w->win = win; w->xic = xic; return w->win && w->xic; } int oswInit(osw * w, osg * g, int x, int y, int width, int height, int bl) { int ok; if (!bl) { x -= g->bw; y -= g->bh; } ok = openwin(w, g, x, y, width, height); if (ok && bl) { long flags[5] = {0}; Atom hatom = XInternAtom(g->dpy, "_MOTIF_WM_HINTS", 1); flags[0] = 2; //mwm.flags = MWM_HINTS_DECORATIONS; flags[2] = 0; XChangeProperty(g->dpy, w->win, hatom, hatom, 32, PropModeReplace, (unsigned char*)flags, sizeof(flags) / 4); } if (g->dpy) XSync(g->dpy, False); return ok; } int oswTerm(osw * w) { XDestroyIC(w->xic); XDestroyWindow(wgroup(w)->dpy, w->win); return 1; } int oswSwapBuffers(osw * w) { glXSwapBuffers(wgroup(w)->dpy, w->win); return 1; } int oswMakeCurrent(osw * w, osc * c) { return glXMakeCurrent(wgroup(w)->dpy, w->win, c->ctx); } int oswClearCurrent(osw * w) { return glXMakeCurrent(wgroup(w)->dpy, 0, 0); } int oswShow(osw * w) { int ret = 0; ret |= XMapWindow(wgroup(w)->dpy, w->win); ret |= sync(); return ret; } int oswHide(osw * w) { int ret = 0; ret |= XUnmapWindow(wgroup(w)->dpy, w->win); ret |= sync(); return ret; } static int mapButton(int button) { int which; switch (button) { case Button1: which = AW_KEY_MOUSELEFT; break; case Button2: which = AW_KEY_MOUSEMIDDLE; break; case Button3: which = AW_KEY_MOUSERIGHT; break; case Button4: which = AW_KEY_MOUSEWHEELUP; break; case Button5: which = AW_KEY_MOUSEWHEELDOWN; break; default: which = AW_KEY_NONE; } return which; } static void configure(osw * w, int x, int y, int width, int height) { if (width != w->lastw || height != w->lasth) got(w, AW_EVENT_RESIZE, width, height); w->lastw = width; w->lasth = height; if (x != w->lastx || y != w->lasty) got(w, AW_EVENT_POSITION, x, y); w->lastx = x; w->lasty = y; } static int isAutoRepeat(osw * w, XEvent * e) { XEvent next; XCheckTypedWindowEvent(wgroup(w)->dpy, w->win, KeyPress, &next); XPutBackEvent(wgroup(w)->dpy, &next); return next.xkey.keycode == e->xkey.keycode && next.xkey.time - e->xkey.time < 2; } static void handle(osw * w, XEvent * e) { extern unsigned mapkeycode(unsigned); switch(e->type) { case ClientMessage: got(w, AW_EVENT_CLOSE, 0, 0); break; case ConfigureNotify: { int x, y; Window child; XTranslateCoordinates(wgroup(w)->dpy, w->win, XRootWindow(wgroup(w)->dpy, 0), 0, 0, &x, &y, &child); configure(w, x, y, //e->xconfigure.x, e->xconfigure.y, e->xconfigure.width, e->xconfigure.height); } break; case ButtonPress: got(w, AW_EVENT_DOWN, mapButton(e->xbutton.button), 0); break; case ButtonRelease: got(w, AW_EVENT_UP, mapButton(e->xbutton.button), 0); break; case MotionNotify: got(w, AW_EVENT_MOTION, e->xmotion.x, e->xmotion.y); break; case KeyPress: { wchar_t buf[64]; KeySym ks; Status st; int i; int n; got(w, AW_EVENT_DOWN, mapkeycode(e->xkey.keycode), 0); n = XwcLookupString(w->xic, &e->xkey, buf, sizeof(buf) / sizeof(wchar_t), &ks, &st); if (st == XLookupChars || st == XLookupBoth) for (i = 0; i < n; i++) got(w, AW_EVENT_UNICODE, buf[i], 0); } break; case KeyRelease: if (!isAutoRepeat(w, e)) got(w, AW_EVENT_UP, mapkeycode(e->xkey.keycode), 0); default: got(w, AW_EVENT_UNKNOWN, 0, 0); break; } } static int pollEvent(osw * w, XEvent * e) { return XCheckWindowEvent(wgroup(w)->dpy, w->win, EVMASK, e) || XCheckTypedWindowEvent(wgroup(w)->dpy, w->win, ClientMessage, e); } void oswPollEvent(osw * w) { XEvent e; sync(); if (pollEvent(w, &e)) handle(w, &e); } int oswSetSwapInterval(osw * w, int interval) { return !wgroup(w)->swapInterval || 0 == wgroup(w)->swapInterval(interval); } int oswMaximize(osw * w) { osg * g = wgroup(w); unsigned width = DisplayWidth(g->dpy, g->screen); unsigned height = DisplayHeight(g->dpy, g->screen); return oswGeometry(w, 0, 0, width, height); } int oswGeometry(osw * w, int x, int y, unsigned width, unsigned height) { int ret = 0; ret |= XMoveResizeWindow(wgroup(w)->dpy, w->win, x - wgroup(w)->bw, y - wgroup(w)->bh, width, height); ret |= sync(); return ret; } int oscInit(osc * c, osg * g, osc * share) { XVisualInfo * vinfo = chooseVisual(g->dpy, g->screen); GLXContext ctx = 0; if (vinfo) { ctx = glXCreateContext(g->dpy, vinfo, share? share->ctx : 0, True); XFree(vinfo); } c->ctx = ctx; return c->ctx != 0; } int oscTerm(osc * c) { glXDestroyContext(cgroup(c)->dpy, c->ctx); return 1; } int ospInit(osp * p, const void * rgba, unsigned hotx, unsigned hoty) { return 1; } int ospTerm(osp * p) { return 1; } unsigned oswOrder(osw ** w) { return 0; } void oswPointer(osw * w) { } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
awx.c
C
bsd
11,598
import os import os.path import string import SCons.Action import SCons.Builder import SCons.Tool import SCons.Util def generate(env): sdkprefix = \ '/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/' gnu_tools = ['gcc', 'g++', 'applelink', 'ar', 'gas'] for tool in gnu_tools: SCons.Tool.Tool(tool)(env) env['CC'] = sdkprefix + 'gcc' env['CXX'] = sdkprefix + 'g++' env['LINK'] = sdkprefix + 'gcc' env.Append(CPPDEFINES=[['__IPHONE_OS_VERSION_MIN_REQUIRED', 30000]]) env.Append(LINKFLAGS=' -arch i386 -m32 ') env.Append(CFLAGS=' -arch i386 -m32 ') env.Append(CFLAGS=' -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk ') env.Append(LINKFLAGS=' -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk ') env.Append(CFLAGS=' -mmacosx-version-min=10.5 ') env.Append(LINKFLAGS=' -mmacosx-version-min=10.5 ') env['AS'] = sdkprefix + 'as' def exists(env): return find(env)
zzywany123-libaw-1
iphonesim.py
Python
bsd
1,047
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Copyright (c) 2004, Apple Computer, Inc. and The Mozilla Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the names of Apple Computer, Inc. ("Apple") or The Mozilla * Foundation ("Mozilla") nor the names of their contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE, MOZILLA AND THEIR CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE, MOZILLA OR * THEIR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Revision 1 (March 4, 2004): * Initial proposal. * * Revision 2 (March 10, 2004): * All calls into script were made asynchronous. Results are * provided via the NPScriptResultFunctionPtr callback. * * Revision 3 (March 10, 2004): * Corrected comments to not refer to class retain/release FunctionPtrs. * * Revision 4 (March 11, 2004): * Added additional convenience NPN_SetExceptionWithUTF8(). * Changed NPHasPropertyFunctionPtr and NPHasMethodFunctionPtr to take NPClass * pointers instead of NPObject pointers. * Added NPIsValidIdentifier(). * * Revision 5 (March 17, 2004): * Added context parameter to result callbacks from ScriptObject functions. * * Revision 6 (March 29, 2004): * Renamed functions implemented by user agent to NPN_*. Removed _ from * type names. * Renamed "JavaScript" types to "Script". * * Revision 7 (April 21, 2004): * NPIdentifier becomes a void*, was int32_t * Remove NP_IsValidIdentifier, renamed NP_IdentifierFromUTF8 to NP_GetIdentifier * Added NPVariant and modified functions to use this new type. * * Revision 8 (July 9, 2004): * Updated to joint Apple-Mozilla license. * */ #ifndef _NP_RUNTIME_H_ #define _NP_RUNTIME_H_ #ifdef __cplusplus extern "C" { #endif #include "nptypes.h" /* This API is used to facilitate binding code written in C to script objects. The API in this header does not assume the presence of a user agent. That is, it can be used to bind C code to scripting environments outside of the context of a user agent. However, the normal use of the this API is in the context of a scripting environment running in a browser or other user agent. In particular it is used to support the extended Netscape script-ability API for plugins (NP-SAP). NP-SAP is an extension of the Netscape plugin API. As such we have adopted the use of the "NP" prefix for this API. The following NP{N|P}Variables were added to the Netscape plugin API (in npapi.h): NPNVWindowNPObject NPNVPluginElementNPObject NPPVpluginScriptableNPObject These variables are exposed through NPN_GetValue() and NPP_GetValue() (respectively) and are used to establish the initial binding between the user agent and native code. The DOM objects in the user agent can be examined and manipulated using the NPN_ functions that operate on NPObjects described in this header. To the extent possible the assumptions about the scripting language used by the scripting environment have been minimized. */ #define NP_BEGIN_MACRO do { #define NP_END_MACRO } while (0) /* Objects (non-primitive data) passed between 'C' and script is always wrapped in an NPObject. The 'interface' of an NPObject is described by an NPClass. */ typedef struct NPObject NPObject; typedef struct NPClass NPClass; typedef char NPUTF8; typedef struct _NPString { const NPUTF8 *UTF8Characters; uint32_t UTF8Length; } NPString; typedef enum { NPVariantType_Void, NPVariantType_Null, NPVariantType_Bool, NPVariantType_Int32, NPVariantType_Double, NPVariantType_String, NPVariantType_Object } NPVariantType; typedef struct _NPVariant { NPVariantType type; union { bool boolValue; int32_t intValue; double doubleValue; NPString stringValue; NPObject *objectValue; } value; } NPVariant; /* NPN_ReleaseVariantValue is called on all 'out' parameters references. Specifically it is to be called on variants that own their value, as is the case with all non-const NPVariant* arguments after a successful call to any methods (except this one) in this API. After calling NPN_ReleaseVariantValue, the type of the variant will be NPVariantType_Void. */ void NPN_ReleaseVariantValue(NPVariant *variant); #define NPVARIANT_IS_VOID(_v) ((_v).type == NPVariantType_Void) #define NPVARIANT_IS_NULL(_v) ((_v).type == NPVariantType_Null) #define NPVARIANT_IS_BOOLEAN(_v) ((_v).type == NPVariantType_Bool) #define NPVARIANT_IS_INT32(_v) ((_v).type == NPVariantType_Int32) #define NPVARIANT_IS_DOUBLE(_v) ((_v).type == NPVariantType_Double) #define NPVARIANT_IS_STRING(_v) ((_v).type == NPVariantType_String) #define NPVARIANT_IS_OBJECT(_v) ((_v).type == NPVariantType_Object) #define NPVARIANT_TO_BOOLEAN(_v) ((_v).value.boolValue) #define NPVARIANT_TO_INT32(_v) ((_v).value.intValue) #define NPVARIANT_TO_DOUBLE(_v) ((_v).value.doubleValue) #define NPVARIANT_TO_STRING(_v) ((_v).value.stringValue) #define NPVARIANT_TO_OBJECT(_v) ((_v).value.objectValue) #define VOID_TO_NPVARIANT(_v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_Void; \ (_v).value.objectValue = NULL; \ NP_END_MACRO #define NULL_TO_NPVARIANT(_v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_Null; \ (_v).value.objectValue = NULL; \ NP_END_MACRO #define BOOLEAN_TO_NPVARIANT(_val, _v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_Bool; \ (_v).value.boolValue = !!(_val); \ NP_END_MACRO #define INT32_TO_NPVARIANT(_val, _v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_Int32; \ (_v).value.intValue = _val; \ NP_END_MACRO #define DOUBLE_TO_NPVARIANT(_val, _v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_Double; \ (_v).value.doubleValue = _val; \ NP_END_MACRO #define STRINGZ_TO_NPVARIANT(_val, _v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_String; \ NPString str = { _val, strlen(_val) }; \ (_v).value.stringValue = str; \ NP_END_MACRO #define STRINGN_TO_NPVARIANT(_val, _len, _v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_String; \ NPString str = { _val, _len }; \ (_v).value.stringValue = str; \ NP_END_MACRO #define OBJECT_TO_NPVARIANT(_val, _v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_Object; \ (_v).value.objectValue = _val; \ NP_END_MACRO /* Type mappings (JavaScript types have been used for illustration purposes): JavaScript to C (NPVariant with type:) undefined NPVariantType_Void null NPVariantType_Null Boolean NPVariantType_Bool Number NPVariantType_Double or NPVariantType_Int32 String NPVariantType_String Object NPVariantType_Object C (NPVariant with type:) to JavaScript NPVariantType_Void undefined NPVariantType_Null null NPVariantType_Bool Boolean NPVariantType_Int32 Number NPVariantType_Double Number NPVariantType_String String NPVariantType_Object Object */ typedef void *NPIdentifier; /* NPObjects have methods and properties. Methods and properties are identified with NPIdentifiers. These identifiers may be reflected in script. NPIdentifiers can be either strings or integers, IOW, methods and properties can be identified by either strings or integers (i.e. foo["bar"] vs foo[1]). NPIdentifiers can be compared using ==. In case of any errors, the requested NPIdentifier(s) will be NULL. NPIdentifier lifetime is controlled by the browser. Plugins do not need to worry about memory management with regards to NPIdentifiers. */ NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name); void NPN_GetStringIdentifiers(const NPUTF8 **names, int32_t nameCount, NPIdentifier *identifiers); NPIdentifier NPN_GetIntIdentifier(int32_t intid); bool NPN_IdentifierIsString(NPIdentifier identifier); /* The NPUTF8 returned from NPN_UTF8FromIdentifier SHOULD be freed. */ NPUTF8 *NPN_UTF8FromIdentifier(NPIdentifier identifier); /* Get the integer represented by identifier. If identifier is not an integer identifier, the behaviour is undefined. */ int32_t NPN_IntFromIdentifier(NPIdentifier identifier); /* NPObject behavior is implemented using the following set of callback functions. The NPVariant *result argument of these functions (where applicable) should be released using NPN_ReleaseVariantValue(). */ typedef NPObject *(*NPAllocateFunctionPtr)(NPP npp, NPClass *aClass); typedef void (*NPDeallocateFunctionPtr)(NPObject *npobj); typedef void (*NPInvalidateFunctionPtr)(NPObject *npobj); typedef bool (*NPHasMethodFunctionPtr)(NPObject *npobj, NPIdentifier name); typedef bool (*NPInvokeFunctionPtr)(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); typedef bool (*NPInvokeDefaultFunctionPtr)(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); typedef bool (*NPHasPropertyFunctionPtr)(NPObject *npobj, NPIdentifier name); typedef bool (*NPGetPropertyFunctionPtr)(NPObject *npobj, NPIdentifier name, NPVariant *result); typedef bool (*NPSetPropertyFunctionPtr)(NPObject *npobj, NPIdentifier name, const NPVariant *value); typedef bool (*NPRemovePropertyFunctionPtr)(NPObject *npobj, NPIdentifier name); typedef bool (*NPEnumerationFunctionPtr)(NPObject *npobj, NPIdentifier **value, uint32_t *count); typedef bool (*NPConstructFunctionPtr)(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); /* NPObjects returned by create, retain, invoke, and getProperty pass a reference count to the caller. That is, the callee adds a reference count which passes to the caller. It is the caller's responsibility to release the returned object. NPInvokeFunctionPtr function may return 0 to indicate a void result. NPInvalidateFunctionPtr is called by the scripting environment when the native code is shutdown. Any attempt to message a NPObject instance after the invalidate callback has been called will result in undefined behavior, even if the native code is still retaining those NPObject instances. (The runtime will typically return immediately, with 0 or NULL, from an attempt to dispatch to a NPObject, but this behavior should not be depended upon.) The NPEnumerationFunctionPtr function may pass an array of NPIdentifiers back to the caller. The callee allocs the memory of the array using NPN_MemAlloc(), and it's the caller's responsibility to release it using NPN_MemFree(). */ struct NPClass { uint32_t structVersion; NPAllocateFunctionPtr allocate; NPDeallocateFunctionPtr deallocate; NPInvalidateFunctionPtr invalidate; NPHasMethodFunctionPtr hasMethod; NPInvokeFunctionPtr invoke; NPInvokeDefaultFunctionPtr invokeDefault; NPHasPropertyFunctionPtr hasProperty; NPGetPropertyFunctionPtr getProperty; NPSetPropertyFunctionPtr setProperty; NPRemovePropertyFunctionPtr removeProperty; NPEnumerationFunctionPtr enumerate; NPConstructFunctionPtr construct; }; #define NP_CLASS_STRUCT_VERSION 3 #define NP_CLASS_STRUCT_VERSION_ENUM 2 #define NP_CLASS_STRUCT_VERSION_CTOR 3 #define NP_CLASS_STRUCT_VERSION_HAS_ENUM(npclass) \ ((npclass)->structVersion >= NP_CLASS_STRUCT_VERSION_ENUM) #define NP_CLASS_STRUCT_VERSION_HAS_CTOR(npclass) \ ((npclass)->structVersion >= NP_CLASS_STRUCT_VERSION_CTOR) struct NPObject { NPClass *_class; uint32_t referenceCount; /* * Additional space may be allocated here by types of NPObjects */ }; /* If the class has an allocate function, NPN_CreateObject invokes that function, otherwise a NPObject is allocated and returned. This method will initialize the referenceCount member of the NPObject to 1. */ NPObject *NPN_CreateObject(NPP npp, NPClass *aClass); /* Increment the NPObject's reference count. */ NPObject *NPN_RetainObject(NPObject *npobj); /* Decremented the NPObject's reference count. If the reference count goes to zero, the class's destroy function is invoke if specified, otherwise the object is freed directly. */ void NPN_ReleaseObject(NPObject *npobj); /* Functions to access script objects represented by NPObject. Calls to script objects are synchronous. If a function returns a value, it will be supplied via the result NPVariant argument. Successful calls will return true, false will be returned in case of an error. Calls made from plugin code to script must be made from the thread on which the plugin was initialized. */ bool NPN_Invoke(NPP npp, NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result); bool NPN_InvokeDefault(NPP npp, NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); bool NPN_Evaluate(NPP npp, NPObject *npobj, NPString *script, NPVariant *result); bool NPN_GetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName, NPVariant *result); bool NPN_SetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName, const NPVariant *value); bool NPN_RemoveProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName); bool NPN_HasProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName); bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier methodName); bool NPN_Enumerate(NPP npp, NPObject *npobj, NPIdentifier **identifier, uint32_t *count); bool NPN_Construct(NPP npp, NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); /* NPN_SetException may be called to trigger a script exception upon return from entry points into NPObjects. Typical usage: NPN_SetException (npobj, message); */ void NPN_SetException(NPObject *npobj, const NPUTF8 *message); #ifdef __cplusplus } #endif #endif
zzywany123-libaw-1
npapi/npruntime.h
C
bsd
17,537
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef npapi_h_ #define npapi_h_ #ifdef __OS2__ #pragma pack(1) #endif #include "nptypes.h" #if defined (__OS2__) || defined (OS2) # ifndef XP_OS2 # define XP_OS2 1 # endif /* XP_OS2 */ #endif /* __OS2__ */ #ifdef _WINDOWS # include <windef.h> # ifndef XP_WIN # define XP_WIN 1 # endif /* XP_WIN */ #endif /* _WINDOWS */ #ifdef XP_MACOSX #ifdef __LP64__ #define NP_NO_QUICKDRAW #else #include <Carbon/Carbon.h> #endif #endif #if defined(XP_UNIX) # include <stdio.h> # if defined(MOZ_X11) # include <X11/Xlib.h> # include <X11/Xutil.h> # endif #endif /*----------------------------------------------------------------------*/ /* Plugin Version Constants */ /*----------------------------------------------------------------------*/ #define NP_VERSION_MAJOR 0 #define NP_VERSION_MINOR 22 /* The OS/2 version of Netscape uses RC_DATA to define the mime types, file extensions, etc that are required. Use a vertical bar to separate types, end types with \0. FileVersion and ProductVersion are 32bit ints, all other entries are strings the MUST be terminated wwith a \0. AN EXAMPLE: RCDATA NP_INFO_ProductVersion { 1,0,0,1,} RCDATA NP_INFO_MIMEType { "video/x-video|", "video/x-flick\0" } RCDATA NP_INFO_FileExtents { "avi|", "flc\0" } RCDATA NP_INFO_FileOpenName{ "MMOS2 video player(*.avi)|", "MMOS2 Flc/Fli player(*.flc)\0" } RCDATA NP_INFO_FileVersion { 1,0,0,1 } RCDATA NP_INFO_CompanyName { "Netscape Communications\0" } RCDATA NP_INFO_FileDescription { "NPAVI32 Extension DLL\0" RCDATA NP_INFO_InternalName { "NPAVI32\0" ) RCDATA NP_INFO_LegalCopyright { "Copyright Netscape Communications \251 1996\0" RCDATA NP_INFO_OriginalFilename { "NVAPI32.DLL" } RCDATA NP_INFO_ProductName { "NPAVI32 Dynamic Link Library\0" } */ /* RC_DATA types for version info - required */ #define NP_INFO_ProductVersion 1 #define NP_INFO_MIMEType 2 #define NP_INFO_FileOpenName 3 #define NP_INFO_FileExtents 4 /* RC_DATA types for version info - used if found */ #define NP_INFO_FileDescription 5 #define NP_INFO_ProductName 6 /* RC_DATA types for version info - optional */ #define NP_INFO_CompanyName 7 #define NP_INFO_FileVersion 8 #define NP_INFO_InternalName 9 #define NP_INFO_LegalCopyright 10 #define NP_INFO_OriginalFilename 11 #ifndef RC_INVOKED /*----------------------------------------------------------------------*/ /* Definition of Basic Types */ /*----------------------------------------------------------------------*/ typedef unsigned char NPBool; typedef int16_t NPError; typedef int16_t NPReason; typedef char* NPMIMEType; /*----------------------------------------------------------------------*/ /* Structures and definitions */ /*----------------------------------------------------------------------*/ #if !defined(__LP64__) #if defined(XP_MAC) || defined(XP_MACOSX) #pragma options align=mac68k #endif #endif /* __LP64__ */ /* * NPP is a plug-in's opaque instance handle */ typedef struct _NPP { void* pdata; /* plug-in private data */ void* ndata; /* netscape private data */ } NPP_t; typedef NPP_t* NPP; typedef struct _NPStream { void* pdata; /* plug-in private data */ void* ndata; /* netscape private data */ const char* url; uint32_t end; uint32_t lastmodified; void* notifyData; const char* headers; /* Response headers from host. * Exists only for >= NPVERS_HAS_RESPONSE_HEADERS. * Used for HTTP only; NULL for non-HTTP. * Available from NPP_NewStream onwards. * Plugin should copy this data before storing it. * Includes HTTP status line and all headers, * preferably verbatim as received from server, * headers formatted as in HTTP ("Header: Value"), * and newlines (\n, NOT \r\n) separating lines. * Terminated by \n\0 (NOT \n\n\0). */ } NPStream; typedef struct _NPByteRange { int32_t offset; /* negative offset means from the end */ uint32_t length; struct _NPByteRange* next; } NPByteRange; typedef struct _NPSavedData { int32_t len; void* buf; } NPSavedData; typedef struct _NPRect { uint16_t top; uint16_t left; uint16_t bottom; uint16_t right; } NPRect; typedef struct _NPSize { int32_t width; int32_t height; } NPSize; #ifdef XP_UNIX /* * Unix specific structures and definitions */ /* * Callback Structures. * * These are used to pass additional platform specific information. */ enum { NP_SETWINDOW = 1, NP_PRINT }; typedef struct { int32_t type; } NPAnyCallbackStruct; typedef struct { int32_t type; #ifdef MOZ_X11 Display* display; Visual* visual; Colormap colormap; unsigned int depth; #endif } NPSetWindowCallbackStruct; typedef struct { int32_t type; FILE* fp; } NPPrintCallbackStruct; #endif /* XP_UNIX */ #ifdef XP_MACOSX typedef enum { #ifndef NP_NO_QUICKDRAW NPDrawingModelQuickDraw = 0, #endif NPDrawingModelCoreGraphics = 1 } NPDrawingModel; #endif /* * The following masks are applied on certain platforms to NPNV and * NPPV selectors that pass around pointers to COM interfaces. Newer * compilers on some platforms may generate vtables that are not * compatible with older compilers. To prevent older plugins from * not understanding a new browser's ABI, these masks change the * values of those selectors on those platforms. To remain backwards * compatible with differenet versions of the browser, plugins can * use these masks to dynamically determine and use the correct C++ * ABI that the browser is expecting. This does not apply to Windows * as Microsoft's COM ABI will likely not change. */ #define NP_ABI_GCC3_MASK 0x10000000 /* * gcc 3.x generated vtables on UNIX and OSX are incompatible with * previous compilers. */ #if (defined(XP_UNIX) && defined(__GNUC__) && (__GNUC__ >= 3)) #define _NP_ABI_MIXIN_FOR_GCC3 NP_ABI_GCC3_MASK #else #define _NP_ABI_MIXIN_FOR_GCC3 0 #endif #ifdef XP_MACOSX #define NP_ABI_MACHO_MASK 0x01000000 #define _NP_ABI_MIXIN_FOR_MACHO NP_ABI_MACHO_MASK #else #define _NP_ABI_MIXIN_FOR_MACHO 0 #endif #define NP_ABI_MASK (_NP_ABI_MIXIN_FOR_GCC3 | _NP_ABI_MIXIN_FOR_MACHO) /* * List of variable names for which NPP_GetValue shall be implemented */ typedef enum { NPPVpluginNameString = 1, NPPVpluginDescriptionString, NPPVpluginWindowBool, NPPVpluginTransparentBool, NPPVjavaClass, /* Not implemented in Mozilla 1.0 */ NPPVpluginWindowSize, NPPVpluginTimerInterval, NPPVpluginScriptableInstance = (10 | NP_ABI_MASK), NPPVpluginScriptableIID = 11, /* Introduced in Mozilla 0.9.9 */ NPPVjavascriptPushCallerBool = 12, /* Introduced in Mozilla 1.0 */ NPPVpluginKeepLibraryInMemory = 13, NPPVpluginNeedsXEmbed = 14, /* Get the NPObject for scripting the plugin. Introduced in Firefox * 1.0 (NPAPI minor version 14). */ NPPVpluginScriptableNPObject = 15, /* Get the plugin value (as \0-terminated UTF-8 string data) for * form submission if the plugin is part of a form. Use * NPN_MemAlloc() to allocate memory for the string data. Introduced * in Mozilla 1.8b2 (NPAPI minor version 15). */ NPPVformValue = 16, NPPVpluginUrlRequestsDisplayedBool = 17, /* Checks if the plugin is interested in receiving the http body of * all http requests (including failed ones, http status != 200). */ NPPVpluginWantsAllNetworkStreams = 18 #ifdef XP_MACOSX /* Used for negotiating drawing models */ , NPPVpluginDrawingModel = 1000 #endif #ifdef MOZ_PLATFORM_HILDON , NPPVpluginWindowlessLocalBool = 2002 #endif } NPPVariable; /* * List of variable names for which NPN_GetValue is implemented by Mozilla */ typedef enum { NPNVxDisplay = 1, NPNVxtAppContext, NPNVnetscapeWindow, NPNVjavascriptEnabledBool, NPNVasdEnabledBool, NPNVisOfflineBool, /* 10 and over are available on Mozilla builds starting with 0.9.4 */ NPNVserviceManager = (10 | NP_ABI_MASK), NPNVDOMElement = (11 | NP_ABI_MASK), /* available in Mozilla 1.2 */ NPNVDOMWindow = (12 | NP_ABI_MASK), NPNVToolkit = (13 | NP_ABI_MASK), NPNVSupportsXEmbedBool = 14, /* Get the NPObject wrapper for the browser window. */ NPNVWindowNPObject = 15, /* Get the NPObject wrapper for the plugins DOM element. */ NPNVPluginElementNPObject = 16, NPNVSupportsWindowless = 17, NPNVprivateModeBool = 18 #ifdef XP_MACOSX /* Used for negotiating drawing models */ , NPNVpluginDrawingModel = 1000 #ifndef NP_NO_QUICKDRAW , NPNVsupportsQuickDrawBool = 2000 #endif , NPNVsupportsCoreGraphicsBool = 2001 #endif #ifdef MOZ_PLATFORM_HILDON , NPNVSupportsWindowlessLocal = 2002 #endif } NPNVariable; typedef enum { NPNURLVCookie = 501, NPNURLVProxy } NPNURLVariable; /* * The type of Tookkit the widgets use */ typedef enum { NPNVGtk12 = 1, NPNVGtk2 } NPNToolkitType; /* * The type of a NPWindow - it specifies the type of the data structure * returned in the window field. */ typedef enum { NPWindowTypeWindow = 1, NPWindowTypeDrawable } NPWindowType; typedef struct _NPWindow { void* window; /* Platform specific window handle */ /* OS/2: x - Position of bottom left corner */ /* OS/2: y - relative to visible netscape window */ int32_t x; /* Position of top left corner relative */ int32_t y; /* to a netscape page. */ uint32_t width; /* Maximum window size */ uint32_t height; NPRect clipRect; /* Clipping rectangle in port coordinates */ /* Used by MAC only. */ #if defined(XP_UNIX) && !defined(XP_MACOSX) void * ws_info; /* Platform-dependent additonal data */ #endif /* XP_UNIX */ NPWindowType type; /* Is this a window or a drawable? */ } NPWindow; typedef struct _NPImageExpose { char* data; /* image pointer */ int32_t stride; /* Stride of data image pointer */ int32_t depth; /* Depth of image pointer */ int32_t x; /* Expose x */ int32_t y; /* Expose y */ uint32_t width; /* Expose width */ uint32_t height; /* Expose height */ NPSize dataSize; /* Data buffer size */ float translateX; /* translate X matrix value */ float translateY; /* translate Y matrix value */ float scaleX; /* scale X matrix value */ float scaleY; /* scale Y matrix value */ } NPImageExpose; typedef struct _NPFullPrint { NPBool pluginPrinted;/* Set TRUE if plugin handled fullscreen printing */ NPBool printOne; /* TRUE if plugin should print one copy to default printer */ void* platformPrint; /* Platform-specific printing info */ } NPFullPrint; typedef struct _NPEmbedPrint { NPWindow window; void* platformPrint; /* Platform-specific printing info */ } NPEmbedPrint; typedef struct _NPPrint { uint16_t mode; /* NP_FULL or NP_EMBED */ union { NPFullPrint fullPrint; /* if mode is NP_FULL */ NPEmbedPrint embedPrint; /* if mode is NP_EMBED */ } print; } NPPrint; #ifdef XP_MACOSX typedef EventRecord NPEvent; #elif defined(XP_WIN) typedef struct _NPEvent { uint16_t event; uint32_t wParam; uint32_t lParam; } NPEvent; #elif defined(XP_OS2) typedef struct _NPEvent { uint32_t event; uint32_t wParam; uint32_t lParam; } NPEvent; #elif defined (XP_UNIX) && defined(MOZ_X11) typedef XEvent NPEvent; #else typedef void* NPEvent; #endif /* XP_MACOSX */ #ifdef XP_MACOSX typedef void* NPRegion; #ifndef NP_NO_QUICKDRAW typedef RgnHandle NPQDRegion; #endif typedef CGPathRef NPCGRegion; #elif defined(XP_WIN) typedef HRGN NPRegion; #elif defined(XP_UNIX) && defined(MOZ_X11) typedef Region NPRegion; #else typedef void *NPRegion; #endif #ifdef XP_MACOSX typedef struct NP_Port { CGrafPtr port; int32_t portx; /* position inside the topmost window */ int32_t porty; } NP_Port; typedef struct NP_CGContext { CGContextRef context; WindowRef window; } NP_CGContext; /* Non-standard event types that can be passed to HandleEvent */ enum NPEventType { NPEventType_GetFocusEvent = (osEvt + 16), NPEventType_LoseFocusEvent, NPEventType_AdjustCursorEvent, NPEventType_MenuCommandEvent, NPEventType_ClippingChangedEvent, NPEventType_ScrollingBeginsEvent = 1000, NPEventType_ScrollingEndsEvent }; #ifdef OBSOLETE #define getFocusEvent (osEvt + 16) #define loseFocusEvent (osEvt + 17) #define adjustCursorEvent (osEvt + 18) #endif #endif /* XP_MACOSX */ /* * Values for mode passed to NPP_New: */ #define NP_EMBED 1 #define NP_FULL 2 /* * Values for stream type passed to NPP_NewStream: */ #define NP_NORMAL 1 #define NP_SEEK 2 #define NP_ASFILE 3 #define NP_ASFILEONLY 4 #define NP_MAXREADY (((unsigned)(~0)<<1)>>1) #if !defined(__LP64__) #if defined(XP_MAC) || defined(XP_MACOSX) #pragma options align=reset #endif #endif /* __LP64__ */ /*----------------------------------------------------------------------*/ /* Error and Reason Code definitions */ /*----------------------------------------------------------------------*/ /* * Values of type NPError: */ #define NPERR_BASE 0 #define NPERR_NO_ERROR (NPERR_BASE + 0) #define NPERR_GENERIC_ERROR (NPERR_BASE + 1) #define NPERR_INVALID_INSTANCE_ERROR (NPERR_BASE + 2) #define NPERR_INVALID_FUNCTABLE_ERROR (NPERR_BASE + 3) #define NPERR_MODULE_LOAD_FAILED_ERROR (NPERR_BASE + 4) #define NPERR_OUT_OF_MEMORY_ERROR (NPERR_BASE + 5) #define NPERR_INVALID_PLUGIN_ERROR (NPERR_BASE + 6) #define NPERR_INVALID_PLUGIN_DIR_ERROR (NPERR_BASE + 7) #define NPERR_INCOMPATIBLE_VERSION_ERROR (NPERR_BASE + 8) #define NPERR_INVALID_PARAM (NPERR_BASE + 9) #define NPERR_INVALID_URL (NPERR_BASE + 10) #define NPERR_FILE_NOT_FOUND (NPERR_BASE + 11) #define NPERR_NO_DATA (NPERR_BASE + 12) #define NPERR_STREAM_NOT_SEEKABLE (NPERR_BASE + 13) /* * Values of type NPReason: */ #define NPRES_BASE 0 #define NPRES_DONE (NPRES_BASE + 0) #define NPRES_NETWORK_ERR (NPRES_BASE + 1) #define NPRES_USER_BREAK (NPRES_BASE + 2) /* * Don't use these obsolete error codes any more. */ #define NP_NOERR NP_NOERR_is_obsolete_use_NPERR_NO_ERROR #define NP_EINVAL NP_EINVAL_is_obsolete_use_NPERR_GENERIC_ERROR #define NP_EABORT NP_EABORT_is_obsolete_use_NPRES_USER_BREAK /* * Version feature information */ #define NPVERS_HAS_STREAMOUTPUT 8 #define NPVERS_HAS_NOTIFICATION 9 #define NPVERS_HAS_LIVECONNECT 9 #define NPVERS_68K_HAS_LIVECONNECT 11 #define NPVERS_HAS_WINDOWLESS 11 #define NPVERS_HAS_XPCONNECT_SCRIPTING 13 #define NPVERS_HAS_NPRUNTIME_SCRIPTING 14 #define NPVERS_HAS_FORM_VALUES 15 #define NPVERS_HAS_POPUPS_ENABLED_STATE 16 #define NPVERS_HAS_RESPONSE_HEADERS 17 #define NPVERS_HAS_NPOBJECT_ENUM 18 #define NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL 19 #define NPVERS_HAS_ALL_NETWORK_STREAMS 20 #define NPVERS_HAS_URL_AND_AUTH_INFO 21 /*----------------------------------------------------------------------*/ /* Function Prototypes */ /*----------------------------------------------------------------------*/ #if defined(__OS2__) #define NP_LOADDS _System #else #define NP_LOADDS #endif #ifdef __cplusplus extern "C" { #endif /* NPP_* functions are provided by the plugin and called by the navigator. */ #ifdef XP_UNIX char* NPP_GetMIMEDescription(); #endif NPError NP_LOADDS NPP_Initialize(); void NP_LOADDS NPP_Shutdown(); NPError NP_LOADDS NPP_New(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved); NPError NP_LOADDS NPP_Destroy(NPP instance, NPSavedData** save); NPError NP_LOADDS NPP_SetWindow(NPP instance, NPWindow* window); NPError NP_LOADDS NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype); NPError NP_LOADDS NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason); int32_t NP_LOADDS NPP_WriteReady(NPP instance, NPStream* stream); int32_t NP_LOADDS NPP_Write(NPP instance, NPStream* stream, int32_t offset, int32_t len, void* buffer); void NP_LOADDS NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname); void NP_LOADDS NPP_Print(NPP instance, NPPrint* platformPrint); int16_t NP_LOADDS NPP_HandleEvent(NPP instance, void* event); void NP_LOADDS NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData); NPError NP_LOADDS NPP_GetValue(NPP instance, NPPVariable variable, void *value); NPError NP_LOADDS NPP_SetValue(NPP instance, NPNVariable variable, void *value); /* NPN_* functions are provided by the navigator and called by the plugin. */ void NP_LOADDS NPN_Version(int* plugin_major, int* plugin_minor, int* netscape_major, int* netscape_minor); NPError NP_LOADDS NPN_GetURLNotify(NPP instance, const char* url, const char* target, void* notifyData); NPError NP_LOADDS NPN_GetURL(NPP instance, const char* url, const char* target); NPError NP_LOADDS NPN_PostURLNotify(NPP instance, const char* url, const char* target, uint32_t len, const char* buf, NPBool file, void* notifyData); NPError NP_LOADDS NPN_PostURL(NPP instance, const char* url, const char* target, uint32_t len, const char* buf, NPBool file); NPError NP_LOADDS NPN_RequestRead(NPStream* stream, NPByteRange* rangeList); NPError NP_LOADDS NPN_NewStream(NPP instance, NPMIMEType type, const char* target, NPStream** stream); int32_t NP_LOADDS NPN_Write(NPP instance, NPStream* stream, int32_t len, void* buffer); NPError NP_LOADDS NPN_DestroyStream(NPP instance, NPStream* stream, NPReason reason); void NP_LOADDS NPN_Status(NPP instance, const char* message); const char* NP_LOADDS NPN_UserAgent(NPP instance); void* NP_LOADDS NPN_MemAlloc(uint32_t size); void NP_LOADDS NPN_MemFree(void* ptr); uint32_t NP_LOADDS NPN_MemFlush(uint32_t size); void NP_LOADDS NPN_ReloadPlugins(NPBool reloadPages); NPError NP_LOADDS NPN_GetValue(NPP instance, NPNVariable variable, void *value); NPError NP_LOADDS NPN_SetValue(NPP instance, NPPVariable variable, void *value); void NP_LOADDS NPN_InvalidateRect(NPP instance, NPRect *invalidRect); void NP_LOADDS NPN_InvalidateRegion(NPP instance, NPRegion invalidRegion); void NP_LOADDS NPN_ForceRedraw(NPP instance); void NP_LOADDS NPN_PushPopupsEnabledState(NPP instance, NPBool enabled); void NP_LOADDS NPN_PopPopupsEnabledState(NPP instance); void NP_LOADDS NPN_PluginThreadAsyncCall(NPP instance, void (*func) (void *), void *userData); NPError NP_LOADDS NPN_GetValueForURL(NPP instance, NPNURLVariable variable, const char *url, char **value, uint32_t *len); NPError NP_LOADDS NPN_SetValueForURL(NPP instance, NPNURLVariable variable, const char *url, const char *value, uint32_t len); NPError NP_LOADDS NPN_GetAuthenticationInfo(NPP instance, const char *protocol, const char *host, int32_t port, const char *scheme, const char *realm, char **username, uint32_t *ulen, char **password, uint32_t *plen); #ifdef __cplusplus } /* end extern "C" */ #endif #endif /* RC_INVOKED */ #ifdef __OS2__ #pragma pack() #endif #endif /* npapi_h_ */
zzywany123-libaw-1
npapi/npapi.h
C
bsd
23,038
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef npfunctions_h_ #define npfunctions_h_ #ifdef __OS2__ #pragma pack(1) #define NP_LOADDS _System #else #define NP_LOADDS #endif #include "npapi.h" #include "npruntime.h" typedef void (* NP_LOADDS NPP_InitializeProcPtr)(); typedef void (* NP_LOADDS NPP_ShutdownProcPtr)(); typedef NPError (* NP_LOADDS NPP_NewProcPtr)(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved); typedef NPError (* NP_LOADDS NPP_DestroyProcPtr)(NPP instance, NPSavedData** save); typedef NPError (* NP_LOADDS NPP_SetWindowProcPtr)(NPP instance, NPWindow* window); typedef NPError (* NP_LOADDS NPP_NewStreamProcPtr)(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype); typedef NPError (* NP_LOADDS NPP_DestroyStreamProcPtr)(NPP instance, NPStream* stream, NPReason reason); typedef int32_t (* NP_LOADDS NPP_WriteReadyProcPtr)(NPP instance, NPStream* stream); typedef int32_t (* NP_LOADDS NPP_WriteProcPtr)(NPP instance, NPStream* stream, int32_t offset, int32_t len, void* buffer); typedef void (* NP_LOADDS NPP_StreamAsFileProcPtr)(NPP instance, NPStream* stream, const char* fname); typedef void (* NP_LOADDS NPP_PrintProcPtr)(NPP instance, NPPrint* platformPrint); typedef int16_t (* NP_LOADDS NPP_HandleEventProcPtr)(NPP instance, void* event); typedef void (* NP_LOADDS NPP_URLNotifyProcPtr)(NPP instance, const char* url, NPReason reason, void* notifyData); /* Any NPObjects returned to the browser via NPP_GetValue should be retained by the plugin on the way out. The browser is responsible for releasing. */ typedef NPError (* NP_LOADDS NPP_GetValueProcPtr)(NPP instance, NPPVariable variable, void *ret_value); typedef NPError (* NP_LOADDS NPP_SetValueProcPtr)(NPP instance, NPNVariable variable, void *value); typedef NPError (*NPN_GetValueProcPtr)(NPP instance, NPNVariable variable, void *ret_value); typedef NPError (*NPN_SetValueProcPtr)(NPP instance, NPPVariable variable, void *value); typedef NPError (*NPN_GetURLNotifyProcPtr)(NPP instance, const char* url, const char* window, void* notifyData); typedef NPError (*NPN_PostURLNotifyProcPtr)(NPP instance, const char* url, const char* window, uint32_t len, const char* buf, NPBool file, void* notifyData); typedef NPError (*NPN_GetURLProcPtr)(NPP instance, const char* url, const char* window); typedef NPError (*NPN_PostURLProcPtr)(NPP instance, const char* url, const char* window, uint32_t len, const char* buf, NPBool file); typedef NPError (*NPN_RequestReadProcPtr)(NPStream* stream, NPByteRange* rangeList); typedef NPError (*NPN_NewStreamProcPtr)(NPP instance, NPMIMEType type, const char* window, NPStream** stream); typedef int32_t (*NPN_WriteProcPtr)(NPP instance, NPStream* stream, int32_t len, void* buffer); typedef NPError (*NPN_DestroyStreamProcPtr)(NPP instance, NPStream* stream, NPReason reason); typedef void (*NPN_StatusProcPtr)(NPP instance, const char* message); /* Browser manages the lifetime of the buffer returned by NPN_UserAgent, don't depend on it sticking around and don't free it. */ typedef const char* (*NPN_UserAgentProcPtr)(NPP instance); typedef void* (*NPN_MemAllocProcPtr)(uint32_t size); typedef void (*NPN_MemFreeProcPtr)(void* ptr); typedef uint32_t (*NPN_MemFlushProcPtr)(uint32_t size); typedef void (*NPN_ReloadPluginsProcPtr)(NPBool reloadPages); typedef void* (*NPN_GetJavaEnvProcPtr)(); typedef void* (*NPN_GetJavaPeerProcPtr)(NPP instance); typedef void (*NPN_InvalidateRectProcPtr)(NPP instance, NPRect *rect); typedef void (*NPN_InvalidateRegionProcPtr)(NPP instance, NPRegion region); typedef void (*NPN_ForceRedrawProcPtr)(NPP instance); typedef NPIdentifier (*NPN_GetStringIdentifierProcPtr)(const NPUTF8* name); typedef void (*NPN_GetStringIdentifiersProcPtr)(const NPUTF8** names, int32_t nameCount, NPIdentifier* identifiers); typedef NPIdentifier (*NPN_GetIntIdentifierProcPtr)(int32_t intid); typedef bool (*NPN_IdentifierIsStringProcPtr)(NPIdentifier identifier); typedef NPUTF8* (*NPN_UTF8FromIdentifierProcPtr)(NPIdentifier identifier); typedef int32_t (*NPN_IntFromIdentifierProcPtr)(NPIdentifier identifier); typedef NPObject* (*NPN_CreateObjectProcPtr)(NPP npp, NPClass *aClass); typedef NPObject* (*NPN_RetainObjectProcPtr)(NPObject *obj); typedef void (*NPN_ReleaseObjectProcPtr)(NPObject *obj); typedef bool (*NPN_InvokeProcPtr)(NPP npp, NPObject* obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result); typedef bool (*NPN_InvokeDefaultProcPtr)(NPP npp, NPObject* obj, const NPVariant *args, uint32_t argCount, NPVariant *result); typedef bool (*NPN_EvaluateProcPtr)(NPP npp, NPObject *obj, NPString *script, NPVariant *result); typedef bool (*NPN_GetPropertyProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName, NPVariant *result); typedef bool (*NPN_SetPropertyProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName, const NPVariant *value); typedef bool (*NPN_RemovePropertyProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName); typedef bool (*NPN_HasPropertyProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName); typedef bool (*NPN_HasMethodProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName); typedef void (*NPN_ReleaseVariantValueProcPtr)(NPVariant *variant); typedef void (*NPN_SetExceptionProcPtr)(NPObject *obj, const NPUTF8 *message); typedef bool (*NPN_PushPopupsEnabledStateProcPtr)(NPP npp, NPBool enabled); typedef bool (*NPN_PopPopupsEnabledStateProcPtr)(NPP npp); typedef bool (*NPN_EnumerateProcPtr)(NPP npp, NPObject *obj, NPIdentifier **identifier, uint32_t *count); typedef void (*NPN_PluginThreadAsyncCallProcPtr)(NPP instance, void (*func)(void *), void *userData); typedef bool (*NPN_ConstructProcPtr)(NPP npp, NPObject* obj, const NPVariant *args, uint32_t argCount, NPVariant *result); typedef NPError (*NPN_GetValueForURLPtr)(NPP npp, NPNURLVariable variable, const char *url, char **value, uint32_t *len); typedef NPError (*NPN_SetValueForURLPtr)(NPP npp, NPNURLVariable variable, const char *url, const char *value, uint32_t len); typedef NPError (*NPN_GetAuthenticationInfoPtr)(NPP npp, const char *protocol, const char *host, int32_t port, const char *scheme, const char *realm, char **username, uint32_t *ulen, char **password, uint32_t *plen); typedef struct _NPPluginFuncs { uint16_t size; uint16_t version; NPP_NewProcPtr newp; NPP_DestroyProcPtr destroy; NPP_SetWindowProcPtr setwindow; NPP_NewStreamProcPtr newstream; NPP_DestroyStreamProcPtr destroystream; NPP_StreamAsFileProcPtr asfile; NPP_WriteReadyProcPtr writeready; NPP_WriteProcPtr write; NPP_PrintProcPtr print; NPP_HandleEventProcPtr event; NPP_URLNotifyProcPtr urlnotify; void* javaClass; NPP_GetValueProcPtr getvalue; NPP_SetValueProcPtr setvalue; } NPPluginFuncs; typedef struct _NPNetscapeFuncs { uint16_t size; uint16_t version; NPN_GetURLProcPtr geturl; NPN_PostURLProcPtr posturl; NPN_RequestReadProcPtr requestread; NPN_NewStreamProcPtr newstream; NPN_WriteProcPtr write; NPN_DestroyStreamProcPtr destroystream; NPN_StatusProcPtr status; NPN_UserAgentProcPtr uagent; NPN_MemAllocProcPtr memalloc; NPN_MemFreeProcPtr memfree; NPN_MemFlushProcPtr memflush; NPN_ReloadPluginsProcPtr reloadplugins; NPN_GetJavaEnvProcPtr getJavaEnv; NPN_GetJavaPeerProcPtr getJavaPeer; NPN_GetURLNotifyProcPtr geturlnotify; NPN_PostURLNotifyProcPtr posturlnotify; NPN_GetValueProcPtr getvalue; NPN_SetValueProcPtr setvalue; NPN_InvalidateRectProcPtr invalidaterect; NPN_InvalidateRegionProcPtr invalidateregion; NPN_ForceRedrawProcPtr forceredraw; NPN_GetStringIdentifierProcPtr getstringidentifier; NPN_GetStringIdentifiersProcPtr getstringidentifiers; NPN_GetIntIdentifierProcPtr getintidentifier; NPN_IdentifierIsStringProcPtr identifierisstring; NPN_UTF8FromIdentifierProcPtr utf8fromidentifier; NPN_IntFromIdentifierProcPtr intfromidentifier; NPN_CreateObjectProcPtr createobject; NPN_RetainObjectProcPtr retainobject; NPN_ReleaseObjectProcPtr releaseobject; NPN_InvokeProcPtr invoke; NPN_InvokeDefaultProcPtr invokeDefault; NPN_EvaluateProcPtr evaluate; NPN_GetPropertyProcPtr getproperty; NPN_SetPropertyProcPtr setproperty; NPN_RemovePropertyProcPtr removeproperty; NPN_HasPropertyProcPtr hasproperty; NPN_HasMethodProcPtr hasmethod; NPN_ReleaseVariantValueProcPtr releasevariantvalue; NPN_SetExceptionProcPtr setexception; NPN_PushPopupsEnabledStateProcPtr pushpopupsenabledstate; NPN_PopPopupsEnabledStateProcPtr poppopupsenabledstate; NPN_EnumerateProcPtr enumerate; NPN_PluginThreadAsyncCallProcPtr pluginthreadasynccall; NPN_ConstructProcPtr construct; NPN_GetValueForURLPtr getvalueforurl; NPN_SetValueForURLPtr setvalueforurl; NPN_GetAuthenticationInfoPtr getauthenticationinfo; } NPNetscapeFuncs; #ifdef XP_MACOSX /* * Mac OS X version(s) of NP_GetMIMEDescription(const char *) * These can be called to retreive MIME information from the plugin dynamically * * Note: For compatibility with Quicktime, BPSupportedMIMEtypes is another way * to get mime info from the plugin only on OSX and may not be supported * in furture version -- use NP_GetMIMEDescription instead */ enum { kBPSupportedMIMETypesStructVers_1 = 1 }; typedef struct _BPSupportedMIMETypes { SInt32 structVersion; /* struct version */ Handle typeStrings; /* STR# formated handle, allocated by plug-in */ Handle infoStrings; /* STR# formated handle, allocated by plug-in */ } BPSupportedMIMETypes; OSErr BP_GetSupportedMIMETypes(BPSupportedMIMETypes *mimeInfo, UInt32 flags); #define NP_GETMIMEDESCRIPTION_NAME "NP_GetMIMEDescription" typedef const char* (*NP_GetMIMEDescriptionProcPtr)(); typedef OSErr (*BP_GetSupportedMIMETypesProcPtr)(BPSupportedMIMETypes*, UInt32); #endif #if defined(_WINDOWS) #define OSCALL WINAPI #else #if defined(__OS2__) #define OSCALL _System #else #define OSCALL #endif #endif #if defined(XP_UNIX) /* GCC 3.3 and later support the visibility attribute. */ #if defined(__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) #define NP_VISIBILITY_DEFAULT __attribute__((visibility("default"))) #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) #define NP_VISIBILITY_DEFAULT __global #else #define NP_VISIBILITY_DEFAULT #endif #define NP_EXPORT(__type) NP_VISIBILITY_DEFAULT __type #endif #if defined(_WINDOWS) || defined (__OS2__) #ifdef __cplusplus extern "C" { #endif /* plugin meta member functions */ #if defined(__OS2__) typedef struct _NPPluginData { /* Alternate OS2 Plugin interface */ char *pMimeTypes; char *pFileExtents; char *pFileOpenTemplate; char *pProductName; char *pProductDescription; unsigned long dwProductVersionMS; unsigned long dwProductVersionLS; } NPPluginData; NPError OSCALL NP_GetPluginData(NPPluginData * pPluginData); #endif NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs); NPError OSCALL NP_Initialize(NPNetscapeFuncs* bFuncs); NPError OSCALL NP_Shutdown(); char* NP_GetMIMEDescription(); #ifdef __cplusplus } #endif #endif #if defined(__OS2__) #pragma pack() #endif #ifdef XP_UNIX #ifdef __cplusplus extern "C" { #endif NP_EXPORT(char*) NP_GetPluginVersion(); NP_EXPORT(char*) NP_GetMIMEDescription(); #ifdef XP_MACOSX NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs); NP_EXPORT(NPError) NP_GetEntryPoints(NPPluginFuncs* pFuncs); #else NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs); #endif NP_EXPORT(NPError) NP_Shutdown(); NP_EXPORT(NPError) NP_GetValue(void *future, NPPVariable aVariable, void *aValue); #ifdef __cplusplus } #endif #endif #endif /* npfunctions_h_ */
zzywany123-libaw-1
npapi/npfunctions.h
C
bsd
13,839
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * mozilla.org. * Portions created by the Initial Developer are Copyright (C) 2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Johnny Stenback <jst@mozilla.org> (Original author) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * Header file for ensuring that C99 types ([u]int32_t and bool) and * true/false macros are available. */ #if defined(WIN32) || defined(OS2) /* * Win32 and OS/2 don't know C99, so define [u]int_16/32 here. The bool * is predefined tho, both in C and C++. */ typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned int uint32_t; typedef int bool; #elif defined(_AIX) || defined(__sun) || defined(__osf__) || defined(IRIX) || defined(HPUX) /* * AIX and SunOS ship a inttypes.h header that defines [u]int32_t, * but not bool for C. */ #include <inttypes.h> #ifndef __cplusplus typedef int bool; #define true 1 #define false 0 #endif #elif defined(bsdi) || defined(FREEBSD) || defined(OPENBSD) /* * BSD/OS, FreeBSD, and OpenBSD ship sys/types.h that define int32_t and * u_int32_t. */ #include <sys/types.h> /* * BSD/OS ships no header that defines uint32_t, nor bool (for C) */ #if defined(bsdi) typedef u_int32_t uint32_t; #if !defined(__cplusplus) typedef int bool; #define true 1 #define false 0 #endif #else /* * FreeBSD and OpenBSD define uint32_t and bool. */ #include <inttypes.h> #include <stdbool.h> #endif #elif defined(BEOS) #include <inttypes.h> #else /* * For those that ship a standard C99 stdint.h header file, include * it. Can't do the same for stdbool.h tho, since some systems ship * with a stdbool.h file that doesn't compile! */ #include <stdint.h> #ifndef __cplusplus #if !defined(__GNUC__) || (__GNUC__ > 2 || __GNUC_MINOR__ > 95) #include <stdbool.h> #else /* * GCC 2.91 can't deal with a typedef for bool, but a #define * works. */ #define bool int #define true 1 #define false 0 #endif #endif #endif
zzywany123-libaw-1
npapi/nptypes.h
C
bsd
3,689
typedef struct _co co; co * coMain(void *); co * coNew(void (*)(void*), void *); void coDel(co *); void coSwitchTo(co *); co * coCurrent(); void * coData(co *);
zzywany123-libaw-1
co.h
C
bsd
161
#include "awnpapios.h" #include <stdlib.h> #include <X11/X.h> #include <GL/glx.h> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <gtk/gtk.h> struct _ins { insHeader h; Window w; Display * dpy; GLXContext ctx; GtkWidget * plug; guint to; }; ins * awosNew(NPNetscapeFuncs * browser, NPP i) { return calloc(1, sizeof(ins)); } static XVisualInfo * chooseVisual(Display * dpy, int screen) { int att[64]; int * p = att; *p++ = GLX_RGBA; *p++ = GLX_DOUBLEBUFFER; *p++ = GLX_RED_SIZE; *p++ = 1; *p++ = GLX_GREEN_SIZE; *p++ = 1; *p++ = GLX_BLUE_SIZE; *p++ = 1; *p++ = GLX_DEPTH_SIZE; *p++ = 1; *p++ = None; return glXChooseVisual(dpy, screen, att); } static unsigned mapbutton(unsigned b) { unsigned ret; switch (b) { default: ret = AW_KEY_NONE; break; case 1: ret = AW_KEY_MOUSELEFT; break; case 2: ret = AW_KEY_MOUSEMIDDLE; break; case 3: ret = AW_KEY_MOUSERIGHT; break; } return ret; } static gboolean event(GtkWidget * wid, GdkEvent * ev, gpointer data) { extern unsigned mapkeycode(unsigned); ins * o = (ins*)data; aw * w = &o->h.w; int ret = TRUE; switch (ev->type) { case GDK_KEY_PRESS: { GdkEventKey * kev = (GdkEventKey*)ev; got(w, AW_EVENT_DOWN, mapkeycode(kev->hardware_keycode), 0); break; } case GDK_KEY_RELEASE: { GdkEventKey * kev = (GdkEventKey*)ev; got(w, AW_EVENT_UP, mapkeycode(kev->hardware_keycode), 0); break; } case GDK_BUTTON_PRESS: { GdkEventButton * bev = (GdkEventButton*)ev; gtk_widget_grab_focus(o->plug); got(w, AW_EVENT_DOWN, mapbutton(bev->button), 0); break; } case GDK_BUTTON_RELEASE: { GdkEventButton * bev = (GdkEventButton*)ev; got(w, AW_EVENT_UP, mapbutton(bev->button), 0); break; } case GDK_MOTION_NOTIFY: { GdkEventMotion * mev = (GdkEventMotion*)ev; got(w, AW_EVENT_MOTION, mev->x, mev->y); break; } default: ret = FALSE; break; } return ret; } static gboolean update(gpointer data) { ins * o = (ins*)data; coSwitchTo(o->h.coaw); glXSwapBuffers(o->dpy, o->w); return !o->h.awdone; } void awosSetWindow(ins * o, NPWindow * win) { if (!o->plug) { NPSetWindowCallbackStruct * info = (NPSetWindowCallbackStruct*)win->ws_info; XVisualInfo * vinfo; GtkWidget * plug; plug = gtk_plug_new((GdkNativeWindow)(win->window)); GTK_WIDGET_SET_FLAGS(GTK_WIDGET(plug), GTK_CAN_FOCUS); gtk_widget_add_events(plug, 0 | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_POINTER_MOTION_MASK ); g_signal_connect(G_OBJECT(plug), "event", G_CALLBACK(event), o); gtk_widget_show_all(plug); gtk_widget_grab_focus(plug); o->dpy = info->display; o->plug = plug; o->w = gtk_plug_get_id(GTK_PLUG(o->plug)); o->to = g_timeout_add(10, update, o); vinfo = chooseVisual(o->dpy, 0); o->ctx = glXCreateContext(o->dpy, vinfo, 0, True); XFree(vinfo); glXMakeCurrent(o->dpy, o->w, o->ctx); } } void awosDel(ins * o) { g_source_remove(o->to); glXMakeCurrent(o->dpy, 0, 0); if (o->ctx) glXDestroyContext(o->dpy, 0); gtk_widget_destroy(o->plug); free(o); } int awosMakeCurrentI(ins * o) { return glXMakeCurrent(o->dpy, o->w, o->ctx); } int awosClearCurrentI(ins * o) { return glXMakeCurrent(o->dpy, 0, 0); } void awosUpdate(ins * o) { update(o); } NPError awosEvent(ins * o, void * ev) { // NPEvent * e = (NPEvent *)ev; debug("osevent"); return NPERR_NO_ERROR; } const char * awosResourcesPath(ins * o) { return "."; } NPError awosGetValue(NPP i, NPPVariable var, void * v) { // ins * o = (ins*)i->pdata; NPError ret = NPERR_NO_ERROR; debug("os getvalue"); switch(var) { case NPPVpluginNeedsXEmbed: *(int*)v = 1; break; default: debug("os getval default"); ret = NPERR_GENERIC_ERROR; break; } return ret; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
awxembednpapi.c
C
bsd
4,999
#include <CoreServices/CoreServices.r> resource 'STR#' (126, "Description") { { "NAME", "NAME" } }; resource 'STR#' (127, "MIME type description") { { "NAME" } }; resource 'STR#' (128, "MIME type") { { "application/NAME" } };
zzywany123-libaw-1
template.r
R
bsd
227
#include <assert.h> #include <string.h> #include "awnpapios.h" typedef void (*awmethod)(void); static NPNetscapeFuncs * s_browser = 0; static NPObject * s_so = 0; static char s_plgname[256]; static awmethod resolve(NPIdentifier method) { static void * me = 0; char * mname = s_browser->utf8fromidentifier(method); awmethod ret; if (!me) me = awosSelf(s_plgname); ret = awosResolve(me, mname); debug("resolve %s %p", mname, ret); // leak mname? return ret; } static bool hasmethod(NPObject* obj, NPIdentifier method) { return resolve(method) != 0; } static bool invoke(NPObject* obj, NPIdentifier method, const NPVariant *args, uint32_t nargs, NPVariant *res) { awmethod func = resolve(method); if (func) func(); else { debug("no such method"); s_browser->setexception(obj, "no such method"); } return func != 0; } static bool invokedefault(NPObject *obj, const NPVariant *args, uint32_t nargs, NPVariant *res) { debug("invokedefault"); return 0; } static bool hasproperty(NPObject *obj, NPIdentifier prop) { debug("hasproperty"); return 0; } static bool getproperty(NPObject *obj, NPIdentifier prop, NPVariant *res) { debug("getproperty"); return 0; } static NPClass scriptable = { NP_CLASS_STRUCT_VERSION, 0, 0, 0, hasmethod, invoke, invokedefault, hasproperty, getproperty, 0, 0, }; static void ev(ins * o, int ev, int x, int y) { insHeader * h = (insHeader*)o; got(&h->w, ev, x, y); debug("event %d %d %d", ev, x, y); } insHeader * getHeader() { return (insHeader*)coData(coCurrent()); } void awentry(void * data) { extern int main(int argc, char ** argv); int argc = 1; char * argv0 = "awnpapi"; debug("entry"); main(argc, &argv0); getHeader()->awdone = 1; coSwitchTo(getHeader()->comain); assert(0); } static NPError nnew(NPMIMEType type, NPP i, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved) { ins * o; insHeader * h; unsigned j; snprintf(s_plgname, sizeof s_plgname - 1, "%s", argv[0]); debug("new"); for (j = 0; j < argc; j++) { debug(" %s", argv[j]); debug(" %s", argn[j]); } o = awosNew(s_browser, i); h = (insHeader*)o; memset(&h->w, 0, sizeof(h->w)); memset(&h->c, 0, sizeof(h->c)); i->pdata = o; h->comain = coMain(o); debug("comain: %p", h->comain); h->coaw = coNew(awentry, o); h->awdone = 0; return NPERR_NO_ERROR; } static NPError setwindow(NPP i, NPWindow* w) { ins * o = (ins*)i->pdata; debug("setwindow %p", w->window); debug("%dx%d", w->width, w->height); ev(o, AW_EVENT_RESIZE, w->width, w->height); awosSetWindow(o, w); return NPERR_NO_ERROR; } static NPError destroy(NPP i, NPSavedData **save) { ins * o = (ins*)i->pdata; debug("destroy"); ev(o, AW_EVENT_CLOSE, 0, 0); debug("destroy>aw"); while (!getHeader()->awdone) coSwitchTo(getHeader()->coaw); debug("aw>destroy"); coDel(getHeader()->coaw); coDel(getHeader()->comain); awosDel(o); i->pdata = 0; if(s_so) s_browser->releaseobject(s_so); return NPERR_NO_ERROR; } static NPError getvalue(NPP i, NPPVariable variable, void *v) { ins * o; NPError ret = NPERR_NO_ERROR; debug("getvalue"); o = i? (ins*)i->pdata : 0; switch(variable) { default: debug("getval default"); ret = awosGetValue(i, variable, v); break; case NPPVpluginNameString: debug("getval pluginname"); *(char **)v = "plugin name"; break; case NPPVpluginDescriptionString: debug("getval plugindesc"); *(char **)v = "plugin description"; break; case NPPVpluginScriptableNPObject: debug("getval scriptable"); if(!s_so) s_so = s_browser->createobject(i, &scriptable); s_browser->retainobject(s_so); *(void**)v = s_so; break; case NPPVpluginWindowBool: *(int*)v = 1; break; } return ret; } static NPError hevent(NPP i, void * ve) { ins * o = (ins*)i->pdata; debug("event"); return awosEvent(o, ve); } EXPORTED NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* f) { debug("getentrypoints %p", f); f->size = sizeof (NPPluginFuncs); f->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; f->newp = nnew; f->setwindow = setwindow; f->destroy = destroy; f->getvalue = getvalue; f->event = hevent; debug("/getentrypoints %p", f); return NPERR_NO_ERROR; } EXPORTED NPError OSCALL NP_Initialize(NPNetscapeFuncs* f #if defined XP_UNIX && !defined XP_MACOSX ,NPPluginFuncs * funcs #endif ) { debug("initialize"); s_browser = f; if(!f) { debug("invalid functable"); return NPERR_INVALID_FUNCTABLE_ERROR; } if(((f->version & 0xff00) >> 8) > NP_VERSION_MAJOR) { debug("incompatible"); return NPERR_INCOMPATIBLE_VERSION_ERROR; } #if defined XP_UNIX && !defined XP_MACOSX NP_GetEntryPoints(funcs); #endif return NPERR_NO_ERROR; } EXPORTED NPError OSCALL NP_Shutdown() { debug("shutdown"); return NPERR_NO_ERROR; } EXPORTED char * NP_GetMIMEDescription(void) { static char buf[256]; char tmp[256]; const char * modpath = awosModPath(); const char * last = strrchr(modpath, '/'); if (!last) last = strrchr(modpath, '\\'); snprintf(tmp, sizeof tmp - 1, "%s", last+1); *strrchr(tmp, '.') = 0; snprintf(buf, sizeof buf - 1, "application/%s::xx@foo.bar", 0 == strncmp(buf, "lib", 3)? tmp+3 : 0 == strncmp(buf, "np", 2)? tmp+2 : tmp); report("getmimedesc %s", buf); return buf; } EXPORTED NPError OSCALL NP_GetValue( #if defined(XP_UNIX) void * #else NPP #endif npp, NPPVariable variable, void *val) { debug("npgetvalue"); return getvalue(npp, variable, val); } int awosInit() { debug("awosInit"); return 1; } int awosEnd() { debug("awosEnd"); return 1; } aw * awosOpen(int x, int y, int width, int height, int fs, int bl) { insHeader * h = getHeader(); debug("awosOpen"); return &h->w; } int awosSetTitle(aw * w, const char * t) { debug("awosSetTitle"); return 1; } int awosClose(aw * w) { debug("awosClose"); return 1; } int awosMakeCurrent(aw * w, ac * c) { debug("awosMakeCurrent"); return awosMakeCurrentI((ins*)w); } int awosClearCurrent(aw * w) { debug("awosClearCurrent"); return awosClearCurrentI((ins*)w); } int awosSwapBuffers(aw * w) { insHeader * hdr = getHeader(); debug("aw>main %p", hdr->comain); coSwitchTo(hdr->comain); debug("main>aw"); awosUpdate((ins*)hdr); return 1; } int awosShow(aw * w) { debug("awosShow"); return 1; } int awosHide(aw * w) { debug("awosHide"); return 1; } void awosPollEvent(aw * w) { debug("awosPollEvent"); } int awosSetSwapInterval(aw * w, int interval) { debug("awosSetSwapInterval"); return 1; } int acosInit() { debug("acosInit"); return 1; } int acosEnd() { debug("acosEnd"); return 1; } ac * acosNew(ac * c) { insHeader * h = getHeader(); debug("acosNew"); return &h->c; } int acosDel(ac * c) { debug("acosDel"); return 1; } const char * agResourcesPath(ag * g) { insHeader * hdr = getHeader(); return awosResourcesPath((ins*)hdr); } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
awnpapi.c
C
bsd
7,293
<html> <head> <title>aw plugin test</title> </head> <body> <center> <object id="awplugin" type="application/awplugin" width=640 height=480> </object><br> <button onclick="document['awplugin'].hello('world');">hello</button> </center> </body> </html>
zzywany123-libaw-1
test.html
HTML
bsd
300
#include <windows.h> #include "aw.h" #if !defined MAPVK_VK_TO_CHAR #define MAPVK_VK_TO_CHAR 2 #endif #if !defined VK_OEM_PLUS #define VK_OEM_PLUS 0xbb #endif #if !defined VK_OEM_COMMA #define VK_OEM_COMMA 0xbc #endif #if !defined VK_OEM_MINUS #define VK_OEM_MINUS 0xbd #endif #if !defined VK_OEM_PERIOD #define VK_OEM_PERIOD 0xbe #endif #if !defined VK_VOLUME_MUTE #define VK_VOLUME_MUTE 0xad #endif #if !defined VK_VOLUME_DOWN #define VK_VOLUME_DOWN 0xae #endif #if !defined VK_VOLUME_UP #define VK_VOLUME_UP 0xaf #endif unsigned mapkeycode(unsigned vk) { int ret; switch (vk) { case 'A': ret = AW_KEY_A; break; case 'S': ret = AW_KEY_S; break; case 'D': ret = AW_KEY_D; break; case 'F': ret = AW_KEY_F; break; case 'H': ret = AW_KEY_H; break; case 'G': ret = AW_KEY_G; break; case 'Z': ret = AW_KEY_Z; break; case 'X': ret = AW_KEY_X; break; case 'C': ret = AW_KEY_C; break; case 'V': ret = AW_KEY_V; break; case 'B': ret = AW_KEY_B; break; case 'Q': ret = AW_KEY_Q; break; case 'W': ret = AW_KEY_W; break; case 'E': ret = AW_KEY_E; break; case 'R': ret = AW_KEY_R; break; case 'Y': ret = AW_KEY_Y; break; case 'T': ret = AW_KEY_T; break; case '1': ret = AW_KEY_1; break; case '2': ret = AW_KEY_2; break; case '3': ret = AW_KEY_3; break; case '4': ret = AW_KEY_4; break; case '6': ret = AW_KEY_6; break; case '5': ret = AW_KEY_5; break; case VK_OEM_PLUS: ret = AW_KEY_EQUAL; break; case '9': ret = AW_KEY_9; break; case '7': ret = AW_KEY_7; break; case VK_OEM_MINUS: ret = AW_KEY_MINUS; break; case '8': ret = AW_KEY_8; break; case '0': ret = AW_KEY_0; break; case VK_OEM_6: ret = AW_KEY_RIGHTBRACKET; break; case 'O': ret = AW_KEY_O; break; case 'U': ret = AW_KEY_U; break; case VK_OEM_4: ret = AW_KEY_LEFTBRACKET; break; case 'I': ret = AW_KEY_I; break; case 'P': ret = AW_KEY_P; break; case 'L': ret = AW_KEY_L; break; case 'J': ret = AW_KEY_J; break; case VK_OEM_7: ret = AW_KEY_QUOTE; break; case 'K': ret = AW_KEY_K; break; case VK_OEM_1: ret = AW_KEY_SEMICOLON; break; case VK_OEM_5: ret = AW_KEY_BACKSLASH; break; case VK_OEM_COMMA: ret = AW_KEY_COMMA; break; case VK_OEM_2: ret = AW_KEY_SLASH; break; case 'N': ret = AW_KEY_N; break; case 'M': ret = AW_KEY_M; break; case VK_OEM_PERIOD: ret = AW_KEY_PERIOD; break; case VK_OEM_3: ret = AW_KEY_GRAVE; break; case VK_DECIMAL: ret = AW_KEY_KEYPADDECIMAL; break; case VK_MULTIPLY: ret = AW_KEY_KEYPADMULTIPLY; break; case VK_ADD: ret = AW_KEY_KEYPADPLUS; break; // case 'K'eypadClear: ret = AW_KEY_KEYPADCLEAR; break; case VK_DIVIDE: ret = AW_KEY_KEYPADDIVIDE; break; // case 'K'eypadEnter: ret = AW_KEY_KEYPADENTER; break; case VK_SUBTRACT: ret = AW_KEY_KEYPADMINUS; break; // case 'K'eypadEquals: ret = AW_KEY_KEYPADEQUALS; break; case VK_NUMPAD0: ret = AW_KEY_KEYPAD0; break; case VK_NUMPAD1: ret = AW_KEY_KEYPAD1; break; case VK_NUMPAD2: ret = AW_KEY_KEYPAD2; break; case VK_NUMPAD3: ret = AW_KEY_KEYPAD3; break; case VK_NUMPAD4: ret = AW_KEY_KEYPAD4; break; case VK_NUMPAD5: ret = AW_KEY_KEYPAD5; break; case VK_NUMPAD6: ret = AW_KEY_KEYPAD6; break; case VK_NUMPAD7: ret = AW_KEY_KEYPAD7; break; case VK_NUMPAD8: ret = AW_KEY_KEYPAD8; break; case VK_NUMPAD9: ret = AW_KEY_KEYPAD9; break; case VK_RETURN: ret = AW_KEY_RETURN; break; case VK_TAB: ret = AW_KEY_TAB; break; case VK_SPACE: ret = AW_KEY_SPACE; break; case VK_BACK: ret = AW_KEY_DELETE; break; case VK_ESCAPE: ret = AW_KEY_ESCAPE; break; case VK_LMENU: case VK_MENU: ret = AW_KEY_OPTION; break; case VK_LSHIFT: case VK_SHIFT: ret = AW_KEY_SHIFT; break; case VK_LWIN: case VK_RWIN: ret = AW_KEY_COMMAND; break; case VK_CAPITAL: ret = AW_KEY_CAPSLOCK; break; case VK_CONTROL: ret = AW_KEY_CONTROL; break; case VK_RSHIFT: ret = AW_KEY_RIGHTSHIFT; break; case VK_RMENU: ret = AW_KEY_RIGHTOPTION; break; case VK_RCONTROL: ret = AW_KEY_RIGHTCONTROL; break; case VK_F17: ret = AW_KEY_F17; break; case VK_VOLUME_UP: ret = AW_KEY_VOLUMEUP; break; case VK_VOLUME_DOWN: ret = AW_KEY_VOLUMEDOWN; break; case VK_VOLUME_MUTE: ret = AW_KEY_MUTE; break; case VK_F18: ret = AW_KEY_F18; break; case VK_F19: ret = AW_KEY_F19; break; case VK_F20: ret = AW_KEY_F20; break; case VK_F5: ret = AW_KEY_F5; break; case VK_F6: ret = AW_KEY_F6; break; case VK_F7: ret = AW_KEY_F7; break; case VK_F3: ret = AW_KEY_F3; break; case VK_F8: ret = AW_KEY_F8; break; case VK_F9: ret = AW_KEY_F9; break; case VK_F11: ret = AW_KEY_F11; break; case VK_F13: ret = AW_KEY_F13; break; case VK_F16: ret = AW_KEY_F16; break; case VK_F14: ret = AW_KEY_F14; break; case VK_F10: ret = AW_KEY_F10; break; case VK_F12: ret = AW_KEY_F12; break; case VK_F15: ret = AW_KEY_F15; break; case VK_HELP: ret = AW_KEY_HELP; break; case VK_HOME: ret = AW_KEY_HOME; break; case VK_PRIOR: ret = AW_KEY_PAGEUP; break; case VK_INSERT: ret = AW_KEY_FUNCTION; break; case VK_DELETE: ret = AW_KEY_FORWARDDELETE; break; case VK_F4: ret = AW_KEY_F4; break; case VK_END: ret = AW_KEY_END; break; case VK_F2: ret = AW_KEY_F2; break; case VK_NEXT: ret = AW_KEY_PAGEDOWN; break; case VK_F1: ret = AW_KEY_F1; break; case VK_LEFT: ret = AW_KEY_LEFTARROW; break; case VK_RIGHT: ret = AW_KEY_RIGHTARROW; break; case VK_DOWN: ret = AW_KEY_DOWNARROW; break; case VK_UP: ret = AW_KEY_UPARROW; break; case VK_SCROLL: ret = AW_KEY_SCROLL; break; case VK_NUMLOCK: ret = AW_KEY_NUMLOCK; break; case VK_CLEAR: ret = AW_KEY_CLEAR; break; case VK_SNAPSHOT: ret = AW_KEY_SYSREQ; break; case VK_PAUSE: ret = AW_KEY_PAUSE; break; default: ret = AW_KEY_NONE; break; } return ret; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
awntkeycodes.c
C
bsd
6,520
#include <pthread.h> #include <stdlib.h> #include "aw.h" #include "awos.h" #include "tls.h" struct _tls { pthread_key_t key; }; tls * tlsNew() { tls * tls = malloc(sizeof(*tls)); pthread_key_create(&tls->key, 0); debug("created key %d", (int)tls->key); return tls; } void * tlsGet(tls * tls) { void * ret; ret = pthread_getspecific(tls->key); debug("get %d -> %p", (int)tls->key, ret); return ret; } void tlsSet(tls * tls, void * val) { debug("set %d <- %p", (int)tls->key, val); pthread_setspecific(tls->key, val); }
zzywany123-libaw-1
tlspthread.c
C
bsd
534
#define _GNU_SOURCE #include <dlfcn.h> #include <stdio.h> #include <string.h> void * awosSelf(const char * name) { char buf[256]; snprintf(buf, sizeof buf - 1, "lib%s.so", name); return dlopen(buf, 0); } void * awosResolve(void * in, const char * name) { return dlsym(in, name); } const char * awosModPath() { static Dl_info info; dladdr(awosModPath, &info); return info.dli_fname; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
awposixresolve.c
C
bsd
550
#include <stdarg.h> #include <stdio.h> void report(const char *fmt, ...) { #if defined(_WIN32) FILE *out = fopen("aw.log", "a"); #else FILE *out = fopen("/tmp/aw.log", "a"); #endif va_list ap; va_start(ap, fmt); if(out) { vfprintf(out, fmt, ap); fputs("\n", out); fclose(out); } va_end(ap); }
zzywany123-libaw-1
awreportfile.c
C
bsd
309
#include <stdarg.h> #include <stdio.h> void report(const char * fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "AW ERROR: "); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); fflush(stderr); }
zzywany123-libaw-1
awreportconsole.c
C
bsd
276
#define setcontext(u) setmcontext(&(u)->uc_mcontext) #define getcontext(u) getmcontext(&(u)->uc_mcontext) typedef struct mcontext mcontext_t; typedef struct ucontext ucontext_t; extern int swapcontext(ucontext_t*, const ucontext_t*); extern void makecontext(ucontext_t*, void(*)(void), int, ...); extern int getmcontext(mcontext_t*); extern void setmcontext(const mcontext_t*); /*- * Copyright (c) 1999 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD: src/sys/sys/ucontext.h,v 1.4 1999/10/11 20:33:17 luoqi Exp $ */ /* #include <machine/ucontext.h> */ /*- * Copyright (c) 1999 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD: src/sys/i386/include/ucontext.h,v 1.4 1999/10/11 20:33:09 luoqi Exp $ */ struct mcontext { /* * The first 20 fields must match the definition of * sigcontext. So that we can support sigcontext * and ucontext_t at the same time. */ long mc_onstack; /* XXX - sigcontext compat. */ long mc_rdi; /* machine state (struct trapframe) */ long mc_rsi; long mc_rdx; long mc_rcx; long mc_r8; long mc_r9; long mc_rax; long mc_rbx; long mc_rbp; long mc_r10; long mc_r11; long mc_r12; long mc_r13; long mc_r14; long mc_r15; long mc_trapno; long mc_addr; long mc_flags; long mc_err; long mc_rip; long mc_cs; long mc_rflags; long mc_rsp; long mc_ss; long mc_len; /* sizeof(mcontext_t) */ #define _MC_FPFMT_NODEV 0x10000 /* device not present or configured */ #define _MC_FPFMT_XMM 0x10002 long mc_fpformat; #define _MC_FPOWNED_NONE 0x20000 /* FP state not used */ #define _MC_FPOWNED_FPU 0x20001 /* FP state came from FPU */ #define _MC_FPOWNED_PCB 0x20002 /* FP state came from PCB */ long mc_ownedfp; /* * See <machine/fpu.h> for the internals of mc_fpstate[]. */ long mc_fpstate[64]; long mc_spare[8]; }; struct ucontext { /* * Keep the order of the first two fields. Also, * keep them the first two fields in the structure. * This way we can have a union with struct * sigcontext and ucontext_t. This allows us to * support them both at the same time. * note: the union is not defined, though. */ sigset_t uc_sigmask; mcontext_t uc_mcontext; struct __ucontext *uc_link; stack_t uc_stack; int __spare__[8]; };
zzywany123-libaw-1
coroutine/source/amd64-ucontext.h
C
bsd
5,114
/* Copyright (c) 2005-2006 Russ Cox, MIT; see COPYRIGHT */ #include "taskimpl.h" #if defined(__APPLE__) #if defined(__i386__) #define NEEDX86MAKECONTEXT #define NEEDSWAPCONTEXT #elif defined(__x86_64__) #define NEEDAMD64MAKECONTEXT #define NEEDSWAPCONTEXT #else #define NEEDPOWERMAKECONTEXT #define NEEDSWAPCONTEXT #endif #endif #if defined(__FreeBSD__) && defined(__i386__) && __FreeBSD__ < 5 #define NEEDX86MAKECONTEXT #define NEEDSWAPCONTEXT #endif #if defined(__OpenBSD__) && defined(__i386__) #define NEEDX86MAKECONTEXT #define NEEDSWAPCONTEXT #endif #if defined(__linux__) && defined(__arm__) #define NEEDSWAPCONTEXT #define NEEDARMMAKECONTEXT #endif #ifdef NEEDPOWERMAKECONTEXT void makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...) { ulong *sp, *tos; va_list arg; tos = (ulong*)ucp->uc_stack.ss_sp+ucp->uc_stack.ss_size/sizeof(ulong); sp = tos - 16; ucp->mc.pc = (long)func; ucp->mc.sp = (long)sp; va_start(arg, argc); ucp->mc.r3 = va_arg(arg, long); va_end(arg); } #endif #ifdef NEEDX86MAKECONTEXT void makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...) { int *sp; sp = (int*)ucp->uc_stack.ss_sp+ucp->uc_stack.ss_size/4; sp -= argc; sp = (void*)((uintptr_t)sp - (uintptr_t)sp%16); /* 16-align for OS X */ memmove(sp, &argc+1, argc*sizeof(int)); *--sp = 0; /* return address */ ucp->uc_mcontext.mc_eip = (long)func; ucp->uc_mcontext.mc_esp = (int)sp; } #endif #ifdef NEEDAMD64MAKECONTEXT void makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...) { long *sp; va_list va; memset(&ucp->uc_mcontext, 0, sizeof ucp->uc_mcontext); if(argc != 2) *(int*)0 = 0; va_start(va, argc); ucp->uc_mcontext.mc_rdi = va_arg(va, int); ucp->uc_mcontext.mc_rsi = va_arg(va, int); va_end(va); sp = (long*)ucp->uc_stack.ss_sp+ucp->uc_stack.ss_size/sizeof(long); sp -= argc; sp = (void*)((uintptr_t)sp - (uintptr_t)sp%16); /* 16-align for OS X */ *--sp = 0; /* return address */ ucp->uc_mcontext.mc_rip = (long)func; ucp->uc_mcontext.mc_rsp = (long)sp; } #endif #ifdef NEEDARMMAKECONTEXT void makecontext(ucontext_t *uc, void (*fn)(void), int argc, ...) { int i, *sp; va_list arg; sp = (int*)uc->uc_stack.ss_sp+uc->uc_stack.ss_size/4; va_start(arg, argc); for(i=0; i<4 && i<argc; i++) uc->uc_mcontext.gregs[i] = va_arg(arg, uint); va_end(arg); uc->uc_mcontext.gregs[13] = (uint)sp; uc->uc_mcontext.gregs[14] = (uint)fn; } #endif #ifdef NEEDSWAPCONTEXT int swapcontext(ucontext_t *oucp, const ucontext_t *ucp) { if(getcontext(oucp) == 0) setcontext(ucp); return 0; } #endif
zzywany123-libaw-1
coroutine/source/context.c
C
bsd
2,561
#ifndef TASKIMPL_DEFINED #define TASKIMPL_DEFINED 1 #include <stdarg.h> /* Copyright (c) 2005-2006 Russ Cox, MIT; see COPYRIGHT */ #if defined(__sun__) # define __EXTENSIONS__ 1 /* SunOS */ # if defined(__SunOS5_6__) || defined(__SunOS5_7__) || defined(__SunOS5_8__) /* NOT USING #define __MAKECONTEXT_V2_SOURCE 1 / * SunOS */ # else # define __MAKECONTEXT_V2_SOURCE 1 # endif #endif //#define USE_UCONTEXT 1 #if defined(__OpenBSD__) #undef USE_UCONTEXT #define USE_UCONTEXT 0 #endif #if defined(__APPLE__) #include <AvailabilityMacros.h> #if defined(MAC_OS_X_VERSION_10_5) #undef USE_UCONTEXT #define USE_UCONTEXT 0 #endif #endif #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> #include <time.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <sched.h> #include <signal.h> #if USE_UCONTEXT #include <ucontext.h> #endif #include <sys/utsname.h> #include <inttypes.h> //#include "task.h" #define nil ((void*)0) #define nelem(x) (sizeof(x)/sizeof((x)[0])) /* #define ulong task_ulong #define uint task_uint #define uchar task_uchar #define ushort task_ushort #define uvlong task_uvlong #define vlong task_vlong typedef unsigned long ulong; typedef unsigned int uint; typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned long long uvlong; typedef long long vlong; #define print task_print #define fprint task_fprint #define snprint task_snprint #define seprint task_seprint #define vprint task_vprint #define vfprint task_vfprint #define vsnprint task_vsnprint #define vseprint task_vseprint #define strecpy task_strecpy int print(char*, ...); int fprint(int, char*, ...); char *snprint(char*, uint, char*, ...); char *seprint(char*, char*, char*, ...); int vprint(char*, va_list); int vfprint(int, char*, va_list); char *vsnprint(char*, uint, char*, va_list); char *vseprint(char*, char*, char*, va_list); char *strecpy(char*, char*, char*); */ #if defined(__FreeBSD__) && __FreeBSD__ < 5 extern int getmcontext(mcontext_t*); extern void setmcontext(const mcontext_t*); #define setcontext(u) setmcontext(&(u)->uc_mcontext) #define getcontext(u) getmcontext(&(u)->uc_mcontext) extern int swapcontext(ucontext_t*, const ucontext_t*); extern void makecontext(ucontext_t*, void(*)(), int, ...); #endif #if defined(__APPLE__) # define mcontext libthread_mcontext # define mcontext_t libthread_mcontext_t # define ucontext libthread_ucontext # define ucontext_t libthread_ucontext_t # if defined(__i386__) # include "386-ucontext.h" # elif defined(__x86_64__) # include "amd64-ucontext.h" # else # include "power-ucontext.h" # endif #endif #if defined(__OpenBSD__) # define mcontext libthread_mcontext # define mcontext_t libthread_mcontext_t # define ucontext libthread_ucontext # define ucontext_t libthread_ucontext_t # if defined __i386__ # include "386-ucontext.h" # else # include "power-ucontext.h" # endif extern pid_t rfork_thread(int, void*, int(*)(void*), void*); #endif #if 0 && defined(__sun__) # define mcontext libthread_mcontext # define mcontext_t libthread_mcontext_t # define ucontext libthread_ucontext # define ucontext_t libthread_ucontext_t # include "sparc-ucontext.h" #endif #if defined(__arm__) int getmcontext(mcontext_t*); void setmcontext(const mcontext_t*); #define setcontext(u) setmcontext(&(u)->uc_mcontext) #define getcontext(u) getmcontext(&(u)->uc_mcontext) #endif /* typedef struct Context Context; enum { STACK = 8192 }; struct Context { ucontext_t uc; }; struct Task { char name[256]; // offset known to acid char state[256]; Task *next; Task *prev; Task *allnext; Task *allprev; Context context; uvlong alarmtime; uint id; uchar *stk; uint stksize; int exiting; int alltaskslot; int system; int ready; void (*startfn)(void*); void *startarg; void *udata; }; void taskready(Task*); void taskswitch(void); void addtask(Tasklist*, Task*); void deltask(Tasklist*, Task*); extern Task *taskrunning; extern int taskcount; */ #endif
zzywany123-libaw-1
coroutine/source/taskimpl.h
C
bsd
4,021
/* Credits Originally based on Edgar Toernig's Minimalistic cooperative multitasking http://www.goron.de/~froese/ reorg by Steve Dekorte and Chis Double Symbian and Cygwin support by Chis Double Linux/PCC, Linux/Opteron, Irix and FreeBSD/Alpha, ucontext support by Austin Kurahone FreeBSD/Intel support by Faried Nawaz Mingw support by Pit Capitain Visual C support by Daniel Vollmer Solaris support by Manpreet Singh Fibers support by Jonas Eschenburg Ucontext arg support by Olivier Ansaldi Ucontext x86-64 support by James Burgess and Jonathan Wright Russ Cox for the newer portable ucontext implementions. Mac OS X support by Jorge Acereda Guessed setjmp support (Android/Mac OS X/others?) by Jorge Acereda Notes This is the system dependent coro code. Setup a jmp_buf so when we longjmp, it will invoke 'func' using 'stack'. Important: 'func' must not return! Usually done by setting the program counter and stack pointer of a new, empty stack. If you're adding a new platform, look in the setjmp.h for PC and SP members of the stack structure If you don't see those members, Kentaro suggests writting a simple test app that calls setjmp and dumps out the contents of the jmp_buf. (The PC and SP should be in jmp_buf->__jmpbuf). Using something like GDB to be able to peek into register contents right before the setjmp occurs would be helpful also. */ #include "Coro.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <stddef.h> #if defined(USE_UCONTEXT) #define _XOPEN_SOURCE #include <ucontext.h> #endif #if defined(USE_FIBERS) #include <windows.h> typedef unsigned size_t; typedef unsigned char uint8_t; #endif #define io_calloc calloc #define io_free free #ifdef USE_VALGRIND #include <valgrind/valgrind.h> #define STACK_REGISTER(coro) \ { \ Coro *c = (coro); \ c->valgrindStackId = VALGRIND_STACK_REGISTER( \ c->stack, \ c->stack + c->requestedStackSize); \ } #define STACK_DEREGISTER(coro) \ VALGRIND_STACK_DEREGISTER((coro)->valgrindStackId) #else #define STACK_REGISTER(coro) #define STACK_DEREGISTER(coro) #endif typedef struct CallbackBlock { void *context; CoroStartCallback *func; } CallbackBlock; static CallbackBlock globalCallbackBlock; Coro *Coro_new(void) { Coro *self = (Coro *)io_calloc(1, sizeof(Coro)); self->requestedStackSize = CORO_DEFAULT_STACK_SIZE; self->allocatedStackSize = 0; #ifdef USE_FIBERS self->fiber = NULL; #else self->stack = NULL; #endif return self; } void Coro_allocStackIfNeeded(Coro *self) { if (self->stack && self->requestedStackSize < self->allocatedStackSize) { io_free(self->stack); self->stack = NULL; self->requestedStackSize = 0; } if (!self->stack) { self->stack = (void *)io_calloc(1, self->requestedStackSize + 16); self->allocatedStackSize = self->requestedStackSize; //printf("Coro_%p allocating stack size %i\n", (void *)self, self->requestedStackSize); STACK_REGISTER(self); } } void Coro_free(Coro *self) { #ifdef USE_FIBERS // If this coro has a fiber, delete it. // Don't delete the main fiber. We don't want to commit suicide. if (self->fiber && !self->isMain) { DeleteFiber(self->fiber); } #else STACK_DEREGISTER(self); #endif if (self->stack) { io_free(self->stack); } //printf("Coro_%p io_free\n", (void *)self); io_free(self); } // stack void *Coro_stack(Coro *self) { return self->stack; } size_t Coro_stackSize(Coro *self) { return self->requestedStackSize; } void Coro_setStackSize_(Coro *self, size_t sizeInBytes) { self->requestedStackSize = sizeInBytes; //self->stack = (void *)io_realloc(self->stack, sizeInBytes); //printf("Coro_%p io_reallocating stack size %i\n", (void *)self, sizeInBytes); } #if __GNUC__ == 4 uint8_t *Coro_CurrentStackPointer(void) __attribute__ ((noinline)); #endif uint8_t *Coro_CurrentStackPointer(void) { uint8_t a; uint8_t *b = &a; // to avoid compiler warning about unused variables return b; } size_t Coro_bytesLeftOnStack(Coro *self) { unsigned char dummy; ptrdiff_t p1 = (ptrdiff_t)(&dummy); ptrdiff_t p2 = (ptrdiff_t)Coro_CurrentStackPointer(); int stackMovesUp = p2 > p1; ptrdiff_t start = ((ptrdiff_t)self->stack); ptrdiff_t end = start + self->requestedStackSize; if (stackMovesUp) // like x86 { return end - p1; } else // like OSX on PPC { return p1 - start; } } int Coro_stackSpaceAlmostGone(Coro *self) { return Coro_bytesLeftOnStack(self) < CORO_STACK_SIZE_MIN; } void Coro_initializeMainCoro(Coro *self) { self->isMain = 1; #ifdef USE_FIBERS // We must convert the current thread into a fiber if it hasn't already been done. if ((LPVOID) 0x1e00 == GetCurrentFiber()) // value returned when not a fiber { // Make this thread a fiber and set its data field to the main coro's address ConvertThreadToFiber(self); } // Make the main coro represent the current fiber self->fiber = GetCurrentFiber(); #endif } void Coro_startCoro_(Coro *self, Coro *other, void *context, CoroStartCallback *callback) { CallbackBlock sblock; CallbackBlock *block = &sblock; //CallbackBlock *block = malloc(sizeof(CallbackBlock)); // memory leak block->context = context; block->func = callback; Coro_allocStackIfNeeded(other); Coro_setup(other, block); Coro_switchTo_(self, other); } /* void Coro_startCoro_(Coro *self, Coro *other, void *context, CoroStartCallback *callback) { globalCallbackBlock.context = context; globalCallbackBlock.func = callback; Coro_allocStackIfNeeded(other); Coro_setup(other, &globalCallbackBlock); Coro_switchTo_(self, other); } */ #if defined(USE_UCONTEXT) && defined(__x86_64__) void Coro_StartWithArg(unsigned int hiArg, unsigned int loArg) { CallbackBlock *block = (CallbackBlock*)(((long long)hiArg << 32) | (long long)loArg); (block->func)(block->context); printf("Scheduler error: returned from coro start function\n"); exit(-1); } /* void Coro_Start(void) { CallbackBlock block = globalCallbackBlock; unsigned int hiArg = (unsigned int)(((long long)&block) >> 32); unsigned int loArg = (unsigned int)(((long long)&block) & 0xFFFFFFFF); Coro_StartWithArg(hiArg, loArg); } */ #else void Coro_StartWithArg(CallbackBlock *block) { (block->func)(block->context); printf("Scheduler error: returned from coro start function\n"); exit(-1); } void Coro_Start(void) { CallbackBlock block = globalCallbackBlock; Coro_StartWithArg(&block); } #endif // -------------------------------------------------------------------- void Coro_UnsupportedPlatformError(void) { printf("Io Scheduler error: no Coro_setupJmpbuf entry for this platform\n."); exit(1); } void Coro_switchTo_(Coro *self, Coro *next) { #if defined(__SYMBIAN32__) ProcessUIEvent(); #elif defined(USE_FIBERS) SwitchToFiber(next->fiber); #elif defined(USE_UCONTEXT) swapcontext(&self->env, &next->env); #elif defined USE_SETJMP || defined USE_GUESSED_SETJMP if (setjmp(self->env) == 0) { longjmp(next->env, 1); } #endif } // ---- setup ------------------------------------------ #if defined USE_GUESSED_SETJMP // This isn't bulletproof, but seems to work Well Enough (TM) void Coro_setup(Coro *self, void *arg) { uintptr_t stackend = Coro_stackSize(self) + (uintptr_t)Coro_stack(self); uintptr_t start = (uintptr_t)Coro_Start; /* since ucontext seems to be broken on amd64 */ globalCallbackBlock.context=((CallbackBlock*)arg)->context; globalCallbackBlock.func=((CallbackBlock*)arg)->func; setjmp(self->env); end: { uintptr_t i; uintptr_t * sav = (uintptr_t*)self->env; size_t sz = sizeof(self->env)/sizeof(sav[0]); // Try to guess PC index i = sz; while (i--) if (sav[i] == (uintptr_t)&&end) break; assert(i < sz); sav[i] = start; // Try to guess SP index i = sz; while (i--) if (64 > (- sav[i] + (uintptr_t)&i)) break; assert(i < sz); sav[i] = stackend - sizeof(uintptr_t) - 128; } } #elif defined USE_SETJMP void Coro_setup(Coro *self, void *arg) { uintptr_t stackend = Coro_stackSize(self) + (uintptr_t)Coro_stack(self); uintptr_t start = (uintptr_t)Coro_Start; /* since ucontext seems to be broken on amd64 */ globalCallbackBlock.context=((CallbackBlock*)arg)->context; globalCallbackBlock.func=((CallbackBlock*)arg)->func; setjmp(self->env); /* This is probably not nice in that it deals directly with * something with __ in front of it. * * Anyhow, Coro.h makes the member env of a struct Coro a * jmp_buf. A jmp_buf, as defined in the amd64 setjmp.h * is an array of one struct that wraps the actual __jmp_buf type * which is the array of longs (on a 64 bit machine) that * the programmer below expected. This struct begins with * the __jmp_buf array of longs, so I think it was supposed * to work like he originally had it, but for some reason * it didn't. I don't know why. * - Bryce Schroeder, 16 December 2006 * * Explaination of `magic' numbers: 6 is the stack pointer * (RSP, the 64 bit equivalent of ESP), 7 is the program counter. * This information came from this file on my Gentoo linux * amd64 computer: * /usr/include/gento-multilib/amd64/bits/setjmp.h * Which was ultimatly included from setjmp.h in /usr/include. */ #if defined(__APPLE__) && defined(__x86_64__) *(uintptr_t*)(self->env+4) = stackend - 8; *(uintptr_t*)(self->env+14) = start; #elif defined(__APPLE__) *(uintptr_t*)(self->env+9) = stackend - 4; *(uintptr_t*)(self->env+12) = start; #elif defined(_MSC_VER) // Broken, use fibers *(uintptr_t*)(self->env+4) = stackend - 8; *(uintptr_t*)(self->env+5) = start; #else self->env[0].__jmpbuf[6] = ((unsigned long)(Coro_stack(self))); self->env[0].__jmpbuf[7] = ((long)Coro_Start); #endif } #elif defined(HAS_UCONTEXT_ON_PRE_SOLARIS_10) typedef void (*makecontext_func)(void); void Coro_setup(Coro *self, void *arg) { ucontext_t *ucp = (ucontext_t *) &self->env; getcontext(ucp); ucp->uc_stack.ss_sp = Coro_stack(self) + Coro_stackSize(self) - 8; ucp->uc_stack.ss_size = Coro_stackSize(self); ucp->uc_stack.ss_flags = 0; ucp->uc_link = NULL; makecontext(ucp, (makecontext_func)Coro_StartWithArg, 1, arg); } #elif defined(USE_UCONTEXT) typedef void (*makecontext_func)(void); void Coro_setup(Coro *self, void *arg) { ucontext_t *ucp = (ucontext_t *) &self->env; getcontext(ucp); ucp->uc_stack.ss_sp = Coro_stack(self); ucp->uc_stack.ss_size = Coro_stackSize(self); #if !defined(__APPLE__) ucp->uc_stack.ss_flags = 0; ucp->uc_link = NULL; #endif #if defined(__x86_64__) unsigned int hiArg = (unsigned int)((long long)arg >> 32); unsigned int loArg = (unsigned int)((long long)arg & 0xFFFFFFFF); makecontext(ucp, (makecontext_func)Coro_StartWithArg, 2, hiArg, loArg); #else makecontext(ucp, (makecontext_func)Coro_StartWithArg, 1, arg); #endif } #elif defined(USE_FIBERS) void Coro_setup(Coro *self, void *arg) { // If this coro was recycled and already has a fiber, delete it. // Don't delete the main fiber. We don't want to commit suicide. if (self->fiber && !self->isMain) { DeleteFiber(self->fiber); } self->fiber = CreateFiber(Coro_stackSize(self), (LPFIBER_START_ROUTINE)Coro_StartWithArg, (LPVOID)arg); if (!self->fiber) { DWORD err = GetLastError(); exit(err); } } #elif defined(__CYGWIN__) #define buf (self->env) void Coro_setup(Coro *self, void *arg) { setjmp(buf); buf[7] = (long)(Coro_stack(self) + Coro_stackSize(self) - 16); buf[8] = (long)Coro_Start; globalCallbackBlock.context=((CallbackBlock*)arg)->context; globalCallbackBlock.func=((CallbackBlock*)arg)->func; } #elif defined(__SYMBIAN32__) void Coro_setup(Coro *self, void *arg) { /* setjmp/longjmp is flakey under Symbian. If the setjmp is done inside the call then a crash occurs. Inlining it here solves the problem */ setjmp(self->env); self->env[0] = 0; self->env[1] = 0; self->env[2] = 0; self->env[3] = (unsigned long)(Coro_stack(self)) + Coro_stackSize(self) - 64; self->env[9] = (long)Coro_Start; self->env[8] = self->env[3] + 32; } #elif defined(_BSD_PPC_SETJMP_H_) #define buf (self->env) #define setjmp _setjmp #define longjmp _longjmp void Coro_setup(Coro *self, void *arg) { size_t *sp = (size_t *)(((intptr_t)Coro_stack(self) + Coro_stackSize(self) - 64 + 15) & ~15); setjmp(buf); //printf("self = %p\n", self); //printf("sp = %p\n", sp); buf[0] = (long)sp; buf[21] = (long)Coro_Start; globalCallbackBlock.context=((CallbackBlock*)arg)->context; globalCallbackBlock.func=((CallbackBlock*)arg)->func; //sp[-4] = (size_t)self; // for G5 10.3 //sp[-6] = (size_t)self; // for G4 10.4 //printf("self = %p\n", (void *)self); //printf("sp = %p\n", sp); } /* void Coro_setup(Coro *self, void *arg) { size_t *sp = (size_t *)(((intptr_t)Coro_stack(self) + Coro_stackSize(self) - 64 + 15) & ~15); setjmp(buf); //printf("self = %p\n", self); //printf("sp = %p\n", sp); buf[0] = (long)sp; buf[21] = (long)Coro_Start; //sp[-4] = (size_t)self; // for G5 10.3 //sp[-6] = (size_t)self; // for G4 10.4 //printf("self = %p\n", (void *)self); //printf("sp = %p\n", sp); } */ #elif defined(__DragonFly__) #define buf (self->env) void Coro_setup(Coro *self, void *arg) { void *stack = Coro_stack(self); size_t stacksize = Coro_stackSize(self); void *func = (void *)Coro_Start; setjmp(buf); buf->_jb[2] = (long)(stack + stacksize); buf->_jb[0] = (long)func; return; } #elif defined(__arm__) // contributed by Peter van Hardenberg #define buf (self->env) void Coro_setup(Coro *self, void *arg) { setjmp(buf); buf[8] = (int)Coro_stack(self) + (int)Coro_stackSize(self) - 16; buf[9] = (int)Coro_Start; } #else #error "Coro.c Error: Coro_setup() function needs to be defined for this platform." #endif // old code /* // APPLE coros are handled by PortableUContext now #elif defined(_BSD_PPC_SETJMP_H_) #define buf (self->env) #define setjmp _setjmp #define longjmp _longjmp void Coro_setup(Coro *self, void *arg) { size_t *sp = (size_t *)(((intptr_t)Coro_stack(self) + Coro_stackSize(self) - 64 + 15) & ~15); setjmp(buf); //printf("self = %p\n", self); //printf("sp = %p\n", sp); buf[0] = (int)sp; buf[21] = (int)Coro_Start; //sp[-4] = (size_t)self; // for G5 10.3 //sp[-6] = (size_t)self; // for G4 10.4 //printf("self = %p\n", (void *)self); //printf("sp = %p\n", sp); } #elif defined(_BSD_I386_SETJMP_H) #define buf (self->env) void Coro_setup(Coro *self, void *arg) { size_t *sp = (size_t *)((intptr_t)Coro_stack(self) + Coro_stackSize(self)); setjmp(buf); buf[9] = (int)(sp); // esp buf[12] = (int)Coro_Start; // eip //buf[8] = 0; // ebp } */ /* Solaris supports ucontext - so we don't need this stuff anymore void Coro_setup(Coro *self, void *arg) { // this bit goes before the setjmp call // Solaris 9 Sparc with GCC #if defined(__SVR4) && defined (__sun) #if defined(_JBLEN) && (_JBLEN == 12) && defined(__sparc) #if defined(_LP64) || defined(_I32LPx) #define JBTYPE long JBTYPE x; #else #define JBTYPE int JBTYPE x; asm("ta 3"); // flush register window #endif #define SUN_STACK_END_INDEX 1 #define SUN_PROGRAM_COUNTER 2 #define SUN_STACK_START_INDEX 3 // Solaris 9 i386 with GCC #elif defined(_JBLEN) && (_JBLEN == 10) && defined(__i386) #if defined(_LP64) || defined(_I32LPx) #define JBTYPE long JBTYPE x; #else #define JBTYPE int JBTYPE x; #endif #define SUN_PROGRAM_COUNTER 5 #define SUN_STACK_START_INDEX 3 #define SUN_STACK_END_INDEX 4 #endif #endif */ /* Irix supports ucontext - so we don't need this stuff anymore #elif defined(sgi) && defined(_IRIX4_SIGJBLEN) // Irix/SGI void Coro_setup(Coro *self, void *arg) { setjmp(buf); buf[JB_SP] = (__uint64_t)((char *)stack + stacksize - 8); buf[JB_PC] = (__uint64_t)Coro_Start; } */ /* Linux supports ucontext - so we don't need this stuff anymore #elif defined(linux) // Various flavors of Linux. #if defined(JB_GPR1) // Linux/PPC buf->__jmpbuf[JB_GPR1] = ((int) stack + stacksize - 64 + 15) & ~15; buf->__jmpbuf[JB_LR] = (int) Coro_Start; return; #elif defined(JB_RBX) // Linux/Opteron buf->__jmpbuf[JB_RSP] = (long int )stack + stacksize; buf->__jmpbuf[JB_PC] = Coro_Start; return; #elif defined(JB_SP) // Linux/x86 with glibc2 buf->__jmpbuf[JB_SP] = (int)stack + stacksize; buf->__jmpbuf[JB_PC] = (int)Coro_StartWithArg; // Push the argument on the stack (stack grows downwards) // note: stack is stacksize + 16 bytes long ((int *)stack)[stacksize/sizeof(int) + 1] = (int)self; return; #elif defined(_I386_JMP_BUF_H) // x86-linux with libc5 buf->__sp = (int)stack + stacksize; buf->__pc = Coro_Start; return; #elif defined(__JMP_BUF_SP) // arm-linux on the sharp zauras buf->__jmpbuf[__JMP_BUF_SP] = (int)stack + stacksize; buf->__jmpbuf[__JMP_BUF_SP+1] = (int)Coro_Start; return; #else */ /* Windows supports fibers - so we don't need this stuff anymore #elif defined(__MINGW32__) void Coro_setup(Coro *self, void *arg) { setjmp(buf); buf[4] = (int)((unsigned char *)stack + stacksize - 16); // esp buf[5] = (int)Coro_Start; // eip } #elif defined(_MSC_VER) void Coro_setup(Coro *self, void *arg) { setjmp(buf); // win32 visual c // should this be the same as __MINGW32__? buf[4] = (int)((unsigned char *)stack + stacksize - 16); // esp buf[5] = (int)Coro_Start; // eip } */ /* FreeBSD supports ucontext - so we don't need this stuff anymore #elif defined(__FreeBSD__) // FreeBSD. #if defined(_JBLEN) && (_JBLEN == 81) // FreeBSD/Alpha buf->_jb[2] = (long)Coro_Start; // sc_pc buf->_jb[26+4] = (long)Coro_Start; // sc_regs[R_RA] buf->_jb[27+4] = (long)Coro_Start; // sc_regs[R_T12] buf->_jb[30+4] = (long)(stack + stacksize); // sc_regs[R_SP] return; #elif defined(_JBLEN) // FreeBSD on IA32 buf->_jb[2] = (long)(stack + stacksize); buf->_jb[0] = (long)Coro_Start; return; #else Coro_UnsupportedPlatformError(); #endif */ /* NetBSD supports ucontext - so we don't need this stuff anymore #elif defined(__NetBSD__) void Coro_setup(Coro *self, void *arg) { setjmp(buf); #if defined(_JB_ATTRIBUTES) // NetBSD i386 buf[2] = (long)(stack + stacksize); buf[0] = (long)Coro_Start; #else Coro_UnsupportedPlatformError(); #endif } */ /* Sun supports ucontext - so we don't need this stuff anymore // Solaris supports ucontext - so we don't need this stuff anymore void Coro_setup(Coro *self, void *arg) { // this bit goes before the setjmp call // Solaris 9 Sparc with GCC #if defined(__SVR4) && defined (__sun) #if defined(_JBLEN) && (_JBLEN == 12) && defined(__sparc) #if defined(_LP64) || defined(_I32LPx) #define JBTYPE long JBTYPE x; #else #define JBTYPE int JBTYPE x; asm("ta 3"); // flush register window #endif #define SUN_STACK_END_INDEX 1 #define SUN_PROGRAM_COUNTER 2 #define SUN_STACK_START_INDEX 3 // Solaris 9 i386 with GCC #elif defined(_JBLEN) && (_JBLEN == 10) && defined(__i386) #if defined(_LP64) || defined(_I32LPx) #define JBTYPE long JBTYPE x; #else #define JBTYPE int JBTYPE x; #endif #define SUN_PROGRAM_COUNTER 5 #define SUN_STACK_START_INDEX 3 #define SUN_STACK_END_INDEX 4 #endif #endif #elif defined(__SVR4) && defined(__sun) // Solaris #if defined(SUN_PROGRAM_COUNTER) // SunOS 9 buf[SUN_PROGRAM_COUNTER] = (JBTYPE)Coro_Start; x = (JBTYPE)stack; while ((x % 8) != 0) x --; // align on an even boundary buf[SUN_STACK_START_INDEX] = (JBTYPE)x; x = (JBTYPE)((JBTYPE)stack-stacksize / 2 + 15); while ((x % 8) != 0) x ++; // align on an even boundary buf[SUN_STACK_END_INDEX] = (JBTYPE)x; */
zzywany123-libaw-1
coroutine/source/Coro.c
C
bsd
19,519
#define setcontext(u) _setmcontext(&(u)->mc) #define getcontext(u) _getmcontext(&(u)->mc) typedef struct mcontext mcontext_t; typedef struct ucontext ucontext_t; struct mcontext { ulong pc; /* lr */ ulong cr; /* mfcr */ ulong ctr; /* mfcr */ ulong xer; /* mfcr */ ulong sp; /* callee saved: r1 */ ulong toc; /* callee saved: r2 */ ulong r3; /* first arg to function, return register: r3 */ ulong gpr[19]; /* callee saved: r13-r31 */ /* // XXX: currently do not save vector registers or floating-point state // ulong pad; // uvlong fpr[18]; / * callee saved: f14-f31 * / // ulong vr[4*12]; / * callee saved: v20-v31, 256-bits each * / */ }; struct ucontext { struct { void *ss_sp; uint ss_size; } uc_stack; sigset_t uc_sigmask; mcontext_t mc; }; void makecontext(ucontext_t*, void(*)(void), int, ...); int swapcontext(ucontext_t*, const ucontext_t*); int _getmcontext(mcontext_t*); void _setmcontext(const mcontext_t*);
zzywany123-libaw-1
coroutine/source/power-ucontext.h
C
bsd
945
/* Copyright (c) 2005-2006 Russ Cox, MIT; see COPYRIGHT */ #if defined(__FreeBSD__) && defined(__i386__) && __FreeBSD__ < 5 #define NEEDX86CONTEXT 1 #define SET setmcontext #define GET getmcontext #endif #if defined(__OpenBSD__) && defined(__i386__) #define NEEDX86CONTEXT 1 #define SET setmcontext #define GET getmcontext #endif #if defined(__APPLE__) #if defined(__i386__) #define NEEDX86CONTEXT 1 #define SET _setmcontext #define GET _getmcontext #elif defined(__x86_64__) #define NEEDAMD64CONTEXT 1 #define SET _setmcontext #define GET _getmcontext #else #define NEEDPOWERCONTEXT 1 #define SET __setmcontext #define GET __getmcontext #endif #endif #if defined(__linux__) && defined(__arm__) #define NEEDARMCONTEXT 1 #define SET setmcontext #define GET getmcontext #endif #ifdef NEEDX86CONTEXT .globl SET SET: movl 4(%esp), %eax movl 8(%eax), %fs movl 12(%eax), %es movl 16(%eax), %ds movl 76(%eax), %ss movl 20(%eax), %edi movl 24(%eax), %esi movl 28(%eax), %ebp movl 36(%eax), %ebx movl 40(%eax), %edx movl 44(%eax), %ecx movl 72(%eax), %esp pushl 60(%eax) /* new %eip */ movl 48(%eax), %eax ret .globl GET GET: movl 4(%esp), %eax movl %fs, 8(%eax) movl %es, 12(%eax) movl %ds, 16(%eax) movl %ss, 76(%eax) movl %edi, 20(%eax) movl %esi, 24(%eax) movl %ebp, 28(%eax) movl %ebx, 36(%eax) movl %edx, 40(%eax) movl %ecx, 44(%eax) movl $1, 48(%eax) /* %eax */ movl (%esp), %ecx /* %eip */ movl %ecx, 60(%eax) leal 4(%esp), %ecx /* %esp */ movl %ecx, 72(%eax) movl 44(%eax), %ecx /* restore %ecx */ movl $0, %eax ret #endif #ifdef NEEDAMD64CONTEXT .globl SET SET: movq 16(%rdi), %rsi movq 24(%rdi), %rdx movq 32(%rdi), %rcx movq 40(%rdi), %r8 movq 48(%rdi), %r9 movq 56(%rdi), %rax movq 64(%rdi), %rbx movq 72(%rdi), %rbp movq 80(%rdi), %r10 movq 88(%rdi), %r11 movq 96(%rdi), %r12 movq 104(%rdi), %r13 movq 112(%rdi), %r14 movq 120(%rdi), %r15 movq 184(%rdi), %rsp pushq 160(%rdi) /* new %eip */ movq 8(%rdi), %rdi ret .globl GET GET: movq %rdi, 8(%rdi) movq %rsi, 16(%rdi) movq %rdx, 24(%rdi) movq %rcx, 32(%rdi) movq %r8, 40(%rdi) movq %r9, 48(%rdi) movq $1, 56(%rdi) /* %rax */ movq %rbx, 64(%rdi) movq %rbp, 72(%rdi) movq %r10, 80(%rdi) movq %r11, 88(%rdi) movq %r12, 96(%rdi) movq %r13, 104(%rdi) movq %r14, 112(%rdi) movq %r15, 120(%rdi) movq (%rsp), %rcx /* %rip */ movq %rcx, 160(%rdi) leaq 8(%rsp), %rcx /* %rsp */ movq %rcx, 184(%rdi) movq 32(%rdi), %rcx /* restore %rcx */ movq $0, %rax ret #endif #ifdef NEEDPOWERCONTEXT /* get FPR and VR use flags with sc 0x7FF3 */ /* get vsave with mfspr reg, 256 */ .text .align 2 .globl GET GET: /* xxx: instruction scheduling */ mflr r0 mfcr r5 mfctr r6 mfxer r7 stw r0, 0*4(r3) stw r5, 1*4(r3) stw r6, 2*4(r3) stw r7, 3*4(r3) stw r1, 4*4(r3) stw r2, 5*4(r3) li r5, 1 /* return value for setmcontext */ stw r5, 6*4(r3) stw r13, (0+7)*4(r3) /* callee-save GPRs */ stw r14, (1+7)*4(r3) /* xxx: block move */ stw r15, (2+7)*4(r3) stw r16, (3+7)*4(r3) stw r17, (4+7)*4(r3) stw r18, (5+7)*4(r3) stw r19, (6+7)*4(r3) stw r20, (7+7)*4(r3) stw r21, (8+7)*4(r3) stw r22, (9+7)*4(r3) stw r23, (10+7)*4(r3) stw r24, (11+7)*4(r3) stw r25, (12+7)*4(r3) stw r26, (13+7)*4(r3) stw r27, (14+7)*4(r3) stw r28, (15+7)*4(r3) stw r29, (16+7)*4(r3) stw r30, (17+7)*4(r3) stw r31, (18+7)*4(r3) li r3, 0 /* return */ blr .globl SET SET: lwz r13, (0+7)*4(r3) /* callee-save GPRs */ lwz r14, (1+7)*4(r3) /* xxx: block move */ lwz r15, (2+7)*4(r3) lwz r16, (3+7)*4(r3) lwz r17, (4+7)*4(r3) lwz r18, (5+7)*4(r3) lwz r19, (6+7)*4(r3) lwz r20, (7+7)*4(r3) lwz r21, (8+7)*4(r3) lwz r22, (9+7)*4(r3) lwz r23, (10+7)*4(r3) lwz r24, (11+7)*4(r3) lwz r25, (12+7)*4(r3) lwz r26, (13+7)*4(r3) lwz r27, (14+7)*4(r3) lwz r28, (15+7)*4(r3) lwz r29, (16+7)*4(r3) lwz r30, (17+7)*4(r3) lwz r31, (18+7)*4(r3) lwz r1, 4*4(r3) lwz r2, 5*4(r3) lwz r0, 0*4(r3) mtlr r0 lwz r0, 1*4(r3) mtcr r0 /* mtcrf 0xFF, r0 */ lwz r0, 2*4(r3) mtctr r0 lwz r0, 3*4(r3) mtxer r0 lwz r3, 6*4(r3) blr #endif #ifdef NEEDARMCONTEXT .globl GET GET: str r1, [r0,#4] str r2, [r0,#8] str r3, [r0,#12] str r4, [r0,#16] str r5, [r0,#20] str r6, [r0,#24] str r7, [r0,#28] str r8, [r0,#32] str r9, [r0,#36] str r10, [r0,#40] str r11, [r0,#44] str r12, [r0,#48] str r13, [r0,#52] str r14, [r0,#56] /* store 1 as r0-to-restore */ mov r1, #1 str r1, [r0] /* return 0 */ mov r0, #0 mov pc, lr .globl SET SET: ldr r1, [r0,#4] ldr r2, [r0,#8] ldr r3, [r0,#12] ldr r4, [r0,#16] ldr r5, [r0,#20] ldr r6, [r0,#24] ldr r7, [r0,#28] ldr r8, [r0,#32] ldr r9, [r0,#36] ldr r10, [r0,#40] ldr r11, [r0,#44] ldr r12, [r0,#48] ldr r13, [r0,#52] ldr r14, [r0,#56] ldr r0, [r0] mov pc, lr #endif
zzywany123-libaw-1
coroutine/source/asm.S
Unix Assembly
bsd
4,769
/* */ #ifndef CORO_DEFINED #define CORO_DEFINED 1 //#include "Common.h" //#include "PortableUContext.h" //#include "taskimpl.h" #if defined(_WIN32) typedef unsigned size_t; typedef unsigned char uint8_t; #else #include <sys/types.h> #include <stdint.h> #endif #if defined(__SYMBIAN32__) #define CORO_STACK_SIZE 8192 #define CORO_STACK_SIZE_MIN 1024 #else //#define CORO_DEFAULT_STACK_SIZE (65536/2) //#define CORO_DEFAULT_STACK_SIZE (65536*4) //128k needed on PPC due to parser #define CORO_DEFAULT_STACK_SIZE (128*1024) #define CORO_STACK_SIZE_MIN 8192 #endif #if defined(BUILDING_CORO_DLL) && !defined(__MINGW32__) && defined(WIN32) #if defined(BUILDING_CORO_DLL) || defined(BUILDING_IOVMALL_DLL) #define CORO_API __declspec(dllexport) #else #define CORO_API __declspec(dllimport) #endif #else #define CORO_API #endif /* #if defined(__amd64__) && !defined(__x86_64__) #define __x86_64__ 1 #endif */ // Pick which coro implementation to use // The make file can set -DUSE_FIBERS, -DUSE_UCONTEXT or -DUSE_SETJMP to force this choice. #if !defined(USE_FIBERS) && !defined(USE_UCONTEXT) && !defined(USE_SETJMP) #if defined(WIN32) && defined(HAS_FIBERS) # define USE_FIBERS #elif defined(HAS_UCONTEXT) //#elif defined(HAS_UCONTEXT) && !defined(__x86_64__) # if !defined(USE_UCONTEXT) # define USE_UCONTEXT # endif #else # define USE_SETJMP #endif #endif #if defined(USE_FIBERS) #define CORO_IMPLEMENTATION "fibers" #elif defined(USE_UCONTEXT) #include <sys/ucontext.h> #define CORO_IMPLEMENTATION "ucontext" #elif defined(USE_SETJMP) #include <setjmp.h> #define CORO_IMPLEMENTATION "setjmp" #endif #ifdef __cplusplus extern "C" { #endif typedef struct Coro Coro; struct Coro { size_t requestedStackSize; size_t allocatedStackSize; void *stack; #ifdef USE_VALGRIND unsigned int valgrindStackId; #endif #if defined(USE_FIBERS) void *fiber; #elif defined(USE_UCONTEXT) ucontext_t env; #elif defined(USE_SETJMP) jmp_buf env; #endif unsigned char isMain; }; CORO_API Coro *Coro_new(void); CORO_API void Coro_free(Coro *self); // stack CORO_API void *Coro_stack(Coro *self); CORO_API size_t Coro_stackSize(Coro *self); CORO_API void Coro_setStackSize_(Coro *self, size_t sizeInBytes); CORO_API size_t Coro_bytesLeftOnStack(Coro *self); CORO_API int Coro_stackSpaceAlmostGone(Coro *self); CORO_API void Coro_initializeMainCoro(Coro *self); typedef void (CoroStartCallback)(void *); CORO_API void Coro_startCoro_(Coro *self, Coro *other, void *context, CoroStartCallback *callback); CORO_API void Coro_switchTo_(Coro *self, Coro *next); CORO_API void Coro_setup(Coro *self, void *arg); // private #ifdef __cplusplus } #endif #endif
zzywany123-libaw-1
coroutine/source/Coro.h
C
bsd
2,675
#define setcontext(u) setmcontext(&(u)->uc_mcontext) #define getcontext(u) getmcontext(&(u)->uc_mcontext) typedef struct mcontext mcontext_t; typedef struct ucontext ucontext_t; extern int swapcontext(ucontext_t*, const ucontext_t*); extern void makecontext(ucontext_t*, void(*)(void), int, ...); extern int getmcontext(mcontext_t*); extern void setmcontext(const mcontext_t*); /*- * Copyright (c) 1999 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD: src/sys/sys/ucontext.h,v 1.4 1999/10/11 20:33:17 luoqi Exp $ */ /* #include <machine/ucontext.h> */ /*- * Copyright (c) 1999 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD: src/sys/i386/include/ucontext.h,v 1.4 1999/10/11 20:33:09 luoqi Exp $ */ struct mcontext { /* * The first 20 fields must match the definition of * sigcontext. So that we can support sigcontext * and ucontext_t at the same time. */ int mc_onstack; /* XXX - sigcontext compat. */ int mc_gs; int mc_fs; int mc_es; int mc_ds; int mc_edi; int mc_esi; int mc_ebp; int mc_isp; int mc_ebx; int mc_edx; int mc_ecx; int mc_eax; int mc_trapno; int mc_err; int mc_eip; int mc_cs; int mc_eflags; int mc_esp; /* machine state */ int mc_ss; int mc_fpregs[28]; /* env87 + fpacc87 + u_long */ int __spare__[17]; }; struct ucontext { /* * Keep the order of the first two fields. Also, * keep them the first two fields in the structure. * This way we can have a union with struct * sigcontext and ucontext_t. This allows us to * support them both at the same time. * note: the union is not defined, though. */ sigset_t uc_sigmask; mcontext_t uc_mcontext; struct __ucontext *uc_link; stack_t uc_stack; int __spare__[8]; };
zzywany123-libaw-1
coroutine/source/386-ucontext.h
C
bsd
4,600
<!--#include virtual="/menu.cgi?path=/projects/opensource/libCoroutine/docs" --> <UL> <table cellpadding=0 cellspacing=0 border=0 width=90%> <tr> <td> <h2>Overview</h2> libCoroutine is a simple stackfull coroutine implementation. On unix platforms, the implementation uses ucontext if available or with setjmp/longjmp otherwise except on OSX where some assembly is used. On windows, fibers are used. <br> <p> <h3>Main</h3> First you'll need to create a coro instance to represent the C stack that was allocated to run the host program's main() function: <pre> Coro *mainCoro = Coro_new(); Coro_initializeMainCoro(mainCoro); </pre> <h3>Starting</h3> To create a coroutine: <pre> Coro *newCoro = Coro_new(); Coro_startCoro_(currentCoro, newCoro, aContext, aCallback); </pre> currentCoro should be a pointer to the currenting running coroutine (which would be mainCoro, if this is the first corountine you're creating). aCallback is a function pointer for the function which will be called when the coroutine starts and aContext is the argument that will be passed to the callback function. <h3>Switching</h3> To switch to the coroutine: <pre> Coro_switchTo_(currentCoro, nextCoro); </pre> <h3>Freeing</h3> <pre> Coro_free(aCoro); </pre> Note that you can't free the currently running coroutine as this would free the current C stack. <h3>Stacks</h3> You can check to see whether a corouinte has nearly exhasted it's stack space by calling: <pre> Coro_stackSpaceAlmostGone(aCoro); </pre> This returns 1 if the remaining stack space is less than CORO_STACK_SIZE_MIN. <p> The define CORO_STACK_SIZE can be used to adjust the default stack size. There is also a #ifdef on USE_VALGRIND which, when enabled, will register stack switches with valgrind, so it won't be confused. <h3>Chaining</h3> A trick to provide effectively get unlimited stack space while keeping stack allocations small is to periodically call Coro_stackSpaceAlmostGone() and create a new Coro in which to continue the computation when the stack gets low. <h2>Credits</h2> I (Steve Dekorte) mostly just put together bits of code from other folks to make this library. Russ Cox deserves the most credit currently for the portable ucontext code. Some history: <p> Originally based on Edgar Toernig's Minimalistic cooperative multitasking (http://www.goron.de/~froese/) <br> reorg by Steve Dekorte and Chis Double <br> Symbian and Cygwin support by Chis Double <br> Linux/PCC, Linux/Opteron, Irix and FreeBSD/Alpha, ucontext support by Austin Kurahone <br> FreeBSD/Intel support by Faried Nawaz <br> Mingw support by Pit Capitain <br> Visual C support by Daniel Vollmer <br> Solaris support by Manpreet Singh <br> Fibers support by Jonas Eschenburg <br> Ucontext arg support by Olivier Ansaldi <br> Ucontext x86-64 support by James Burgess and Jonathan Wright <br> Russ Cox for the newer portable ucontext implementions.<br> </td> </tr> </table> <br><br><br> </UL>
zzywany123-libaw-1
coroutine/docs/index.html
HTML
bsd
3,039
include ./Makefile.lib CFLAGS += -DBUILDING_CORO_DLL $(IOVMALLFLAGS) # Manually control which coro implementation to use #CFLAGS += -DUSE_UCONTEXT # preferred on OSX, Linux and friends #CFLAGS += -DUSE_FIBERS # preferred on Windows #CFLAGS += -DUSE_SETJMP # method of last resort
zzywany123-libaw-1
coroutine/Makefile
Makefile
bsd
286
twoCoroTest: twoCoroTest.c $(CC) -I../../basekit/_build/headers -I../_build/headers -L../_build/lib -o $@ $< -lcoroutine
zzywany123-libaw-1
coroutine/samples/Makefile
Makefile
bsd
123
#include "Coro.h" #include <stdio.h> Coro *firstCoro, *secondCoro; void secondTask(void *context) { int num = 0; printf("secondTask created with value %d\n", *(int *)context); while (1) { printf("secondTask: %d %d\n", (int)Coro_bytesLeftOnStack(secondCoro), num++); Coro_switchTo_(secondCoro, firstCoro); } } void firstTask(void *context) { int value = 2; int num = 0; printf("firstTask created with value %d\n", *(int *)context); secondCoro = Coro_new(); Coro_startCoro_(firstCoro, secondCoro, (void *)&value, secondTask); while (1) { printf("firstTask: %d %d\n", (int)Coro_bytesLeftOnStack(firstCoro), num++); Coro_switchTo_(firstCoro, secondCoro); } } int main() { Coro *mainCoro = Coro_new(); int value = 1; Coro_initializeMainCoro(mainCoro); firstCoro = Coro_new(); Coro_startCoro_(mainCoro, firstCoro, (void *)&value, firstTask); }
zzywany123-libaw-1
coroutine/samples/twoCoroTest.c
C
bsd
883
"""SCons.Tool.gcc Tool-specific initialization for MinGW (http://www.mingw.org/) There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation # # 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. # __revision__ = "/home/scons/scons/branch.0/branch.96/baseline/src/engine/SCons/Tool/mingw.py 0.96.90.D001 2005/02/15 20:11:37 knight" import os import os.path import string import SCons.Action import SCons.Builder import SCons.Tool import SCons.Util # This is what we search for to find mingw: prefixes = SCons.Util.Split(""" mingw32- mingw32msvc- i386-mingw32- i486-mingw32- i586-mingw32- i686-mingw32- i386-mingw32msvc- i486-mingw32msvc- i586-mingw32msvc- i686-mingw32msvc- i686-unknown-mingw32- """) def find(env): for prefix in prefixes: # First search in the SCons path and then the OS path: if env.WhereIs(prefix + 'gcc') or SCons.Util.WhereIs(prefix + 'gcc'): return prefix return '' def shlib_generator(target, source, env, for_signature): cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS']) dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') if dll: cmd.extend(['-o', dll]) cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS']) implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX') if implib: cmd.append('-Wl,--out-implib,'+implib.get_string(for_signature)) def_target = env.FindIxes(target, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX') if def_target: cmd.append('-Wl,--output-def,'+def_target.get_string(for_signature)) return [cmd] def shlib_emitter(target, source, env): dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') no_import_lib = env.get('no_import_lib', 0) if not dll: raise SCons.Errors.UserError, "A shared library should have exactly one target with the suffix: %s" % env.subst("$SHLIBSUFFIX") if not no_import_lib and \ not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'): # Append an import library to the list of targets. target.append(env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'LIBPREFIX', 'LIBSUFFIX')) # Append a def file target if there isn't already a def file target # or a def file source. There is no option to disable def file # target emitting, because I can't figure out why someone would ever # want to turn it off. def_source = env.FindIxes(source, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX') def_target = env.FindIxes(target, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX') if not def_source and not def_target: target.append(env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX')) return (target, source) shlib_action = SCons.Action.Action(shlib_generator, generator=1) res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR') res_builder = SCons.Builder.Builder(action=res_action, suffix='.o', source_scanner=SCons.Tool.SourceFileScanner) SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan) def generate(env): mingw_prefix = find(env) if mingw_prefix: dir = os.path.dirname(env.WhereIs(mingw_prefix + 'gcc') or SCons.Util.WhereIs(mingw_prefix + 'gcc')) # The mingw bin directory must be added to the path: path = env['ENV'].get('PATH', []) if not path: path = [] if SCons.Util.is_String(path): path = string.split(path, os.pathsep) env['ENV']['PATH'] = string.join([dir] + path, os.pathsep) # Most of mingw is the same as gcc and friends... gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas'] for tool in gnu_tools: SCons.Tool.Tool(tool)(env) #... but a few things differ: env['CC'] = mingw_prefix + 'gcc' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') env['CXX'] = mingw_prefix + 'g++' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') env['SHLINKCOM'] = shlib_action env.Append(SHLIBEMITTER = [shlib_emitter]) env['LINK'] = mingw_prefix + 'gcc' env['AS'] = mingw_prefix + 'as' env['AR'] = mingw_prefix + 'ar' env['RANLIB'] = mingw_prefix + 'ranlib' env['WIN32DEFPREFIX'] = '' env['WIN32DEFSUFFIX'] = '.def' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['RC'] = mingw_prefix + 'windres' env['RCFLAGS'] = SCons.Util.CLVar('') env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS ${INCPREFIX}${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET' env['BUILDERS']['RES'] = res_builder # Some setting from the platform also have to be overridden: env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.o' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = [ '$LIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ] def exists(env): return find(env)
zzywany123-libaw-1
crossmingw.py
Python
bsd
6,513
/* Copyright (c) 2008-2010, Jorge Acereda Maciá All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "aw.h" #include "awos.h" #include "sysgl.h" #include "co.h" #include <OpenGLES/ES1/glext.h> #include <assert.h> #include <Foundation/Foundation.h> #include <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> @interface glview : UIView {} @end @interface awdelegate : NSObject <UIApplicationDelegate, UITextFieldDelegate> { UIWindow * win; glview* view; EAGLContext * ctx; CADisplayLink * dpylink; UITextField * tf; @public co * comain; co * coaw; int awdone; osw * w; osc * c; } @end awdelegate * getDelegate() { return (awdelegate*)coData(coCurrent()); } static void dgot(int e, int x, int y) { got(getDelegate()->w, e, x, y); } static void fakekeyuni(unsigned key, unsigned unicode) { dgot(AW_EVENT_DOWN, key, 0); dgot(AW_EVENT_UNICODE, unicode, 0); dgot(AW_EVENT_UP, key, 0); } static unsigned mapkey(unsigned k) { unsigned ret; switch (k) { case 'A': ret = AW_KEY_A; break; case 'B': ret = AW_KEY_B; break; case 'C': ret = AW_KEY_C; break; case 'D': ret = AW_KEY_D; break; case 'E': ret = AW_KEY_E; break; case 'F': ret = AW_KEY_F; break; case 'G': ret = AW_KEY_G; break; case 'H': ret = AW_KEY_H; break; case 'I': ret = AW_KEY_I; break; case 'J': ret = AW_KEY_J; break; case 'K': ret = AW_KEY_K; break; case 'L': ret = AW_KEY_L; break; case 'M': ret = AW_KEY_M; break; case 'N': ret = AW_KEY_N; break; case 'O': ret = AW_KEY_O; break; case 'P': ret = AW_KEY_P; break; case 'Q': ret = AW_KEY_Q; break; case 'R': ret = AW_KEY_R; break; case 'S': ret = AW_KEY_S; break; case 'T': ret = AW_KEY_T; break; case 'U': ret = AW_KEY_U; break; case 'V': ret = AW_KEY_V; break; case 'W': ret = AW_KEY_W; break; case 'X': ret = AW_KEY_X; break; case 'Y': ret = AW_KEY_Y; break; case 'Z': ret = AW_KEY_Z; break; case '0': ret = AW_KEY_0; break; case '1': ret = AW_KEY_1; break; case '2': ret = AW_KEY_2; break; case '3': ret = AW_KEY_3; break; case '4': ret = AW_KEY_4; break; case '5': ret = AW_KEY_5; break; case '6': ret = AW_KEY_6; break; case '7': ret = AW_KEY_7; break; case '8': ret = AW_KEY_8; break; case '9': ret = AW_KEY_9; break; case '=': ret = AW_KEY_EQUAL; break; case '\b': ret = AW_KEY_DELETE; break; case '\n': ret = AW_KEY_RETURN; break; default: ret = AW_KEY_NONE; } return ret; } static void fakekey(unsigned unicode) { int upper = isupper(unicode); int luni = toupper(unicode); if (upper) dgot(AW_EVENT_DOWN, AW_KEY_SHIFT, 0); fakekeyuni(mapkey(luni), unicode); if (upper) dgot(AW_EVENT_UP, AW_KEY_SHIFT, 0); } @implementation glview + (Class) layerClass { return [CAEAGLLayer class]; } - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) e { UITouch* touch = [touches anyObject]; CGPoint loc = [touch locationInView: self]; dgot(AW_EVENT_MOTION, loc.x, loc.y); dgot(AW_EVENT_DOWN, AW_KEY_MOUSELEFT, 0); } - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) e { UITouch* touch = [touches anyObject]; CGPoint loc = [touch locationInView: self]; dgot(AW_EVENT_MOTION, loc.x, loc.y); dgot(AW_EVENT_UP, AW_KEY_MOUSELEFT, 0); } - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) e { UITouch* touch = [touches anyObject]; CGPoint loc = [touch previousLocationInView: self]; dgot(AW_EVENT_MOTION, loc.x, loc.y); } @end void awentry(void * data) { extern int fakemain(int argc, char ** argv); int argc = 1; char * argv0 = "awiphone"; fakemain(argc, &argv0); coSwitchTo(getDelegate()->comain); assert(0); } @implementation awdelegate - (BOOL) textField: (UITextField *)tf shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)s { int sl = [s length]; int i; if (!sl) fakekey('\b'); for (i = 0; i < sl; i++) fakekey([s characterAtIndex: i]); return NO; } - (BOOL)textFieldShouldReturn: (UITextField*)tf { fakekey('\n'); return NO; } - (void) update { coSwitchTo(coaw); [ctx presentRenderbuffer: GL_RENDERBUFFER_OES]; } - (void) applicationDidFinishLaunching: (UIApplication*) application { comain = coMain(self); coaw = coNew(awentry, self); CGRect r = [[UIScreen mainScreen] bounds]; win = [[UIWindow alloc] initWithFrame: r]; view = [[glview alloc] initWithFrame: r]; tf = [[UITextField alloc] initWithFrame: r]; [tf becomeFirstResponder]; [tf setDelegate: self]; [tf setAutocapitalizationType: UITextAutocapitalizationTypeNone]; [tf setAutocorrectionType: UITextAutocorrectionTypeNo]; [tf setEnablesReturnKeyAutomatically: NO]; [tf setText: @" "]; [tf setHidden: YES]; [win makeKeyAndVisible]; [win addSubview: view]; [win addSubview: tf]; ctx = [[EAGLContext alloc] initWithAPI: kEAGLRenderingAPIOpenGLES2]; [EAGLContext setCurrentContext: ctx]; GLuint cb; GLuint fb; glGenFramebuffersOES(1, &fb); glGenRenderbuffersOES(1, &cb); glBindFramebufferOES(GL_FRAMEBUFFER_OES, fb); glBindRenderbufferOES(GL_RENDERBUFFER_OES , cb); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, cb); [ctx renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: (CAEAGLLayer *) [view layer]]; dpylink = [CADisplayLink displayLinkWithTarget: self selector: @selector(update)]; [dpylink setFrameInterval: 1]; [dpylink addToRunLoop: [NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode]; } - (void) dealloc { [dpylink release]; [win release]; [view release]; [ctx release]; [super dealloc]; } @end int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int ret = UIApplicationMain(argc, argv, nil, @"awdelegate"); [pool release]; return ret; } int osgInit(osg * g, const char * name) { return 1; } int osgTerm(osg * g) { return 1; } int oswSetTitle(osw * w, const char * t) { return 1; } int oswInit(osw * w, osg * g, int x, int y, int width, int height, int bl) { getDelegate()->w = w; return 1; } int oswTerm(osw * w) { return 1; } int oswSwapBuffers(osw * w) { coSwitchTo(getDelegate()->comain); return 1; } int oswShow(osw * w) { return 1; } int oswHide(osw * w) { return 1; } void oswPollEvent(osw * w) { } int oswSetSwapInterval(osw * w, int i) { return 1; } int oswClearCurrent(osw * w) { return 1; } int oswMakeCurrent(osw * w, osc * c) { return 1; } int oscInit(osc * c, osg * g, osc * share) { return 1; } int oscTerm(osc * cc) { return 1; } int ospInit(osp * p, const void * rgba, unsigned hotx, unsigned hoty) { return 1; } int ospTerm(osp * p) { return 1; } int oswMaximize(osw * w) { CGRect r = [[UIScreen mainScreen] bounds]; dgot(AW_EVENT_RESIZE, r.size.width, r.size.height); return 1; } int oswGeometry(osw * w, int x, int y, unsigned width, unsigned height) { return oswMaximize(w); } void oswPointer(osw * w) { } unsigned oswOrder(osw ** w) { return 0; }
zzywany123-libaw-1
awiphone.m
Objective-C
bsd
8,949
#include "awnpapios.h" #include <stdlib.h> #include <windows.h> #include <windowsx.h> struct _ins { insHeader h; WNDPROC oldproc; }; static void setPF(HDC dc) { PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd 1, // version number PFD_DRAW_TO_WINDOW | // support window PFD_SUPPORT_OPENGL | // support OpenGL PFD_DOUBLEBUFFER, // double buffered PFD_TYPE_RGBA, // RGBA type 24, // 24-bit color depth 0, 0, 0, 0, 0, 0, // color bits ignored 0, // no alpha buffer 0, // shift bit ignored 0, // no accumulation buffer 0, 0, 0, 0, // accum bits ignored 32, // 32-bit z-buffer 0, // no stencil buffer 0, // no auxiliary buffer PFD_MAIN_PLANE, // main layer 0, // reserved 0, 0, 0 // layer masks ignored }; SetPixelFormat(dc, ChoosePixelFormat(dc, &pfd), &pfd); } ins * awosNew(NPNetscapeFuncs * browser, NPP i) { return calloc(1, sizeof(ins)); } LONG WINAPI plghandle(HWND win, UINT msg, WPARAM w, LPARAM l) { extern LONG WINAPI handle(HWND win, UINT msg, WPARAM w, LPARAM l); LONG r; switch (msg) { case WM_TIMER: PostMessage(win, WM_PAINT, 0, 0); break; case WM_PAINT: { insHeader * hdr = (insHeader*)GetWindowLongPtrW(win, GWL_USERDATA); PAINTSTRUCT ps; HDC hdc = BeginPaint(win, &ps); coSwitchTo(hdr->coaw); EndPaint(win, &ps); r = 0; } break; default: r = handle(win, msg, w, l); } return r; } void awosSetWindow(ins * o, NPWindow * npwin) { HANDLE win = npwin->window; HDC dc; if (!o->oldproc) { o->h.w.handle = win; o->oldproc = SubclassWindow(win, plghandle); SetWindowLongPtrW(win, GWL_USERDATA, (LONG_PTR)o); dc = GetDC(win); setPF(dc); o->h.c.handle = wglCreateContext(dc); wglMakeCurrent(dc, o->h.c.handle); ReleaseDC(win, dc); SetTimer(win, 1, 10, 0); } } void awosDel(ins * o) { if (o->oldproc) SubclassWindow(o->h.w.handle, o->oldproc); free(o); } static BOOL (APIENTRY *wglSwapInterval) (int interval) = 0; int awosMakeCurrentI(ins * o) { HANDLE win = (HANDLE)o->h.w.handle; HDC dc = GetDC(win); int ret; ret = wglMakeCurrent(dc, (HGLRC)o->h.c.handle); if (!wglSwapInterval) wglSwapInterval = (void*)wglGetProcAddress("wglSwapIntervalEXT"); if (wglSwapInterval) wglSwapInterval(1); ReleaseDC(win, dc); return ret; } int awosClearCurrentI(ins * o) { return wglMakeCurrent(0, 0); } void awosUpdate(ins * o) { HDC dc = GetDC(o->h.w.handle); SwapBuffers(dc); ReleaseDC(o->h.w.handle, dc); } NPError awosEvent(ins * o, void * ev) { NPEvent * e = (NPEvent *)ev; debug("osevent"); return NPERR_NO_ERROR; } extern IMAGE_DOS_HEADER __ImageBase; const char * awosResourcesPath(ins * o) { static char buf[256]; static char * ret = 0; if (!ret) { GetModuleFileName((HINSTANCE)&__ImageBase, buf, sizeof(buf)); *(strrchr(buf, '\\') + 1) = 0; ret = buf; } return ret; } NPError awosGetValue(NPP i, NPPVariable var, void * v) { ins * o = (ins*)i->pdata; NPError ret; debug("os getvalue"); switch(var) { default: debug("os getval default"); ret = NPERR_GENERIC_ERROR; break; } return ret; }
zzywany123-libaw-1
awntnpapi.c
C
bsd
3,657
#ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 102 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1006 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
zzywany123-libaw-1
resource.h
C
bsd
251
#include <sys/types.h> #include "co.h" #include "aw.h" #include "awos.h" #if defined __APPLE__ #define NP_NO_CARBON #include <WebKit/npapi.h> #include <WebKit/npfunctions.h> #include <QuartzCore/QuartzCore.h> #else #include <npapi.h> #include <npfunctions.h> #endif struct _aw { awHeader hdr; void * handle; }; struct _ac { acHeader hdr; void * handle; }; typedef struct _ins ins; typedef struct _insHeader { aw w; ac c; co * comain; co * coaw; int awdone; } insHeader; ins * awosNew(NPNetscapeFuncs *, NPP); void awosDel(ins *); void awosUpdate(ins *); void awosSetWindow(ins *, NPWindow *); int awosMakeCurrentI(ins *); int awosClearCurrentI(ins *); NPError awosEvent(ins *, void *); NPError awosGetValue(NPP, NPPVariable, void *); void * awosSelf(const char * plgname); void * awosResolve(void * in, const char * name); const char * awosModPath(); const char * awosResourcesPath(ins *); #if defined _WIN32 #undef EXPORTED #define EXPORTED #else #define OSCALL #endif
zzywany123-libaw-1
awnpapios.h
C
bsd
1,003
#include <Carbon/Carbon.h> // For keycodes #include "aw.h" unsigned mapkeycode(unsigned k) { unsigned ret; switch (k) { case kVK_ANSI_A: ret = AW_KEY_A; break; case kVK_ANSI_S: ret = AW_KEY_S; break; case kVK_ANSI_D: ret = AW_KEY_D; break; case kVK_ANSI_F: ret = AW_KEY_F; break; case kVK_ANSI_H: ret = AW_KEY_H; break; case kVK_ANSI_G: ret = AW_KEY_G; break; case kVK_ANSI_Z: ret = AW_KEY_Z; break; case kVK_ANSI_X: ret = AW_KEY_X; break; case kVK_ANSI_C: ret = AW_KEY_C; break; case kVK_ANSI_V: ret = AW_KEY_V; break; case kVK_ANSI_B: ret = AW_KEY_B; break; case kVK_ANSI_Q: ret = AW_KEY_Q; break; case kVK_ANSI_W: ret = AW_KEY_W; break; case kVK_ANSI_E: ret = AW_KEY_E; break; case kVK_ANSI_R: ret = AW_KEY_R; break; case kVK_ANSI_Y: ret = AW_KEY_Y; break; case kVK_ANSI_T: ret = AW_KEY_T; break; case kVK_ANSI_1: ret = AW_KEY_1; break; case kVK_ANSI_2: ret = AW_KEY_2; break; case kVK_ANSI_3: ret = AW_KEY_3; break; case kVK_ANSI_4: ret = AW_KEY_4; break; case kVK_ANSI_6: ret = AW_KEY_6; break; case kVK_ANSI_5: ret = AW_KEY_5; break; case kVK_ANSI_Equal: ret = AW_KEY_EQUAL; break; case kVK_ANSI_9: ret = AW_KEY_9; break; case kVK_ANSI_7: ret = AW_KEY_7; break; case kVK_ANSI_Minus: ret = AW_KEY_MINUS; break; case kVK_ANSI_8: ret = AW_KEY_8; break; case kVK_ANSI_0: ret = AW_KEY_0; break; case kVK_ANSI_RightBracket: ret = AW_KEY_RIGHTBRACKET; break; case kVK_ANSI_O: ret = AW_KEY_O; break; case kVK_ANSI_U: ret = AW_KEY_U; break; case kVK_ANSI_LeftBracket: ret = AW_KEY_LEFTBRACKET; break; case kVK_ANSI_I: ret = AW_KEY_I; break; case kVK_ANSI_P: ret = AW_KEY_P; break; case kVK_ANSI_L: ret = AW_KEY_L; break; case kVK_ANSI_J: ret = AW_KEY_J; break; case kVK_ANSI_Quote: ret = AW_KEY_QUOTE; break; case kVK_ANSI_K: ret = AW_KEY_K; break; case kVK_ANSI_Semicolon: ret = AW_KEY_SEMICOLON; break; case kVK_ANSI_Backslash: ret = AW_KEY_BACKSLASH; break; case kVK_ANSI_Comma: ret = AW_KEY_COMMA; break; case kVK_ANSI_Slash: ret = AW_KEY_SLASH; break; case kVK_ANSI_N: ret = AW_KEY_N; break; case kVK_ANSI_M: ret = AW_KEY_M; break; case kVK_ANSI_Period: ret = AW_KEY_PERIOD; break; case kVK_ANSI_Grave: ret = AW_KEY_GRAVE; break; case kVK_ANSI_KeypadDecimal: ret = AW_KEY_KEYPADDECIMAL; break; case kVK_ANSI_KeypadMultiply: ret = AW_KEY_KEYPADMULTIPLY; break; case kVK_ANSI_KeypadPlus: ret = AW_KEY_KEYPADPLUS; break; case kVK_ANSI_KeypadClear: ret = AW_KEY_KEYPADCLEAR; break; case kVK_ANSI_KeypadDivide: ret = AW_KEY_KEYPADDIVIDE; break; case kVK_ANSI_KeypadEnter: ret = AW_KEY_KEYPADENTER; break; case kVK_ANSI_KeypadMinus: ret = AW_KEY_KEYPADMINUS; break; case kVK_ANSI_KeypadEquals: ret = AW_KEY_KEYPADEQUALS; break; case kVK_ANSI_Keypad0: ret = AW_KEY_KEYPAD0; break; case kVK_ANSI_Keypad1: ret = AW_KEY_KEYPAD1; break; case kVK_ANSI_Keypad2: ret = AW_KEY_KEYPAD2; break; case kVK_ANSI_Keypad3: ret = AW_KEY_KEYPAD3; break; case kVK_ANSI_Keypad4: ret = AW_KEY_KEYPAD4; break; case kVK_ANSI_Keypad5: ret = AW_KEY_KEYPAD5; break; case kVK_ANSI_Keypad6: ret = AW_KEY_KEYPAD6; break; case kVK_ANSI_Keypad7: ret = AW_KEY_KEYPAD7; break; case kVK_ANSI_Keypad8: ret = AW_KEY_KEYPAD8; break; case kVK_ANSI_Keypad9: ret = AW_KEY_KEYPAD9; break; case kVK_Return: ret = AW_KEY_RETURN; break; case kVK_Tab: ret = AW_KEY_TAB; break; case kVK_Space: ret = AW_KEY_SPACE; break; case kVK_Delete: ret = AW_KEY_DELETE; break; case kVK_Escape: ret = AW_KEY_ESCAPE; break; case kVK_Command: ret = AW_KEY_COMMAND; break; case kVK_Shift: ret = AW_KEY_SHIFT; break; case kVK_CapsLock: ret = AW_KEY_CAPSLOCK; break; case kVK_Option: ret = AW_KEY_OPTION; break; case kVK_Control: ret = AW_KEY_CONTROL; break; case kVK_RightShift: ret = AW_KEY_RIGHTSHIFT; break; case kVK_RightOption: ret = AW_KEY_RIGHTOPTION; break; case kVK_RightControl: ret = AW_KEY_RIGHTCONTROL; break; case kVK_Function: ret = AW_KEY_FUNCTION; break; case kVK_F17: ret = AW_KEY_F17; break; case kVK_VolumeUp: ret = AW_KEY_VOLUMEUP; break; case kVK_VolumeDown: ret = AW_KEY_VOLUMEDOWN; break; case kVK_Mute: ret = AW_KEY_MUTE; break; case kVK_F18: ret = AW_KEY_F18; break; case kVK_F19: ret = AW_KEY_F19; break; case kVK_F20: ret = AW_KEY_F20; break; case kVK_F5: ret = AW_KEY_F5; break; case kVK_F6: ret = AW_KEY_F6; break; case kVK_F7: ret = AW_KEY_F7; break; case kVK_F3: ret = AW_KEY_F3; break; case kVK_F8: ret = AW_KEY_F8; break; case kVK_F9: ret = AW_KEY_F9; break; case kVK_F11: ret = AW_KEY_F11; break; case kVK_F13: ret = AW_KEY_F13; break; case kVK_F16: ret = AW_KEY_F16; break; case kVK_F14: ret = AW_KEY_F14; break; case kVK_F10: ret = AW_KEY_F10; break; case kVK_F12: ret = AW_KEY_F12; break; case kVK_F15: ret = AW_KEY_F15; break; case kVK_Help: ret = AW_KEY_HELP; break; case kVK_Home: ret = AW_KEY_HOME; break; case kVK_PageUp: ret = AW_KEY_PAGEUP; break; case kVK_ForwardDelete: ret = AW_KEY_FORWARDDELETE; break; case kVK_F4: ret = AW_KEY_F4; break; case kVK_End: ret = AW_KEY_END; break; case kVK_F2: ret = AW_KEY_F2; break; case kVK_PageDown: ret = AW_KEY_PAGEDOWN; break; case kVK_F1: ret = AW_KEY_F1; break; case kVK_LeftArrow: ret = AW_KEY_LEFTARROW; break; case kVK_RightArrow: ret = AW_KEY_RIGHTARROW; break; case kVK_DownArrow: ret = AW_KEY_DOWNARROW; break; case kVK_UpArrow: ret = AW_KEY_UPARROW; break; default: ret = AW_KEY_NONE; } return ret; }
zzywany123-libaw-1
awmackeycodes.c
C
bsd
5,350
#if !defined(__APPLE__) || AWBACKEND != cocoa #include <GL/glu.h> #else #include <OpenGL/glu.h> #endif
zzywany123-libaw-1
sysglu.h
C
bsd
104
#if !defined _AWTYPES_H_ #define _AWTYPES_H_ typedef struct _ag ag; typedef struct _aw aw; typedef struct _ac ac; typedef struct _ap ap; typedef struct _ae ae; #endif
zzywany123-libaw-1
awtypes.h
C
bsd
167
/* Adapted from the Red Book */ #include <stdarg.h> #include <stdio.h> #include <aw/sysgl.h> #include <aw/sysglu.h> #include <aw/aw.h> #include "log.h" static void reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); } static void display(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 1.0, 1.0); glBegin(GL_POLYGON); { glVertex3f(0.25, 0.25, 0.0); glVertex3f(0.75, 0.25, 0.0); glVertex3f(0.75, 0.75, 0.0); glVertex3f(0.25, 0.75, 0.0); } glEnd(); glFlush(); } static void init(void) { glClearColor(0.0, 0.0, 0.0, 0.0); } #include "redbook.h" /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/hello.c
C
bsd
774
/* Adapted from the Red Book */ #include <stdarg.h> #include <stdio.h> #include <aw/sysgl.h> #include <aw/sysglu.h> #include <aw/aw.h> #include "log.h" static int shoulder = 0, elbow = 0; static void drawBox(GLfloat size, GLenum type) { static GLfloat n[6][3] = { {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0} }; static GLint faces[6][4] = { {0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4}, {4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} }; GLfloat v[8][3]; GLint i; v[0][0] = v[1][0] = v[2][0] = v[3][0] = -size / 2; v[4][0] = v[5][0] = v[6][0] = v[7][0] = size / 2; v[0][1] = v[1][1] = v[4][1] = v[5][1] = -size / 2; v[2][1] = v[3][1] = v[6][1] = v[7][1] = size / 2; v[0][2] = v[3][2] = v[4][2] = v[7][2] = -size / 2; v[1][2] = v[2][2] = v[5][2] = v[6][2] = size / 2; for (i = 5; i >= 0; i--) { glBegin(type); glNormal3fv(&n[i][0]); glVertex3fv(&v[faces[i][0]][0]); glVertex3fv(&v[faces[i][1]][0]); glVertex3fv(&v[faces[i][2]][0]); glVertex3fv(&v[faces[i][3]][0]); glEnd(); } } static void init(void) { glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_FLAT); } static void display(void) { glClear (GL_COLOR_BUFFER_BIT); glPushMatrix(); glTranslatef (-1.0, 0.0, 0.0); glRotatef ((GLfloat) shoulder, 0.0, 0.0, 1.0); glTranslatef (1.0, 0.0, 0.0); glPushMatrix(); glScalef (2.0, 0.4, 1.0); drawBox(1.0, GL_LINE_LOOP); glPopMatrix(); glTranslatef (1.0, 0.0, 0.0); glRotatef ((GLfloat) elbow, 0.0, 0.0, 1.0); glTranslatef (1.0, 0.0, 0.0); glPushMatrix(); glScalef (2.0, 0.4, 1.0); drawBox(1.0, GL_LINE_LOOP); glPopMatrix(); glPopMatrix(); } static void reshape (int w, int h) { glViewport (0, 0, w, h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective(65.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef (0.0, 0.0, -5.0); } static void keyboard (unsigned char key) { switch (key) { case 's': shoulder = (shoulder + 5) % 360; break; case 'd': shoulder = (shoulder - 5) % 360; break; case 'e': elbow = (elbow + 5) % 360; break; case 'r': elbow = (elbow - 5) % 360; break; default: break; } } static void updateTitle(aw * w, int x, int y); static int processEvents(ag * g, aw * w, ac * c) { int keepgoing = 1; const ae * e; while ((e = awNextEvent(w))) switch (aeType(e)) { case AW_EVENT_RESIZE: reshape(aeWidth(e), aeHeight(e)); updateTitle(w, aeWidth(e), aeHeight(e)); break; case AW_EVENT_CLOSE: keepgoing = 0; break; case AW_EVENT_DOWN: case AW_EVENT_UP: keyboard(aeWhich(e)); break; } return keepgoing; } #define NO_HANDLER #include "redbook.h" /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/robot.c
C
bsd
2,809
#include <stdarg.h> #include <stdio.h> #if defined AWPLUGIN extern void report(const char * fmt, ...); #define Log report #else static void Log(const char * fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); printf("\n"); fflush(stdout); va_end(ap); } #endif /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/log.h
C
bsd
367
#include <aw/sysgl.h> #include <aw/aw.h> #include "log.h" static GLuint loadShader(GLenum type, const char * src) { GLuint sh = glCreateShader(type); glShaderSource(sh, 1, &src, NULL); glCompileShader(sh); return sh; } static GLuint g_prg; static GLint g_time; static void init(void) { const char vss[] = "attribute vec4 pos; \n" "uniform float t; \n" "void main() \n" "{ \n" " gl_Position = pos; \n" " gl_Position.y += sin(t) / 2.0; \n" "} \n"; const char fss[] = "precision mediump float; \n" "void main() \n" "{ \n" " gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n" "} \n"; GLuint vs, fs, prg; vs = loadShader(GL_VERTEX_SHADER, vss); fs = loadShader(GL_FRAGMENT_SHADER, fss); prg = glCreateProgram(); glAttachShader(prg, vs); glAttachShader(prg, fs); glLinkProgram(prg); g_prg = prg; glBindAttribLocation(g_prg, 0, "vPosition"); g_time = glGetUniformLocation(g_prg, "t"); } static void display(void) { GLfloat ver[] = {0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f}; static float t = 0; t += 1/60.0; glClearColor(0.7, 0.7, 0.7, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(g_prg); glUniform1f(g_time, t); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ver); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 3); } static void reshape (int w, int h) { glViewport(0, 0, w, h); } #include "redbook.h" /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/gles.c
C
bsd
1,721
static void updateTitle(aw * w, int x, int y) { char buf[16] = {0}; snprintf(buf, sizeof(buf), "%dx%d", x, y); awSetTitle(w, buf); } #if !defined NO_HANDLER static int processEvents(ag * g, aw * w, ac * c) { int keepgoing = 1; const ae * e; while ((e = awNextEvent(w))) switch (aeType(e)) { case AW_EVENT_DOWN: if (aeWhich(e) == 'f') awMaximize(w); if (aeWhich(e) == 'w') awNormalize(w); if (aeWhich(e) == 'q') keepgoing = 0; break; case AW_EVENT_RESIZE: reshape(aeWidth(e), aeHeight(e)); updateTitle(w, aeWidth(e), aeHeight(e)); break; case AW_EVENT_CLOSE: keepgoing = 0; break; default: break; } return keepgoing; } #endif static void loop(ag * g, aw * w, ac * c) { while (processEvents(g, w, c)) { awMakeCurrent(w, c); display(); awSwapBuffers(w); } } static void go(ag * g, aw * w, ac * c) { awMakeCurrent(w, c); init(); loop(g, w, c); awMakeCurrent(w, 0); awDel(w); acDel(c); agDel(g); } int main(int argc, char ** argv) { ag * g = 0; aw * w = 0; ac * c = 0; g = agNew("redbook"); if (g) w = awNew(g); else Log("unable to initialize AW"); if (!w) Log("unable to open window (is DISPLAY set?)"); if (w) c = acNew(g, 0); if (w) awGeometry(w, 100, 100, 500, 500); if (w) awShow(w); if (w) awSetInterval(w, 1); if (c) go(g, w, c); return w == 0; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/redbook.h
C
bsd
1,452
#include <aw/sysgl.h> #include <aw/aw.h> #include "log.h" static int g_exit = 0; static void processEvents(aw * w, ac * c, int n) { const ae * e; while ((e = awNextEvent(w))) switch (aeType(e)) { case AW_EVENT_RESIZE: Log("Resized %d: %d %d", n, aeWidth(e), aeHeight(e)); break; case AW_EVENT_DOWN: Log("Down %d: %d", n, aeWhich(e)); break; case AW_EVENT_UP: Log("Up %d: %d", n, aeWhich(e)); break; case AW_EVENT_MOTION: Log("Motion %d: %d,%d", n, aeX(e), aeY(e)); break; case AW_EVENT_CLOSE: Log("Exit requested"); g_exit = 1; break; } } #define NWIN 6 static void draw(int n) { float f = (float)n / NWIN; glClearColor(0, 1 - f, f, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } static void handle(aw * w, ac * c, int n) { awMakeCurrent(w, c); draw(n); awSwapBuffers(w); awMakeCurrent(w, 0); processEvents(w, c, n); } int main(int argc, char ** argv) { int i; ag * g; aw * w[NWIN]; ac * c[NWIN]; ac * ic; g = agNew("sharing"); ic = acNew(g, 0); for (i = 0; i < NWIN; i++) { c[i] = acNew(g, ic); w[i] = awNew(g); awGeometry(w[i], 100 + 16*i, 100+16*i, 300, 400); } for (i = 0; i < NWIN; i++) awSetTitle(w[i], argv[0]); for (i = 0; i < NWIN; i++) awShow(w[i]); while (!g_exit) for (i = 0; i < NWIN; i++) handle(w[i], c[i], i); for (i = 0; i < NWIN; i++) awDel(w[i]); agDel(g); return 0; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/sharing.c
C
bsd
1,474
#include <aw/aw.h> #include <aw/sysgl.h> #include "log.h" static int g_exit; static const char * g_progname; static ap * g_p = 0; static const struct gimp_image { unsigned int width; unsigned int height; unsigned int bytes_per_pixel; /* 3:RGB, 4:RGBA */ unsigned char pixel_data[32 * 32 * 4 + 1]; } gimp_image = { 32, 32, 4, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377" "\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377" "\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377" "\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377" "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377" "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" "\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" "\377\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377" "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" "\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" "\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377" "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377" "\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\377\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\377\377\377" "\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\377\377" "\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0" "\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377" "\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377" "\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377" "\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377" "\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\0\0" "\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0", }; // To test the browser plugin EXPORTED void hello() { Log("Hello World!"); } static void resize(aw * w, int ww, int wh) { char buf[256] = {0}; snprintf(buf, sizeof(buf), "%s %dx%d", g_progname, ww, wh); awSetTitle(w, buf); } static void deletePointer(aw * w) { if (g_p) { awPointer(w, 0); apDel(g_p); } } static void setCursor1(aw * w) { deletePointer(w); g_p = apNew(gimp_image.pixel_data, 10, 5); awPointer(w, g_p); } static void setCursor2(aw * w) { static unsigned char rgba[32*32*4]; int x, y; deletePointer(w); for (y = 0; y < 32; y++) { for (x = 0; x < 32; x++) { unsigned char * c = rgba + (y*32 + x) * 4; c[0] = 0; c[1] = 0; c[2] = 0; c[3] = 0xff; if ((x < 8) || (y < 8)) c[0] = 0xff; else if ((x < 16) || (y < 16)) c[1] = 0xff; else if ((x < 24) || (y < 24)) c[2] = 0xff; else c[3] = 0; } } g_p = apNew(rgba, 10, 5); awPointer(w, g_p); } static aw * processEvents(ag * g, aw * w, ac * c) { const ae * e; while ((e = awNextEvent(w))) switch (aeType(e)) { case AW_EVENT_RESIZE: resize(w, aeWidth(e), aeHeight(e)); Log("Resized to %d %d", aeWidth(e), aeHeight(e)); break; case AW_EVENT_POSITION: Log("Moved to %d %d", aeX(e), aeY(e)); break; case AW_EVENT_UNICODE: Log("Unicode: %s", aeKeyName(e)); break; case AW_EVENT_DOWN: Log("Down: %s", aeKeyName(e)); break; case AW_EVENT_UP: Log("Up: %s", aeKeyName(e)); switch (aeWhich(e)) { case AW_KEY_1: setCursor1(w); break; case AW_KEY_2: setCursor2(w); break; case AW_KEY_S: awShowBorders(w); break; case AW_KEY_H: awHideBorders(w); break; case AW_KEY_M: awMaximize(w); break; case AW_KEY_N: awNormalize(w); break; case AW_KEY_V: { static int v = 0; v = 1 - v; awGeometry(w, 100-v*20, 200-v*20, 300+v*40, 400+v*40); } break; case AW_KEY_Q: g_exit = 1; break; default: break; } break; case AW_EVENT_MOTION: Log("Motion: %d,%d", aeX(e), aeY(e)); break; case AW_EVENT_EXPOSED: Log("Exposed"); break; case AW_EVENT_KILLFOCUS: Log("Kill focus"); break; case AW_EVENT_SETFOCUS: Log("Set focus"); break; case AW_EVENT_DROP: Log("Drop %s", aePath(e)); break; case AW_EVENT_CLOSE: Log("Exit requested"); g_exit = 1; break; default: break; } if (awPressed(w, AW_KEY_A)) Log("a pressed"); if (awPressed(w, AW_KEY_MOUSELEFT)) Log("mleft pressed"); if (awPressed(w, AW_KEY_MOUSERIGHT)) Log("mright pressed"); return w; } static void draw() { static int i = 0; glClearColor((i++ & 0xff) / 255.0f, 0.f, 1.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFlush(); } int main(int argc, char ** argv) { ag * g = 0; aw * w = 0; ac * c = 0; g_progname = argv[0]; g = agNew("awtest"); if (g) w = awNew(g); if (g) c = acNew(g, 0); awSetInterval(w, 1); awMakeCurrent(w, c); awGeometry(w, 100, 200, 300, 400); awShow(w); g_exit = 0; while (!g_exit) { // Log("Z order: %d", awOrder(w)); w = processEvents(g, w, c); if (!g_exit) { draw(); awSwapBuffers(w); } } awMakeCurrent(w, 0); deletePointer(w); acDel(c); awDel(w); agDel(g); return 0; } /* Local variables: ** c-file-style: "bsd" ** indent-tabs-mode: nil ** End: ** */
zzywany123-libaw-1
test/awtest.c
C
bsd
15,842
/* Adapted from the Red Book */ #include <stdarg.h> #include <stdio.h> #include <aw/sysgl.h> #include <aw/sysglu.h> #include <aw/aw.h> static GLuint startList; static void errorCallback(GLenum errorCode) { Log("Quadric Error: %s", gluErrorString(errorCode)); } static void init(void) { GLUquadricObj *qobj; GLfloat mat_ambient[] = { 0.5, 0.5, 0.5, 1.0 }; GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat mat_shininess[] = { 50.0 }; GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 }; GLfloat model_ambient[] = { 0.5, 0.5, 0.5, 1.0 }; glClearColor(0.0, 0.0, 0.0, 0.0); glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, model_ambient); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); /* Create 4 display lists, each with a different quadric object. * Different drawing styles and surface normal specifications * are demonstrated. */ startList = glGenLists(4); qobj = gluNewQuadric(); gluQuadricCallback(qobj, GLU_ERROR, errorCallback); gluQuadricDrawStyle(qobj, GLU_FILL); /* smooth shaded */ gluQuadricNormals(qobj, GLU_SMOOTH); glNewList(startList, GL_COMPILE); gluSphere(qobj, 0.75, 15, 10); glEndList(); gluQuadricDrawStyle(qobj, GLU_FILL); /* flat shaded */ gluQuadricNormals(qobj, GLU_FLAT); glNewList(startList+1, GL_COMPILE); gluCylinder(qobj, 0.5, 0.3, 1.0, 15, 5); glEndList(); gluQuadricDrawStyle(qobj, GLU_LINE); /* all polygons wireframe */ gluQuadricNormals(qobj, GLU_NONE); glNewList(startList+2, GL_COMPILE); gluDisk(qobj, 0.25, 1.0, 20, 4); glEndList(); gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); /* boundary only */ gluQuadricNormals(qobj, GLU_NONE); glNewList(startList+3, GL_COMPILE); gluPartialDisk(qobj, 0.0, 1.0, 20, 4, 0.0, 225.0); glEndList(); } static void display(void) { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); glEnable(GL_LIGHTING); glShadeModel (GL_SMOOTH); glTranslatef(-1.0, -1.0, 0.0); glCallList(startList); glShadeModel (GL_FLAT); glTranslatef(0.0, 2.0, 0.0); glPushMatrix(); glRotatef(300.0, 1.0, 0.0, 0.0); glCallList(startList+1); glPopMatrix(); glDisable(GL_LIGHTING); glColor3f(0.0, 1.0, 1.0); glTranslatef(2.0, -2.0, 0.0); glCallList(startList+2); glColor3f(1.0, 1.0, 0.0); glTranslatef(0.0, 2.0, 0.0); glCallList(startList+3); glPopMatrix(); glFlush(); } static void resize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho(-2.5, 2.5, -2.5*(GLfloat)h/(GLfloat)w, 2.5*(GLfloat)h/(GLfloat)w, -10.0, 10.0); else glOrtho(-2.5*(GLfloat)w/(GLfloat)h, 2.5*(GLfloat)w/(GLfloat)h, -2.5, 2.5, -10.0, 10.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } static int processEvents(aw * w, ac * c) { int keepgoing = 1; const awEvent * e; while ((e = awNextEvent(w))) switch (aeType(e)) { case AW_EVENT_RESIZE: resize(aeWidth(e), aeHeight(e)); break; case AW_EVENT_CLOSE: keepgoing = 0; break; } return keepgoing; } #include "redbook.h" /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/quadric.c
C
bsd
3,292
#include <aw/sysgl.h> #include <aw/aw.h> #include "log.h" static int g_exit = 0; static void processEvents(aw * w, ac * c, int n) { const ae * e; while ((e = awNextEvent(w))) switch (aeType(e)) { case AW_EVENT_RESIZE: Log("Resized %d: %d %d", n, aeWidth(e), aeHeight(e)); break; case AW_EVENT_DOWN: Log("Down %d: %d", n, aeWhich(e)); break; case AW_EVENT_UP: Log("Up %d: %d", n, aeWhich(e)); break; case AW_EVENT_MOTION: Log("Motion %d: %d,%d", n, aeX(e), aeY(e)); break; case AW_EVENT_CLOSE: Log("Exit requested"); g_exit = 1; break; } } #define NWIN 2 static void draw(int n) { float f = (float)n / NWIN; glClearColor(0, 1 - f, f, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } static void handle(aw * w, ac * c, int n) { awMakeCurrent(w, c); draw(n); awSwapBuffers(w); awMakeCurrent(w, 0); processEvents(w, c, n); } int main(int argc, char ** argv) { int i; aw * w[NWIN]; ac * c; ag * g; g = agNew("multi"); c = acNew(g, 0); for (i = 0; i < NWIN; i++) w[i] = awNew(g); for (i = 0; i < NWIN; i++) awSetInterval(w[i], 1); for (i = 0; i < NWIN; i++) awGeometry(w[i], 100 + 16*i, 100+16*i, 300, 400); for (i = 0; i < NWIN; i++) awSetTitle(w[i], argv[0]); for (i = 0; i < NWIN; i++) awShow(w[i]); while (!g_exit) for (i = 0; i < NWIN; i++) { Log("Order %d %d", i, awOrder(w[i])); handle(w[i], c, i); } for (i = 0; i < NWIN; i++) awDel(w[i]); agDel(g); return 0; } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/multi.c
C
bsd
1,611
static void drawBox(GLfloat size, GLenum type) { static GLfloat n[6][3] = { {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0} }; static GLint faces[6][4] = { {0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4}, {4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} }; GLfloat v[8][3]; GLint i; v[0][0] = v[1][0] = v[2][0] = v[3][0] = -size / 2; v[4][0] = v[5][0] = v[6][0] = v[7][0] = size / 2; v[0][1] = v[1][1] = v[4][1] = v[5][1] = -size / 2; v[2][1] = v[3][1] = v[6][1] = v[7][1] = size / 2; v[0][2] = v[3][2] = v[4][2] = v[7][2] = -size / 2; v[1][2] = v[2][2] = v[5][2] = v[6][2] = size / 2; for (i = 5; i >= 0; i--) { glBegin(type); glNormal3fv(&n[i][0]); glVertex3fv(&v[faces[i][0]][0]); glVertex3fv(&v[faces[i][1]][0]); glVertex3fv(&v[faces[i][2]][0]); glVertex3fv(&v[faces[i][3]][0]); glEnd(); } } /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/drawbox.h
C
bsd
1,001
/* Adapted from the Red Book */ #include <aw/sysgl.h> #include <aw/sysglu.h> #include <aw/aw.h> #include "log.h" #include "drawbox.h" static void init(void) { glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_FLAT); } static void display(void) { static int angle = 0; glClear (GL_COLOR_BUFFER_BIT); glColor3f (1.0, 1.0, 1.0); glLoadIdentity (); /* clear the matrix */ /* viewing transformation */ gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glScalef (1.0, 1.0, 1.0); /* modeling transformation */ glRotatef(angle++, 0,0,1); drawBox(1.0, GL_LINE_LOOP); glFlush (); } static void reshape (int w, int h) { float aspect = (float)w / h; glViewport (0, 0, w, h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glFrustum (-aspect, aspect, -1.0, 1.0, 1.5, 20.0); glMatrixMode (GL_MODELVIEW); } #include "redbook.h" /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/cube.c
C
bsd
960
/* Adapted from the Red Book */ #include <stdarg.h> #include <stdio.h> #include <aw/sysgl.h> #include <aw/sysglu.h> #include <aw/aw.h> #include "log.h" static int board[3][3]; /* amount of color for each square*/ /* Clear color value for every square on the board */ static void init(void) { int i, j; for (i = 0; i < 3; i++) for (j = 0; j < 3; j ++) board[i][j] = 0; glClearColor (0.0, 0.0, 0.0, 0.0); } /* The nine squares are drawn. In selection mode, each * square is given two names: one for the row and the * other for the column on the grid. The color of each * square is determined by its position on the grid, and * the value in the board[][] array. */ static void drawSquares(GLenum mode) { GLuint i, j; for (i = 0; i < 3; i++) { if (mode == GL_SELECT) glLoadName (i); for (j = 0; j < 3; j ++) { if (mode == GL_SELECT) glPushName (j); glColor3f ((GLfloat) i/3.0, (GLfloat) j/3.0, (GLfloat) board[i][j]/3.0); glRecti (i, j, i+1, j+1); if (mode == GL_SELECT) glPopName (); } } } /* processHits prints out the contents of the * selection array. */ static void processHits (GLint hits, GLuint buffer[]) { unsigned int i, j; GLuint ii=0, jj=0, names, *ptr; Log("hits = %d", (int)hits); ptr = (GLuint *) buffer; for (i = 0; i < hits; i++) {/* for each hit */ names = *ptr; Log(" number of names for this hit = %d", names); ptr++; Log(" z1 is %g;", (float) *ptr/0x7fffffff); ptr++; Log(" z2 is %g", (float) *ptr/0x7fffffff); ptr++; Log(" names are: "); for (j = 0; j < names; j++) { /* for each name */ Log(" %d ", *ptr); if (j == 0) /* set row and column */ ii = *ptr; else if (j == 1) jj = *ptr; ptr++; } board[ii][jj] = (board[ii][jj] + 1) % 3; } } /* pickSquares() sets up selection mode, name stack, * and projection matrix for picking. Then the * objects are drawn. */ #define BUFSIZE 512 static void pickSquares(int x, int y) { GLuint selectBuf[BUFSIZE]; GLint hits; GLint viewport[4]; glGetIntegerv (GL_VIEWPORT, viewport); glSelectBuffer (BUFSIZE, selectBuf); (void) glRenderMode (GL_SELECT); glInitNames(); glPushName(0); glMatrixMode (GL_PROJECTION); glPushMatrix (); glLoadIdentity (); /* create 5x5 pixel picking region near cursor location*/ gluPickMatrix ((GLdouble) x, (GLdouble) (viewport[3] - y), 5.0, 5.0, viewport); gluOrtho2D (0.0, 3.0, 0.0, 3.0); drawSquares (GL_SELECT); glMatrixMode (GL_PROJECTION); glPopMatrix (); glFlush (); hits = glRenderMode (GL_RENDER); processHits (hits, selectBuf); } static void display(void) { glClear(GL_COLOR_BUFFER_BIT); drawSquares (GL_RENDER); glFlush(); } static void reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D (0.0, 3.0, 0.0, 3.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } static void updateTitle(aw * w, int x, int y); static int processEvents(ag * g, aw * w, ac * c) { int keepgoing = 1; static int s_x = 0; static int s_y = 0; const ae * e; while ((e = awNextEvent(w))) switch (aeType(e)) { case AW_EVENT_RESIZE: reshape(aeWidth(e), aeHeight(e)); updateTitle(w, aeWidth(e), aeHeight(e)); break; case AW_EVENT_CLOSE: keepgoing = 0; break; case AW_EVENT_MOTION: s_x = aeX(e); s_y = aeY(e); break; case AW_EVENT_DOWN: if (aeWhich(e) == AW_KEY_MOUSELEFT) pickSquares(s_x, s_y); break; default: break; } return keepgoing; } #define NO_HANDLER #include "redbook.h" /* Local variables: ** c-file-style: "bsd" ** c-basic-offset: 8 ** End: ** */
zzywany123-libaw-1
test/picksquare.c
C
bsd
3,621
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Samples.Helper; namespace Tasks.ASP.NET.SimpleOAuth2 { /// <summary> /// This class provides the client credentials for all the samples in this solution. /// In order to run all of the samples, you have to enable API access for every API /// you want to use, enter your credentials here. /// /// You can find your credentials here: /// https://code.google.com/apis/console/#:access /// /// For your own application you should find a more secure way than just storing your client secret inside a string, /// as it can be lookup up easily using a reflection tool. /// </summary> internal static class ClientCredentials { /// <summary> /// The OAuth2.0 Client ID of your project. /// </summary> public static readonly string ClientID = "<Enter your ClientID here>"; /// <summary> /// The OAuth2.0 Client secret of your project. /// </summary> public static readonly string ClientSecret = "<Enter your ClientSecret here>"; /// <summary> /// Your Api/Developer key. /// </summary> public static readonly string ApiKey = "<Enter your ApiKey here>"; #region Verify Credentials static ClientCredentials() { ReflectionUtils.VerifyCredentials(typeof(ClientCredentials)); } #endregion } }
zzfocuzz-
Tasks.ASP.NET.SimpleOAuth2/ClientCredentials.cs
C#
asf20
2,021
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.ASP.NET.SimpleOAuth2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Tasks.ASP.NET.SimpleOAuth2")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3eab9992-044c-4242-a089-7c5df8dcac76")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-
Tasks.ASP.NET.SimpleOAuth2/Properties/AssemblyInfo.cs
C#
asf20
1,441
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Linq; using System.Threading; using System.Web; using System.Web.UI.WebControls; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Services; using Google.Apis.Samples.Helper; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace Tasks.ASP.NET.SimpleOAuth2 { /// <summary> /// This sample uses the Tasks service and OAuth2 authentication /// to list all of your tasklists and tasks. /// </summary> public partial class _Default : System.Web.UI.Page { private static TasksService _service; // We don't need individual service instances for each client. private static OAuth2Authenticator<WebServerClient> _authenticator; private IAuthorizationState _state; /// <summary> /// Returns the authorization state which was either cached or set for this session. /// </summary> private IAuthorizationState AuthState { get { return _state ?? HttpContext.Current.Session["AUTH_STATE"] as IAuthorizationState; } } protected void Page_Load(object sender, EventArgs e) { // Create the Tasks-Service if it is null. if (_service == null) { _authenticator = CreateAuthenticator(); _service = new TasksService(new BaseClientService.Initializer() { Authenticator = _authenticator, ApplicationName = "Tasks API Sample", }); } // Check if we received OAuth2 credentials with this request; if yes: parse it. if (HttpContext.Current.Request["code"] != null) { _authenticator.LoadAccessToken(); } // Change the button depending on our auth-state. listButton.Text = AuthState == null ? "Authenticate" : "Fetch Tasklists"; } private OAuth2Authenticator<WebServerClient> CreateAuthenticator() { // Register the authenticator. var provider = new WebServerClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = ClientCredentials.ClientID; provider.ClientSecret = ClientCredentials.ClientSecret; var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true }; return authenticator; } private IAuthorizationState GetAuthorization(WebServerClient client) { // If this user is already authenticated, then just return the auth state. IAuthorizationState state = AuthState; if (state != null) { return state; } // Check if an authorization request already is in progress. state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request)); if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken))) { // Store and return the credentials. HttpContext.Current.Session["AUTH_STATE"] = _state = state; return state; } // Otherwise do a new authorization request. string scope = TasksService.Scopes.TasksReadonly.GetStringValue(); OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope }); response.Send(); // Will throw a ThreadAbortException to prevent sending another response. return null; } /// <summary> /// Gets the TasksLists of the user. /// </summary> public void FetchTaskslists() { try { // Execute all TasksLists of the user asynchronously. TaskLists response = _service.Tasklists.List().Execute(); ShowTaskslists(response); } catch (ThreadAbortException) { // User was not yet authenticated and is being forwarded to the authorization page. throw; } catch (Exception ex) { output.Text = ex.ToHtmlString(); } } private void ShowTaskslists(TaskLists response) { if (response.Items == null) // If no item is in the response, .Items will be null. { output.Text += "You have no task lists!<br/>"; return; } output.Text += "Showing task lists...<br/>"; foreach (TaskList list in response.Items) { Panel listPanel = new Panel() { BorderWidth = Unit.Pixel(1), BorderColor = Color.Black }; listPanel.Controls.Add(new Label { Text = list.Title }); listPanel.Controls.Add(new Label { Text = "<hr/>" }); listPanel.Controls.Add(new Label { Text = GetTasks(list) }); lists.Controls.Add(listPanel); } } private string GetTasks(TaskList taskList) { var tasks = _service.Tasks.List(taskList.Id).Execute(); if (tasks.Items == null) { return "<i>No items</i>"; } var query = from t in tasks.Items select t.Title; return query.Select((str) => "&bull; " + str).Aggregate((a, b) => a + "<br/>" + b); } protected void listButton_Click(object sender, EventArgs e) { FetchTaskslists(); } } }
zzfocuzz-
Tasks.ASP.NET.SimpleOAuth2/Default.aspx.cs
C#
asf20
6,558
<%@ Page Language="C#" EnableSessionState="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Async="true" Inherits="Tasks.ASP.NET.SimpleOAuth2._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <h1>ASP.NET Tasks API &ndash; OAuth2 Sample</h1> <form id="mainForm" runat="server"> Click the button below to authorize this application/list all TaskLists and Tasks. <br/><br/> <div> &nbsp; &nbsp; <asp:Button ID="listButton" runat="server" Text="List Tasks!" onclick="listButton_Click" /> </div> <br/> <asp:PlaceHolder ID="lists" runat="server"></asp:PlaceHolder><br/> <asp:Label ID="output" runat="server"></asp:Label> </form> <p> <i>&copy; 2011 Google Inc</i> </p> </body> </html>
zzfocuzz-
Tasks.ASP.NET.SimpleOAuth2/Default.aspx
ASP.NET
asf20
1,009
<html> <title>Google .NET Client API &ndash; Tasks.ASP.NET.SimpleOAuth2</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.ASP.NET.SimpleOAuth2</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.ASP.NET.SimpleOAuth2">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ASP.NET.SimpleOAuth2/Default.aspx.cs?repo=samples">Default.aspx.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> <li>Edit <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ASP.NET.SimpleOAuth2/ClientCredentials.cs?repo=samples">ClientCredentials.cs</a> to insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane.</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Run the webpage using the builtin Visual Studio ASP.NET server (press F5)</li> </ul> </body> </html>
zzfocuzz-
Tasks.ASP.NET.SimpleOAuth2/README.html
HTML
asf20
1,848
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Authentication; using Google.Apis.Samples.Helper; using Google.Apis.Urlshortener.v1; using Google.Apis.Urlshortener.v1.Data; namespace Google.Apis.Samples.CmdUrlShortener { /// <summary> /// This example shows you how to use a CodeGenerated library to access Google APIs. /// In this case the URLShortener service is used to execute simple resolve & get requests. /// </summary> internal class Program { /// <summary> /// Main method /// </summary> internal static void Main(string[] args) { // Initialize this sample CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("URL Shortener"); // Create the service var service = new UrlshortenerService(); // Ask the user what he wants to do CommandLine.RequestUserChoice( "What do you want to do?", new UserOption("Create a short URL", () => CreateShortURL(service)), new UserOption("Resolve a short URL", () => ResolveShortURL(service))); CommandLine.PressAnyKeyToExit(); } private static void ResolveShortURL(UrlshortenerService service) { // Request input string urlToResolve = "http://goo.gl/hcEg7"; CommandLine.RequestUserInput("URL to resolve", ref urlToResolve); CommandLine.WriteLine(); // Resolve URL Url response = service.Url.Get(urlToResolve).Execute(); // Display response CommandLine.WriteLine(" ^1Status: ^9{0}", response.Status); CommandLine.WriteLine(" ^1Long URL: ^9{0}", response.LongUrl); } private static void CreateShortURL(UrlshortenerService service) { // Request input string urlToShorten = "http://maps.google.com/"; CommandLine.RequestUserInput("URL to shorten", ref urlToShorten); CommandLine.WriteLine(); // Shorten URL Url response = service.Url.Insert(new Url { LongUrl = urlToShorten }).Execute(); // Display response CommandLine.WriteLine(" ^1Short URL: ^9{0}", response.Id); } } }
zzfocuzz-
UrlShortener.ShortenURL/Program.cs
C#
asf20
2,910
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Urlshortener.v1.Cmd")] [assembly: AssemblyDescription("URL Shortener Sample")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Urlshortener.v1.Cmd")] [assembly: AssemblyCopyright("© 2011 Google Inc")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b4e58c0f-6600-4d38-b92a-97149c9ec01a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-
UrlShortener.ShortenURL/Properties/AssemblyInfo.cs
C#
asf20
1,446
<html> <title>Google .NET Client API &ndash; UrlShortener.ShortenURL</title> <body> <h2>Instructions for the Google .NET Client API &ndash; UrlShortener.ShortenURL</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FUrlShortener.ShortenURL">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/UrlShortener.ShortenURL/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the UrlShortener API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>UrlShortener.ShortenURL\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-
UrlShortener.ShortenURL/README.html
HTML
asf20
1,675
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Urlshortener.v1; using Google.Apis.Urlshortener.v1.Data; using Google.Apis.Util; namespace UrlShortener.ListURLs { /// <summary> /// URLShortener OAuth2 Sample /// /// This sample uses OAuth2 to retrieve a list of all the URL's you have shortened so far. /// </summary> internal class Program { private static readonly string Scope = UrlshortenerService.Scopes.Urlshortener.GetStringValue(); static void Main(string[] args) { // Initialize this sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("URLShortener -- List URLs"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret, }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); // Create the service. var service = new UrlshortenerService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "UrlShortener API Sample", }); // List all shortened URLs: CommandLine.WriteAction("Retrieving list of shortened urls..."); int i = 0; string nextPageToken = null; do { // Create and execute the request. var request = service.Url.List(); request.StartToken = nextPageToken; UrlHistory result = request.Execute(); // List all items on this page. if (result.Items != null) { foreach (Url item in result.Items) { CommandLine.WriteResult((++i) + ".) URL", item.Id + " -> " + item.LongUrl); } } // Continue with the next page nextPageToken = result.NextPageToken; } while (!string.IsNullOrEmpty(nextPageToken)); if (i == 0) { CommandLine.WriteAction("You don't have any shortened URLs! Visit http://goo.gl and create some."); } // ... and we are done. CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.urlshortener"; const string KEY = "S7Uf8AsapUWrac798uga5U8e5azePhAf"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } } }
zzfocuzz-
UrlShortener.ListURLs/Program.cs
C#
asf20
4,769
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UrlShortener.ListURLs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("UrlShortener.ListURLs")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a9aca0ea-7fb7-44ee-8874-dcc4519ffe0d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-
UrlShortener.ListURLs/Properties/AssemblyInfo.cs
C#
asf20
1,434
<html> <title>Google .NET Client API &ndash; UrlShortener.ListURLs</title> <body> <h2>Instructions for the Google .NET Client API &ndash; UrlShortener.ListURLs</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FUrlShortener.ListURLs">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/UrlShortener.ListURLs/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the UrlShortener API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>UrlShortener.ListURLs\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-
UrlShortener.ListURLs/README.html
HTML
asf20
1,665
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("Calendar.VB.ConsoleApp")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Google")> <Assembly: AssemblyProduct("Calendar.VB.ConsoleApp")> <Assembly: AssemblyCopyright("Copyright © Google 2013")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("72b4cdb2-a015-4731-8d87-304369908274")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
zzfocuzz-
Calendar.VB.ConsoleApp/My Project/AssemblyInfo.vb
Visual Basic .NET
asf20
1,210
'Copyright 2013 Google Inc 'Licensed under the Apache License, Version 2.0(the "License"); 'you may not use this file except in compliance with the License. 'You may obtain a copy of the License at ' http://www.apache.org/licenses/LICENSE-2.0 'Unless required by applicable law or agreed to in writing, software 'distributed under the License is distributed on an "AS IS" BASIS, 'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 'See the License for the specific language governing permissions and 'limitations under the License. Imports System.Collections.Generic Imports DotNetOpenAuth.OAuth2 Imports Google.Apis.Authentication.OAuth2 Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth Imports Google.Apis.Calendar.v3 Imports Google.Apis.Calendar.v3.Data Imports Google.Apis.Calendar.v3.EventsResource Imports Google.Apis.Samples.Helper Imports Google.Apis.Services Imports Google.Apis.Util ''' <summary> ''' An sample for the Calendar API which displays a list of calendars and events in the first calendar. ''' https://developers.google.com/google-apps/calendar/ ''' </summary> Module Program '' Calendar scopes which is initialized on the main method Dim scopes As IList(Of String) = New List(Of String)() '' Calendar service Dim service As CalendarService Sub Main() ' Add the calendar specific scope to the scopes list scopes.Add(CalendarService.Scopes.Calendar.GetStringValue()) ' Display the header and initialize the sample CommandLine.EnableExceptionHandling() CommandLine.DisplayGoogleSampleHeader("Google.Api.Calendar.v3 Sample") ' Create the authenticator Dim credentials As FullClientCredentials = PromptingClientCredentials.EnsureFullClientCredentials() Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description) provider.ClientIdentifier = credentials.ClientId provider.ClientSecret = credentials.ClientSecret Dim auth As New OAuth2Authenticator(Of NativeApplicationClient)(provider, AddressOf GetAuthorization) ' Create the calendar service using an initializer instance Dim initializer As New BaseClientService.Initializer() initializer.Authenticator = auth service = New CalendarService(initializer) ' Fetch the list of calendar list Dim list As IList(Of CalendarListEntry) = service.CalendarList.List().Execute().Items() ' Display all calendars DisplayList(list) For Each calendar As Data.CalendarListEntry In list ' Display calendar's events DisplayFirstCalendarEvents(calendar) Next CommandLine.PressAnyKeyToExit() End Sub Function GetAuthorization(client As NativeApplicationClient) As IAuthorizationState ' You should use a more secure way of storing the key here as ' .NET applications can be disassembled using a reflection tool. Const STORAGE As String = "google.samples.dotnet.calendar" Const KEY As String = "s0mekey" ' Check if there is a cached refresh token available. Dim state As IAuthorizationState = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY) If Not state Is Nothing Then Try client.RefreshToken(state) Return state ' we are done Catch ex As DotNetOpenAuth.Messaging.ProtocolException CommandLine.WriteError("Using an existing refresh token failed: " + ex.Message) CommandLine.WriteLine() End Try End If ' Retrieve the authorization from the user state = AuthorizationMgr.RequestNativeAuthorization(client, scopes.ToArray()) AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state) Return state End Function ''' <summary>Displays all calendars.</summary> Private Sub DisplayList(list As IList(Of CalendarListEntry)) CommandLine.WriteLine("Lists of calendars:") For Each item As CalendarListEntry In list CommandLine.WriteResult(item.Summary, "Location: " & item.Location & ", TimeZone: " & item.TimeZone) Next End Sub ''' <summary>Displays the calendar's events.</summary> Private Sub DisplayFirstCalendarEvents(list As CalendarListEntry) CommandLine.WriteLine(Environment.NewLine & "Maximum 5 first events from {0}:", list.Summary) Dim requeust As ListRequest = service.Events.List(list.Id) ' Set MaxResults and TimeMin with sample values requeust.MaxResults = 5 requeust.TimeMin = "2012-01-01T00:00:00-00:00" ' Fetch the list of events For Each calendarEvent As Data.Event In requeust.Execute().Items Dim startDate As String = "Unspecified" If (Not calendarEvent.Start Is Nothing) Then If (Not calendarEvent.Start.Date Is Nothing) Then startDate = calendarEvent.Start.Date.ToString() End If End If CommandLine.WriteResult(calendarEvent.Summary, "Start at: " & startDate) Next End Sub End Module
zzfocuzz-
Calendar.VB.ConsoleApp/Program.vb
Visual Basic .NET
asf20
5,307
<html> <title>Google .NET Client API &ndash; Calendar.VB.ConsoleApp</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Calendar.VB.ConsoleApp</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FCalendar.VB.ConsoleApp">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Calendar.VB.ConsoleApp/Program.vb?repo=samples">Program.vb</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Calendar.VB.ConsoleApp\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-
Calendar.VB.ConsoleApp/README.html
HTML
asf20
1,480
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Linq; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Services; using Google.Apis.Samples.Helper; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace TasksSample.CreateTasks { /// <summary> /// Tasks API sample using OAuth2. /// This sample demonstrates how to use OAuth2 and how to request an access code. /// The application will only ask you to grant access to this sample once, even when run multiple times. /// </summary> internal class Program { private const string SampleListName = ".NET Tasks API Example"; private static readonly string Scope = TasksService.Scopes.Tasks.GetStringValue(); public static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Tasks API"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); // Create the service. var service = new TasksService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Tasks API Sample", }); // Execute request: Create sample list. if (!ListExists(service, SampleListName) && CommandLine.RequestUserChoice("Do you want to create a sample list?")) { CreateSampleTasklist(service); } CommandLine.WriteLine(); // Execute request: List task-lists. ListTaskLists(service); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.siteverification"; const string KEY = "y},drdzf11x9;87"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } private static bool ListExists(TasksService service, string list) { return (from TaskList taskList in service.Tasklists.List().Execute().Items where taskList.Title == list select taskList).Count() > 0; } private static void CreateSampleTasklist(TasksService service) { var list = new TaskList(); list.Title = SampleListName; list = service.Tasklists.Insert(list).Execute(); service.Tasks.Insert(new Task { Title = "Test the Tasklist API" }, list.Id).Execute(); service.Tasks.Insert(new Task { Title = "Do the laundry" }, list.Id).Execute(); } private static void ListTaskLists(TasksService service) { CommandLine.WriteLine(" ^1Task lists:"); var list = service.Tasklists.List().Execute(); foreach (var item in list.Items) { CommandLine.WriteLine(" ^2" + item.Title); Tasks tasks = service.Tasks.List(item.Id).Execute(); if (tasks.Items != null) { foreach (Task t in tasks.Items) { CommandLine.WriteLine(" ^4" + t.Title); } } } } } }
zzfocuzz-
Tasks.CreateTasks/Program.cs
C#
asf20
5,527
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.CreateTasks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Tasks.CreateTasks")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c85adfc3-ca73-4eea-8d59-db3bf2769a44")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-
Tasks.CreateTasks/Properties/AssemblyInfo.cs
C#
asf20
1,466
<html> <title>Google .NET Client API &ndash; Tasks.CreateTasks</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.CreateTasks</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.CreateTasks">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.CreateTasks/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Tasks.CreateTasks\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-
Tasks.CreateTasks/README.html
HTML
asf20
1,638
@echo off EnterCredentials\static\EnterCredentials.exe %1 %2 %3 %4 %5 %6 %7 %8
zzfocuzz-
enterCredentials.cmd
Batchfile
asf20
79
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using Google.Apis.Tasks.v1.Data; namespace TasksExample.WinForms.NoteMgr { /// <summary> /// A single graphical note. /// </summary> public partial class NoteItem : UserControl { /// <summary> /// The text this note contains. /// </summary> [Category("Note")] public string NoteText { get { return text.Text; } set { text.Text = value; } } /// <summary> /// Whether this note is finished or not. /// </summary> [Category("Note")] public bool NoteFinished { get { return checkbox.Checked; } set { checkbox.Checked = value; } } /// <summary> /// The related remote task. /// </summary> public Task RelatedTask { get; set; } /// <summary> /// Called whenever the user wants to create a new note. /// </summary> public event Action NewNoteRequest; /// <summary> /// Called whenever the user wants to delete a note. /// </summary> public event Action<NoteItem> DeleteNoteRequest; /// <summary> /// Called whenever this note is changed by the user. /// </summary> public event Action<NoteItem> OnNoteChanged; public NoteItem() { InitializeComponent(); Dock = DockStyle.Top; } /// <summary> /// Creates a new note item and associates the action events with the specified NoteForm. /// </summary> public NoteItem(NoteForm form, Task relatedTask) : this() { NewNoteRequest += form.AddNote; DeleteNoteRequest += form.DeleteNote; RelatedTask = relatedTask; if (relatedTask != null) { // Use data from the related task. NoteText = relatedTask.Title; NoteFinished = relatedTask.Status == "completed"; } } /// <summary> /// Focuses this note. /// </summary> public void FocusNote() { text.Focus(); } /// <summary> /// Synchronizes changes between this visual note and the related task. /// </summary> /// <returns>True if there have been any changes.</returns> public bool ClientSync() { if (RelatedTask == null) { RelatedTask = new Task(); RelatedTask.Title = NoteText; RelatedTask.Status = NoteFinished ? "completed" : "needsAction"; return true; // Nothing to sync here. } bool changes = false; // Detect changes. if (NoteText != RelatedTask.Title) { RelatedTask.Title = NoteText; changes = true; } if (NoteFinished != (!string.IsNullOrEmpty(RelatedTask.Completed))) { RelatedTask.Status = NoteFinished ? "completed" : "needsAction"; changes = true; } return changes; } private void NoteItem_Paint(object sender, PaintEventArgs e) { // Draw a small, red line on the bottom. int y = ClientSize.Height - 1; e.Graphics.DrawLine(Pens.Pink, 0, y, ClientSize.Width, y); } private void text_KeyDown(object sender, KeyEventArgs e) { if (text.Text.Length == 0 && e.KeyCode == Keys.Back && DeleteNoteRequest != null) { // Delete request. DeleteNoteRequest(this); } else if (text.Text.Length > 0 && e.KeyCode == Keys.Enter && NewNoteRequest != null) { // New note request. NewNoteRequest(); } } private void text_TextChanged(object sender, EventArgs e) { if (text.TextLength > 0 && OnNoteChanged != null) { OnNoteChanged(this); } } private void checkbox_CheckedChanged(object sender, EventArgs e) { text.Font = new Font(text.Font, checkbox.Checked ? FontStyle.Strikeout : FontStyle.Regular); text.ForeColor = checkbox.Checked ? Color.DarkGray : Color.Black; } } }
zzfocuzz-
Tasks.WinForms.NoteMgr/NoteItem.cs
C#
asf20
5,238
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Windows.Forms; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace TasksExample.WinForms.NoteMgr { /// <summary> /// Note Manager /// A more complex example for the tasks API. /// </summary> internal static class Program { /// <summary> /// The remote service on which all the requests are executed. /// </summary> public static TasksService Service { get; private set; } private static IAuthenticator CreateAuthenticator() { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = ClientCredentials.ClientID; provider.ClientSecret = ClientCredentials.ClientSecret; return new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.tasks"; const string KEY = "y},drdzf11x9;87"; string scope = TasksService.Scopes.Tasks.GetStringValue(); // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Initialize the service. Service = new TasksService(new BaseClientService.Initializer() { Authenticator = CreateAuthenticator(), ApplicationName = "Tasks API Sample" }); // Open a NoteForm for every task list. foreach (TaskList list in Service.Tasklists.List().Execute().Items) { // Open a NoteForm. new NoteForm(list).Show(); } Application.Run(); } } }
zzfocuzz-
Tasks.WinForms.NoteMgr/Program.cs
C#
asf20
3,903
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Samples.Helper; namespace TasksExample.WinForms.NoteMgr { /// <summary> /// This class provides the client credentials for all the samples in this solution. /// In order to run all of the samples, you have to enable API access for every API /// you want to use, enter your credentials here. /// /// You can find your credentials here: /// https://code.google.com/apis/console/#:access /// /// For your own application you should find a more secure way than just storing your client secret inside a string, /// as it can be lookup up easily using a reflection tool. /// </summary> internal static class ClientCredentials { /// <summary> /// The OAuth2.0 Client ID of your project. /// </summary> public static readonly string ClientID = "<Enter your ClientID here>"; /// <summary> /// The OAuth2.0 Client secret of your project. /// </summary> public static readonly string ClientSecret = "<Enter your ClientSecret here>"; /// <summary> /// Your Api/Developer key. /// </summary> public static readonly string ApiKey = "<Enter your ApiKey here>"; #region Verify Credentials static ClientCredentials() { ReflectionUtils.VerifyCredentials(typeof(ClientCredentials)); } #endregion } }
zzfocuzz-
Tasks.WinForms.NoteMgr/ClientCredentials.cs
C#
asf20
2,024
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading; using System.Windows.Forms; using Google.Apis.Tasks.v1.Data; namespace TasksExample.WinForms.NoteMgr { /// <summary> /// Visual representation of a tasklist. /// </summary> public partial class NoteForm : Form { private readonly List<NoteItem> deletedNotes = new List<NoteItem>(); private readonly TaskList taskList; private readonly object sync = new object(); public NoteForm() { InitializeComponent(); AddNote(); } public NoteForm(TaskList taskList) { InitializeComponent(); this.taskList = taskList; // Set the title. Text = taskList.Title; // Load all notes: Tasks tasks = Program.Service.Tasks.List(taskList.Id).Execute(); if (tasks.Items != null) { foreach (Task task in tasks.Items) { AddNote(task); } } else { AddNote(); } } /// <summary> /// Adds a new empty note to the note list. /// </summary> public void AddNote() { AddNote(null).FocusNote(); } /// <summary> /// Loads the specified note and adds it to the form. /// </summary> /// <param name="task"></param> /// <returns></returns> public NoteItem AddNote(Task task) { var newNote = new NoteItem(this, task); // Insert the new control as the first element, as it will be displayed on the bottom. var all = (from Control c in Controls select c).ToArray(); SuspendLayout(); Controls.Clear(); Controls.Add(newNote); Controls.AddRange(all); UpdateHeight(); ResumeLayout(); return newNote; } /// <summary> /// Deletes a note from the note list. /// </summary> public void DeleteNote(NoteItem note) { if (Controls.Count <= 1) { return; // Don't remove the last note. } Controls.Remove(note); deletedNotes.Add(note); ((NoteItem)Controls[0]).FocusNote(); UpdateHeight(); } /// <summary> /// Synchronizes this client with the remote server. /// </summary> public void ClientSync() { // TODO(mlinder): Implement batching here. lock (sync) { var requests = new List<Action>(); // Add changes/inserts. NoteItem previous = null; foreach (NoteItem currentNote in (from Control c in Controls where c is NoteItem select c).Reverse()) { NoteItem note = currentNote; if (note.ClientSync()) { bool isNew = String.IsNullOrEmpty(note.RelatedTask.Id); requests.AddRange(GetSyncNoteRequest(note, previous, isNew)); } previous = note; } // Add deletes. foreach (NoteItem note in deletedNotes) { NoteItem noteb = note; if(note.RelatedTask != null && !String.IsNullOrEmpty(note.RelatedTask.Id)) requests.Add(() => Program.Service.Tasks.Delete(taskList.Id, noteb.RelatedTask.Id).Execute()); } deletedNotes.Clear(); // Execute all requests. requests.ForEach(action => action()); } } private IEnumerable<Action> GetSyncNoteRequest(NoteItem note, NoteItem previous, bool isNew) { var tasks = Program.Service.Tasks; if (isNew) { NoteItem previousSaved = previous; yield return () => note.RelatedTask = tasks.Insert(note.RelatedTask, taskList.Id).Execute(); yield return () => { var req = tasks.Move(taskList.Id, note.RelatedTask.Id); if (previousSaved != null) { req.Previous = previousSaved.RelatedTask.Id; } note.RelatedTask = req.Execute(); }; } else { yield return () => { var req = tasks.Update(note.RelatedTask, taskList.Id, note.RelatedTask.Id); note.RelatedTask = req.Execute(); }; } } private void UpdateHeight() { // Change the height of the list to contain all items. int totalY = 0; foreach (Control c in Controls) { totalY += c.Height; } ClientSize = new Size(ClientSize.Width, totalY); } private void NoteForm_Shown(object sender, System.EventArgs e) { // Add a sync timer. var timer = new System.Windows.Forms.Timer(); timer.Interval = 1000 * 60 * 5; // 5 min timer.Tick += (timerSender, timerArgs) => ClientSync(); timer.Start(); // Focus the first note. if (Controls.Count > 0) { ((NoteItem)Controls[0]).FocusNote(); } } private void NoteForm_FormClosing(object sender, FormClosingEventArgs e) { ClientSync(); Application.DoEvents(); lock (sync) {} } private void NoteForm_Deactivate(object sender, EventArgs e) { if (Disposing) { return; } // Sync asynchronously. ThreadPool.QueueUserWorkItem((obj) => ClientSync()); } private void NoteForm_FormClosed(object sender, FormClosedEventArgs e) { if (Application.OpenForms.Count == 0) { // If no more forms are open, exit the WinForms worker thread. Application.Exit(); } } } }
zzfocuzz-
Tasks.WinForms.NoteMgr/NoteForm.cs
C#
asf20
7,504
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.WinForms.NoteMgr")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Tasks.WinForms.NoteMgr")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("093e2a22-deda-4890-98cb-4d8edb3051c7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-
Tasks.WinForms.NoteMgr/Properties/AssemblyInfo.cs
C#
asf20
1,476
<html> <title>Google .NET Client API &ndash; Tasks.WinForms.NoteMgr</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.WinForms.NoteMgr</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.WinForms.NoteMgr">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.WinForms.NoteMgr/NoteForm.cs?repo=samples">NoteForm.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> <li>Edit <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.WinForms.NoteMgr/ClientCredentials.cs?repo=samples">ClientCredentials.cs</a> to insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane.</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Tasks.WinForms.NoteMgr\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-
Tasks.WinForms.NoteMgr/README.html
HTML
asf20
1,806
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using DotNetOpenAuth.OAuth2; using Google; using Google.Apis; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace Tasks.ETagCollision { /// <summary> /// This sample shows the E-Tag collision behaviour when an user tries updating an object, /// which has been modified by another source. /// </summary> internal class Program { private static readonly string Scope = TasksService.Scopes.Tasks.GetStringValue(); public static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Tasks API: E-Tag collision"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new TasksService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Tasks API Sample", }); // Run the sample code. RunSample(service, true, ETagAction.Ignore); RunSample(service, true, ETagAction.IfMatch); RunSample(service, true, ETagAction.IfNoneMatch); RunSample(service, false, ETagAction.Ignore); RunSample(service, false, ETagAction.IfMatch); RunSample(service, false, ETagAction.IfNoneMatch); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.siteverification"; const string KEY = "y},drdzf11x9;87"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } private static void RunSample(TasksService service, bool modify, ETagAction behaviour) { CommandLine.WriteAction("Testing for E-Tag case " + behaviour + " with modified=" + modify + "..."); // Create a new task list. TaskList list = service.Tasklists.Insert(new TaskList() { Title = "E-Tag Collision Test" }).Execute(); // Add a task Task myTask = service.Tasks.Insert(new Task() { Title = "My Task" }, list.Id).Execute(); // Retrieve a second instance of this task, modify it and commit it if (modify) { Task myTaskB = service.Tasks.Get(list.Id, myTask.Id).Execute(); myTaskB.Title = "My Task B!"; service.Tasks.Update(myTaskB, list.Id, myTaskB.Id).Execute(); } // Modfiy the original task, and see what happens myTask.Title = "My Task A!"; var request = service.Tasks.Update(myTask, list.Id, myTask.Id); request.ETagAction = behaviour; try { request.Execute(); CommandLine.WriteResult("Result", "Success!"); } catch (GoogleApiException ex) { CommandLine.WriteResult( "Result", "Failure! (" + ex.Message + ")"); } finally { // Delete the created list. service.Tasklists.Delete(list.Id).Execute(); CommandLine.WriteLine(); } } } }
zzfocuzz-
Tasks.ETagCollision/Program.cs
C#
asf20
5,620
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.ETagCollision")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Tasks.ETagCollision")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4d633636-c985-48c3-b749-bc5d06760ceb")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-
Tasks.ETagCollision/Properties/AssemblyInfo.cs
C#
asf20
1,470
<html> <title>Google .NET Client API &ndash; Tasks.ETagCollision</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.ETagCollision</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.ETagCollision">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ETagCollision/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Tasks.ETagCollision\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-
Tasks.ETagCollision/README.html
HTML
asf20
1,648
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.SiteVerification.v1; using Google.Apis.SiteVerification.v1.Data; using Google.Apis.Util; namespace SiteVerification.VerifySite { /// <summary> /// This sample goes through the site verification process by first obtaining a token, having the user /// add it to the target site, and then inserting the site into the verified owners list. It uses the /// SiteVerification API to do so. /// /// http://code.google.com/apis/siteverification/v1/getting_started.html /// </summary> internal class Program { private static readonly string Scope = SiteVerificationService.Scopes.Siteverification.GetStringValue(); [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Site Verification sample"); // Register the authenticator. var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); provider.ClientIdentifier = credentials.ClientId; provider.ClientSecret = credentials.ClientSecret; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new SiteVerificationService(new BaseClientService.Initializer { Authenticator = auth, ApplicationName = "SiteVerification API Sample", }); RunVerification(service); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // Retrieve the authorization from the user. return AuthorizationMgr.RequestNativeAuthorization(client, Scope); } /// <summary> /// This method contains the actual sample code. /// </summary> private static void RunVerification(SiteVerificationService service) { // Request user input. string site = Util.GetSingleLineClipboardContent(96); CommandLine.WriteAction("Please enter the URL of the site to verify:"); CommandLine.RequestUserInput("URL", ref site); CommandLine.WriteLine(); // Example of a GetToken call. CommandLine.WriteAction("Retrieving a meta token ..."); var request = service.WebResource.GetToken(new SiteVerificationWebResourceGettokenRequest() { VerificationMethod = "meta", Site = new SiteVerificationWebResourceGettokenRequest.SiteData() { Identifier = site, Type = "site" } }); var response = request.Execute(); CommandLine.WriteResult("Token", response.Token); Util.SetClipboard(response.Token); CommandLine.WriteLine(); CommandLine.WriteAction("Please place this token on your webpage now."); CommandLine.PressEnterToContinue(); CommandLine.WriteLine(); // Example of an Insert call. CommandLine.WriteAction("Verifiying..."); var body = new SiteVerificationWebResourceResource(); body.Site = new SiteVerificationWebResourceResource.SiteData(); body.Site.Identifier = site; body.Site.Type = "site"; var verificationResponse = service.WebResource.Insert(body, "meta").Execute(); CommandLine.WriteResult("Verification", verificationResponse.Id); CommandLine.WriteAction("Verification successful!"); } } }
zzfocuzz-
SiteVerification.VerifySite/Program.cs
C#
asf20
4,781
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SiteVerification..VerifySite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google")] [assembly: AssemblyProduct("SiteVerification.VerifySite")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("05d799ca-03b7-4414-98f5-d066850a0877")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-
SiteVerification.VerifySite/Properties/AssemblyInfo.cs
C#
asf20
1,483
<html> <title>Google .NET Client API &ndash; SiteVerification.VerifySite</title> <body> <h2>Instructions for the Google .NET Client API &ndash; SiteVerification.VerifySite</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FSiteVerification.VerifySite">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/SiteVerification.VerifySite/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the SiteVerification API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>SiteVerification.VerifySite\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-
SiteVerification.VerifySite/README.html
HTML
asf20
1,699
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Threading.Tasks; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Books.v1; using Google.Apis.Books.v1.Data; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace Books.ListMyLibrary { /// <summary> /// Sample which demonstrates how to use the Books API. /// Lists all volumes in the the users library, and retrieves more detailed information about the first volume. /// https://code.google.com/apis/books/docs/v1/getting_started.html /// </summary> internal class Program { private static readonly string Scope = BooksService.Scopes.Books.GetStringValue(); [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Books API: List MyLibrary"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new BooksService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Books API Sample", }); ListLibrary(service); Console.ReadLine(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.books"; const string KEY = "=UwuqAtRaqe-3daV"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } private static void ListLibrary(BooksService service) { CommandLine.WriteAction("Listing Bookshelves... (using async execution)"); // execute async var task = service.Mylibrary.Bookshelves.List().ExecuteAsync(); // on success display my library's volumes CommandLine.WriteLine(); task.ContinueWith(async t => await DisplayVolumes(service, t.Result), TaskContinuationOptions.OnlyOnRanToCompletion); // on failure print the error task.ContinueWith(t => { CommandLine.Write("Error occurred on executing async operation"); if (t.IsCanceled) { CommandLine.Write("Task was canceled"); } if (t.Exception != null) { CommandLine.Write("exception occurred. Exception is " + t.Exception.Message); } }, TaskContinuationOptions.NotOnRanToCompletion); } private static async Task DisplayVolumes(BooksService service, Bookshelves bookshelves) { if (bookshelves.Items == null) { CommandLine.WriteError("No bookshelves found!"); return; } foreach (Bookshelf item in bookshelves.Items) { CommandLine.WriteResult(item.Title, item.VolumeCount + " volumes"); // List all volumes in this bookshelf. if (item.VolumeCount > 0) { CommandLine.WriteAction("Query volumes... (Execute Async)"); var request = service.Mylibrary.Bookshelves.Volumes.List(item.Id.ToString()); Volumes inBookshelf = await request.ExecuteAsync(); if (inBookshelf.Items == null) { continue; } foreach (Volume volume in inBookshelf.Items) { CommandLine.WriteResult( "-- " + volume.VolumeInfo.Title, volume.VolumeInfo.Description ?? "no description"); } } } } } }
zzfocuzz-
Books.ListMyLibrary/Program.cs
C#
asf20
6,149
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Books.ListMyLibrary")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Books.v1.ListMyLibrary")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("43e33418-eef3-4859-aac2-ff1615229840")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-
Books.ListMyLibrary/Properties/AssemblyInfo.cs
C#
asf20
1,473
<html> <title>Google .NET Client API &ndash; Books.ListMyLibrary</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Books.ListMyLibrary</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FBooks.ListMyLibrary">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Books.ListMyLibrary/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Books API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Books.ListMyLibrary\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-
Books.ListMyLibrary/README.html
HTML
asf20
1,648
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UrlShortener.ASP.NET")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("UrlShortener.ASP.NET")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f402a950-432b-4bf0-b021-964e8da8e686")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-
UrlShortener.ASP.NET/Properties/AssemblyInfo.cs
C#
asf20
1,429
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Text.RegularExpressions; using Google; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Urlshortener.v1; using Google.Apis.Urlshortener.v1.Data; namespace UrlShortener.ASP.NET { /// <summary> /// ASP.NET UrlShortener Sample /// /// This sample makes use of ASP.NET and the UrlShortener API to demonstrate how to do make unauthenticated /// requests to an api. /// </summary> public partial class _Default : System.Web.UI.Page { private static UrlshortenerService _service; protected void Page_Load(object sender, EventArgs e) { // If we did not construct the service so far, do it now. if (_service == null) { BaseClientService.Initializer initializer = new BaseClientService.Initializer(); // You can enter your developer key for services requiring a developer key. /* initializer.ApiKey = "<Insert Developer Key here>"; */ _service = new UrlshortenerService(initializer); } } protected void input_TextChanged(object sender, EventArgs e) { // Change the text of the button according to the content. action.Text = IsShortUrl(input.Text) ? "Expand" : "Shorten"; } protected void action_Click(object sender, EventArgs e) { string url = input.Text; if (string.IsNullOrEmpty(url)) { return; } // Execute methods on the UrlShortener service based upon the type of the URL provided. try { string resultURL; if (IsShortUrl(url)) { // Expand the URL by using a Url.Get(..) request. Url result = _service.Url.Get(url).Execute(); resultURL = result.LongUrl; } else { // Shorten the URL by inserting a new Url. Url toInsert = new Url { LongUrl = url }; toInsert = _service.Url.Insert(toInsert).Execute(); resultURL = toInsert.Id; } output.Text = string.Format("<a href=\"{0}\">{0}</a>", resultURL); } catch (GoogleApiException ex) { output.Text = ex.ToHtmlString(); } } private static readonly Regex ShortUrlRegex = new Regex("^http[s]?://goo.gl/", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static bool IsShortUrl(string url) { return ShortUrlRegex.IsMatch(url); } } }
zzfocuzz-
UrlShortener.ASP.NET/Default.aspx.cs
C#
asf20
3,446
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UrlShortener.ASP.NET._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <h1>Urlshortener ASP.NET sample</h1> <form id="mainForm" runat="server"> <p> Please enter a shortened or a long url into the textbox, and press the button next to it. </p> <div> <asp:Label ID="Label1" runat="server" Font-Bold="True" Text="Input:"></asp:Label> &nbsp; &nbsp; <asp:TextBox ID="input" runat="server" AutoPostBack="True" ontextchanged="input_TextChanged"></asp:TextBox> <asp:Button ID="action" runat="server" Text="Shorten!" onclick="action_Click" /> </div> <p> <asp:Label ID="Label2" runat="server" Font-Bold="True" Text="Output:"></asp:Label> &nbsp; &nbsp; <asp:Label ID="output" runat="server"></asp:Label> </p> </form> <p> &copy; 2011 Google Inc</p> </body> </html>
zzfocuzz-
UrlShortener.ASP.NET/Default.aspx
ASP.NET
asf20
1,173
<html> <title>Google .NET Client API &ndash; UrlShortener.ASP.NET</title> <body> <h2>Instructions for the Google .NET Client API &ndash; UrlShortener.ASP.NET</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FUrlShortener.ASP.NET">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/UrlShortener.ASP.NET/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the UrlShortener API for your project </li> <li>Edit <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/UrlShortener.ASP.NET/ClientCredentials.cs?repo=samples">ClientCredentials.cs</a> to insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane.</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Select the project as the active project, and press F5 to run the webpage.</li> </ul> </body> </html>
zzfocuzz-
UrlShortener.ASP.NET/README.html
HTML
asf20
1,816