New OffscreenGecko scripting stuff
[divverent/darkplaces.git] / cl_gecko.c
1 /* --- 8< --- 8< ---   OffscreenGecko headers   --- >8 --- >8 --- */
2 /* NOTE: Documentation comments have been omitted. Documentation is
3    available in the OffscreenGecko SDK download. */
4
5 /* OffscreenGecko/defs.h */
6
7 #define OSGK_CLASSTYPE_DEF      struct
8 #define OSGK_CLASSTYPE_REF      struct
9
10 #include <assert.h>
11 #define OSGK_ASSERT(x)  assert(x)
12
13 typedef unsigned int OSGK_GeckoResult;
14
15 #if defined(__cplusplus) || defined(__GNUC__)
16 #  define OSGK_INLINE   inline
17 #elif defined(_MSC_VER)
18 #  define OSGK_INLINE   __inline
19 #else
20 #  define OSGK_INLINE
21 #endif
22
23 /* OffscreenGecko/baseobj.h */
24
25 struct OSGK_BaseObject_s
26 {
27   int reserved;
28 };
29 typedef struct OSGK_BaseObject_s OSGK_BaseObject;
30
31 #define OSGK_DERIVEDTYPE(T)           \
32   typedef struct T ## _s {            \
33     OSGK_BaseObject baseobj;          \
34   } T
35
36 static int (*osgk_addref) (OSGK_BaseObject* obj);
37 static int (*osgk_release) (OSGK_BaseObject* obj);
38
39 static OSGK_INLINE int osgk_addref_real (OSGK_BaseObject* obj)
40 {
41   return osgk_addref (obj);
42 }
43
44 static OSGK_INLINE int osgk_release_real (OSGK_BaseObject* obj)
45 {
46   return osgk_release (obj);
47 }
48
49 #define osgk_addref(obj)    osgk_addref_real (&((obj)->baseobj))
50 #define osgk_release(obj)   osgk_release_real (&((obj)->baseobj))
51
52 /* OffscreenGecko/embedding.h */
53
54 OSGK_DERIVEDTYPE(OSGK_EmbeddingOptions);
55
56 static OSGK_EmbeddingOptions* (*osgk_embedding_options_create) (void);
57 static void (*osgk_embedding_options_add_search_path) (
58   OSGK_EmbeddingOptions* options, const char* path);
59 /*static void (*osgk_embedding_options_add_components_path) (
60   OSGK_EmbeddingOptions* options, const char* path);*/
61 static void (*osgk_embedding_options_set_profile_dir) (
62   OSGK_EmbeddingOptions* options, const char* profileDir,
63   const char* localProfileDir);
64
65 OSGK_DERIVEDTYPE(OSGK_Embedding);
66
67 #define OSGK_API_VERSION    1
68
69 static OSGK_Embedding* (*osgk_embedding_create2) (
70   unsigned int apiVer, OSGK_EmbeddingOptions* options, 
71   OSGK_GeckoResult* geckoResult);
72
73 static OSGK_INLINE OSGK_Embedding* osgk_embedding_create (
74   OSGK_GeckoResult* geckoResult)
75 {
76   return osgk_embedding_create2 (OSGK_API_VERSION, 0, geckoResult);
77 }
78
79 static OSGK_INLINE OSGK_Embedding* osgk_embedding_create_with_options (
80   OSGK_EmbeddingOptions* options, OSGK_GeckoResult* geckoResult)
81 {
82   return osgk_embedding_create2 (OSGK_API_VERSION, options, geckoResult);
83 }
84
85 /*static OSGK_GeckoMem* (*osgk_embedding_get_gecko_mem) (
86   OSGK_Embedding* embedding);*/
87
88 /*static OSGK_ComponentMgr* (*osgk_embedding_get_component_mgr) (
89   OSGK_Embedding* embedding);*/
90
91 /*OSGK_CLASSTYPE_DEF nsIComponentManager;
92 OSGK_CLASSTYPE_DEF nsIComponentRegistrar;
93 OSGK_CLASSTYPE_DEF nsIServiceManager;*/
94
95 /*static OSGK_CLASSTYPE_REF nsIComponentManager* 
96 (*osgk_embedding_get_gecko_component_manager) (OSGK_Embedding* embedding);*/
97 /*static OSGK_CLASSTYPE_REF nsIComponentRegistrar* 
98 (*osgk_embedding_get_gecko_component_registrar) (OSGK_Embedding* embedding);*/
99 /*static OSGK_CLASSTYPE_REF nsIServiceManager* 
100 (*osgk_embedding_get_gecko_service_manager) (OSGK_Embedding* embedding);*/
101
102 enum
103 {
104   jsgPrivileged = 1
105 };
106 /*static int (*osgk_embedding_register_js_global) (
107   OSGK_Embedding* embedding, const char* name, const char* contractID,
108   unsigned int flags, OSGK_String** previousContract,
109   OSGK_GeckoResult* geckoResult);*/
110
111 /*static void (*osgk_embedding_clear_focus*) (OSGK_Embedding* embedding);*/
112 /*void (*osgk_embedding_set_auto_focus) (OSGK_Embedding* embedding, int autoFocus);*/
113 /*static int (*osgk_embedding_get_auto_focus) (OSGK_Embedding* embedding);*/
114
115 /* OffscreenGecko/browser.h */
116 OSGK_DERIVEDTYPE(OSGK_Browser);
117
118 static OSGK_Browser* (*osgk_browser_create) (
119   OSGK_Embedding* embedding, int width, int height);
120 static void (*osgk_browser_navigate) (OSGK_Browser* browser,
121   const char* uri);
122
123 static int (*osgk_browser_query_dirty) (OSGK_Browser* browser);
124 static const unsigned char* (*osgk_browser_lock_data) (
125   OSGK_Browser* browser, int* isDirty);
126 static void (*osgk_browser_unlock_data) (OSGK_Browser* browser,
127   const unsigned char* data);
128
129 typedef enum OSGK_MouseButton
130 {
131   mbLeft, 
132   mbRight, 
133   mbMiddle
134 } OSGK_MouseButton;
135
136 typedef enum OSGK_MouseButtonEventType
137 {
138   meDown,
139   meUp,
140   meDoubleClick
141 } OSGK_MouseButtonEventType;
142
143 static void (*osgk_browser_event_mouse_move) (
144   OSGK_Browser* browser, int x, int y);
145 static void (*osgk_browser_event_mouse_button) (
146   OSGK_Browser* browser, OSGK_MouseButton button, 
147   OSGK_MouseButtonEventType eventType);
148
149 typedef enum OSGK_WheelAxis
150 {
151   waVertical,
152   waHorizontal
153 } OSGK_WheelAxis;
154
155 typedef enum OSGK_WheelDirection
156 {
157   wdPositive,
158   wdNegative,
159   wdPositivePage,
160   wdNegativePage
161 } OSGK_WheelDirection;
162
163 static void (*osgk_browser_event_mouse_wheel) (
164   OSGK_Browser* browser, OSGK_WheelAxis axis, 
165   OSGK_WheelDirection direction);
166
167 typedef enum OSGK_KeyboardEventType
168 {
169   keDown,
170   keUp,
171   kePress
172 } OSGK_KeyboardEventType;
173
174 enum
175 {
176   OSGKKey_First = 0x110000,
177
178   OSGKKey_Backspace = OSGKKey_First,
179   OSGKKey_Tab,
180   OSGKKey_Return,
181   OSGKKey_Shift,
182   OSGKKey_Control,
183   OSGKKey_Alt,
184   OSGKKey_CapsLock,
185   OSGKKey_Escape,
186   OSGKKey_Space,
187   OSGKKey_PageUp,
188   OSGKKey_PageDown,
189   OSGKKey_End,
190   OSGKKey_Home,
191   OSGKKey_Left,
192   OSGKKey_Up,
193   OSGKKey_Right,
194   OSGKKey_Down,
195   OSGKKey_Insert,
196   OSGKKey_Delete,
197   OSGKKey_F1,
198   OSGKKey_F2,
199   OSGKKey_F3,
200   OSGKKey_F4,
201   OSGKKey_F5,
202   OSGKKey_F6,
203   OSGKKey_F7,
204   OSGKKey_F8,
205   OSGKKey_F9,
206   OSGKKey_F10,
207   OSGKKey_F11,
208   OSGKKey_F12,
209   OSGKKey_NumLock,
210   OSGKKey_ScrollLock,
211   OSGKKey_Meta
212 };
213
214 static int (*osgk_browser_event_key) (
215   OSGK_Browser* browser, unsigned int key,
216   OSGK_KeyboardEventType eventType);
217
218 typedef enum OSGK_AntiAliasType
219 {
220   aaNone,
221   aaGray,
222   aaSubpixel
223 } OSGK_AntiAliasType;
224
225 /*static void (*osgk_browser_set_antialias) (
226   OSGK_Browser* browser, OSGK_AntiAliasType aaType);*/
227 /*static OSGK_AntiAliasType (*osgk_browser_get_antialias) (OSGK_Browser* browser);*/
228
229 /*static void (*osgk_browser_focus) (OSGK_Browser* browser);*/
230
231 static void (*osgk_browser_resize) (OSGK_Browser* browser,
232   int width, int height);
233
234 /* OffscreenGecko/string.h */
235 OSGK_DERIVEDTYPE(OSGK_String);
236
237 /*static const char* (*osgk_string_get) (OSGK_String* str);*/
238
239 /*static OSGK_String* (*osgk_string_create) (const char* str);*/
240
241 /* OffscreenGecko/scriptvariant.h */
242
243 OSGK_CLASSTYPE_DEF nsISupports;
244
245 OSGK_DERIVEDTYPE(OSGK_ScriptVariant);
246
247 typedef enum OSGK_ScriptVariantType
248 {
249   svtEmpty,
250   svtInt,
251   svtUint,
252   svtFloat,
253   svtDouble,
254   svtBool,
255   svtChar,
256   svtString,
257   svtISupports,
258   svtScriptObject,
259   svtArray
260 } OSGK_ScriptVariantType;
261
262 /*static OSGK_ScriptVariantType (*osgk_variant_get_type) (
263   OSGK_ScriptVariant* variant);*/
264 /*static OSGK_ScriptVariant* (*osgk_variant_convert) (
265   OSGK_ScriptVariant* variant, OSGK_ScriptVariantType newType);*/
266
267 /*static int (*osgk_variant_get_int) (OSGK_ScriptVariant* variant,
268   int* val);*/
269 /*static int (*osgk_variant_get_uint) (OSGK_ScriptVariant* variant,
270   unsigned int* val);*/
271 /*static int (*osgk_variant_get_float) (OSGK_ScriptVariant* variant,
272   float* val);*/
273 /*static int (*osgk_variant_get_double) (OSGK_ScriptVariant* variant,
274   double* val);*/
275 /*static int (*osgk_variant_get_bool) (OSGK_ScriptVariant* variant,
276   int* val);*/
277 /*static int (*osgk_variant_get_char) (OSGK_ScriptVariant* variant,
278   unsigned int* val);*/
279 /*// Does not increase ref count
280 static int (*osgk_variant_get_string) (OSGK_ScriptVariant* variant,
281   OSGK_String** val);*/
282 /*// Does not increase ref count
283 static int (*osgk_variant_get_isupports) (OSGK_ScriptVariant* variant,
284   OSGK_CLASSTYPE_REF nsISupports** val);*/
285 /*static int (*osgk_variant_get_script_object) (OSGK_ScriptVariant* variant,
286   void** tag);*/
287 /*static int (*osgk_variant_get_array_size) (OSGK_ScriptVariant* variant,
288   size_t* size);*/
289 /*static int (*osgk_variant_get_array_item) (OSGK_ScriptVariant* variant,
290   OSGK_ScriptVariant** val);*/
291
292 /*static OSGK_ScriptVariant* (*osgk_variant_create_empty) (
293   OSGK_Embedding* embedding);*/
294 /*static OSGK_ScriptVariant* (*osgk_variant_create_int) (
295   OSGK_Embedding* embedding, int val);*/
296 /*static OSGK_ScriptVariant* (*osgk_variant_create_uint) (
297   OSGK_Embedding* embedding, unsigned int val);
298 /*static OSGK_ScriptVariant* (*osgk_variant_create_float) (
299   OSGK_Embedding* embedding, float val);
300 /*static OSGK_ScriptVariant* (*osgk_variant_create_double) (
301   OSGK_Embedding* embedding, double val);*/
302 /*OSGK_ScriptVariant* (*osgk_variant_create_bool) (
303   OSGK_Embedding* embedding, int val);*/
304 /*static OSGK_ScriptVariant* (*osgk_variant_create_char) (
305   OSGK_Embedding* embedding, unsigned int val);*/
306 /*static OSGK_ScriptVariant* (*osgk_variant_create_string) (
307   OSGK_Embedding* embedding, OSGK_String* val);*/
308 /*static OSGK_ScriptVariant* (*osgk_variant_create_isupports) (
309   OSGK_Embedding* embedding, OSGK_CLASSTYPE_REF nsISupports* val);*/
310 /*static OSGK_ScriptVariant* (*osgk_variant_create_script_object) (
311   OSGK_Embedding* embedding, void* tag);*/
312 /*static OSGK_ScriptVariant* (*osgk_variant_create_array) (
313   OSGK_Embedding* embedding, size_t numItems, OSGK_ScriptVariant** items);*/
314
315 /* OffscreenGecko/scriptobjecttemplate.h */
316
317 OSGK_DERIVEDTYPE(OSGK_ScriptObjectTemplate);
318
319 typedef enum OSGK_ScriptResult
320 {
321   srSuccess = 0,
322   srFailed = 0x80004005L /* actually NS_ERROR_FAILURE */
323 } OSGK_ScriptResult;
324
325 typedef struct OSGK_ScriptObjectCreateParams_s
326 {
327   void* createParam;
328 } OSGK_ScriptObjectCreateParams;
329
330 typedef OSGK_ScriptResult (*OSGK_CreateObjFunc) (
331   OSGK_ScriptObjectCreateParams* params, void** objTag);
332 typedef void (*OSGK_DestroyObjFunc) (void* objTag);
333
334 /*static OSGK_ScriptObjectTemplate* (*osgk_sot_create) (
335   OSGK_Embedding* embedding,
336   OSGK_CreateObjFunc createFunc, OSGK_DestroyObjFunc destroyFunc,
337   void* createParam);*/
338
339 typedef OSGK_ScriptVariant* (*OSGK_GetPropertyFunc) (void* objTag,
340   void* propTag);
341 typedef OSGK_ScriptResult (*OSGK_SetPropertyFunc) (void* objTag,
342   void* propTag, OSGK_ScriptVariant* val);
343   
344 /*static int (*osgk_sot_add_property) (
345   OSGK_ScriptObjectTemplate* templ, const char* propName, void* propTag,
346   OSGK_GetPropertyFunc getter, OSGK_SetPropertyFunc setter);*/
347
348 typedef OSGK_ScriptResult (*OSGK_FunctionCallFunc) (void* objTag,
349   void* methTag, size_t numParams, OSGK_ScriptVariant** params,
350   OSGK_ScriptVariant** returnVal);
351
352 /*static int (*osgk_sot_add_function) (
353   OSGK_ScriptObjectTemplate* templ, const char* funcName, void* funcTag,
354   OSGK_FunctionCallFunc callFunc);*/
355
356 /*static OSGK_ScriptVariant* (*osgk_sot_instantiate) (
357   OSGK_ScriptObjectTemplate* templ, void** objTag);    */
358
359 /*static int (*osgk_sot_register) (
360   OSGK_ScriptObjectTemplate* templ, OSGK_Embedding* embedding, 
361   const char* name, unsigned int flags);*/
362
363 /* --- >8 --- >8 --- End OffscreenGecko headers --- 8< --- 8< --- */
364
365 #include "quakedef.h"
366 #include "cl_dyntexture.h"
367 #include "cl_gecko.h"
368 #include "timing.h"
369
370 #define DEFAULT_GECKO_SIZE        512
371
372 static rtexturepool_t *cl_geckotexturepool;
373 static OSGK_Embedding *cl_geckoembedding;
374
375 struct clgecko_s {
376         qboolean active;
377         char name[ MAX_QPATH + 32 ];
378
379         OSGK_Browser *browser;
380         int width, height;
381         int texWidth, texHeight;
382         
383         rtexture_t *texture;
384 };
385
386 static clgecko_t cl_geckoinstances[ MAX_GECKO_INSTANCES ];
387
388 static dllhandle_t osgk_dll = NULL;
389
390 static clgecko_t * cl_gecko_findunusedinstance( void ) {
391         int i;
392         for( i = 0 ; i < MAX_GECKO_INSTANCES ; i++ ) {
393                 clgecko_t *instance = &cl_geckoinstances[ i ];
394                 if( !instance->active ) {
395                         return instance;
396                 }
397         }
398         if( developer.integer > 0 ) {
399                 Con_Printf( "cl_gecko_findunusedinstance: out of geckos\n" );
400         }
401         return NULL;
402 }
403
404 clgecko_t * CL_Gecko_FindBrowser( const char *name ) {
405         int i;
406
407         if( !name || !*name || strncmp( name, CLGECKOPREFIX, sizeof( CLGECKOPREFIX ) - 1 ) != 0 ) {
408                 if( developer.integer > 0 ) {
409                         Con_Printf( "CL_Gecko_FindBrowser: Bad gecko texture name '%s'!\n", name );
410                 }
411                 return NULL;
412         }
413
414         for( i = 0 ; i < MAX_GECKO_INSTANCES ; i++ ) {
415                 clgecko_t *instance = &cl_geckoinstances[ i ];
416                 if( instance->active && strcmp( instance->name, name ) == 0 ) {
417                         return instance;
418                 }
419         }
420
421         if( developer.integer > 0 ) {
422                 Con_Printf( "CL_Gecko_FindBrowser: No browser named '%s'!\n", name );
423         }
424
425         return NULL;
426 }
427
428 static void cl_gecko_updatecallback( rtexture_t *texture, void* callbackData ) {
429         clgecko_t *instance = callbackData;
430         const unsigned char *data;
431         if( instance->browser ) {
432                 // TODO: OSGK only supports BGRA right now
433                 TIMING_TIMESTATEMENT(data = osgk_browser_lock_data( instance->browser, NULL ));
434                 R_UpdateTexture( texture, data, 0, 0, instance->width, instance->height );
435                 osgk_browser_unlock_data( instance->browser, data );
436         }
437 }
438
439 static void cl_gecko_linktexture( clgecko_t *instance ) {
440         // TODO: assert that instance->texture == NULL
441         instance->texture = R_LoadTexture2D( cl_geckotexturepool, instance->name, 
442                 instance->texWidth, instance->texHeight, NULL, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_PERSISTENT, NULL );
443         R_MakeTextureDynamic( instance->texture, cl_gecko_updatecallback, instance );
444         CL_LinkDynTexture( instance->name, instance->texture );
445 }
446
447 static void cl_gecko_unlinktexture( clgecko_t *instance ) {
448         if( instance->texture ) {
449                 CL_UnlinkDynTexture( instance->name );
450                 R_FreeTexture( instance->texture );
451                 instance->texture = NULL;
452         }
453 }
454
455 void CL_Gecko_Resize( clgecko_t *instance, int width, int height ) {
456         int newWidth, newHeight;
457
458         // early out if bad parameters are passed (no resize to a texture size bigger than the original texture size)
459         if( !instance || !instance->browser) {
460                 return;
461         }
462
463         newWidth = CeilPowerOf2( width );
464         newHeight = CeilPowerOf2( height );
465         if ((newWidth != instance->texWidth) || (newHeight != instance->texHeight))
466         {
467                 cl_gecko_unlinktexture( instance );
468                 instance->texWidth = newWidth;
469                 instance->texHeight = newHeight;
470                 cl_gecko_linktexture( instance );
471         }
472         else
473         {
474                 /* The gecko area will only cover a part of the texture; to avoid
475                 'old' pixels bleeding in at the border clear the texture. */
476                 R_ClearTexture( instance->texture );
477         }
478
479         osgk_browser_resize( instance->browser, width, height);
480         instance->width = width;
481         instance->height = height;
482 }
483
484 void CL_Gecko_GetTextureExtent( clgecko_t *instance, float* pwidth, float* pheight )
485 {
486         if( !instance || !instance->browser ) {
487                 return;
488         }
489
490         *pwidth = (float)instance->width / instance->texWidth;
491         *pheight = (float)instance->height / instance->texHeight;
492 }
493
494 #if defined(WIN64)
495 # define XULRUNNER_DIR_SUFFIX   "win64"
496 #elif defined(WIN32)
497 # define XULRUNNER_DIR_SUFFIX   "win32"
498 #elif defined(DP_OS_STR) && defined(DP_ARCH_STR)
499 # define XULRUNNER_DIR_SUFFIX   DP_OS_STR "-" DP_ARCH_STR
500 #endif
501
502 clgecko_t * CL_Gecko_CreateBrowser( const char *name ) {
503         clgecko_t *instance;
504
505         if (!osgk_dll) return NULL;
506
507         // TODO: verify that we dont use a name twice
508         instance = cl_gecko_findunusedinstance();
509         // TODO: assert != NULL
510         
511         if( cl_geckoembedding == NULL ) {
512                 char profile_path [MAX_OSPATH];
513                 OSGK_GeckoResult grc;
514                 OSGK_EmbeddingOptions *options;
515
516                 if( developer.integer > 0 ) {
517                         Con_Printf( "CL_Gecko_CreateBrowser: setting up gecko embedding\n" );
518                 }
519
520                 options = osgk_embedding_options_create();
521         #ifdef XULRUNNER_DIR_SUFFIX
522                 osgk_embedding_options_add_search_path( options, "./xulrunner-" XULRUNNER_DIR_SUFFIX "/" );
523         #endif
524                 osgk_embedding_options_add_search_path( options, "./xulrunner/" );
525                 dpsnprintf (profile_path, sizeof (profile_path), "%s/xulrunner_profile/", fs_gamedir);
526                 osgk_embedding_options_set_profile_dir( options, profile_path, 0 );
527                 cl_geckoembedding = osgk_embedding_create_with_options( options, &grc );
528                 osgk_release( options );
529                 
530                 if( cl_geckoembedding == NULL ) {
531                         Con_Printf( "CL_Gecko_CreateBrowser: Couldn't retrieve gecko embedding object (%.8x)!\n", grc );
532                         return NULL;
533                 } else if( developer.integer > 0 ) {
534                         Con_Printf( "CL_Gecko_CreateBrowser: Embedding set up correctly\n" );
535                 }
536         }
537
538         instance->active = true;
539         strlcpy( instance->name, name, sizeof( instance->name ) );
540         instance->browser = osgk_browser_create( cl_geckoembedding, DEFAULT_GECKO_SIZE, DEFAULT_GECKO_SIZE );
541         if( instance->browser == NULL ) {
542                 Con_Printf( "CL_Gecko_CreateBrowser: Browser object creation failed!\n" );
543         }
544         // TODO: assert != NULL
545
546         instance->width = instance->texWidth = DEFAULT_GECKO_SIZE;
547         instance->height = instance->texHeight = DEFAULT_GECKO_SIZE;
548         cl_gecko_linktexture( instance );
549
550         return instance;
551 }
552
553 void CL_Gecko_DestroyBrowser( clgecko_t *instance ) {
554    if( !instance || !instance->active ) {
555                 return;
556         }
557
558         instance->active = false;
559         cl_gecko_unlinktexture( instance );
560
561         osgk_release( instance->browser );
562         instance->browser = NULL;
563 }
564
565 void CL_Gecko_Frame( void ) {
566         int i;
567         // FIXME: track cl_numgeckoinstances to avoid scanning the entire array?
568         for( i = 0 ; i < MAX_GECKO_INSTANCES ; i++ ) {
569                 clgecko_t *instance = &cl_geckoinstances[ i ];
570                 if( instance->active ) {
571                         if( instance->browser && osgk_browser_query_dirty( instance->browser ) == 1 ) {
572                                 R_MarkDirtyTexture( instance->texture );
573                         }
574                 }
575         }
576 }
577
578 static void cl_gecko_start( void )
579 {
580         int i;
581         cl_geckotexturepool = R_AllocTexturePool();
582
583         // recreate textures on module start
584         for( i = 0 ; i < MAX_GECKO_INSTANCES ; i++ ) {
585                 clgecko_t *instance = &cl_geckoinstances[ i ];
586                 if( instance->active ) {
587                         cl_gecko_linktexture( instance );
588                 }
589         }
590 }
591
592 static void cl_gecko_shutdown( void )
593 {
594         int i;
595         for( i = 0 ; i < MAX_GECKO_INSTANCES ; i++ ) {
596                 clgecko_t *instance = &cl_geckoinstances[ i ];
597                 if( instance->active ) {
598                         cl_gecko_unlinktexture( instance );
599                 }
600         }
601         R_FreeTexturePool( &cl_geckotexturepool );
602 }
603
604 static void cl_gecko_newmap( void )
605 {
606         // DO NOTHING
607 }
608
609 void CL_Gecko_Shutdown( void ) {
610         int i;
611         for( i = 0 ; i < MAX_GECKO_INSTANCES ; i++ ) {
612                 clgecko_t *instance = &cl_geckoinstances[ i ];
613                 if( instance->active ) {
614                         cl_gecko_unlinktexture( instance );
615                 }               
616         }
617
618         if (cl_geckoembedding != NULL)
619         {
620             osgk_release( cl_geckoembedding );
621             cl_geckoembedding = NULL;
622         }
623
624         if (osgk_dll != NULL)
625         {
626             Sys_UnloadLibrary (&osgk_dll);
627         }
628 }
629
630 static void cl_gecko_create_f( void ) {
631         char name[MAX_QPATH];
632
633         if (Cmd_Argc() != 2)
634         {
635                 Con_Print("usage: gecko_create <name>\npcreates a browser (full texture path " CLGECKOPREFIX "<name>)\n");
636                 return;
637         }
638
639         // TODO: use snprintf instead
640         sprintf(name, CLGECKOPREFIX "%s", Cmd_Argv(1));
641         CL_Gecko_CreateBrowser( name );
642 }
643
644 static void cl_gecko_destroy_f( void ) {
645         char name[MAX_QPATH];
646
647         if (Cmd_Argc() != 2)
648         {
649                 Con_Print("usage: gecko_destroy <name>\ndestroys a browser\n");
650                 return;
651         }
652
653         // TODO: use snprintf instead
654         sprintf(name, CLGECKOPREFIX "%s", Cmd_Argv(1));
655         CL_Gecko_DestroyBrowser( CL_Gecko_FindBrowser( name ) );
656 }
657
658 static void cl_gecko_navigate_f( void ) {
659         char name[MAX_QPATH];
660         const char *URI;
661
662         if (Cmd_Argc() != 3)
663         {
664                 Con_Print("usage: gecko_navigate <name> <URI>\nnavigates to a certain URI\n");
665                 return;
666         }
667
668         // TODO: use snprintf instead
669         sprintf(name, CLGECKOPREFIX "%s", Cmd_Argv(1));
670         URI = Cmd_Argv( 2 );
671         CL_Gecko_NavigateToURI( CL_Gecko_FindBrowser( name ), URI );
672 }
673
674 static void cl_gecko_injecttext_f( void ) {
675         char name[MAX_QPATH];
676         const char *text;
677         clgecko_t *instance;
678         const char *p;
679
680         if (Cmd_Argc() < 3)
681         {
682                 Con_Print("usage: gecko_injecttext <name> <text>\ninjects a certain text into the browser\n");
683                 return;
684         }
685
686         // TODO: use snprintf instead
687         sprintf(name, CLGECKOPREFIX "%s", Cmd_Argv(1));
688         instance = CL_Gecko_FindBrowser( name );
689         if( !instance ) {
690                 Con_Printf( "cl_gecko_injecttext_f: gecko instance '%s' couldn't be found!\n", name );
691                 return;
692         }
693
694         text = Cmd_Argv( 2 );
695
696         for( p = text ; *p ; p++ ) {
697                 unsigned key = *p;
698                 switch( key ) {
699                         case ' ':
700                                 key = K_SPACE;
701                                 break;
702                         case '\\':
703                                 key = *++p;
704                                 switch( key ) {
705                                 case 'n':
706                                         key = K_ENTER;
707                                         break;
708                                 case '\0':
709                                         --p;
710                                         key = '\\';
711                                         break;
712                                 }
713                                 break;
714                 }
715
716                 CL_Gecko_Event_Key( instance, key, CLG_BET_PRESS );
717         }
718 }
719
720 static void gl_gecko_movecursor_f( void ) {
721         char name[MAX_QPATH];
722         float x, y;
723
724         if (Cmd_Argc() != 4)
725         {
726                 Con_Print("usage: gecko_movecursor <name> <x> <y>\nmove the cursor to a certain position\n");
727                 return;
728         }
729
730         // TODO: use snprintf instead
731         sprintf(name, CLGECKOPREFIX "%s", Cmd_Argv(1));
732         x = atof( Cmd_Argv( 2 ) );
733         y = atof( Cmd_Argv( 3 ) );
734
735         CL_Gecko_Event_CursorMove( CL_Gecko_FindBrowser( name ), x, y );
736 }
737
738 #undef osgk_addref
739 #undef osgk_release
740
741 static const dllfunction_t osgkFuncs[] =
742 {
743         {"osgk_addref",                             (void **) &osgk_addref},
744         {"osgk_release",                            (void **) &osgk_release},
745         {"osgk_embedding_create2",                  (void **) &osgk_embedding_create2},
746         {"osgk_embedding_options_create",           (void **) &osgk_embedding_options_create},
747         {"osgk_embedding_options_add_search_path",  (void **) &osgk_embedding_options_add_search_path},
748         {"osgk_embedding_options_set_profile_dir",  (void **) &osgk_embedding_options_set_profile_dir},
749         {"osgk_browser_create",                     (void **) &osgk_browser_create},
750         {"osgk_browser_query_dirty",                (void **) &osgk_browser_query_dirty},
751         {"osgk_browser_navigate",                   (void **) &osgk_browser_navigate},
752         {"osgk_browser_lock_data",                  (void **) &osgk_browser_lock_data},
753         {"osgk_browser_unlock_data",                (void **) &osgk_browser_unlock_data},
754         {"osgk_browser_resize",                     (void **) &osgk_browser_resize},
755         {"osgk_browser_event_mouse_move",           (void **) &osgk_browser_event_mouse_move},
756         {"osgk_browser_event_mouse_button",         (void **) &osgk_browser_event_mouse_button},
757         {"osgk_browser_event_mouse_wheel",          (void **) &osgk_browser_event_mouse_wheel},
758         {"osgk_browser_event_key",                  (void **) &osgk_browser_event_key},
759         {NULL, NULL}
760 };
761
762 void CL_Gecko_Init( void )
763 {
764         const char* dllnames [] =
765         {
766         #if defined(WIN64)
767                 "OffscreenGecko64.dll",
768         #elif defined(WIN32)
769                 "OffscreenGecko.dll",
770         #elif defined(MACOSX)
771                 "OffscreenGecko.dylib",
772         #else
773                 "libOffscreenGecko.so",
774         #endif
775                 NULL
776         };
777         
778         if (!osgk_dll)
779         {
780                 if (! Sys_LoadLibrary (dllnames, &osgk_dll, osgkFuncs))
781                 {
782                         Con_Printf ("Could not load OffscreenGecko, Gecko support unavailable\n");
783                 }
784         }
785
786         Cmd_AddCommand( "gecko_create", cl_gecko_create_f, "Create a gecko browser instance" );
787         Cmd_AddCommand( "gecko_destroy", cl_gecko_destroy_f, "Destroy a gecko browser instance" );
788         Cmd_AddCommand( "gecko_navigate", cl_gecko_navigate_f, "Navigate a gecko browser to a URI" );
789         Cmd_AddCommand( "gecko_injecttext", cl_gecko_injecttext_f, "Injects text into a browser" );
790         Cmd_AddCommand( "gecko_movecursor", gl_gecko_movecursor_f, "Move the cursor to a certain position" );
791
792         R_RegisterModule( "CL_Gecko", cl_gecko_start, cl_gecko_shutdown, cl_gecko_newmap );
793 }
794
795 void CL_Gecko_NavigateToURI( clgecko_t *instance, const char *URI ) {
796         if( !instance || !instance->browser ) {
797                 return;
798         }
799
800         if( instance->active ) {
801                 osgk_browser_navigate( instance->browser, URI );
802         }
803 }
804
805 void CL_Gecko_Event_CursorMove( clgecko_t *instance, float x, float y ) {
806         // TODO: assert x, y \in [0.0, 1.0]
807         int mappedx, mappedy;
808
809         if( !instance || !instance->browser ) {
810                 return;
811         }
812
813         mappedx = x * instance->width;
814         mappedy = y * instance->height;
815         osgk_browser_event_mouse_move( instance->browser, mappedx, mappedy );
816 }
817
818 typedef struct geckokeymapping_s {
819         keynum_t keycode;
820         unsigned int geckokeycode;
821 } geckokeymapping_t;
822
823 static geckokeymapping_t geckokeymappingtable[] = {
824         { K_BACKSPACE, OSGKKey_Backspace },
825         { K_TAB, OSGKKey_Tab },
826         { K_ENTER, OSGKKey_Return },
827         { K_SHIFT, OSGKKey_Shift },
828         { K_CTRL, OSGKKey_Control },
829         { K_ALT, OSGKKey_Alt },
830         { K_CAPSLOCK, OSGKKey_CapsLock },
831         { K_ESCAPE, OSGKKey_Escape },
832         { K_SPACE, OSGKKey_Space },
833         { K_PGUP, OSGKKey_PageUp },
834         { K_PGDN, OSGKKey_PageDown },
835         { K_END, OSGKKey_End },
836         { K_HOME, OSGKKey_Home },
837         { K_LEFTARROW, OSGKKey_Left },
838         { K_UPARROW, OSGKKey_Up },
839         { K_RIGHTARROW, OSGKKey_Right },
840         { K_DOWNARROW, OSGKKey_Down },
841         { K_INS, OSGKKey_Insert },
842         { K_DEL, OSGKKey_Delete },
843         { K_F1, OSGKKey_F1 },
844         { K_F2, OSGKKey_F2 },
845         { K_F3, OSGKKey_F3 },
846         { K_F4, OSGKKey_F4 },
847         { K_F5, OSGKKey_F5 },
848         { K_F6, OSGKKey_F6 },
849         { K_F7, OSGKKey_F7 },
850         { K_F8, OSGKKey_F8 },
851         { K_F9, OSGKKey_F9 },
852         { K_F10, OSGKKey_F10 },
853         { K_F11, OSGKKey_F11 },
854         { K_F12, OSGKKey_F12 },
855         { K_NUMLOCK, OSGKKey_NumLock },
856         { K_SCROLLOCK, OSGKKey_ScrollLock }
857 };
858
859 qboolean CL_Gecko_Event_Key( clgecko_t *instance, keynum_t key, clgecko_buttoneventtype_t eventtype ) {
860         if( !instance || !instance->browser ) {
861                 return false;
862         }
863
864         // determine whether its a keyboard event
865         if( key < K_OTHERDEVICESBEGIN ) {
866
867                 OSGK_KeyboardEventType mappedtype = kePress;
868                 unsigned int mappedkey = key;
869                 
870                 unsigned int i;
871                 // yes! then convert it if necessary!
872                 for( i = 0 ; i < sizeof( geckokeymappingtable ) / sizeof( *geckokeymappingtable ) ; i++ ) {
873                         const geckokeymapping_t * const mapping = &geckokeymappingtable[ i ];
874                         if( key == mapping->keycode ) {
875                                 mappedkey = mapping->geckokeycode;
876                                 break;
877                         }
878                 }
879
880                 // convert the eventtype
881                 // map the type
882                 switch( eventtype ) {
883                 case CLG_BET_DOWN:
884                         mappedtype = keDown;
885                         break;
886                 case CLG_BET_UP:
887                         mappedtype = keUp;
888                         break;
889                 case CLG_BET_DOUBLECLICK:
890                         // TODO: error message
891                         break;
892                 case CLG_BET_PRESS:
893                         mappedtype = kePress;
894                 }
895
896                 return osgk_browser_event_key( instance->browser, mappedkey, mappedtype ) != 0;
897         } else if( K_MOUSE1 <= key && key <= K_MOUSE3 ) {
898                 OSGK_MouseButtonEventType mappedtype = meDoubleClick;
899                 OSGK_MouseButton mappedbutton;
900
901                 mappedbutton = (OSGK_MouseButton) (mbLeft + (key - K_MOUSE1));
902
903                 switch( eventtype ) {
904                 case CLG_BET_DOWN:
905                         mappedtype = meDown;
906                         break;
907                 case CLG_BET_UP:
908                         mappedtype = meUp;
909                         break;
910                 case CLG_BET_DOUBLECLICK:
911                         mappedtype = meDoubleClick;
912                         break;
913                 case CLG_BET_PRESS:
914                         // hihi, hacky hacky
915                         osgk_browser_event_mouse_button( instance->browser, mappedbutton, meDown );
916                         mappedtype = meUp;
917                         break;
918                 }
919
920                 osgk_browser_event_mouse_button( instance->browser, mappedbutton, mappedtype );
921                 return true;
922         } else if( K_MWHEELUP <= key && key <= K_MWHEELDOWN ) {
923                 if( eventtype == CLG_BET_DOWN )
924                         osgk_browser_event_mouse_wheel( instance->browser, 
925                                 waVertical, (key == K_MWHEELUP) ? wdNegative : wdPositive );
926                 return true;
927         }
928         // TODO: error?
929         return false;
930 }