Compare commits

...

425 commits

Author SHA1 Message Date
Shadowfacts 47fda71672 Build for arm64 macOS 2022-01-17 11:45:44 -05:00
Endolf 447ec94f22 Merge branch 'master' of github.com:jinput/jinput 2019-01-29 19:18:29 +00:00
Endolf d861b32778 Update the example pom to include an exec example 2019-01-29 19:18:13 +00:00
Endolf 8662748d00
Merge pull request #49 from aarre/master
Correct typo
2018-12-11 19:59:25 +00:00
gearcats b98ee86b13 Correct typo 2018-12-11 14:03:28 -05:00
Endolf 8eafaaa61e
Added basic license information. 2018-07-30 17:14:01 +01:00
Endolf 796c4780fd Close resources as per PR #10 2018-07-22 16:12:47 +01:00
Endolf b6150acbce Update example jinput version 2018-06-01 21:33:10 +01:00
Endolf d0487df592 Another attempt to get the release working. 2018-06-01 21:27:58 +01:00
Endolf 33640ec47d Next development release 2018-06-01 20:53:10 +01:00
Endolf f37172befd Produce a javadoc file for the uber jar 2018-06-01 19:33:07 +01:00
Endolf c826412056 Website updates 2018-06-01 18:46:42 +01:00
Endolf 847c20d89c Website updates 2018-06-01 18:32:56 +01:00
Endolf b70a38d9f1 Website updates 2018-06-01 18:31:56 +01:00
Endolf 3b79a57e9f Website updates 2018-06-01 18:30:04 +01:00
Endolf d8fd89c5f2 Website updates 2018-06-01 18:27:05 +01:00
Endolf 196fab2d6f Update the way the fat jar is built and the pom distributed. 2018-06-01 18:20:57 +01:00
Endolf be5f3a6307 Website updates 2018-06-01 17:42:33 +01:00
Endolf 341db62139 Website updates 2018-06-01 17:26:01 +01:00
Endolf ba876c7e34 Website updates 2018-06-01 17:06:16 +01:00
Endolf abceb81d56 Use theme default layout 2018-06-01 16:57:17 +01:00
Endolf 351e8e1201 Website updates 2018-06-01 16:54:05 +01:00
Endolf f7155114ce Website updates 2018-06-01 16:50:20 +01:00
Endolf f12daf06da Website updates 2018-06-01 16:44:38 +01:00
Endolf b15ffc59b4 Update maven dependency details 2018-06-01 16:40:55 +01:00
Endolf d5451041a7 Update maven dependency details 2018-06-01 16:40:35 +01:00
Endolf fc1f43c5cf Using the docs version now 2018-06-01 16:32:46 +01:00
Endolf 6c5b3cf39d
Merge pull request #39 from jinput/github-pages
GitHub pages
2018-06-01 16:30:46 +01:00
Endolf 78ca4c4d18 Update maven details 2018-06-01 16:29:56 +01:00
Endolf f7742fbd95
Merge pull request #31 from dyorgio/master
Included GitHub Pages  support
2018-06-01 16:20:17 +01:00
jinput d166d82729 Set theme jekyll-theme-architect 2018-06-01 16:16:59 +01:00
Endolf 62c5953307 Merge remote-tracking branch 'origin/master' into github-pages 2018-06-01 16:04:07 +01:00
Endolf 5a83f72422
Merge pull request #38 from jinput/issue/36
Issue/36
2018-06-01 16:02:17 +01:00
Endolf 43ba12c160 Move pom version declaration 2018-06-01 15:55:08 +01:00
Endolf 06d9d5ca66 Build uber jars 2018-06-01 15:49:09 +01:00
Endolf 4f6269fdd2 Create a pom that allows all dependencies to be imported easily 2018-06-01 15:04:43 +01:00
Endolf 92f17913ca Add information on log level changes. 2018-05-31 21:07:03 +01:00
Endolf 7ea0ebcc1f Handle packaging changes in readme badges 2018-05-31 21:03:48 +01:00
Endolf 16202823b5
Merge pull request #37 from jinput/issue/32
Issue/32
2018-05-31 20:58:11 +01:00
Endolf 466e4a6bdb Fixed compile warnings 2018-05-31 20:36:30 +01:00
Endolf 67902800ab Fixed compile warnings 2018-05-31 20:16:51 +01:00
Endolf af914ca5e4 Fixed compile warnings 2018-05-31 19:57:36 +01:00
Endolf d057119f79 Fixed compile warnings 2018-05-31 19:54:41 +01:00
Endolf a623d0c271 Fixed compile warnings 2018-05-31 19:42:43 +01:00
Endolf c77ad3226c Fixed compile warnings 2018-05-31 19:39:58 +01:00
Endolf ad452077d4 Fixed compile warnings 2018-05-31 19:31:37 +01:00
Endolf 83dd362c65 Fix license 2018-05-31 19:28:49 +01:00
Endolf 7d3e5f31ae Fixed compile warnings 2018-05-31 19:27:48 +01:00
Endolf 88395eef77 Fixed compile warnings 2018-05-31 19:15:35 +01:00
Endolf a775a55c46 Fixed compile warnings 2018-05-31 19:09:13 +01:00
Endolf 981587abbc Fixed compile warnings 2018-05-30 19:22:39 +01:00
Endolf b87aa830e8 Fixed compile warnings 2018-05-30 19:20:42 +01:00
Endolf 30304ba8f4 Fixed compile warnings 2018-05-30 19:18:31 +01:00
Endolf a19b3c9fa3 Fixed compile warnings 2018-05-30 19:11:46 +01:00
Endolf 59c21d42c5 Fixed compile warnings 2018-05-30 19:09:03 +01:00
Endolf 4ef9e03623 Fixed compile warnings 2018-05-30 18:41:48 +01:00
Endolf d80d2ad2b2 Fixed compile warnings 2018-05-30 18:23:15 +01:00
Endolf 91428ceee0 Fixed compile warnings 2018-05-30 18:19:00 +01:00
Endolf 0cfd2ae7cd Fixed compile warnings 2018-05-30 18:14:58 +01:00
Endolf db8c6804b4 Fixed compile warnings 2018-05-30 17:53:20 +01:00
Endolf c9152a679d Fixed compile warnings 2018-05-30 17:45:52 +01:00
Endolf 4b8183ead9 Fixed compile warnings 2018-05-30 17:42:06 +01:00
Endolf 5ba05aff65 Code tidy up 2018-05-30 17:39:34 +01:00
Endolf b853018676 Add serialVersionUID 2018-05-30 17:38:55 +01:00
Endolf f5f30e17ab Code tidy up 2018-05-30 17:38:20 +01:00
Endolf 516aed2c93 Fixed compile warnings 2018-05-30 17:19:18 +01:00
Endolf 72d4ca05a8 Fail on compiler warnings in the plugins 2018-05-30 17:04:07 +01:00
Endolf f0d7f6db03 Mostly fixed compiler warnings 2018-05-30 17:02:27 +01:00
Endolf 9c639cdfbc Mostly fixed compiler warnings 2018-05-29 22:30:06 +01:00
Endolf 4b00766888 Fail on compiler warnings in the plugins 2018-05-29 22:29:43 +01:00
Endolf 2bc8a793c8 Fixed compile warnings for awt plugin 2018-05-29 21:55:13 +01:00
Endolf 81c9c872cd Fixed compile warnings for core api 2018-05-29 21:43:15 +01:00
Endolf 98a19dbb1a Update to push tags 2018-05-25 22:26:29 +01:00
Endolf 974302e420 Next development release 2018-05-25 21:52:45 +01:00
Endolf 3bc6b827e0 Hopefully fix the release not incrementing or commiting 2018-05-25 21:51:40 +01:00
Endolf c63b09a047 Hopefully fix the release not incrementing or commiting 2018-05-25 21:50:06 +01:00
Endolf 6150206edb Change the release stage name 2018-05-25 21:00:38 +01:00
Endolf a4c7d312d2 Add the git push 2018-05-25 20:59:46 +01:00
Endolf 99debb71a0 Use a parameterised build for release 2018-05-25 20:52:21 +01:00
Endolf 9509787f01 Use a parameterised build for release 2018-05-25 20:43:17 +01:00
Endolf b6ca29e9f1 Move input out of an agent tied stage 2018-05-25 20:30:38 +01:00
Endolf a095351e4a Try and get the version scriptlet working. 2018-05-25 20:24:44 +01:00
Endolf bd571ad746 Add ordinals to milestone 2018-05-25 20:22:09 +01:00
Endolf c72d1fcb01 Input shouldn't have {} 2018-05-25 20:16:48 +01:00
Endolf b997ef8545 Milestone needs () 2018-05-25 20:13:22 +01:00
Endolf 97416d3813 Testing timeout 2018-05-25 20:09:45 +01:00
Endolf d4ce65b28b Try and work out where milestone and input live. 2018-05-25 20:09:15 +01:00
Endolf 8ba4395c2d Try and work out where milestone and input live. 2018-05-25 20:06:03 +01:00
Endolf 544e00cd5c Use the nexus staging plugin for release 2018-05-25 19:50:59 +01:00
Endolf 12496a9fbb Don't use the release plugin 2018-05-25 19:20:30 +01:00
Endolf 76613c2c6f Jenkins file updates for release 2018-05-25 19:17:41 +01:00
Endolf f1b1b5a74f Updates to plugins for release 2018-05-25 19:13:55 +01:00
Endolf ded17f0897 Updates to plugins for release 2018-05-25 19:10:10 +01:00
Endolf b6253e440e Start of a release pipeline build 2018-05-25 18:28:11 +01:00
Endolf 165a4d74e6
Merge pull request #34 from jinput/issue/26
Issue/26
2018-05-25 16:50:15 +01:00
Endolf b440e211e1
Merge pull request #35 from jinput/master
Merge master
2018-05-25 07:35:00 +01:00
Endolf 5eb89d4e12 Disable logging option 2018-05-24 22:41:39 +01:00
Endolf 771499a7ca Fix the javadoc jenkins archive 2018-05-24 21:57:01 +01:00
Endolf 5b799195e3 Build core first 2018-05-24 21:54:32 +01:00
Endolf bd61698f16 Only sign on deploy 2018-05-24 21:33:54 +01:00
Endolf 79a3fc9291 Only deploy on master branch 2018-05-24 20:54:29 +01:00
Endolf aa699f5ffb Remove the log call that added extra new lines 2018-05-24 20:52:18 +01:00
Endolf f228dbcf59
Merge pull request #33 from jinput/jenkinsfile
Jenkinsfile
2018-05-24 20:03:25 +01:00
Endolf b82395833a Update the example pom to use central snapshots and pull in all plugins 2018-05-24 19:56:04 +01:00
Endolf 8a569fdc63 Only run build on linux as windows doesn't like shell scripts.... 2018-05-24 19:28:58 +01:00
Endolf d9586e25bb Refactor the build in to build natives, build and deploy. 2018-05-24 19:25:57 +01:00
Endolf 98cf806325 Use the ready built artifacts 2018-05-24 19:00:01 +01:00
Endolf 0d466440d9 Activate all profiles and don't compile the code 2018-05-24 18:29:02 +01:00
Endolf b93ddcc46e Lower case the profile names 2018-05-24 18:27:46 +01:00
Endolf 70c9291774 Add cacerts property for JDK9 missing cacerts file. 2018-05-24 18:13:44 +01:00
Endolf 99df8dc84c Working towards a working deployment 2018-05-23 22:00:46 +01:00
Endolf 5d19200671 Use ID of settings file. 2018-05-23 21:00:23 +01:00
Endolf 6b177835ff Fix secret key importing. 2018-05-23 20:39:54 +01:00
Endolf 4731a08964 First attempt at deploying snapshots to maven central 2018-05-23 20:12:22 +01:00
Endolf 5b0cafeb36 Fix the stashing and unstashing 2018-05-23 17:49:04 +01:00
Endolf f541fdb219 Fix the stashing and unstashing 2018-05-23 17:29:25 +01:00
Endolf dc75289f96 Merge remote-tracking branch 'origin/master' into jenkinsfile 2018-05-23 17:26:51 +01:00
Endolf 5b7c6314ed Fix use of deprecated methods 2018-05-23 17:26:16 +01:00
Endolf 04b2dce53a Reduce the items we are stashing and unstashing. 2018-05-23 17:19:47 +01:00
dyorgio 676f94ed4c Fix some markdown issues (github pages). 2018-05-23 11:34:50 -03:00
dyorgio b1d6589b73 Added usage example (github pages). 2018-05-23 11:32:42 -03:00
dyorgio 55e0f46eec Fix some markdown issues (github pages). 2018-05-23 11:23:36 -03:00
dyorgio 9f650f8a5d Initial index page contents (github pages). 2018-05-23 11:20:15 -03:00
dyorgio 0f52875091 Included default layout (github pages). 2018-05-23 11:00:54 -03:00
dyorgio e0676a02df Included index.md (github pages). 2018-05-23 10:58:39 -03:00
dyorgio 5119891aa7 Included docs folder and Jekyll config (github pages). 2018-05-23 10:55:19 -03:00
Endolf 9d11cb04da Unstash artifacts 2018-05-23 01:39:46 +01:00
Endolf 517357401e Only keep 5 builds. 2018-05-23 01:29:14 +01:00
Endolf 69d6b1b8a6 Add the tools. 2018-05-23 01:16:53 +01:00
Endolf cc2c663916 Add the tools. 2018-05-23 01:02:13 +01:00
Endolf 4c7eff906e Add the tools. 2018-05-23 01:00:46 +01:00
Endolf 62451c9cb7 Trigger builds once a branch is discovered. 2018-05-23 00:58:17 +01:00
Endolf 49946e27e0 WIP jenkinsfile. 2018-05-23 00:50:27 +01:00
Endolf c6a6d2e8f8 WIP jenkinsfile. 2018-05-23 00:39:22 +01:00
Endolf 2acfe0edaa Start of GPG signing 2018-05-23 00:32:46 +01:00
Endolf 8a213d061c Update missing SCM data. 2018-05-22 23:37:20 +01:00
Endolf a5112ed015
Merge pull request #30 from jinput/issue5
Issue5
2018-05-22 22:46:31 +01:00
Endolf f4876067c1 Merge remote-tracking branch 'origin/master' into issue5 2018-05-22 22:43:00 +01:00
Endolf 4b66611142
Merge pull request #29 from jinput/maven
Maven
2018-05-22 22:38:45 +01:00
Endolf 0e321e77a2 Handle wintab not being available 2018-05-21 21:51:53 +01:00
Endolf 4a7f075d23 Fix typo in profile id 2018-05-20 22:56:51 +01:00
Endolf 92391498cf Activate the wintab profile if we are on windows and the SDK path is set. 2018-05-20 22:55:42 +01:00
Endolf 4cb3cc08fc Activate the wintab profile if we are on windows and the SDK path is set. 2018-05-20 22:49:27 +01:00
Endolf ee9aa09577 Wintab links 2018-05-20 22:01:48 +01:00
Endolf 76669f6b51 Wintab compiles, not linking yet though. 2018-05-20 13:13:50 +01:00
Endolf 9a6fd1cf66 Steps towards wintab build 2018-05-19 21:02:10 +01:00
Endolf c875ade848 Steps towards wintab build 2018-05-18 18:13:26 +01:00
Endolf 40f2e7fd25 Steps towards wintab build 2018-05-18 18:12:17 +01:00
Endolf 809334336c Example using maven 2018-05-17 18:41:04 +01:00
Endolf c82ba65e2b Compile under OSX 2018-05-16 23:54:53 +01:00
Endolf 96eea217e3 Fix the os family name 2018-05-16 22:18:25 +01:00
Endolf ba840b81f4 Wintab changes 2018-05-12 19:24:07 +01:00
Endolf b08843d82b Remove old ant files. 2018-05-12 19:08:54 +01:00
Endolf 64ec6fe8e4 Guard against null pointer 2018-05-12 18:59:54 +01:00
Endolf c8996c0581 Add the osx profile 2018-05-12 11:21:58 +01:00
Endolf 4e98105deb First stab at OSX maven build. 2018-05-12 11:17:38 +01:00
Endolf e0a512be48 Fix version file for generation from Maven. 2018-05-10 00:48:33 +01:00
Endolf 5a80ec7321 Use maven details for version information. 2018-05-10 00:07:24 +01:00
Endolf 557be525a2 Linking working. 2018-05-09 23:49:45 +01:00
Endolf f2b022b197 Compiling working. 2018-05-09 23:21:21 +01:00
Endolf 22b9ee15a4 Fix jni.h file location. 2018-05-09 21:58:39 +01:00
Endolf 3b886a200e Use normal paths, as they work. 2018-05-09 21:46:25 +01:00
Endolf 3faf26532e Remove the clean target and some commented out code. 2018-05-09 21:45:38 +01:00
Endolf 1eea3061f1 Fix path 2018-05-09 20:48:00 +01:00
Endolf 682ebbaf69 Refactor the sources 2018-05-09 20:38:48 +01:00
Endolf c71f96a708 Use javac with the -h arg instead of javah that's now deprecated. 2018-05-09 20:31:37 +01:00
Endolf 252ca8876f Use javac with the -h arg instead of javah that's now deprecated. 2018-05-09 20:16:04 +01:00
Endolf 2b7d10e435 Add profiles for OS builds 2018-05-09 18:56:25 +01:00
Endolf 289a6db298 First commit for windows 2018-05-09 18:55:55 +01:00
Endolf 4517180482 Linux native jar file building. 2018-05-02 11:54:06 +01:00
Endolf b2fd759065 Linux building under maven 2018-04-30 21:31:56 +01:00
Endolf 294629a312 Merge pull request #20 from leif81/patch-1
Add basic README with maven and javadoc badges
2017-06-07 20:29:31 +01:00
Leif Gruenwoldt 2c9654b300 Add basic README with maven and javadoc badges
The badges are handy way to discover the latest artifacts.
2017-06-07 15:20:31 -04:00
Endolf e730077f78 Merge pull request #13 from Razielwar/razielwar/button32
manage button 32
2017-06-06 18:34:00 +01:00
Endolf 822e0b4827 Delete README.txt 2017-05-09 12:37:40 +01:00
Endolf 2f7d29dd39 Delete CHANGES 2017-05-09 12:37:26 +01:00
Endolf e866ea5dc9 Prepare for next version 2017-05-08 22:35:29 +01:00
Endolf c1014ab8a6 Update repo information 2017-05-08 19:41:19 +01:00
Endolf 57586046d8 Add IntelliJ ignores 2017-05-08 19:25:38 +01:00
Razielwar e7ed731ceb manage button 32
manage button 32 (identifier 31) and remove discrepancy between windows identifier and jinput identifier (+1 from identifier 21)
2016-10-16 22:11:37 +02:00
Endolf b813d5594e Merge pull request #9 from jamesjer/master
Remove references to nonexistent EVIOCGUSAGE
2016-05-19 20:00:28 +01:00
Jerry James bbf4c985f0 Remove references to nonexistent EVIOCGUSAGE 2016-05-19 11:37:39 -06:00
Endolf 61edc6b2cd Merge pull request #4 from IceReaper/patch-1
Added Windows 10 to avoid warning.
2015-09-16 08:55:00 +01:00
IceReaper 643e6380ed Added Windows 10 to avoid warning. 2015-09-16 09:52:15 +02:00
Endolf 0943752c25 Fix for windows 8 and 8.1 version not found messages. 2015-06-13 21:50:39 +01:00
Endolf 3c24e13a83 More ignores 2014-07-14 13:36:25 +01:00
Endolf 335552cf71 Make jutils usable from snapshot jars. 2014-07-14 13:35:42 +01:00
Endolf 2837517753 Git ignores 2014-07-14 13:31:09 +01:00
endolf 350d8fec21 Changes for maven 2.0.6 release. 2014-05-26 22:08:04 +00:00
endolf 790b666865 Create the javadoc as part of a dist build 2013-03-25 18:01:56 +00:00
endolf a5c79be8d0 Fix return code for unknown controller buttons on linux controllers. Patch supplied by tctimmeh on JGO.
http://www.java-gaming.org/topics/updating-linux-stick-button-mappings/28838/view.html
2013-03-09 12:30:57 +00:00
endolf 29d8717a75 Add new buttons for linux and the missing start button. Patch supplied by tctimmeh on JGO.
http://www.java-gaming.org/topics/updating-linux-stick-button-mappings/28838/view.html
2013-03-09 12:27:43 +00:00
endolf 229d2c9dda Another update for newer kernels 2013-02-25 19:10:27 +00:00
endolf 9452bb5f80 Updated for version 3 kernels 2013-02-25 19:02:49 +00:00
endolf eee0db5b4f Update for os.arch values seen in the wild 2011-08-01 17:50:59 +00:00
endolf 900a46506a Put the JInput version out on the tests 2011-03-25 23:09:25 +00:00
endolf 87e7d8df2f Reduce the logging during normal running. 2011-03-23 18:54:48 +00:00
endolf 9646122032 Updated api version number after fixing maven release version class. 2011-03-23 18:33:26 +00:00
endolf c07fe191ea Put the correct api version information into the Version class. 2011-03-23 18:11:22 +00:00
endolf 62ed7dc473 Fix maven deploy. 2011-03-22 22:20:33 +00:00
endolf 3c352dc3cc Sepearate the natives out. 2011-03-22 21:35:43 +00:00
endolf 84be9b9b36 Updated maven build, eventually for working from maven central 2011-03-22 19:26:54 +00:00
endolf b1384277ad Update to 2.0.2 in maven 2011-02-20 14:34:23 +00:00
endolf 73fe22bc94 Make sure the files are returned in alpha order, so the order is consitent between runs. 2011-02-20 14:11:41 +00:00
endolf b7302c451f Updated javadoc 2011-02-05 17:38:53 +00:00
endolf 45e8a00390 Updated for windows os arch change. 2011-02-05 14:33:04 +00:00
endolf 823c47bc2b Add targets to ant that make it possible to place JInput in a maven repository. 2010-04-16 17:18:37 +00:00
endolf 0ad4010e80 Directx SDK has changed the location of the x86 libs.
Clean out the exp and libs that are created during a build when clean target is run.
2010-03-20 10:51:45 +00:00
endolf 40af67538f Updated link to latest distribution 2010-01-26 08:40:03 +00:00
endolf 2789d50724 Fix init and clean targets 2009-12-12 13:37:17 +00:00
endolf 32829e5df6 Add version information that hudson will update. 2009-12-12 13:29:01 +00:00
endolf 530a7eaf94 Fix incorrect log method call 2009-10-31 11:13:06 +00:00
endolf 967fde8a93 Use java logging instead of system out in core and plugins. 2009-10-31 11:06:12 +00:00
endolf 86fb3d5499 Recognise windows 7 2009-10-03 20:20:27 +00:00
endolf d4a1fd4ae6 Apply patch from bjunglas for issue 42 to allow 3D Connexions space navigator to be detected on osx 2009-07-15 16:19:15 +00:00
endolf bfce766c46 Make the plugins use the right dll name (oops) 2009-04-01 16:47:21 +00:00
endolf 3cc17edd10 Add the windows 64 bit natives 2009-03-31 21:53:47 +00:00
endolf 2644b47f44 Only build wintab stuff on windows 32 bit, which is the only environment wintab supports. 2009-03-31 21:29:28 +00:00
endolf d60c807a24 The environment under windows decides if it's a 64 bit build or not. On 64 bit windows assume a 64 bit one. 2009-03-31 20:16:53 +00:00
endolf c95cf4bddd Check the arch type before loading the native library 2009-03-28 16:36:03 +00:00
endolf b789b8cd52 Check the arch type before loading the .so 2009-03-28 16:25:28 +00:00
endolf 571769019e Check the arch type before loading the .so 2009-03-28 16:22:05 +00:00
endolf 8a606b3e3f Add linux 64 bit to the natives jar 2009-03-28 16:03:13 +00:00
endolf c5ff2100e2 Build for all 3 architectures 2009-03-26 12:36:38 +00:00
endolf ca1963aadc *** empty log message *** 2009-03-22 21:27:59 +00:00
endolf db9ebeccef *** empty log message *** 2009-03-22 21:16:20 +00:00
endolf 2ed5250bf4 All environment paths passed in. 2009-03-18 01:23:13 +00:00
endolf 8ed1ae2586 *** empty log message *** 2008-11-15 00:28:39 +00:00
endolf 971b9e3e39 *** empty log message *** 2008-11-14 22:31:08 +00:00
endolf eaa55d4860 *** empty log message *** 2008-11-14 22:09:05 +00:00
elias f2a679ae06 Made DirectAndRawInput the default windows plugin. Teach jinput about vista. 2007-11-27 09:14:51 +00:00
endolf 7d527dda1c When running the webstart rumble test, it doesn't seem to want to quit, it should now. 2007-11-13 20:37:47 +00:00
endolf b210efd1d0 Updated javadoc 2007-10-27 09:11:51 +00:00
endolf 3694ba5514 Rather than crashing, just disable the plugin if we an't load the dll 2007-09-23 02:09:55 +00:00
endolf 0015c724b3 Rather than crashing, just disable the plugin if we an't load the dll 2007-09-23 02:01:26 +00:00
endolf 69a2984615 Rather than crashing, just disable the plugin if we an't load the dll 2007-09-22 19:35:06 +00:00
endolf 13e1269023 Fix a potential Array index out of bounds exception. 2007-08-12 22:38:49 +00:00
endolf a2f62499b9 Make joysticks fire events 2007-08-12 22:10:37 +00:00
endolf c6a4aeaf1e Complete - task 36: Linux plugin not reporting normalised values
https://jinput.dev.java.net/issues/show_bug.cgi?id=36
2007-08-12 21:59:25 +00:00
endolf ea90a2d3b4 Make the joystick plugin on linux respect POV Hats 2007-08-12 20:09:14 +00:00
endolf ae8b23e4ba Remove stray debug 2007-08-12 16:02:23 +00:00
endolf 8699a0c8b1 Issue number: 35
Read the axis and button maps from the joystick nodes.
2007-08-12 15:47:51 +00:00
endolf 940c48b558 Bit of a tidy up 2007-08-02 20:30:42 +00:00
endolf aa96d5c1be Tidy up 2007-08-02 20:13:51 +00:00
endolf d418a10639 Changed the default plugin for XP to be the combined raw and direct input plugins. 2007-08-02 20:11:20 +00:00
endolf 0018c62842 Created a plugin that combines the multiple keyboard/mouse support of the raw plugin, with the game controller support of direct input. 2007-08-02 20:10:35 +00:00
endolf 75f65de075 Update the location of the dist folder. 2007-07-31 17:23:42 +00:00
endolf 9f2bd073fe Updated javadoc 2007-06-28 21:35:13 +00:00
endolf 92c7186445 Revert last change, might be a rumbling only device, or a device with only subdevices. 2007-06-28 20:41:47 +00:00
endolf db12311aa5 Don't create devices that are of an unknown type, with no components 2007-06-28 20:38:53 +00:00
endolf fd2a1b073d Make the API docs and the code match for the Mouse.get<button> methods. Add the methods that we actually wanted to be there. 2007-06-28 20:37:24 +00:00
endolf 10214031df Raw input has mouse buttons 4 and 5 as button 3 and 4 not side and extra. 2007-06-20 21:04:46 +00:00
endolf 083eee58ee Implement the isSupported method and make plugins work again. There was an issue where accessing the static methods in DefaultControllerEnvironment and ControllerEnvironment would cause ploblems when the plugins were loaded using the PluginLoader class loader. 2007-06-10 15:03:27 +00:00
endolf d6368e8dc5 Don't put the examples in the main jar 2007-06-10 11:31:30 +00:00
endolf 4c295d9219 Added commented examples 2007-06-10 10:51:31 +00:00
endolf 795f0d1a3f Issue number:
Obtained from:
Submitted by:
Reviewed by:
2007-06-06 19:34:19 +00:00
endolf bd39ae8aef Another formatting shuffle 2007-04-19 18:59:10 +00:00
endolf 6cbebb1061 Added a not to contact us in the forums if you want to get involved 2007-04-19 18:57:03 +00:00
endolf 4a55c75a5e Needed a starting break 2007-04-19 18:34:26 +00:00
endolf ffbec4163d Tried to update the main page a bit, including removing that horrid banner and reflecting the new win32 plugin information 2007-04-19 18:32:54 +00:00
elias 1bfb2dc3c0 Made polling of absolute Components lazy to avoid performance problems with keyboards on mac os x 2007-04-19 11:59:23 +00:00
elias 7716494aee Linux: Added more paths to the jni header search path 2007-04-19 11:40:03 +00:00
elias d71de8a642 Mac OS X: Don't fail the entire device enumeration when one device fails to open 2007-02-25 20:40:02 +00:00
elias 7bf9a5d428 Linux: Bounds check fixes (again) 2006-12-26 09:18:46 +00:00
elias 02196352eb Linux ~: More bounds checks 2006-12-25 09:31:34 +00:00
elias 9d211951c1 Linux: Fix an IndexOutOfBoundsException for unknown controller types 2006-12-23 07:51:58 +00:00
elias 43b4dab801 Mac OS X: Added support for mouse scroll wheel 2006-11-12 18:36:17 +00:00
endolf 58a0518a42 Issue number: 33
Obtained from: vacaro
Submitted by:  vacaro
Reviewed by:  endolf
2006-11-08 13:25:39 +00:00
endolf f107ea2558 Make the default state connected to the cursor 2006-10-31 20:46:46 +00:00
endolf 2a7557fcfb jnlp files for webstart 2006-10-29 20:27:39 +00:00
endolf 8af1163d0c Updates for webstart scripts 2006-10-29 20:10:15 +00:00
endolf e2d5fc8e24 Updates to build system for wintab plugin 2006-10-29 17:47:35 +00:00
endolf 1ef6081c1f First commit of the wintab plugin 2006-10-29 15:57:42 +00:00
elias f201cc526b Linux: Changed uname -i to uname -m to improve 64 bit detection in build scripts 2006-09-08 10:06:51 +00:00
elias 9cc64dd560 DirectInput: Only choose DIDF_RELAXIS id the device has at least one axis, and all axes are relative 2006-08-23 08:04:50 +00:00
elias b251b846f2 DirectInput: Don't fail entire enumeration because of one device failure 2006-08-23 07:53:04 +00:00
elias e48f275cfc DirectInput: Fix an issue with mice devices and DIDF_ABSAXIS axis mode. Now DIDF_RELAXIS is chosen if all device axes are relative. 2006-08-22 21:20:35 +00:00
elias 924d55e7d3 DirectInput: Use Controller.Type.UNKNOWN for the catch-all device type 2006-08-22 09:22:51 +00:00
elias b1892fe307 Linux: Ignore rumblers when device is read only 2006-08-11 08:44:12 +00:00
elias 3d2ce651e8 DirectInput: Ignore unmapped components 2006-08-10 08:05:14 +00:00
elias 027fa2a7a0 Check for NULL malloc result 2006-08-09 08:38:58 +00:00
elias c31a7d8818 Windows: More MinGW compile fixes 2006-07-20 10:45:00 +00:00
elias 13a7aaef3c Windows: Fix more mingw compile warnings 2006-07-17 11:32:38 +00:00
elias 0a481c9adb Windows: More mingw fixes 2006-07-17 11:29:02 +00:00
elias 0fb2152bde Windows: MinGW path fixes 2006-07-15 23:09:40 +00:00
elias e5b009c563 Windows: Added build.xml.mingw for building with mingw compiler. Doesn't work yet since the RawInput API is not supported through mingw yet. 2006-07-15 22:39:32 +00:00
elias f0737680fa Made the core classes and the linux plugin applet compatible. Removed dead code in DefaultControllerEnvironment 2006-07-14 08:31:27 +00:00
elias c9b1dd2ba1 Windows: Handle polled devices in setDataFormat 2006-07-13 18:37:27 +00:00
elias c97630f17d Linux: build fixes for 64 bit 2006-07-11 21:07:38 +00:00
elias 06ecaad638 Changed a System.out.println to use logging 2006-07-11 21:04:54 +00:00
elias 6eb27144d9 Linux: Implemented support for libjinput-linux64.so 64 bit library 2006-07-11 21:02:46 +00:00
elias 8f13bb8862 Windows: Use pre-defined environment variables for the native include and lib paths 2006-07-10 22:20:03 +00:00
elias e1e1d4f564 Windows Raw Plugin: Make sure DefWindowProc is called to clean up resources. Use MSG.time field instead of GetMessageTime. 2006-07-05 08:51:36 +00:00
elias 4931654f9c Windows: Fix RawMouse event bug where all mouse clicks would end up being reported on the left (primary) mouse button 2006-07-04 21:25:51 +00:00
elias 4306f119c2 added DefaultControllerEnvironment.loadLibrary convenience method for plugins. It will also respect the new net.java.games.input.librarypath property for locating natives (useful for applets). Removed the mac os x jinput-osx-legacy library loading, as it is not necessary anymore with the combined 10.3/10.4 library 2006-07-03 11:59:10 +00:00
elias d5ea04d3af Added seal to security sensitive jars 2006-07-03 11:48:11 +00:00
elias 603d4c6ce6 Added ControllerEventTest for testing event queueing 2006-06-23 10:48:04 +00:00
elias 55335e976d Windows: Fixed warning about unsafe _vsnprintf 2006-06-22 14:08:08 +00:00
endolf 99e28a3d9d Add an axis identifier for unknown axis types and get directx to use it
if it doesn't recognise an axis on construction.
2006-05-25 12:40:27 +00:00
endolf 1dc8f9ea11 Merge revision 12 of oddlabs svn repo.
Mac OS X: build.xml fix
Windows: Fixed crash when Raw plugin fails to load
Mac OS X: Tweak native libraries so only one library, libjinput-osx.jnilib contains both gcc 3 ppc code and gcc 4 i386 code. That way, we'll cover all releases and architectures with one native library instead of two
2006-05-14 09:14:52 +00:00
endolf 559c008a02 Make version 2 the main jinput version 2006-04-29 22:29:27 +00:00
endolf 4c91a4eb44 Trying to sort out some of the crashes and failed exits 2006-01-12 22:16:10 +00:00
endolf 552fdad56d Fixed a sigsegv, once we've found a match for an event device and
joystick, don't look at that stick again, especially having nulled the
pointer.
2005-12-04 22:14:35 +00:00
endolf c47f72208e First bodge at pursuading windows to use some of the same button ID's as linux. I dunno which is right, I suspect that both are as there is no standard that both admit to. So for now, lets do that good old nasty hack of string searching. 2005-12-04 16:39:13 +00:00
endolf fb1b49b5a9 Updated button ID's. Trouble is, windows and linux id the buttons differently. 2005-12-02 22:43:14 +00:00
endolf 819e59f33c Don't poll if we are shutting down 2005-11-11 20:05:06 +00:00
endolf db744e1d41 Let me just say ....
Ooops

was forgetting to increment a counter
2005-11-11 19:22:55 +00:00
endolf dc39383a67 Handle cases where there are no event devices, only js ones. 2005-11-07 07:46:34 +00:00
endolf 9a920ade6d Fixes for js devices that are read only 2005-11-03 22:00:11 +00:00
endolf f95cb1ce41 3 Changes
When there are no device files found, jinput won't try to read the 0th
one.

When no js* devices are found in /dev/input it will look in /dev

Try to free some of the memory created in the init process
2005-10-30 21:56:14 +00:00
endolf 3b9688b972 Fixed my debug 2005-09-01 20:37:01 +00:00
endolf 67bcd5f43e Trying to handle more than 2 force feedback axis. Untested. 2005-09-01 20:34:01 +00:00
endolf 2ae95adfcc Added debug for an array out of bounds error that is being seen 2005-09-01 20:02:57 +00:00
endolf 95cf7ab8e7 It helps if you add the files the new changes depend on.
Ooops

(force feedback changes I committed yesterday that is)
2005-08-31 06:43:02 +00:00
endolf b6f7e35321 It appears as though linux can't cope with scaling the effect, it's on
or off. So i'm having to play with the strong/weak rumble settings.
2005-08-30 19:54:25 +00:00
endolf daba6d24cc Unless cleanup is called from the same thread as init, the cleanup
doesn't happen properly and events are left of the ff device meaning we
run out of device space. Added a thread that init and cleanup are called
from via methods on the interface.

Then it became apparent that rumble would only work from the same thread
as the others too, so thats added in there.

Nastyness all round.
2005-08-30 19:37:53 +00:00
endolf ab247c91ad Updated build file to build 1.4 byte code 2005-08-28 21:23:54 +00:00
endolf ae942dd3cc Updated build scripts to build java 1.4 byte code 2005-08-28 20:52:26 +00:00
endolf c15d74238d More rumbler debug 2005-08-28 09:23:00 +00:00
endolf def8e4976b Extra debug for rumblers 2005-08-27 09:22:16 +00:00
endolf be7b59d328 Re added the fade test 2005-08-27 09:21:48 +00:00
endolf f48ee8f6f4 Start of some work to print more debug if force feedback effect creation fails 2005-08-27 08:22:19 +00:00
endolf cebedc9479 Added shutdown hooks to stop rumblers before quitting. 2005-08-27 08:21:42 +00:00
jeffpk 98ab1d6fe4 Added handlign for unknown windows versions 2005-08-23 20:59:32 +00:00
endolf 04e3538e83 Added cleanup stuff for rumblers, it doesn't fix the code, but is nice 2005-07-16 15:09:04 +00:00
endolf d4c72ba15c Couple if inux rumbler differences, including including the added file 2005-07-16 13:07:45 +00:00
endolf df432c29ae Linux rumbler support
IT DOES NOT WORK YET though.

I'm in contact with the kernel module developers as I think it's a kernel bug
2005-07-03 20:05:34 +00:00
endolf 38d108b857 Changed the binary library name 2005-06-19 17:41:40 +00:00
endolf d222fad271 Updated the name of the linux native library 2005-06-19 15:33:12 +00:00
endolf c2bbf1d876 Extra debug info 2005-06-19 15:32:44 +00:00
endolf decd93d226 If the default plugin is not in the classpath, an exception gets thrown.
This should only happen if it's also not in the plugins directory.
2005-06-16 16:32:59 +00:00
endolf 9f9ac8834c Opps 2005-06-16 13:43:04 +00:00
endolf 8fb52e9ea4 Added the simple_dist task and subtasks to build the single
distributable zip/tgz for each platform that includes the core classes,
the default plugins classes, the jutils classes, and the binary library
for that platform.
2005-06-16 13:38:16 +00:00
endolf 4a07a72323 Unless otherwise specified (using the property), the plugin loader will
now automatically try and load the plugin specific to that platform. The
plugins path will be scanned first, and if found, the plugin will not be
reloaded.
2005-06-15 12:26:14 +00:00
endolf e6c082f399 The changes of Axis.Identifier to Component.Identifier was obviously not checked under windows. My fault. Fixed (I hope) 2005-06-15 09:20:16 +00:00
endolf 9dd954a4f4 Guess who found the device that pops the buffer size?, was getting an array out of bounds. 2005-06-15 09:09:09 +00:00
endolf b5bea30cc2 For some reason, my ubunto boxes with jdk 1.5.0_02 all seem to have
java.home set to the jre dir, even though a 'which java' reveals it's
using the jdk one, not the jre one. This causes the include dir not to
be found and causes the build to fail. Made it so that the build file
looks for includes relative to the jre dir and the jdk dir, so all
systems should work (yeah, right)
2005-06-14 11:19:55 +00:00
cjcdoomed 0d155c818c Issue number: Implemented OSXJoystick functionality
Submitted by:  Chris Cooper cjcdoomed@gmail.com
2005-05-20 14:25:24 +00:00
endolf ab7bba58d6 Will try to open the device for read/write first, if that fails, trys
read only and displays a message about not being enabled for force
feedback
2005-05-08 09:58:31 +00:00
cjcdoomed eac5380da4 Issue: OS X Nightly build not compiling
Obtained from:
Submitted by:  Chris Cooper
Reviewed by:
2005-05-06 05:00:46 +00:00
endolf fc587842d0 Handle missing absolute axis ID's 2005-05-05 08:07:51 +00:00
endolf e48688ce73 Regenerated from 2.6.10 headers 2005-05-04 18:16:23 +00:00
endolf fa0b606105 Event devices now opened read only 2005-05-04 18:15:08 +00:00
jeffpk 4be7c6e38b Updated EventDevice.cpp to handle EV_SYN properly 2005-05-01 23:25:38 +00:00
jeffpk 3a67a298a8 Updated linux plugin to build under Linux 2.6.5-7.151
Note, these are hacky fixes that may break it under earlier versions of Linux. Sorry.
2005-04-28 05:19:22 +00:00
endolf fa132b2126 Changes for Axis.Identifier changes. This includes renaming Axis to Component, and creating the Identifier objects for Key Axis and Button. 2004-08-29 21:23:06 +00:00
endolf e312d8dd34 Initial checkin 2004-08-29 20:17:39 +00:00
endolf 9741fccdfa Updates so that for now keyboards are just created as normal devices, this means the Axis.Identifiers are not the standard ones, but the correct things are now show and no excpetions are seen on the Logitech Elite keyboard (or any that has axis as well) 2004-07-07 23:16:03 +00:00
endolf 5fb795d2fd If a joystick hat isn't configured properly, or if it's digital, then the axis data is not -32676, 0 or 32767 it is -1, 0 or 1. Updated the hat object to reflect this. 2004-07-07 23:09:41 +00:00
endolf bbb5c4e0af Issue number: 18 2004-06-21 21:48:44 +00:00
endolf cd663ae444 Possible fix for sigfault on linux, need to test more 2004-06-21 21:44:16 +00:00
endolf 307a1d5ff3 Updated the type guess code so that anything that doesn't have a characteristic of a particular type, wont get guessed as that type, it was possible for devices with no characteristics of any of the known types to be classed as a stick, now it should not. 2004-04-21 16:19:42 +00:00
endolf b0458c08d1 Fix for issue 27
Controller types not set up in linux
2004-04-21 11:00:05 +00:00
endolf 2dc9aae5e2 fixes for issues 25 and 26
Sigsgv with logitec USB keyboard with volume controls and mouse wheel

when valid event device list in /dev/input/event* has invalid devices in the middle of the sequence, a sigsegv is seen
2004-04-21 09:48:55 +00:00
endolf 54ecf9687a Added jinput.controllerPluginPath property to package documentation 2004-04-02 10:09:03 +00:00
endolf 004375ec03 First quick attempt at package javadoc to show the properties for plugin loading 2004-04-02 10:04:45 +00:00
gregorypierce ad0fd45046 Changes for the nightly build 2004-02-28 05:45:22 +00:00
gregorypierce 5c17a27a53 Updated to include OSX information
Issue number:
Obtained from:
Submitted by:  Gregory Pierce
Reviewed by:
2004-02-28 02:52:08 +00:00
gregorypierce 06c28ad3da Updated so that if a key gets enumerated multiple times, only the first enumeration will be accepted. This was done to stop an issue with certain keys in OSX being enumerated more than once - the first being the correct HID code (assumption) and the second being something wrong. It is not clear why those keys were being enumerated more than once to begin with. But this solves the problem. 2004-02-28 01:26:36 +00:00
gregorypierce 6eb181e4be Updated for correct build environment 2004-02-28 01:24:09 +00:00
gregorypierce 32c2c63818 Updated for better debugging output. 2004-02-28 01:23:22 +00:00
gregorypierce 1376adde46 Updated for proper build settings. 2004-02-28 01:22:41 +00:00
djp 212ab383d4 Initial version 1.0.0-b01 2004-02-18 17:17:18 +00:00
endolf 9258d5763c Added Z axis support for rumblers 2003-12-02 19:10:06 +00:00
endolf d7efdf03a0 Updated (added) javadoc 2003-12-02 19:03:37 +00:00
endolf ec62ee8549 Updated rumblers to be able to get their axis name and axis identifier 2003-12-02 18:55:13 +00:00
endolf a4176e75f8 Initial rumbler support 2003-12-01 23:42:30 +00:00
endolf f4c4499bf3 Initial rumbler test support 2003-12-01 23:41:20 +00:00
endolf 28f05a7e9d Added jinput.plugins (or net.java.games.input.plugins, both work) to allow plugin class names to be specified for useage with webstart. 2003-11-28 22:47:24 +00:00
athomas b57d33999e updated navbar 2003-11-22 09:07:52 +00:00
athomas 4155042e11 updated navbar 2003-11-22 08:13:25 +00:00
athomas 0c5d5d09be new navbar to match color scheme. Not so fruity as the purple nav bar (sorry Chris!) 2003-11-15 07:33:25 +00:00
athomas ae53c68797 new navbar to match color scheme. Not so fruity as the purple nav bar (sorry Chris!) 2003-11-15 07:27:48 +00:00
endolf 21cb0446d1 Added the logger macros so I don't have to keep manually adding the
statements back in every time something breaks

Fixed a crash under linux if when it was thinking there was at least one
more joystick that it really had, funnily enough when it tried to get
data from this joystick, it all went bang.
2003-10-29 22:36:31 +00:00
endolf a8cbd46c50 Fixes to solve issue 21 2003-10-20 18:41:26 +00:00
athomas b9346a6a83 fixed link to forums to eliminate IE bug 2003-10-11 06:46:09 +00:00
endolf e749b96a4a Fix and updated error messages for issue 20 2003-10-04 12:48:51 +00:00
endolf 46e48bb00e Fixes for issue 4 and 5, mouse data under DX is normalised
and shouldn't be
Enhancment 19, Windows only supports 4 mouse buttons.
2003-10-03 22:03:25 +00:00
endolf 1b7e1217f7 I had done the mouse axis as normalised to match the windows
version, as I am about to commit changes to fix that version, I
have sitch over the workings of this one too
2003-10-03 21:42:48 +00:00
endolf dadac91706 Added windows 98 to build options as jinput will work with it. 2003-10-03 20:15:06 +00:00
swpalmer 9d6240f1b3 Preliminary Ant build support for OS X 2003-09-04 15:12:02 +00:00
swpalmer 19bfad3e91 Added preliminary OS X support to the Ant build process 2003-09-04 15:11:22 +00:00
endolf 3c3175b242 Forgot to remove debug before commiting 2003-09-04 11:58:06 +00:00
endolf 19b89b0942 Added property java.controllerPluginPath that enables users to specify
their own path for the controller plugin.
2003-09-04 11:50:06 +00:00
gregorypierce 144c3501e5 Add HID properties and CROSSTABLE entries to move from JInput keys to HID cookies and poll keyboard keys 2003-08-09 18:19:34 +00:00
gregorypierce 09ae0599ef Change to ignore non HID compliant devices and to correct a bug where usage page passed as element type 2003-08-09 18:18:43 +00:00
gregorypierce eade1ce044 Couple of bug fixes 2003-08-09 18:17:38 +00:00
gregorypierce d1e7bf020d Added information for keyboard return codes. There are many international keys whose mappings are not totally clear. 2003-08-08 07:08:41 +00:00
gregorypierce aeea752a6f no message 2003-08-07 21:57:08 +00:00
gregorypierce c88f6ab0c6 no message 2003-08-07 18:28:18 +00:00
endolf 61f8b10374 Added dist target 2003-08-06 17:49:43 +00:00
gregorypierce 9aa4e82038 no message 2003-08-06 01:02:58 +00:00
gregorypierce 24d639f5be Initial release of native library 2003-08-05 18:33:07 +00:00
gregorypierce c2688c3ae8 no message 2003-08-05 18:32:27 +00:00
gregorypierce 6e8132cedf Initial update - partial merge with JInput 2003-08-05 18:31:29 +00:00
endolf 6f376aacfe jinput.jar location got moved back 2003-08-05 18:05:23 +00:00
gregorypierce f665e62ad9 Changed bin back to dist, removed extra definition of target all 2003-08-05 17:42:32 +00:00
endolf 80718c255b jinput.jar got moved from bin to dist 2003-08-05 16:56:43 +00:00
endolf 87b9654ed6 The all target had been added giving two all targets, two all targets = build failure :) 2003-08-05 16:33:53 +00:00
gregorypierce 9c58992810 Changed output to /dist/jinput.jar as opposed to /bin/controller.jar 2003-08-05 15:23:30 +00:00
endolf a35964c6ad fixed ant clean fails on windows because the linux ant script can't find
the classes dir to delete
2003-08-05 08:14:46 +00:00
endolf ef7559ab41 Changed controller.jar to jinput.jar as per
http://www.JavaGaming.org/cgi-bin/JGNetForums/YaBB.cgi?board=jinput;action=display;num=1059866464
2003-08-05 08:04:18 +00:00
endolf edc587f3e9 Changed os name on createNativeDefinitons.java as it was
incorrectly capitalised
2003-07-31 20:12:01 +00:00
endolf fce8c6c7ec Initial commit of linux plugin 2003-07-31 20:11:03 +00:00
endolf d3b10d018f Added 4 new mouse buttons 2003-07-31 19:38:44 +00:00
endolf 52ad786cb0 Added I8042 (ps/2) and Parallel port types 2003-07-31 19:37:29 +00:00
endolf 1b4afd7352 Initial commit of Linux plugin 2003-07-31 19:34:46 +00:00
endolf c4bc78af27 no message 2003-07-31 18:46:47 +00:00
endolf bcbbe869a7 no message 2003-07-31 18:36:31 +00:00
endolf 597fd338dd g++ rather than gcc is needed to build C++ files, and added windows xp to the list of OSs to build the native library on. 2003-07-31 18:31:33 +00:00
jeffpk acb4dbdb0c Some additional info added about setting up build environment, 2003-07-30 22:18:20 +00:00
jeffpk 792d51aafb <No Comment Entered> 2003-07-30 22:14:32 +00:00
jeffpk 45411a32c3 Ignore list created 2003-07-30 22:14:23 +00:00
gregorypierce b6a6416f8e Update to move native pointers to Java code, to retrieve the correct device types from the HID tables, to open/close the device and prepare to poll data from the device data queues 2003-07-29 05:15:11 +00:00
gregorypierce 14e0af5493 no message 2003-07-28 14:46:07 +00:00
gregorypierce 09418e2664 Initial revision 2003-07-26 04:50:27 +00:00
gregorypierce 55171e1127 Initial checking 2003-07-24 03:25:48 +00:00
endolf c931dd231c Update to allow hat switches to be in 4 more positions. 2003-07-23 12:22:55 +00:00
jeffpk 7c2ae4030d Add link to dev agreement 2003-07-08 18:26:40 +00:00
athomas 38ad15b535 added navbar 2003-06-26 15:57:23 +00:00
jeffpk b3a1e3aa3c Slightly modified to talk to modified Plugin API in Jutils.
(Will now fail gracefully and silently if there is no controller directory
available to search for plugins.)
2003-06-26 00:04:53 +00:00
jeffpk de25a38b88 Modified so it will only build the dx8 plugin if run under Windows. 2003-06-26 00:03:05 +00:00
jeffpk c90aa7cede The *right* page (intiial upload was incorrect) 2003-06-07 19:21:04 +00:00
jeffpk bd22b4a54f Custom front page. Initial version 2003-06-07 18:50:40 +00:00
jeffpk 0f3b87fadf added note about dependancy on jutils.jar 2003-06-06 21:45:20 +00:00
184 changed files with 20148 additions and 4213 deletions

13
.gitignore vendored Normal file
View file

@ -0,0 +1,13 @@
.classpath
.project
.settings/
build/
target/
apidocs/
bin/
classes/
dist/
eclipse_bin/
*.iml
.idea/
dependency-reduced-pom.xml

144
Jenkinsfile vendored Normal file
View file

@ -0,0 +1,144 @@
pipeline {
agent none
triggers { pollSCM('H/15 * * * *') }
tools {
maven 'Maven 3.5.3'
jdk 'OpenJDK 9'
}
options { buildDiscarder(logRotator(numToKeepStr: '5')) }
parameters {
booleanParam(defaultValue: false, description: 'Perform Release', name: 'release')
}
stages {
stage('Build core') {
agent {
label "osx"
}
steps {
sh 'mvn -B -Dmaven.antrun.skip -Dmaven.source.skip -Dmaven.test.skip -DskipTests -DskipITs -pl coreAPI/ package'
}
post {
success {
archiveArtifacts artifacts: 'coreAPI/target/apidocs/**/*', fingerprint: true
}
}
}
stage('Build natives') {
parallel {
stage('Build Windows natives') {
agent {
label "windows"
}
steps {
bat 'mvn -B -am -pl plugins/windows/,plugins/wintab/ clean compile'
}
post {
success {
stash includes: 'plugins/**/target/natives/*.dll', name: 'windows-natives'
}
}
}
stage('Build Linux natives') {
agent {
label "linux"
}
steps {
sh 'mvn -B -am -pl plugins/linux/ clean compile'
}
post {
success {
stash includes: 'plugins/**/target/natives/*.so*', name: 'linux-natives'
}
}
}
stage('Build OSX natives') {
agent {
label "osx"
}
steps {
sh 'mvn -B -am -pl plugins/OSX/ clean compile'
}
post {
success {
stash includes: '**/target/natives/*.jnilib', name: 'osx-natives'
}
}
}
}
}
stage('Build') {
agent {
label "linux"
}
steps {
unstash 'windows-natives'
unstash 'osx-natives'
unstash 'linux-natives'
sh 'mvn -B -P windows,linux,osx,wintab -Dmaven.antrun.skip -Dmaven.javadoc.skip -Dmaven.source.skip -Dmaven.test.skip -DskipTests -DskipITs package'
}
post {
success {
stash includes: '**/target/*.jar', name: 'all-java-jars'
archiveArtifacts artifacts: '**/target/*.jar*', fingerprint: true
}
}
}
stage('Deploy') {
agent {
label "linux"
}
when { branch 'master' }
steps {
milestone(1)
unstash 'windows-natives'
unstash 'osx-natives'
unstash 'linux-natives'
sh 'echo $GPG_SECRET_KEYS | base64 --decode | gpg --batch --import'
sh 'echo $GPG_OWNERTRUST | base64 --decode | gpg --import-ownertrust'
withMaven(
maven: 'Maven 3.5.3',
jdk: 'OpenJDK 9',
globalMavenSettingsConfig: 'global-maven-settings-ossrh',
mavenOpts: '-Djavax.net.ssl.trustStore=/etc/ssl/certs/java/cacerts' //Work around for JDK9 missing cacerts
) {
sh "mvn -P windows,linux,osx,wintab -Dmaven.antrun.skip -Dmaven.test.skip -DskipTests -DskipITs deploy"
}
}
}
stage('Release') {
agent {
label "linux"
}
when {
expression {
return params.release
}
}
steps {
milestone(3)
unstash 'windows-natives'
unstash 'osx-natives'
unstash 'linux-natives'
sh 'echo $GPG_SECRET_KEYS | base64 --decode | gpg --batch --import'
sh 'echo $GPG_OWNERTRUST | base64 --decode | gpg --import-ownertrust'
withMaven(
maven: 'Maven 3.5.3',
jdk: 'OpenJDK 9',
globalMavenSettingsConfig: 'global-maven-settings-ossrh',
mavenOpts: '-Djavax.net.ssl.trustStore=/etc/ssl/certs/java/cacerts' //Work around for JDK9 missing cacerts
) {
sh "mvn -P windows,linux,osx,wintab versions:set -DremoveSnapshot"
script {
VERSION_TAG = sh(script: "mvn -Dexpression=project.version help:evaluate | grep -e '^[[:digit:]]'", returnStdout: true).trim()
}
sh "git tag -a ${VERSION_TAG} -m 'Release tag ${VERSION_TAG}'"
sh "mvn -P windows,linux,osx,wintab,release -Dmaven.antrun.skip -Dmaven.test.skip -DskipTests -DskipITs deploy"
sh "mvn -P windows,linux,osx,wintab versions:revert"
sh "mvn -P windows,linux,osx,wintab versions:set -DnextSnapshot"
sh "git commit -m 'Next development release' ."
sh "git push origin HEAD:master --follow-tags"
}
}
}
}
}

9
README.md Normal file
View file

@ -0,0 +1,9 @@
# JInput
[![Maven Central](https://img.shields.io/maven-central/v/net.java.jinput/coreapi.svg)](https://maven-badges.herokuapp.com/maven-central/net.java.jinput/coreapi)
[![Javadocs](http://www.javadoc.io/badge/net.java.jinput/coreapi.svg)](http://www.javadoc.io/doc/net.java.jinput/coreapi)
Library for access to input devices.
## License
Licensed under [BSD License](https://opensource.org/licenses/BSD-3-Clause), copyright is attributed in each source file committed.

View file

@ -1,81 +0,0 @@
Project: net.java.games.*
Purpose: Open source game libraries
Authors:
-- input API design:
Michael Martak, Sun Microsystems
Thomas Daniel, Sony Computer Entertainment
-- input API original author:
Michael Martak,Sun Microsystems
-- input API original release author:
Jeff Kesselman, Game Technology Architect,
Advanced Software Technologies Group,
Sun Microsystems.
-- this file updated on 06/06/2003 by Jeff Kesselman
Introduction:
This is the source tree for the Java Game Initiative (JGI) Open Source
client game programming APIs.
Build Requirements:
This project has been built in the follwing environment.
-- Win32 (Win 2000 in the case of our machine)
-- Sun J2SDK 1.4 (available at java.sun.com)
-- MinGW 2.0.0 plus the following updates: (all available at www.mingw.org)
-- binutils 2.13.90
-- w32api-2.2
-- mingw-runtime-2.4
-- "Peter Puck's" directx8 binding
(http://www.urebelscum.speedhost.com/download.html, file: dx8libs.zip
-- ANT 1.4.1 (available at apache.org)
Directory Organization:
The root contains a master ANT build.xml and the following sub directories:
-- coreAPI: The actual API
-- plugins: Directories for bildign controlelr plugins.
(Currently the only plug in is the Win32 DX8 plugin.)
Build instructions:
To clean: ant clean
To build: ant all (or just ant)
To build docs: ant javadoc
To test:
First cd to coreAPI. There are currently 2 tests there.
Textest: A simple discovery test that dumps
the data about the discovered controllers to stdout
To run: ant textest
Readtest: A test that creates a window for each discovered
controller (or sub-controller) which displays the
current state of all the controller's axiis.
(Note: The windows currrently all open at the same
place on the screen so yo uwill have to move them to
see them all.)
To run: ant readtest
Release Info:
Initial Release: This release contains an implementation of the input
API designed by Mike Martak of Sun and Thomas (?) of Sony CEA for
the WIn32 platform. All the code in src/input is cross platform. The
Win32 code is segregated to the DirectX plugin (src/DXplugin) which
depends on DirectInput from DX7 (or later).
05/09/2003: A number of bugs and problems with the DXPlugin are fixed in this
release. This release also brings the code up to date using the DI8
interface. This thus is the first release that requries Peter Puck's
DX8 bindings to compile with MinGW.
05/09/2003 (second update):
This version adds a new standard value type to the API.
Axis.POV holds standard definitions for values for POV (hat) switches
-- Axis.POV.CENTER and Axis.POV.OFF are synonmous and are
the center position.
-- Axis.POV.UP, Axis.POV.DOWN, Axis.POV.LEFT and Axis.POV.RIGHT
should be self explainatory.
Any hat that claims to be "normalized" will return these values. (It is
recommended that all hats be normalized by the systemn specific plugins.)

18
applet/jinput-event.html Normal file
View file

@ -0,0 +1,18 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="content-language" content="en">
<title>JInput Applet Test</title>
<script src="http://java.com/js/deployJava.js"></script>
</head>
<body>
<script>
deployJava.setInstallerType('kernel');
// include any required packages as shown below
deployJava.setAdditionalPackages('javax.swing, javax.xml');
deployJava.runApplet({codebase:".",
archive:"jinput.jar,jinput-test.jar,jinput-applet-test.jar", code:"net.java.games.input.applet.test.ControllerEventTestApplet",
width:"320", Height:"400"}, null, "1.4.2");
</script>
</body>
</html>

18
applet/jinput.html Normal file
View file

@ -0,0 +1,18 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="content-language" content="en">
<title>JInput Applet Test</title>
<script src="http://java.com/js/deployJava.js"></script>
</head>
<body>
<script>
deployJava.setInstallerType('kernel');
// include any required packages as shown below
deployJava.setAdditionalPackages('javax.swing, javax.xml');
deployJava.runApplet({codebase:".",
archive:"jinput.jar,jinput-test.jar,jinput-applet-test.jar", code:"net.java.games.input.applet.test.ControllerReadTestApplet",
width:"320", Height:"400"}, null, "1.4.2");
</script>
</body>
</html>

27
applet/pom.xml Normal file
View file

@ -0,0 +1,27 @@
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>applet</artifactId>
<packaging>jar</packaging>
<name>JInput - applet</name>
<parent>
<groupId>net.java.jinput</groupId>
<artifactId>jinput-parent</artifactId>
<version>2.0.10-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,213 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input.applet;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JInputAppletResourceLoader {
private static final Logger diagnosticLog = Logger.getLogger(JInputAppletResourceLoader.class.getName());
private int percentageDone = 0;
private String getPrivilegedProperty(final String property) {
return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(property));
}
private String setPrivilegedProperty(final String property, final String value) {
return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.setProperty(property, value));
}
public void loadResources(URL codeBase) throws IOException {
downloadNativesJar(codeBase);
extractNativesJar(codeBase);
setJInputClasspath(codeBase);
}
public int getPercentageDone() {
return percentageDone;
}
private void setJInputClasspath(URL codeBase) {
setPrivilegedProperty("net.java.games.input.librarypath", getTempDir(codeBase) + File.separator + "natives" + File.separator);
}
private void extractNativesJar(URL codeBase) throws IOException {
File tempDir = new File(getTempDir(codeBase));
String osName = getPrivilegedProperty("os.name");
String nativeJar = null;
if (osName.startsWith("Win")) {
nativeJar = "jinput-windows-native.jar";
} else if (osName.startsWith("Linux") || osName.startsWith("FreeBSD")) {
nativeJar = "jinput-linux-native.jar";
} else if (osName.startsWith("Mac")) {
nativeJar = "jinput-osx-native.jar";
} else {
}
JarFile localJarFile = new JarFile(new File(tempDir, nativeJar), true);
Enumeration<JarEntry> jarEntries = localJarFile.entries();
int totalUncompressedBytes = 0;
int totalUncompressedBytesWritten = 0;
List<JarEntry> entriesToUse = new ArrayList<>();
while(jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
String entryName = jarEntry.getName();
if(!entryName.startsWith("META-INF")) {
totalUncompressedBytes+=jarEntry.getSize();
entriesToUse.add(jarEntry);
diagnosticLog.log(Level.INFO, "Got entry " + entryName + " " + jarEntry.getSize() + " big, total of " + totalUncompressedBytes);
}
}
File tempNativesDir = new File(tempDir, "natives");
if(!tempNativesDir.exists()) {
tempNativesDir.mkdirs();
tempNativesDir.deleteOnExit();
}
for(int i=0;i<entriesToUse.size();i++) {
JarEntry jarEntry = entriesToUse.get(i);
InputStream inStream = localJarFile.getInputStream(localJarFile.getEntry(jarEntry.getName()));
File nativeFile = new File(tempNativesDir, jarEntry.getName());
FileOutputStream fos = new FileOutputStream(nativeFile);
byte[] dataBuffer = new byte[65535];
int bytesRead = 0;
// Read the first block
bytesRead = inStream.read(dataBuffer, 0, dataBuffer.length);
while(bytesRead!=-1) {
fos.write(dataBuffer, 0, bytesRead);
totalUncompressedBytesWritten+=bytesRead;
int unpackingPercentageDone = (int)((((float)totalUncompressedBytesWritten)/totalUncompressedBytes)*100);
percentageDone = 50 + (unpackingPercentageDone/2); //Reading the file is only 1/2 the job
diagnosticLog.log(Level.INFO, "Written " + totalUncompressedBytesWritten + " out of " + totalUncompressedBytes + " " + unpackingPercentageDone + "%, (" + percentageDone + "% total)");
// Read the next block
bytesRead = inStream.read(dataBuffer, 0, dataBuffer.length);
}
long entryModifiedTime = jarEntry.getTime();
nativeFile.setLastModified(entryModifiedTime);
diagnosticLog.log(Level.INFO, "Setting native modified time to " + new Date(entryModifiedTime));
fos.close();
inStream.close();
}
}
private void downloadNativesJar(URL codeBase) throws IOException {
diagnosticLog.log(Level.INFO, "codebase: " + codeBase);
File tempDir = new File(getTempDir(codeBase));
if(!tempDir.exists()) {
tempDir.mkdirs();
tempDir.deleteOnExit();
}
String osName = getPrivilegedProperty("os.name");
String nativeJar = null;
if (osName.startsWith("Win")) {
nativeJar = "jinput-windows-native.jar";
} else if (osName.startsWith("Linux") || osName.startsWith("FreeBSD")) {
nativeJar = "jinput-linux-native.jar";
} else if (osName.startsWith("Mac")) {
nativeJar = "jinput-osx-native.jar";
} else {
}
File localJarFile = new File(tempDir, nativeJar);
localJarFile.deleteOnExit();
diagnosticLog.log(Level.INFO, "Using local file " + localJarFile.getCanonicalPath());
OutputStream outStream = new FileOutputStream(localJarFile);
outStream = new BufferedOutputStream(outStream);
URL remoteJarURL = new URL(codeBase, nativeJar);
diagnosticLog.log(Level.INFO, "Using remote file " + remoteJarURL);
URLConnection connection = remoteJarURL.openConnection();
connection.setUseCaches(false);
connection.setConnectTimeout(2000);
int contentLength = connection.getContentLength();
diagnosticLog.log(Level.INFO, "remote jar is " + contentLength + " bytes");
InputStream inStream = connection.getInputStream();
byte[] dataBuffer = new byte[65535];
int bytesRead = 0;
int totalRead = 0;
int totalWritten = 0;
// Read the first block
bytesRead = inStream.read(dataBuffer, 0, dataBuffer.length);
while(bytesRead!=-1) {
//Update total read
totalRead+=bytesRead;
outStream.write(dataBuffer, 0, bytesRead);
totalWritten+=bytesRead;
int thisFilePercent = (int)((((float)totalRead)/contentLength)*100);
percentageDone = thisFilePercent/2; //Reading the file is only 1/2 the job
diagnosticLog.log(Level.INFO, "Written " + totalRead + " out of " + contentLength + " " + thisFilePercent + "%, (" + percentageDone + "% total)");
// Read the next block
bytesRead = inStream.read(dataBuffer, 0, dataBuffer.length);
}
inStream.close();
outStream.close();
}
private String getTempDir(URL codeBase) {
return getPrivilegedProperty("java.io.tmpdir") + File.separator + codeBase.getHost() + File.separator + "jinput";
}
}

View file

@ -1,50 +0,0 @@
<?xml version="1.0"?>
<!-- Written to assume that classpath is rooted in the current directory. -->
<!-- So this should be OK if you make this script in the root of a filesystem. -->
<!-- If not, you may prefer to adjust the basedir, or move some directories around. -->
<!-- The idea is that both Ant and NetBeans have to know what the package root is -->
<!-- for the classes in your application. -->
<project name="Sun Games Initiative Client Technologies" basedir="." default="all">
<!-- Don't worry if you don't know the Ant syntax completely or need help on some tasks! -->
<!-- The standard Ant documentation is bundled. See Help | Help Sets | Ant 1.4.1 Manual. -->
<target name="init">
<!-- You can set up any variables you want used throughout the script here. -->
<!-- <property name="hello" value="world"/ -->
<!-- To use e.g. Jikes, uncomment this line. -->
<!-- (Or make the same change in Tools | Options | Ant Settings | Properties.) -->
<!-- <property name="build.compiler" value="jikes"/> -->
<!-- You might like to set up some overridable paths, etc.: -->
<!-- <property name="mylib" value="../lib/mylib.jar"/> -->
</target>
<target name="compile" depends="init">
<!-- Both srcdir and destdir should be package roots. -->
<!-- They could be different of course; in that case NetBeans can also be set -->
<!-- up to compile to a different filesystem in the same way; see Compiler Types: -->
<ant dir="coreAPI" />
<ant dir="plugins/DX8" />
</target>
<target name="javadoc" depends="init">
<!-- Both srcdir and destdir should be package roots. -->
<!-- They could be different of course; in that case NetBeans can also be set -->
<!-- up to compile to a different filesystem in the same way; see Compiler Types: -->
<ant dir="coreAPI" target="javadoc"/>
<ant dir="plugins/DX8" target="javadoc"/>
</target>
<target name="all" depends="init,compile" description="Build everything.">
<echo message="Application built. Hello ${hello}!"/>
</target>
<target name="clean" depends="init" description="Clean all build products.">
<ant dir="plugins/DX8" target="clean"/>
<ant dir="coreAPI" target="clean"/>
</target>
</project>

View file

@ -1,54 +0,0 @@
This file modified last on 06/06/2003 by Jeff Kesselman
This is the source tree for the core input API.
Directory Organization:
The root contains a master ANT build.xml.
After a successful build of the project you will have the following sub directories:
-- apidocs Where the javadocs get built to
-- lib Where dependant libraries are kept.
-- bin Where the actual API is built to
-- src The source files.
-- src/test Execution directories and data for tests.
Build instructions:
To clean: ant clean
To build: ant all (or just ant)
To build docs: ant javadoc
To test:
Textest: A simple discovery test that dumps
the data about the discovered controllers to stdout
To run: ant textest
Readtest: A test that creates a window for each discovered
controller (or sub-controller) which displays the
current state of all the controller's axiis.
(Note: The windows currrently all open at the same
place on the screen so yo uwill have to move them to
see them all.)
To run: ant readtest
Release Info:
Initial Release: This release contains an implementation of the input
API designed by Mike Martak of Sun and Thomas (?) of Sony CEA for
the WIn32 platform. All the code in src/input is cross platform. The
Win32 code is segregated to the DirectX plugin (src/DXplugin) which
depends on DirectInput from DX7 (or later).
05/09/2003: A number of bugs and problems with the DXPlugin are fixed in this
release. This release also brings the code up to date using the DI8
interface. This thus is the first release that requries Peter Puck's
DX8 bindings to compile with MinGW.
05/09/2003 (second update):
This version adds a new standard value type to the API.
Axis.POV holds standard definitions for values for POV (hat) switches
-- Axis.POV.CENTER and Axis.POV.OFF are synonmous and are
the center position.
-- Axis.POV.UP, Axis.POV.DOWN, Axis.POV.LEFT and Axis.POV.RIGHT
should be self explainatory.
Any hat that claims to be "normalized" will return these values. (It is
recommended that all hats be normalized by the systemn specific plugins.)

View file

@ -1,116 +0,0 @@
<?xml version="1.0"?>
<!-- Written to assume that classpath is rooted in the current directory. -->
<!-- So this should be OK if you make this script in the root of a filesystem. -->
<!-- If not, you may prefer to adjust the basedir, or move some directories around. -->
<!-- The idea is that both Ant and NetBeans have to know what the package root is -->
<!-- for the classes in your application. -->
<project name="Game Input API" basedir="." default="all">
<!-- Don't worry if you don't know the Ant syntax completely or need help on some tasks! -->
<!-- The standard Ant documentation is bundled. See Help | Help Sets | Ant 1.4.1 Manual. -->
<target name="init">
<!-- You can set up any variables you want used throughout the script here. -->
<!-- property name="hello" value="world" -->
<!-- To use e.g. Jikes, uncomment this line. -->
<!-- (Or make the same change in Tools | Options | Ant Settings | Properties.) -->
<!-- <property name="build.compiler" value="jikes"/> -->
<!-- You might like to set up some overridable paths, etc.: -->
<property name="utils" value="lib/jutils.jar"/>
<mkdir dir="apidocs"/>
<mkdir dir="classes"/>
<mkdir dir="bin"/>
</target>
<target name="compile" depends="init">
<!-- Both srcdir and destdir should be package roots. -->
<!-- They could be different of course; in that case NetBeans can also be set -->
<!-- up to compile to a different filesystem in the same way; see Compiler Types: -->
<javac srcdir="src/java" destdir="classes" debug="true" deprecation="true" source="1.4">
<include name="net/**"/>
<!-- To add something to the classpath: -->
<classpath>
<pathelement location="${utils}"/>
</classpath>
<!-- To exclude some files: -->
<!--
<exclude name="com/foo/SomeFile.java"/>
<exclude name="com/foo/somepackage/"/>
-->
</javac>
</target>
<target name="jar" depends="init,compile">
<!-- To make a standalone app: -->
<!-- 1. Create a myapp.mf manifest somewhere. -->
<!-- 2. Put in it: -->
<!-- Manifest-Version: 1.0 -->
<!-- Main-Class: com.foo.Main -->
<!-- 3. Pass to <jar>: manifest="myapp.mf" -->
<jar jarfile="bin/controller.jar" compress="true" basedir="classes">
<include name="net/**"/>
<exclude name="**/*.java"/>
<exclude name="**/*.form"/>
<exclude name="myapp.mf"/>
<exclude name="myapp.jar"/>
</jar>
<copy file="bin/controller.jar" todir="../plugins/DX8/lib" />
</target>
<target name="all" depends="init,jar" description="Build everything.">
<echo message="Application built. Hello ${hello}!"/>
</target>
<target name="texttest" depends="init,all" description="Try running it.">
<java classname="net.java.games.input.test.ControllerTextTest"
fork="true" failonerror="true" dir="src/tests">
<classpath>
<pathelement location="bin/controller.jar"/>
<pathelement location="${utils}"/>
</classpath>
<!-- Pass some args, perhaps: -->
<!-- <arg value="-myfile"/> -->
<!-- Will be given as an absolute path: -->
<!-- <arg file="myfile.txt"/> -->
</java>
</target>
<target name="readtest" depends="init,all" description="Try running it.">
<java classname="net.java.games.input.test.ControllerReadTest"
fork="true" failonerror="true" dir="src/tests">
<classpath>
<pathelement location="bin/controller.jar"/>
<pathelement location="${utils}"/>
</classpath>
<!-- Pass some args, perhaps: -->
<!-- <arg value="-myfile"/> -->
<!-- Will be given as an absolute path: -->
<!-- <arg file="myfile.txt"/> -->
</java>
</target>
<target name="javadoc" depends="init" description="Javadoc for my API.">
<javadoc packagenames="net.java.games.input.*"
destdir="apidocs"
additionalparam="-source 1.4">
<sourcepath>
<pathelement location="src/java"/>
</sourcepath>
<classpath>
<pathelement location="${utils}"/>
</classpath>
</javadoc>
</target>
<target name="clean" depends="init" description="Clean all build products.">
<delete>
<fileset dir="classes">
<include name="**/*.class"/>
</fileset>
</delete>
<delete file="bin/controller.jar"/>
<delete dir="apidocs"/>
<delete file="../plugins/DX8/lib/controller.jar" />
</target>
</project>

31
coreAPI/pom.xml Normal file
View file

@ -0,0 +1,31 @@
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>coreapi</artifactId>
<packaging>jar</packaging>
<name>JInput - core API</name>
<parent>
<groupId>net.java.jinput</groupId>
<artifactId>jinput-parent</artifactId>
<version>2.0.10-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>net.java.jutils</groupId>
<artifactId>jutils</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<!-- <plugin> -->
<!-- <artifactId>maven-javadoc-plugin</artifactId> -->
<!-- </plugin> -->
</plugins>
</build>
</project>

View file

@ -1,349 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
/**
* An axis is a single button, slider, or dial, which has a single range. An
* axis can hold information for motion (linear or rotational), velocity,
* force, or acceleration.
*/
public interface Axis {
/**
* Returns the identifier of the axis.
*/
public abstract Identifier getIdentifier();
/**
* Returns <code>true</code> if data returned from <code>poll</code>
* is relative to the last call, or <code>false</code> if data
* is absolute.
*/
public abstract boolean isRelative();
/**
* Returns whether or not the axis is analog, or false if it is digital.
*/
public abstract boolean isAnalog();
/**
* Returns whether or not data polled from this axis is normalized
* between the values of -1.0f and 1.0f.
* @see #getPollData
*/
public abstract boolean isNormalized();
/**
* Returns whether or not this axis is ready to receive polling data.
* @see #getPollData
* @see Controller#poll
* @see #setPolling
*/
public abstract boolean isPolling();
/**
* Sets whether or not the axis should receive polling data.
* @see #getPollData
* @see Controller#poll
* @see #isPolling
*/
public abstract void setPolling(boolean polling);
/**
* Returns the suggested dead zone for this axis. Dead zone is the
* amount polled data can vary before considered a significant change
* in value. An application can safely ignore changes less than this
* value in the positive or negative direction.
* @see #getPollData
*/
public abstract float getDeadZone();
/**
* Returns the data from the last time the control has been polled.
* If this axis is a button, the value returned will be either 0.0f or 1.0f.
* If this axis is normalized, the value returned will be between -1.0f and
* 1.0f.
* @see Controller#poll
*/
public abstract float getPollData();
/**
* Returns a human-readable name for this axis.
*/
public abstract String getName();
/**
* Identifiers for different Axes.
*/
public static class Identifier {
/**
* Name of axis type
*/
private final String name;
/**
* Protected constructor
*/
protected Identifier(String name) {
this.name = name;
}
/**
* Returns a non-localized string description of this axis type.
*/
public String getName() {
return name;
}
/**
* Returns a non-localized string description of this axis type.
*/
public String toString() {
return name;
}
/**
* An axis for specifying vertical data.
*/
public static final Identifier X = new Identifier("x");
/**
* An axis for specifying horizontal data.
*/
public static final Identifier Y = new Identifier("y");
/**
* An axis for specifying third dimensional up/down
* data, or linear data in any direction that is
* neither horizontal nor vertical.
*/
public static final Identifier Z = new Identifier("z");
/**
* An axis for specifying left-right rotational data.
*/
public static final Identifier RX = new Identifier("rx");
/**
* An axis for specifying forward-back rotational data.
*/
public static final Identifier RY = new Identifier("ry");
/**
* An axis for specifying up-down rotational data
* (rudder control).
*/
public static final Identifier RZ = new Identifier("rz");
/**
* An axis for a button or key.
*/
public static final Identifier BUTTON = new Identifier("button");
/**
* An axis for a slider or mouse wheel.
*/
public static final Identifier SLIDER = new Identifier("slider");
/**
* An axis for a point-of-view control.
*/
public static final Identifier POV = new Identifier("pov");
/**
* An axis for specifying vertical velocity data.
*/
public static final Identifier X_VELOCITY =
new Identifier("x-velocity");
/**
* An axis for specifying horizontal velocity data.
*/
public static final Identifier Y_VELOCITY =
new Identifier("y-velocity");
/**
* An axis for specifying third dimensional up/down velocity
* data.
*/
public static final Identifier Z_VELOCITY =
new Identifier("z-velocity");
/**
* An axis for specifying left-right angular velocity data.
*/
public static final Identifier RX_VELOCITY =
new Identifier("rx-velocity");
/**
* An axis for specifying forward-back angular velocity data.
*/
public static final Identifier RY_VELOCITY =
new Identifier("ry-velocity");
/**
* An axis for specifying up-down angular velocity data.
*/
public static final Identifier RZ_VELOCITY =
new Identifier("rz-velocity");
/**
* An axis for slider or mouse wheel velocity data.
*/
public static final Identifier SLIDER_VELOCITY =
new Identifier("slider-velocity");
/**
* An axis for specifying vertical acceleration data.
*/
public static final Identifier X_ACCELERATION =
new Identifier("x-acceleration");
/**
* An axis for specifying horizontal acceleration data.
*/
public static final Identifier Y_ACCELERATION =
new Identifier("y-acceleration");
/**
* An axis for specifying third dimensional up/down acceleration
* data.
*/
public static final Identifier Z_ACCELERATION =
new Identifier("z-acceleration");
/**
* An axis for specifying left-right angular acceleration data.
*/
public static final Identifier RX_ACCELERATION =
new Identifier("rx-acceleration");
/**
* An axis for specifying forward-back angular acceleration data.
*/
public static final Identifier RY_ACCELERATION =
new Identifier("ry-acceleration");
/**
* An axis for specifying up-down angular acceleration data.
*/
public static final Identifier RZ_ACCELERATION =
new Identifier("rz-acceleration");
/**
* An axis for slider or mouse wheel acceleration data.
*/
public static final Identifier SLIDER_ACCELERATION =
new Identifier("slider-acceleration");
/**
* An axis for specifying vertical force data.
*/
public static final Identifier X_FORCE =
new Identifier("x-force");
/**
* An axis for specifying horizontal force data.
*/
public static final Identifier Y_FORCE =
new Identifier("y-force");
/**
* An axis for specifying third dimensional up/down force
* data.
*/
public static final Identifier Z_FORCE =
new Identifier("z-force");
/**
* An axis for specifying left-right angular force (torque) data.
*/
public static final Identifier RX_FORCE =
new Identifier("rx-force");
/**
* An axis for specifying forward-back angular force (torque) data.
*/
public static final Identifier RY_FORCE =
new Identifier("ry-force");
/**
* An axis for specifying up-down angular force (torque) data.
*/
public static final Identifier RZ_FORCE =
new Identifier("rz-force");
/**
* An axis for slider force data.
*/
public static final Identifier SLIDER_FORCE =
new Identifier("slider-force");
} // class Axis.Identifier
/**
* POV enum for different positions.
*/
public static class POV {
/**
* Standard value for center HAT position
*/
public static final float OFF = 0.0f;
/**
* Synonmous with OFF
*/
public static final float CENTER = OFF;
/**
* Standard value for up HAT position
*/
public static final float UP = 0.25f;
/**
* Standard value for right HAT position
*/
public static final float RIGHT = 0.50f;
/**
* Standard value for down HAT position
*/
public static final float DOWN = 0.75f;
/**
* Standard value for left HAT position
*/
public static final float LEFT = 1.0f;
} // class Axis.POV
} // interface Axis

View file

@ -1,232 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import net.java.games.util.plugins.*;
/**
* The default controller environment.
*
* @version %I% %G%
* @author Michael Martak
*/
class DefaultControllerEnvironment extends ControllerEnvironment {
static final boolean DEBUG =false;
/**
* The name of the properties file to find plugins.
*/
private final static String PROPERTY_FILENAME =
"controller.properties";
/**
* The name of the property for identifying a plugin (used
* as the value, the key being the class name).
*/
private final static String ID_PLUGIN =
"ControllerEnvironment";
/**
* Location of the LIB directory.
*/
static String libPath;
/**
* List of all controllers in this environment
*/
private ArrayList controllers;
/**
* Plug-in properties.
*/
private Properties properties = new Properties();
/**
* Plug-in class loader.
*/
private PluginClassLoader pluginLoader = new PluginClassLoader();
/**
* Public no-arg constructor.
*/
public DefaultControllerEnvironment() {
}
/**
* Returns a list of all controllers available to this environment,
* or an empty array if there are no controllers in this environment.
*/
public Controller[] getControllers() {
if (controllers == null) {
// Controller list has not been scanned.
controllers = new ArrayList();
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
scanControllers();
return DefaultControllerEnvironment.this;
}
});
}
Controller[] ret = new Controller[controllers.size()];
Iterator it = controllers.iterator();
int i = 0;
while (it.hasNext()) {
ret[i] = (Controller)it.next();
i++;
}
return ret;
}
/**
* Scans for controllers, placing them in the controllers list.
*/
/* This is Mike's old plugin code.
private void scanControllers() {
// Load properties object.
try {
loadProperties();
} catch (IOException e) {
// Could not find or read file, simply return.
return;
}
// Create a list of ControllerEnvironment classes.
// For each ControllerEnvironment, locate the class
// using the plugin class loader.
Iterator it = properties.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
assert key != null;
Object value = properties.get(key);
assert value != null;
if (value.equals(ID_PLUGIN)) {
try {
ControllerEnvironment plugin =
newPlugin(key.toString());
addControllers(plugin.getControllers());
} catch (Throwable t) {
System.err.println(
"Warning : could not load plugin " +
key.toString() + ", received exeption " +
t.toString());
t.printStackTrace(System.err);
}
}
}
}*/
/* This is jeff's new plugin code using Jeff's Plugin manager */
private void scanControllers() {
scanControllersAt(System.getProperty("java.home") +
File.separator + "lib"+File.separator+"controller");
scanControllersAt(System.getProperty("user.dir")+
File.separator+ "controller");
}
private void scanControllersAt(String path) {
try {
Plugins plugins = new Plugins(new File(path));
Class[] envClasses = plugins.getExtends(ControllerEnvironment.class);
for(int i=0;i<envClasses.length;i++){
try {
if (DEBUG) {
System.out.println("ControllerEnvironment "+
envClasses[i].getName()
+" loaded by "+envClasses[i].getClassLoader());
}
ControllerEnvironment ce = (ControllerEnvironment)
envClasses[i].newInstance();
addControllers(ce.getControllers());
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Retrieve the file "lib/control.properties" and
* load properties into properties object.
*/
private void loadProperties() throws IOException {
if (libPath == null) {
libPath = System.getProperty("java.home") +
File.separator + "lib";
}
File file = new File(libPath + File.separator +
PROPERTY_FILENAME);
FileInputStream inputStream = new FileInputStream(file);
properties.load(inputStream);
inputStream.close();
}
/**
* Create a new plugin ControllerEnvironment object
*/
/*
private ControllerEnvironment newPlugin(String name) throws
ClassNotFoundException, InstantiationException,
IllegalAccessException {
Class pluginClass = pluginLoader.loadClass(name);
if (!ControllerEnvironment.class.isAssignableFrom(pluginClass)) {
throw new ClassCastException(
"Plugin class must be assignable from " +
ControllerEnvironment.class.getName());
}
Object instance = pluginClass.newInstance();
return (ControllerEnvironment)instance;
}
*/
/**
* Add the array of controllers to our list of controllers.
*/
private void addControllers(Controller[] c) {
for (int i = 0; i < c.length; i++) {
controllers.add(c[i]);
}
}
}

View file

@ -1,168 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
/**
* A Keyboard is a type of controller consisting of a single controller,
* they keypad, which contains several axes (the keys). By default, all keys
* are set to receive polling data.
*/
public abstract class Keyboard extends AbstractController {
/**
* Protected constructor.
* Subclasses should initialize the array of axes to an array of keys.
* @param name The name of the keyboard
*/
protected Keyboard(String name) {
super(name);
}
/**
* Returns the type of the Controller.
*/
public Type getType() {
return Type.KEYBOARD;
}
/**
* Returns the axis corresponding to a particular key on the keypad,
* or null if a key with the specified ID could not be found.
*/
public Axis getAxis(Axis.Identifier id) {
assert axes != null;
// Default implementation uses indices to lookup keys
// in the array of axes
if (id instanceof KeyID) {
KeyID kid = (KeyID)id;
int index = kid.getKeyIndex();
assert axes.length > index;
return axes[index];
}
return null;
}
/**
* Returns whether or not the given key has been pressed since the last
* call to poll. This is called from a key's getPollData method.
*/
protected abstract boolean isKeyPressed(Key key);
/**
* Axis representing a single key. By default, all keys are set to receive
* polling data.
*/
public class Key extends AbstractAxis {
/**
* Key identifier
*/
private final KeyID keyID;
/**
* Construct a new key object
*/
public Key(KeyID keyID) {
super(keyID.toString(), keyID);
this.keyID = keyID;
}
/**
* Returns <code>true</code> if data returned from <code>poll</code>
* is relative to the last call, or <code>false</code> if data
* is absolute.
* @return false by default, can be overridden
*/
public final boolean isRelative() {
return false;
}
/**
* Returns the data from the last time the control has been polled.
* The value returned will be either 0.0f or 1.0f. The result is always
* 0.0f if polling is turned off.
*/
public float getPollData() {
if (!isPolling()) {
return 0.0f;
}
return (isKeyPressed(this) ? 1.0f : 0.0f);
}
} // class Keyboard.Key
/**
* Identifiers for physical keys.
*/
public static class KeyID extends Axis.Identifier {
/**
* Key string
*/
private static final String NAME_KEY = "key";
/**
* Index in the array of axes supplied to the keyboard contructor for
* this key.
*/
protected final int keyIndex;
/**
* Protected constructor
* @param keyIndex the index for looking up the key in the array of axes
*/
protected KeyID(int keyIndex) {
super(NAME_KEY);
this.keyIndex = keyIndex;
}
/**
* The index for this key for looking up the in the array of axes.
*/
public int getKeyIndex() {
return keyIndex;
}
/**
* Returns a non-localized string description of this control type.
*/
public String toString() {
return super.toString() + " " + Integer.toString(keyIndex);
}
} // class Keyboard.KeyID
} // class Keyboard

View file

@ -1,315 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
/**
* A Mouse is a type of controller consisting of two child controllers,
* a ball and a button pad. This includes devices such as touch pads,
* trackballs, and fingersticks.
*/
public abstract class Mouse extends AbstractController {
/**
* Mouse ball; should be initialized by subclasses
*/
protected Ball ball;
/**
* Mouse buttons; should be initialized by subclasses
*/
protected Buttons buttons;
/**
* Protected constructor;
* Subclasses should initialize the ball and buttons
*/
protected Mouse(String name) {
super(name);
}
/**
* Returns the controllers connected to make up this controller, or
* an empty array if this controller contains no child controllers.
* The objects in the array are returned in order of assignment priority
* (primary stick, secondary buttons, etc.).
*/
public Controller[] getControllers() {
if (children.length == 0 && ball != null && buttons != null) {
children = new Controller[] { ball, buttons };
}
return children;
}
/**
* Returns the control for the ball of the mouse, never null.
*/
public Ball getBall() {
return ball;
}
/**
* Returns the control for the buttons of the mouse, never null.
*/
public Buttons getButtons() {
return buttons;
}
/**
* Returns the type of the Controller.
*/
public Type getType() {
return Type.MOUSE;
}
/**
* Mouse ball controller
*/
public abstract class Ball extends AbstractController {
/**
* X-axis; should be initialized by subclasses
*/
protected Axis x;
/**
* Y-axis; should be initialized by subclasses
*/
protected Axis y;
/**
* Mouse wheel; should be initialized by subclasses
*/
protected Axis wheel;
/**
* Protected constructor
*/
protected Ball(String name) {
super(name);
}
/**
* Returns the type of Controller.
*/
public Type getType() {
return Type.BALL;
}
/**
* Returns the x-axis for the mouse ball, never null.
*/
public Axis getX() {
return x;
}
/**
* Returns the y-axis for the mouse ball, never null.
*/
public Axis getY() {
return y;
}
/**
* Returns the mouse wheel, or null if no mouse wheel is present.
*/
public Axis getWheel() {
return wheel;
}
/**
* Returns the axes on this controller, in order of assignment priority.
* Overridden to return the x-axis, followed by the y-axes, followed by
* the wheel (if present).
* The array returned is an empty array if this controller contains no
* axes (such as a logical grouping of child controllers).
*/
public Axis[] getAxes() {
if (axes.length == 0 && x != null && y != null) {
if (wheel == null) {
axes = new Axis[] { x, y };
} else {
axes = new Axis[] { x, y, wheel };
}
}
return axes;
}
/**
* Polls axes for data. Returns false if the controller is no longer
* valid. Polling reflects the current state of the device when polled.
* By default, polling a mouse ball or button polls the entire mouse
* control.
*/
public boolean poll() {
return Mouse.this.poll();
}
} // class Mouse.Ball
/**
* Mouse buttons controller
*/
public abstract class Buttons extends AbstractController {
/**
* Left button; should be initialized by subclasses
*/
protected Button left;
/**
* Right button; should be initialized by subclasses
*/
protected Button right;
/**
* Middle button; should be initialized by subclasses
*/
protected Button middle;
/**
* Protected constructor
*/
protected Buttons(String name) {
super(name);
}
/**
* Returns the type or identifier of the Controller.
*/
public Type getType() {
return Type.BUTTONS;
}
/**
* Returns the left or primary mouse button, never null.
*/
public Button getLeft() {
return left;
}
/**
* Returns the right or secondary mouse button, null if the mouse is
* a single-button mouse.
*/
public Button getRight() {
return right;
}
/**
* Returns the middle or tertiary mouse button, null if the mouse has
* fewer than three buttons.
*/
public Button getMiddle() {
return middle;
}
/**
* Returns the axes on this controller, in order of assignment priority.
* Overridden to return the the primary or leftmost mouse button,
* followed by the secondary or rightmost mouse button (if present),
* followed by the middle mouse button (if present).
* The array returned is an empty array if this controller contains no
* axes (such as a logical grouping of child controllers).
*/
public Axis[] getAxes() {
if (axes.length == 0 && left != null) {
if (right == null) {
axes = new Axis[] { left };
} else if (middle == null) {
axes = new Axis[] { left, right };
} else {
axes = new Axis[] { left, right, middle };
}
}
return axes;
}
/**
* Polls axes for data. Returns false if the controller is no longer
* valid. Polling reflects the current state of the device when polled.
* By default, polling a mouse ball or button polls the entire mouse
* control.
*/
public boolean poll() {
return Mouse.this.poll();
}
} // class Mouse.Buttons
/**
* Mouse button axis
*/
public abstract class Button extends AbstractAxis {
/**
* Protected constructor
*/
protected Button(String name, ButtonID id) {
super(name, id);
}
} // class Mouse.Button
/**
* Identifier for types of mouse buttons
*/
public static class ButtonID extends Axis.Identifier {
/**
* Protected constructor
*/
protected ButtonID(String name) {
super(name);
}
/**
* The primary or leftmost mouse button.
*/
public static final ButtonID LEFT = new ButtonID("left");
/**
* The secondary or rightmost mouse button, not present if
* the mouse is a single-button mouse.
*/
public static final ButtonID RIGHT = new ButtonID("right");
/**
* Returns the middle mouse button, not present if the
* mouse has fewer than three buttons.
*/
public static final ButtonID MIDDLE = new ButtonID("middle");
} // class Mouse.ButtonID
} // class Mouse

View file

@ -1,261 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
/**
* Identifiers for physical keys for standard PC (LATIN-1) keyboards.
*/
public abstract class StandardKeyboard extends Keyboard {
private Key[] standardKeys = {
new Key(KeyID.VOID ), new Key(KeyID.ESCAPE ),
new Key(KeyID._1 ), new Key(KeyID._2 ),
new Key(KeyID._3 ), new Key(KeyID._4 ),
new Key(KeyID._5 ), new Key(KeyID._6 ),
new Key(KeyID._7 ), new Key(KeyID._8 ),
new Key(KeyID._9 ), new Key(KeyID._0 ),
new Key(KeyID.MINUS ), new Key(KeyID.EQUALS ),
new Key(KeyID.BACK ), new Key(KeyID.TAB ),
new Key(KeyID.Q ), new Key(KeyID.W ),
new Key(KeyID.E ), new Key(KeyID.R ),
new Key(KeyID.T ), new Key(KeyID.Y ),
new Key(KeyID.U ), new Key(KeyID.I ),
new Key(KeyID.O ), new Key(KeyID.P ),
new Key(KeyID.LBRACKET ), new Key(KeyID.RBRACKET ),
new Key(KeyID.RETURN ), new Key(KeyID.LCONTROL ),
new Key(KeyID.A ), new Key(KeyID.S ),
new Key(KeyID.D ), new Key(KeyID.F ),
new Key(KeyID.G ), new Key(KeyID.H ),
new Key(KeyID.J ), new Key(KeyID.K ),
new Key(KeyID.L ), new Key(KeyID.SEMICOLON ),
new Key(KeyID.APOSTROPHE ), new Key(KeyID.GRAVE ),
new Key(KeyID.LSHIFT ), new Key(KeyID.BACKSLASH ),
new Key(KeyID.Z ), new Key(KeyID.X ),
new Key(KeyID.C ), new Key(KeyID.V ),
new Key(KeyID.B ), new Key(KeyID.N ),
new Key(KeyID.M ), new Key(KeyID.COMMA ),
new Key(KeyID.PERIOD ), new Key(KeyID.SLASH ),
new Key(KeyID.RSHIFT ), new Key(KeyID.MULTIPLY ),
new Key(KeyID.LALT ), new Key(KeyID.SPACE ),
new Key(KeyID.CAPITAL ), new Key(KeyID.F1 ),
new Key(KeyID.F2 ), new Key(KeyID.F3 ),
new Key(KeyID.F4 ), new Key(KeyID.F5 ),
new Key(KeyID.F6 ), new Key(KeyID.F7 ),
new Key(KeyID.F8 ), new Key(KeyID.F9 ),
new Key(KeyID.F10 ), new Key(KeyID.NUMLOCK ),
new Key(KeyID.SCROLL ), new Key(KeyID.NUMPAD7 ),
new Key(KeyID.NUMPAD8 ), new Key(KeyID.NUMPAD9 ),
new Key(KeyID.SUBTRACT ), new Key(KeyID.NUMPAD4 ),
new Key(KeyID.NUMPAD5 ), new Key(KeyID.NUMPAD6 ),
new Key(KeyID.ADD ), new Key(KeyID.NUMPAD1 ),
new Key(KeyID.NUMPAD2 ), new Key(KeyID.NUMPAD3 ),
new Key(KeyID.NUMPAD0 ), new Key(KeyID.DECIMAL ),
new Key(KeyID.F11 ), new Key(KeyID.F12 ),
new Key(KeyID.F13 ), new Key(KeyID.F14 ),
new Key(KeyID.F15 ), new Key(KeyID.KANA ),
new Key(KeyID.CONVERT ), new Key(KeyID.NOCONVERT ),
new Key(KeyID.YEN ), new Key(KeyID.NUMPADEQUAL),
new Key(KeyID.CIRCUMFLEX ), new Key(KeyID.AT ),
new Key(KeyID.COLON ), new Key(KeyID.UNDERLINE ),
new Key(KeyID.KANJI ), new Key(KeyID.STOP ),
new Key(KeyID.AX ), new Key(KeyID.UNLABELED ),
new Key(KeyID.NUMPADENTER), new Key(KeyID.RCONTROL ),
new Key(KeyID.NUMPADCOMMA), new Key(KeyID.DIVIDE ),
new Key(KeyID.SYSRQ ), new Key(KeyID.RALT ),
new Key(KeyID.PAUSE ), new Key(KeyID.HOME ),
new Key(KeyID.UP ), new Key(KeyID.PRIOR ),
new Key(KeyID.LEFT ), new Key(KeyID.RIGHT ),
new Key(KeyID.END ), new Key(KeyID.DOWN ),
new Key(KeyID.NEXT ), new Key(KeyID.INSERT ),
new Key(KeyID.DELETE ), new Key(KeyID.LWIN ),
new Key(KeyID.RWIN ), new Key(KeyID.APPS ),
new Key(KeyID.POWER ), new Key(KeyID.SLEEP ),
};
/**
* Creates a new standard keyboard object with the default keys
* for a standard keyboard.
*/
protected StandardKeyboard(String name) {
super(name);
axes = standardKeys;
}
/**
* KeyIDs for standard PC (LATIN-1) keyboards
*/
public static class KeyID extends Keyboard.KeyID {
/**
* Protected constructor
*/
protected KeyID(int keyID) {
super(keyID);
}
/**
* Standard keyboard (LATIN-1) keys
* UNIX X11 keysym values are listed to the right
*/
public static final KeyID VOID = new KeyID(0); // MS 0x00 UNIX 0xFFFFFF
public static final KeyID ESCAPE = new KeyID(1); // MS 0x01 UNIX 0xFF1B
public static final KeyID _1 = new KeyID(2); // MS 0x02 UNIX 0x031 EXCLAM 0x021
public static final KeyID _2 = new KeyID(3); // MS 0x03 UNIX 0x032 AT 0x040
public static final KeyID _3 = new KeyID(4); // MS 0x04 UNIX 0x033 NUMBERSIGN 0x023
public static final KeyID _4 = new KeyID(5); // MS 0x05 UNIX 0x034 DOLLAR 0x024
public static final KeyID _5 = new KeyID(6); // MS 0x06 UNIX 0x035 PERCENT 0x025
public static final KeyID _6 = new KeyID(7); // MS 0x07 UNIX 0x036 CIRCUMFLEX 0x05e
public static final KeyID _7 = new KeyID(8); // MS 0x08 UNIX 0x037 AMPERSAND 0x026
public static final KeyID _8 = new KeyID(9); // MS 0x09 UNIX 0x038 ASTERISK 0x02a
public static final KeyID _9 = new KeyID(10); // MS 0x0A UNIX 0x039 PARENLEFT 0x028
public static final KeyID _0 = new KeyID(11); // MS 0x0B UNIX 0x030 PARENRIGHT 0x029
public static final KeyID MINUS = new KeyID(12); // MS 0x0C UNIX 0x02d UNDERSCORE 0x05f
public static final KeyID EQUALS = new KeyID(13); // MS 0x0D UNIX 0x03d PLUS 0x02b
public static final KeyID BACK = new KeyID(14); // MS 0x0E UNIX 0xFF08
public static final KeyID TAB = new KeyID(15); // MS 0x0F UNIX 0xFF09
public static final KeyID Q = new KeyID(16); // MS 0x10 UNIX 0x071 UPPER 0x051
public static final KeyID W = new KeyID(17); // MS 0x11 UNIX 0x077 UPPER 0x057
public static final KeyID E = new KeyID(18); // MS 0x12 UNIX 0x065 UPPER 0x045
public static final KeyID R = new KeyID(19); // MS 0x13 UNIX 0x072 UPPER 0x052
public static final KeyID T = new KeyID(20); // MS 0x14 UNIX 0x074 UPPER 0x054
public static final KeyID Y = new KeyID(21); // MS 0x15 UNIX 0x079 UPPER 0x059
public static final KeyID U = new KeyID(22); // MS 0x16 UNIX 0x075 UPPER 0x055
public static final KeyID I = new KeyID(23); // MS 0x17 UNIX 0x069 UPPER 0x049
public static final KeyID O = new KeyID(24); // MS 0x18 UNIX 0x06F UPPER 0x04F
public static final KeyID P = new KeyID(25); // MS 0x19 UNIX 0x070 UPPER 0x050
public static final KeyID LBRACKET = new KeyID(26); // MS 0x1A UNIX 0x05b BRACE 0x07b
public static final KeyID RBRACKET = new KeyID(27); // MS 0x1B UNIX 0x05d BRACE 0x07d
public static final KeyID RETURN = new KeyID(28); // MS 0x1C UNIX 0xFF0D
public static final KeyID LCONTROL = new KeyID(29); // MS 0x1D UNIX 0xFFE3
public static final KeyID A = new KeyID(30); // MS 0x1E UNIX 0x061 UPPER 0x041
public static final KeyID S = new KeyID(31); // MS 0x1F UNIX 0x073 UPPER 0x053
public static final KeyID D = new KeyID(32); // MS 0x20 UNIX 0x064 UPPER 0x044
public static final KeyID F = new KeyID(33); // MS 0x21 UNIX 0x066 UPPER 0x046
public static final KeyID G = new KeyID(34); // MS 0x22 UNIX 0x067 UPPER 0x047
public static final KeyID H = new KeyID(35); // MS 0x23 UNIX 0x068 UPPER 0x048
public static final KeyID J = new KeyID(36); // MS 0x24 UNIX 0x06A UPPER 0x04A
public static final KeyID K = new KeyID(37); // MS 0x25 UNIX 0x06B UPPER 0x04B
public static final KeyID L = new KeyID(38); // MS 0x26 UNIX 0x06C UPPER 0x04C
public static final KeyID SEMICOLON = new KeyID(39); // MS 0x27 UNIX 0x03b COLON 0x03a
public static final KeyID APOSTROPHE = new KeyID(40); // MS 0x28 UNIX 0x027 QUOTEDBL 0x022
public static final KeyID GRAVE = new KeyID(41); // MS 0x29 UNIX 0x060 TILDE 0x07e
public static final KeyID LSHIFT = new KeyID(42); // MS 0x2A UNIX 0xFFE1
public static final KeyID BACKSLASH = new KeyID(43); // MS 0x2B UNIX 0x05c BAR 0x07c
public static final KeyID Z = new KeyID(44); // MS 0x2C UNIX 0x07A UPPER 0x05A
public static final KeyID X = new KeyID(45); // MS 0x2D UNIX 0x078 UPPER 0x058
public static final KeyID C = new KeyID(46); // MS 0x2E UNIX 0x063 UPPER 0x043
public static final KeyID V = new KeyID(47); // MS 0x2F UNIX 0x076 UPPER 0x056
public static final KeyID B = new KeyID(48); // MS 0x30 UNIX 0x062 UPPER 0x042
public static final KeyID N = new KeyID(49); // MS 0x31 UNIX 0x06E UPPER 0x04E
public static final KeyID M = new KeyID(50); // MS 0x32 UNIX 0x06D UPPER 0x04D
public static final KeyID COMMA = new KeyID(51); // MS 0x33 UNIX 0x02c LESS 0x03c
public static final KeyID PERIOD = new KeyID(52); // MS 0x34 UNIX 0x02e GREATER 0x03e
public static final KeyID SLASH = new KeyID(53); // MS 0x35 UNIX 0x02f QUESTION 0x03f
public static final KeyID RSHIFT = new KeyID(54); // MS 0x36 UNIX 0xFFE2
public static final KeyID MULTIPLY = new KeyID(55); // MS 0x37 UNIX 0xFFAA
public static final KeyID LALT = new KeyID(56); // MS 0x38 UNIX 0xFFE9
public static final KeyID SPACE = new KeyID(57); // MS 0x39 UNIX 0x020
public static final KeyID CAPITAL = new KeyID(58); // MS 0x3A UNIX 0xFFE5 SHIFTLOCK 0xFFE6
public static final KeyID F1 = new KeyID(59); // MS 0x3B UNIX 0xFFBE
public static final KeyID F2 = new KeyID(60); // MS 0x3C UNIX 0xFFBF
public static final KeyID F3 = new KeyID(61); // MS 0x3D UNIX 0xFFC0
public static final KeyID F4 = new KeyID(62); // MS 0x3E UNIX 0xFFC1
public static final KeyID F5 = new KeyID(63); // MS 0x3F UNIX 0xFFC2
public static final KeyID F6 = new KeyID(64); // MS 0x40 UNIX 0xFFC3
public static final KeyID F7 = new KeyID(65); // MS 0x41 UNIX 0xFFC4
public static final KeyID F8 = new KeyID(66); // MS 0x42 UNIX 0xFFC5
public static final KeyID F9 = new KeyID(67); // MS 0x43 UNIX 0xFFC6
public static final KeyID F10 = new KeyID(68); // MS 0x44 UNIX 0xFFC7
public static final KeyID NUMLOCK = new KeyID(69); // MS 0x45 UNIX 0xFF7F
public static final KeyID SCROLL = new KeyID(70); // MS 0x46 UNIX 0xFF14
public static final KeyID NUMPAD7 = new KeyID(71); // MS 0x47 UNIX 0xFFB7 HOME 0xFF95
public static final KeyID NUMPAD8 = new KeyID(72); // MS 0x48 UNIX 0xFFB8 UP 0xFF97
public static final KeyID NUMPAD9 = new KeyID(73); // MS 0x49 UNIX 0xFFB9 PRIOR 0xFF9A
public static final KeyID SUBTRACT = new KeyID(74); // MS 0x4A UNIX 0xFFAD
public static final KeyID NUMPAD4 = new KeyID(75); // MS 0x4B UNIX 0xFFB4 LEFT 0xFF96
public static final KeyID NUMPAD5 = new KeyID(76); // MS 0x4C UNIX 0xFFB5
public static final KeyID NUMPAD6 = new KeyID(77); // MS 0x4D UNIX 0xFFB6 RIGHT 0xFF98
public static final KeyID ADD = new KeyID(78); // MS 0x4E UNIX 0xFFAB
public static final KeyID NUMPAD1 = new KeyID(79); // MS 0x4F UNIX 0xFFB1 END 0xFF9C
public static final KeyID NUMPAD2 = new KeyID(80); // MS 0x50 UNIX 0xFFB2 DOWN 0xFF99
public static final KeyID NUMPAD3 = new KeyID(81); // MS 0x51 UNIX 0xFFB3 NEXT 0xFF9B
public static final KeyID NUMPAD0 = new KeyID(82); // MS 0x52 UNIX 0xFFB0 INSERT 0xFF9E
public static final KeyID DECIMAL = new KeyID(83); // MS 0x53 UNIX 0xFFAE DELETE 0xFF9F
public static final KeyID F11 = new KeyID(84); // MS 0x57 UNIX 0xFFC8
public static final KeyID F12 = new KeyID(85); // MS 0x58 UNIX 0xFFC9
public static final KeyID F13 = new KeyID(86); // MS 0x64 UNIX 0xFFCA
public static final KeyID F14 = new KeyID(87); // MS 0x65 UNIX 0xFFCB
public static final KeyID F15 = new KeyID(88); // MS 0x66 UNIX 0xFFCC
public static final KeyID KANA = new KeyID(89); // MS 0x70 UNIX 0xFF2D
public static final KeyID CONVERT = new KeyID(90); // MS 0x79 Japanese keyboard
public static final KeyID NOCONVERT = new KeyID(91); // MS 0x7B Japanese keyboard
public static final KeyID YEN = new KeyID(92); // MS 0x7D UNIX 0x0a5
public static final KeyID NUMPADEQUAL = new KeyID(93); // MS 0x8D UNIX 0xFFBD
public static final KeyID CIRCUMFLEX = new KeyID(94); // MS 0x90 Japanese keyboard
public static final KeyID AT = new KeyID(95); // MS 0x91 UNIX 0x040
public static final KeyID COLON = new KeyID(96); // MS 0x92 UNIX 0x03a
public static final KeyID UNDERLINE = new KeyID(97); // MS 0x93 NEC PC98
public static final KeyID KANJI = new KeyID(98); // MS 0x94 UNIX 0xFF21
public static final KeyID STOP = new KeyID(99); // MS 0x95 UNIX 0xFF69
public static final KeyID AX = new KeyID(100); // MS 0x96 Japan AX
public static final KeyID UNLABELED = new KeyID(101); // MS 0x97 J3100
public static final KeyID NUMPADENTER = new KeyID(102); // MS 0x9C UNIX 0xFF8D
public static final KeyID RCONTROL = new KeyID(103); // MS 0x9D UNIX 0xFFE4
public static final KeyID NUMPADCOMMA = new KeyID(104); // MS 0xB3 UNIX 0xFFAC
public static final KeyID DIVIDE = new KeyID(105); // MS 0xB5 UNIX 0xFFAF
public static final KeyID SYSRQ = new KeyID(106); // MS 0xB7 UNIX 0xFF15 PRINT 0xFF61
public static final KeyID RALT = new KeyID(107); // MS 0xB8 UNIX 0xFFEA
public static final KeyID PAUSE = new KeyID(108); // MS 0xC5 UNIX 0xFF13 BREAK 0xFF6B
public static final KeyID HOME = new KeyID(109); // MS 0xC7 UNIX 0xFF50
public static final KeyID UP = new KeyID(110); // MS 0xC8 UNIX 0xFF52
public static final KeyID PRIOR = new KeyID(111); // MS 0xC9 UNIX 0xFF55
public static final KeyID LEFT = new KeyID(112); // MS 0xCB UNIX 0xFF51
public static final KeyID RIGHT = new KeyID(113); // MS 0xCD UNIX 0xFF53
public static final KeyID END = new KeyID(114); // MS 0xCF UNIX 0xFF57
public static final KeyID DOWN = new KeyID(115); // MS 0xD0 UNIX 0xFF54
public static final KeyID NEXT = new KeyID(116); // MS 0xD1 UNIX 0xFF56
public static final KeyID INSERT = new KeyID(117); // MS 0xD2 UNIX 0xFF63
public static final KeyID DELETE = new KeyID(118); // MS 0xD3 UNIX 0xFFFF
public static final KeyID LWIN = new KeyID(119); // MS 0xDB UNIX META 0xFFE7 SUPER 0xFFEB HYPER 0xFFED
public static final KeyID RWIN = new KeyID(120); // MS 0xDC UNIX META 0xFFE8 SUPER 0xFFEC HYPER 0xFFEE
public static final KeyID APPS = new KeyID(121); // MS 0xDD UNIX 0xFF67
public static final KeyID POWER = new KeyID(122); // MS 0xDE Sun 0x1005FF76 SHIFT 0x1005FF7D
public static final KeyID SLEEP = new KeyID(123); // MS 0xDF No UNIX keysym
protected static final KeyID FIRST = VOID;
protected static final KeyID LAST = SLEEP;
} // class StandardKeyboard.KeyID
} // class StandardKeyboard

View file

@ -1,279 +0,0 @@
/*
* ConrtollerReadTest.java
*
* Created on May 5, 2003, 3:15 PM
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input.test;
/**
*
* @author administrator
*/
import net.java.games.input.*;
import javax.swing.*;
import java.util.*;
import java.util.List;
import java.awt.*;
abstract class AxisPanel extends JPanel{
Axis axis;
float data;
public AxisPanel(Axis ax){
axis = ax;
setLayout(new BorderLayout());
add(new JLabel(ax.getName()+"("+ax.getIdentifier()+")"),
BorderLayout.NORTH);
}
public void poll(){
data = axis.getPollData();
renderData();
}
protected abstract void renderData();
}
class DigitalAxisPanel extends AxisPanel {
JLabel digitalState = new JLabel("<unread>");
public DigitalAxisPanel(Axis ax) {
super(ax);
add(digitalState,BorderLayout.CENTER);
}
protected void renderData(){
if (data == 0.0f){
digitalState.setBackground(getBackground());
digitalState.setText("OFF");
} else if ( data == 1.0f) {
digitalState.setBackground(Color.green);
digitalState.setText("ON");
}else { // shoudl never happen
digitalState.setBackground(Color.red);
digitalState.setText("ERR:"+data);
}
digitalState.repaint();
}
}
class DigitalHatPanel extends AxisPanel {
JLabel digitalState = new JLabel("<unread>");
public DigitalHatPanel(Axis ax) {
super(ax);
add(digitalState,BorderLayout.CENTER);
}
protected void renderData(){
if (data == Axis.POV.OFF){
digitalState.setBackground(getBackground());
digitalState.setText("OFF");
} else if ( data == Axis.POV.UP) {
digitalState.setBackground(Color.green);
digitalState.setText("UP");
} else if ( data == Axis.POV.RIGHT) {
digitalState.setBackground(Color.green);
digitalState.setText("RIGHT");
} else if ( data == Axis.POV.DOWN) {
digitalState.setBackground(Color.green);
digitalState.setText("DOWN");
} else if ( data == Axis.POV.LEFT) {
digitalState.setBackground(Color.green);
digitalState.setText("LEFT");
}else { // shoudl never happen
digitalState.setBackground(Color.red);
digitalState.setText("ERR:"+data);
}
digitalState.repaint();
}
}
class AnalogAxisPanel extends AxisPanel {
JLabel analogState = new JLabel("<unread>");
public AnalogAxisPanel(Axis ax) {
super(ax);
add(analogState,BorderLayout.CENTER);
}
protected void renderData(){
analogState.setText(""+data);
analogState.repaint();
}
}
class ControllerWindow extends JFrame {
Controller ca;
List axisList = new ArrayList();
boolean disabled = false;
public ControllerWindow(JFrame frame,Controller ca){
super(ca.getName());
this.setName(ca.getName());
this.ca = ca;
Container c = this.getContentPane();
c.setLayout(new BorderLayout());
Axis[] axis = ca.getAxes();
System.out.println("Axis count = "+axis.length);
if (axis.length>0) {
int width = (int)Math.ceil(Math.sqrt(axis.length));
JPanel p = new JPanel();
p.setLayout(new GridLayout(width,0));
for(int j=0;j<axis.length;j++){
addAxis(p,axis[j]);
}
c.add(new JScrollPane(p),BorderLayout.CENTER);
}
setSize(400,400);
setLocation(50,50);
setVisible(true);
}
public boolean disabled() {
return disabled;
}
private void setDisabled(boolean b){
disabled = b;
if (!disabled){
this.setTitle(ca.getName());
System.out.println(ca.getName()+" enabled");
} else {
this.setTitle(ca.getName()+" DISABLED!");
System.out.println(ca.getName()+" disabled");
}
repaint();
}
private void addAxis(JPanel p, Axis ax){
JPanel p2;
if (ax.isAnalog()) {
p2 = new AnalogAxisPanel(ax);
} else {
if (ax.getIdentifier() == Axis.Identifier.POV) {
p2 = new DigitalHatPanel(ax);
} else {
p2 = new DigitalAxisPanel(ax);
}
}
p.add(p2);
axisList.add(p2);
ax.setPolling(true);
}
public void poll(){
if (!ca.poll()) {
if (!disabled()){
setDisabled(true);
}
return;
}
if (disabled()){
setDisabled(false);
}
//System.out.println("Polled "+ca.getName());
for(Iterator i =axisList.iterator();i.hasNext();){
try {
((AxisPanel)i.next()).poll();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class ControllerReadTest extends JFrame{
static final long HEARTBEATMS =100; // 10th of a second
List controllers = new ArrayList();
/** Creates a new instance of ConrtollerReadTest */
public ControllerReadTest() {
super("Controller Read Test");
ControllerEnvironment ce = ControllerEnvironment.getDefaultEnvironment();
Controller[] ca = ce.getControllers();
for(int i =0;i<ca.length;i++){
makeController(ca[i]);
}
new Thread(new Runnable() {
public void run(){
try {
while(true){
for(Iterator i=controllers.iterator();i.hasNext();){
try {
ControllerWindow cw = (ControllerWindow)i.next();
cw.poll();
} catch (Exception e) {
e.printStackTrace();
}
}
Thread.sleep(HEARTBEATMS);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
pack();
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void makeController(Controller c) {
Controller[] subControllers = c.getControllers();
if (subControllers.length == 0 ) {
createControllerWindow(c);
} else {
for(int i=0;i<subControllers.length;i++){
makeController(subControllers[i]);
}
}
}
private void createControllerWindow(Controller c){
controllers.add(new ControllerWindow(this,c));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new ControllerReadTest().setVisible(true);
}
}

View file

@ -38,34 +38,31 @@
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/**
* Skeleton implementation of a named axis.
*/
public abstract class AbstractAxis implements Axis {
public abstract class AbstractComponent implements Component {
/**
* Human-readable name for this Axis
*/
protected String name;
private final String name;
/**
* Identifier for the axis
*/
protected Identifier id;
private final Identifier id;
/**
* Whether this axis is ready to receive polling data
*/
private boolean polling;
private boolean has_polled;
private float value;
private float event_value;
/**
* Protected constructor
* @param name A name for the axis
*/
protected AbstractAxis(String name, Identifier id) {
protected AbstractComponent(String name, Identifier id) {
this.name = name;
this.id = id;
this.polling = true;
}
/**
@ -83,30 +80,6 @@ public abstract class AbstractAxis implements Axis {
return false;
}
/**
* Returns whether or not data polled from this axis is normalized
* between the values of -1.0f and 1.0f.
* @return true by default, can be overridden
*/
public boolean isNormalized() {
return true;
}
/**
* Returns whether or not this axis is ready to receive polling data.
* By default, an abstract axis is set to receive polling data.
*/
public boolean isPolling() {
return polling;
}
/**
* Sets whether or not the axis should receive polling data.
*/
public void setPolling(boolean polling) {
this.polling = polling;
}
/**
* Returns the suggested dead zone for this axis. Dead zone is the
* amount polled data can vary before considered a significant change
@ -121,12 +94,36 @@ public abstract class AbstractAxis implements Axis {
/**
* Returns the data from the last time the control has been polled.
* If this axis is a button, the value returned will be either 0.0f or 1.0f.
* If this axis is normalized, the value returned will be between -1.0f and
* If this axis is normalised, the value returned will be between -1.0f and
* 1.0f.
* @return 0.0f by default, can be overridden
* @return The data from the last time the control has been polled.
*/
public float getPollData() {
return 0.0f;
public final float getPollData() {
if (!has_polled && !isRelative()) {
has_polled = true;
try {
setPollData(poll());
} catch (IOException e) {
ControllerEnvironment.log("Failed to poll component: " + e);
}
}
return value;
}
final void resetHasPolled() {
has_polled = false;
}
final void setPollData(float value) {
this.value = value;
}
final float getEventValue() {
return event_value;
}
final void setEventValue(float event_value) {
this.event_value = event_value;
}
/**
@ -143,11 +140,6 @@ public abstract class AbstractAxis implements Axis {
return name;
}
/**
* Changes the name of this Axis. This should be done only during
* initialization of the axis so that its name remains immutable.
*/
public void setName(String name) {
this.name = name;
}
protected abstract float poll() throws IOException;
} // AbstractAxis

View file

@ -1,10 +1,4 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@ -35,29 +29,22 @@
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
*/
package net.java.games.input;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
/**
* An AbstractController is a skeleton implementation of a controller that
* contains a fixed number of axes, controllers, and rumblers.
*/
public abstract class AbstractController implements Controller {
final static int EVENT_QUEUE_DEPTH = 32;
/**
* Null array representing no axes
*/
protected static final Axis[] NO_AXES = {};
/**
* Null array representing no child controllers
*/
protected static final Controller[] NO_CONTROLLERS = {};
/**
* Null array representing no rumblers
*/
protected static final Rumbler[] NO_RUMBLERS = {};
private final static Event event = new Event();
/**
* Human-readable name for this Controller
@ -65,43 +52,44 @@ public abstract class AbstractController implements Controller {
private final String name;
/**
* Array of axes
* Array of components
*/
protected Axis[] axes;
private final Component[] components;
/**
* Array of child controllers
*/
protected Controller[] children;
private final Controller[] children;
/**
* Array of rumblers
*/
protected Rumbler[] rumblers;
private final Rumbler[] rumblers;
/**
* Protected constructor for a controller; initially contains no axes,
* child controllers, or rumblers.
* @param name The name for the controller
* Map from Component.Identifiers to Components
*/
protected AbstractController(String name) {
this(name, NO_AXES, NO_CONTROLLERS, NO_RUMBLERS);
}
private final Map<Component.Identifier, Component> id_to_components = new HashMap<>();
private EventQueue event_queue = new EventQueue(EVENT_QUEUE_DEPTH);
/**
* Protected constructor for a controller containing the specified
* axes, child controllers, and rumblers
* @param name name for the controller
* @param axes axes for the controller
* @param components components for the controller
* @param children child controllers for the controller
* @param rumblers rumblers for the controller
*/
protected AbstractController(String name, Axis[] axes,
Controller[] children, Rumbler[] rumblers) {
protected AbstractController(String name, Component[] components, Controller[] children, Rumbler[] rumblers) {
this.name = name;
this.axes = axes;
this.components = components;
this.children = children;
this.rumblers = rumblers;
// process from last to first to let earlier listed Components get higher priority
for (int i = components.length - 1; i >= 0; i--) {
id_to_components.put(components[i].getIdentifier(), components[i]);
}
}
/**
@ -110,48 +98,36 @@ public abstract class AbstractController implements Controller {
* The objects in the array are returned in order of assignment priority
* (primary stick, secondary buttons, etc.).
*/
public Controller[] getControllers() {
public final Controller[] getControllers() {
return children;
}
/**
* Returns the axes on this controller, in order of assignment priority.
* Returns the components on this controller, in order of assignment priority.
* For example, the button controller on a mouse returns an array containing
* the primary or leftmost mouse button, followed by the secondary or
* rightmost mouse button (if present), followed by the middle mouse button
* (if present).
* The array returned is an empty array if this controller contains no axes
* The array returned is an empty array if this controller contains no components
* (such as a logical grouping of child controllers).
*/
public Axis[] getAxes() {
return axes;
public final Component[] getComponents() {
return components;
}
/**
* Returns a single axis based on its identifier, or null
* if no axis with the specified type could be found.
* By default, AbstractController calls getAxes in this method so that
* subclasses may lazily initialize the array of axes, if necessary.
* Returns a single component based on its identifier, or null
* if no component with the specified type could be found.
*/
public Axis getAxis(Axis.Identifier id) {
// Calls getAxes() so that subclasses may lazily set the array of axes.
Axis[] axes = getAxes();
if (axes.length == 0) {
return null;
}
for (int i = 0; i < axes.length; i++) {
if (axes[i].getIdentifier() == id) {
return axes[i];
}
}
return null;
public final Component getComponent(Component.Identifier id) {
return id_to_components.get(id);
}
/**
* Returns the rumblers for sending feedback to this controller, or an
* empty array if there are no rumblers on this controller.
*/
public Rumbler[] getRumblers() {
public final Rumbler[] getRumblers() {
return rumblers;
}
@ -174,7 +150,7 @@ public abstract class AbstractController implements Controller {
/**
* Returns a human-readable name for this Controller.
*/
public String getName() {
public final String getName() {
return name;
}
@ -191,4 +167,67 @@ public abstract class AbstractController implements Controller {
return Type.UNKNOWN;
}
/**
* Creates a new EventQueue. Events in old queue are lost.
*/
public final void setEventQueueSize(int size) {
try {
setDeviceEventQueueSize(size);
event_queue = new EventQueue(size);
} catch (IOException e) {
ControllerEnvironment.log("Failed to create new event queue of size " + size + ": " + e);
}
}
/**
* Plugins override this method to adjust their internal event queue size
*/
protected void setDeviceEventQueueSize(int size) throws IOException {
}
public final EventQueue getEventQueue() {
return event_queue;
}
protected abstract boolean getNextDeviceEvent(Event event) throws IOException;
protected void pollDevice() throws IOException {
}
/* poll() is synchronized to protect the static event */
public synchronized boolean poll() {
Component[] components = getComponents();
try {
pollDevice();
for (int i = 0; i < components.length; i++) {
AbstractComponent component = (AbstractComponent)components[i];
if (component.isRelative()) {
component.setPollData(0);
} else {
// Let the component poll itself lazily
component.resetHasPolled();
}
}
while (getNextDeviceEvent(event)) {
AbstractComponent component = (AbstractComponent)event.getComponent();
float value = event.getValue();
if (component.isRelative()) {
if (value == 0)
continue;
component.setPollData(component.getPollData() + value);
} else {
if (value == component.getEventValue())
continue;
component.setEventValue(value);
}
if (!event_queue.isFull())
event_queue.add(event);
}
return true;
} catch (IOException e) {
ControllerEnvironment.log("Failed to poll device: " + e.getMessage());
return false;
}
}
} // class AbstractController

View file

@ -0,0 +1,782 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
/**
* An axis is a single button, slider, or dial, which has a single range. An
* axis can hold information for motion (linear or rotational), velocity,
* force, or acceleration.
*/
public interface Component {
/**
* Returns the identifier of the axis.
*/
public abstract Identifier getIdentifier();
/**
* Returns <code>true</code> if data returned from <code>poll</code>
* is relative to the last call, or <code>false</code> if data
* is absolute.
*/
public abstract boolean isRelative();
/**
* Returns whether or not the axis is analog, or false if it is digital.
*/
public abstract boolean isAnalog();
/**
* Returns the suggested dead zone for this axis. Dead zone is the
* amount polled data can vary before considered a significant change
* in value. An application can safely ignore changes less than this
* value in the positive or negative direction.
* @see #getPollData
*/
public abstract float getDeadZone();
/**
* Returns the data from the last time the control has been polled.
* If this axis is a button, the value returned will be either 0.0f or 1.0f.
* If this axis is normalized, the value returned will be between -1.0f and
* 1.0f.
* @see Controller#poll
*/
public abstract float getPollData();
/**
* Returns a human-readable name for this axis.
*/
public abstract String getName();
/**
* Identifiers for different Axes.
*/
public static class Identifier {
/**
* Name of axis type
*/
private final String name;
/**
* Protected constructor
*/
protected Identifier(String name) {
this.name = name;
}
/**
* Returns a non-localized string description of this axis type.
*/
public String getName() {
return name;
}
/**
* Returns a non-localized string description of this axis type.
*/
public String toString() {
return name;
}
public static class Axis extends Identifier {
/**
* @param name
*/
protected Axis(String name) {
super(name);
}
/**
* An axis for specifying vertical data.
*/
public static final Axis X = new Axis("x");
/**
* An axis for specifying horizontal data.
*/
public static final Axis Y = new Axis("y");
/**
* An axis for specifying third dimensional up/down
* data, or linear data in any direction that is
* neither horizontal nor vertical.
*/
public static final Axis Z = new Axis("z");
/**
* An axis for specifying left-right rotational data.
*/
public static final Axis RX = new Axis("rx");
/**
* An axis for specifying forward-back rotational data.
*/
public static final Axis RY = new Axis("ry");
/**
* An axis for specifying up-down rotational data
* (rudder control).
*/
public static final Axis RZ = new Axis("rz");
/**
* An axis for a slider or mouse wheel.
*/
public static final Axis SLIDER = new Axis("slider");
/**
* An axis for slider or mouse wheel acceleration data.
*/
public static final Axis SLIDER_ACCELERATION = new Axis("slider-acceleration");
/**
* An axis for slider force data.
*/
public static final Axis SLIDER_FORCE = new Axis("slider-force");
/**
* An axis for slider or mouse wheel velocity data.
*/
public static final Axis SLIDER_VELOCITY = new Axis("slider-velocity");
/**
* An axis for specifying vertical acceleration data.
*/
public static final Axis X_ACCELERATION = new Axis("x-acceleration");
/**
* An axis for specifying vertical force data.
*/
public static final Axis X_FORCE = new Axis("x-force");
/**
* An axis for specifying vertical velocity data.
*/
public static final Axis X_VELOCITY = new Axis("x-velocity");
/**
* An axis for specifying horizontal acceleration data.
*/
public static final Axis Y_ACCELERATION = new Axis("y-acceleration");
/**
* An axis for specifying horizontal force data.
*/
public static final Axis Y_FORCE = new Axis("y-force");
/**
* An axis for specifying horizontal velocity data.
*/
public static final Axis Y_VELOCITY = new Axis("y-velocity");
/**
* An axis for specifying third dimensional up/down acceleration data.
*/
public static final Axis Z_ACCELERATION = new Axis("z-acceleration");
/**
* An axis for specifying third dimensional up/down force data.
*/
public static final Axis Z_FORCE = new Axis("z-force");
/**
* An axis for specifying third dimensional up/down velocity data.
*/
public static final Axis Z_VELOCITY = new Axis("z-velocity");
/**
* An axis for specifying left-right angular acceleration data.
*/
public static final Axis RX_ACCELERATION = new Axis("rx-acceleration");
/**
* An axis for specifying left-right angular force (torque) data.
*/
public static final Axis RX_FORCE = new Axis("rx-force");
/**
* An axis for specifying left-right angular velocity data.
*/
public static final Axis RX_VELOCITY = new Axis("rx-velocity");
/**
* An axis for specifying forward-back angular acceleration data.
*/
public static final Axis RY_ACCELERATION = new Axis("ry-acceleration");
/**
* An axis for specifying forward-back angular force (torque) data.
*/
public static final Axis RY_FORCE = new Axis("ry-force");
/**
* An axis for specifying forward-back angular velocity data.
*/
public static final Axis RY_VELOCITY = new Axis("ry-velocity");
/**
* An axis for specifying up-down angular acceleration data.
*/
public static final Axis RZ_ACCELERATION = new Axis("rz-acceleration");
/**
* An axis for specifying up-down angular force (torque) data.
*/
public static final Axis RZ_FORCE = new Axis("rz-force");
/**
* An axis for specifying up-down angular velocity data.
*/
public static final Axis RZ_VELOCITY = new Axis("rz-velocity");
/**
* An axis for a point-of-view control.
*/
public static final Axis POV = new Axis("pov");
/**
* An unknown axis.
*/
public static final Axis UNKNOWN = new Axis("unknown");
}
public static class Button extends Identifier {
public Button(String name) {
super(name);
}
/** First device button
*/
public static final Button _0 = new Button("0");
/** Second device button
*/
public static final Button _1 = new Button("1");
/** Thrid device button
*/
public static final Button _2 = new Button("2");
/** Fourth device button
*/
public static final Button _3 = new Button("3");
/** Fifth device button
*/
public static final Button _4 = new Button("4");
/** Sixth device button
*/
public static final Button _5 = new Button("5");
/** Seventh device button
*/
public static final Button _6 = new Button("6");
/** Eighth device button
*/
public static final Button _7 = new Button("7");
/** Ninth device button
*/
public static final Button _8 = new Button("8");
/** 10th device button
*/
public static final Button _9 = new Button("9");
public static final Button _10 = new Button("10");
public static final Button _11 = new Button("11");
public static final Button _12 = new Button("12");
public static final Button _13 = new Button("13");
public static final Button _14 = new Button("14");
public static final Button _15 = new Button("15");
public static final Button _16 = new Button("16");
public static final Button _17 = new Button("17");
public static final Button _18 = new Button("18");
public static final Button _19 = new Button("19");
public static final Button _20 = new Button("20");
public static final Button _21 = new Button("21");
public static final Button _22 = new Button("22");
public static final Button _23 = new Button("23");
public static final Button _24 = new Button("24");
public static final Button _25 = new Button("25");
public static final Button _26 = new Button("26");
public static final Button _27 = new Button("27");
public static final Button _28 = new Button("28");
public static final Button _29 = new Button("29");
public static final Button _30 = new Button("30");
public static final Button _31 = new Button("31");
/** Joystick trigger button
*/
public static final Button TRIGGER = new Button("Trigger");
/** Joystick thumb button
*/
public static final Button THUMB = new Button("Thumb");
/** Second joystick thumb button
*/
public static final Button THUMB2 = new Button("Thumb 2");
/** Joystick top button
*/
public static final Button TOP = new Button("Top");
/** Second joystick top button
*/
public static final Button TOP2 = new Button("Top 2");
/** The joystick button you play with with you little finger (Pinkie on *that* side
* of the pond :P)
*/
public static final Button PINKIE = new Button("Pinkie");
/** Joystick button on the base of the device
*/
public static final Button BASE = new Button("Base");
/** Second joystick button on the base of the device
*/
public static final Button BASE2 = new Button("Base 2");
/** Thrid joystick button on the base of the device
*/
public static final Button BASE3 = new Button("Base 3");
/** Fourth joystick button on the base of the device
*/
public static final Button BASE4 = new Button("Base 4");
/** Fifth joystick button on the base of the device
*/
public static final Button BASE5 = new Button("Base 5");
/** Sixth joystick button on the base of the device
*/
public static final Button BASE6 = new Button("Base 6");
/** erm, dunno, but it's in the defines so it might exist.
*/
public static final Button DEAD = new Button("Dead");
/** 'A' button on a gamepad
*/
public static final Button A = new Button("A");
/** 'B' button on a gamepad
*/
public static final Button B = new Button("B");
/** 'C' button on a gamepad
*/
public static final Button C = new Button("C");
/** 'X' button on a gamepad
*/
public static final Button X = new Button("X");
/** 'Y' button on a gamepad
*/
public static final Button Y = new Button("Y");
/** 'Z' button on a gamepad
*/
public static final Button Z = new Button("Z");
/** Left thumb button on a gamepad
*/
public static final Button LEFT_THUMB = new Button("Left Thumb");
/** Right thumb button on a gamepad
*/
public static final Button RIGHT_THUMB = new Button("Right Thumb");
/** Second left thumb button on a gamepad
*/
public static final Button LEFT_THUMB2 = new Button("Left Thumb 2");
/** Second right thumb button on a gamepad
*/
public static final Button RIGHT_THUMB2 = new Button("Right Thumb 2");
/** 'Select' button on a gamepad
*/
public static final Button SELECT = new Button("Select");
/** 'Start' button on a gamepad
*/
public static final Button START = new Button("Start");
/** 'Mode' button on a gamepad
*/
public static final Button MODE = new Button("Mode");
/** Another left thumb button on a gamepad (how many thumbs do you have??)
*/
public static final Button LEFT_THUMB3 = new Button("Left Thumb 3");
/** Another right thumb button on a gamepad
*/
public static final Button RIGHT_THUMB3 = new Button("Right Thumb 3");
/** Digitiser pen tool button
*/
public static final Button TOOL_PEN = new Button("Pen");
/** Digitiser rubber (eraser) tool button
*/
public static final Button TOOL_RUBBER = new Button("Rubber");
/** Digitiser brush tool button
*/
public static final Button TOOL_BRUSH = new Button("Brush");
/** Digitiser pencil tool button
*/
public static final Button TOOL_PENCIL = new Button("Pencil");
/** Digitiser airbrush tool button
*/
public static final Button TOOL_AIRBRUSH = new Button("Airbrush");
/** Digitiser finger tool button
*/
public static final Button TOOL_FINGER = new Button("Finger");
/** Digitiser mouse tool button
*/
public static final Button TOOL_MOUSE = new Button("Mouse");
/** Digitiser lens tool button
*/
public static final Button TOOL_LENS = new Button("Lens");
/** Digitiser touch button
*/
public static final Button TOUCH = new Button("Touch");
/** Digitiser stylus button
*/
public static final Button STYLUS = new Button("Stylus");
/** Second digitiser stylus button
*/
public static final Button STYLUS2 = new Button("Stylus 2");
/**
* An unknown button
*/
public static final Button UNKNOWN = new Button("Unknown");
/**
* Returns the back mouse button.
*/
public static final Button BACK = new Button("Back");
/**
* Returns the extra mouse button.
*/
public static final Button EXTRA = new Button("Extra");
/**
* Returns the forward mouse button.
*/
public static final Button FORWARD = new Button("Forward");
/**
* The primary or leftmost mouse button.
*/
public static final Button LEFT = new Button("Left");
/**
* Returns the middle mouse button, not present if the mouse has fewer than three buttons.
*/
public static final Button MIDDLE = new Button("Middle");
/**
* The secondary or rightmost mouse button, not present if the mouse is a single-button mouse.
*/
public static final Button RIGHT = new Button("Right");
/**
* Returns the side mouse button.
*/
public static final Button SIDE = new Button("Side");
/**
* Extra, unnamed, buttons
*/
public static final Button EXTRA_1 = new Button("Extra 1");
public static final Button EXTRA_2 = new Button("Extra 2");
public static final Button EXTRA_3 = new Button("Extra 3");
public static final Button EXTRA_4 = new Button("Extra 4");
public static final Button EXTRA_5 = new Button("Extra 5");
public static final Button EXTRA_6 = new Button("Extra 6");
public static final Button EXTRA_7 = new Button("Extra 7");
public static final Button EXTRA_8 = new Button("Extra 8");
public static final Button EXTRA_9 = new Button("Extra 9");
public static final Button EXTRA_10 = new Button("Extra 10");
public static final Button EXTRA_11 = new Button("Extra 11");
public static final Button EXTRA_12 = new Button("Extra 12");
public static final Button EXTRA_13 = new Button("Extra 13");
public static final Button EXTRA_14 = new Button("Extra 14");
public static final Button EXTRA_15 = new Button("Extra 15");
public static final Button EXTRA_16 = new Button("Extra 16");
public static final Button EXTRA_17 = new Button("Extra 17");
public static final Button EXTRA_18 = new Button("Extra 18");
public static final Button EXTRA_19 = new Button("Extra 19");
public static final Button EXTRA_20 = new Button("Extra 20");
public static final Button EXTRA_21 = new Button("Extra 21");
public static final Button EXTRA_22 = new Button("Extra 22");
public static final Button EXTRA_23 = new Button("Extra 23");
public static final Button EXTRA_24 = new Button("Extra 24");
public static final Button EXTRA_25 = new Button("Extra 25");
public static final Button EXTRA_26 = new Button("Extra 26");
public static final Button EXTRA_27 = new Button("Extra 27");
public static final Button EXTRA_28 = new Button("Extra 28");
public static final Button EXTRA_29 = new Button("Extra 29");
public static final Button EXTRA_30 = new Button("Extra 30");
public static final Button EXTRA_31 = new Button("Extra 31");
public static final Button EXTRA_32 = new Button("Extra 32");
public static final Button EXTRA_33 = new Button("Extra 33");
public static final Button EXTRA_34 = new Button("Extra 34");
public static final Button EXTRA_35 = new Button("Extra 35");
public static final Button EXTRA_36 = new Button("Extra 36");
public static final Button EXTRA_37 = new Button("Extra 37");
public static final Button EXTRA_38 = new Button("Extra 38");
public static final Button EXTRA_39 = new Button("Extra 39");
public static final Button EXTRA_40 = new Button("Extra 40");
}
/**
* KeyIDs for standard PC (LATIN-1) keyboards
*/
public static class Key extends Identifier {
/**
* Protected constructor
*/
protected Key(String name) {
super(name);
}
/**
* Standard keyboard (LATIN-1) keys
* UNIX X11 keysym values are listed to the right
*/
public static final Key VOID = new Key("Void"); // MS 0x00 UNIX 0xFFFFFF
public static final Key ESCAPE = new Key("Escape"); // MS 0x01 UNIX 0xFF1B
public static final Key _1 = new Key("1"); // MS 0x02 UNIX 0x031 EXCLAM 0x021
public static final Key _2 = new Key("2"); // MS 0x03 UNIX 0x032 AT 0x040
public static final Key _3 = new Key("3"); // MS 0x04 UNIX 0x033 NUMBERSIGN 0x023
public static final Key _4 = new Key("4"); // MS 0x05 UNIX 0x034 DOLLAR 0x024
public static final Key _5 = new Key("5"); // MS 0x06 UNIX 0x035 PERCENT 0x025
public static final Key _6 = new Key("6"); // MS 0x07 UNIX 0x036 CIRCUMFLEX 0x05e
public static final Key _7 = new Key("7"); // MS 0x08 UNIX 0x037 AMPERSAND 0x026
public static final Key _8 = new Key("8"); // MS 0x09 UNIX 0x038 ASTERISK 0x02a
public static final Key _9 = new Key("9"); // MS 0x0A UNIX 0x039 PARENLEFT 0x028
public static final Key _0 = new Key("0"); // MS 0x0B UNIX 0x030 PARENRIGHT 0x029
public static final Key MINUS = new Key("-"); // MS 0x0C UNIX 0x02d UNDERSCORE 0x05f
public static final Key EQUALS = new Key("="); // MS 0x0D UNIX 0x03d PLUS 0x02b
public static final Key BACK = new Key("Back"); // MS 0x0E UNIX 0xFF08
public static final Key TAB = new Key("Tab"); // MS 0x0F UNIX 0xFF09
public static final Key Q = new Key("Q"); // MS 0x10 UNIX 0x071 UPPER 0x051
public static final Key W = new Key("W"); // MS 0x11 UNIX 0x077 UPPER 0x057
public static final Key E = new Key("E"); // MS 0x12 UNIX 0x065 UPPER 0x045
public static final Key R = new Key("R"); // MS 0x13 UNIX 0x072 UPPER 0x052
public static final Key T = new Key("T"); // MS 0x14 UNIX 0x074 UPPER 0x054
public static final Key Y = new Key("Y"); // MS 0x15 UNIX 0x079 UPPER 0x059
public static final Key U = new Key("U"); // MS 0x16 UNIX 0x075 UPPER 0x055
public static final Key I = new Key("I"); // MS 0x17 UNIX 0x069 UPPER 0x049
public static final Key O = new Key("O"); // MS 0x18 UNIX 0x06F UPPER 0x04F
public static final Key P = new Key("P"); // MS 0x19 UNIX 0x070 UPPER 0x050
public static final Key LBRACKET = new Key("["); // MS 0x1A UNIX 0x05b BRACE 0x07b
public static final Key RBRACKET = new Key("]"); // MS 0x1B UNIX 0x05d BRACE 0x07d
public static final Key RETURN = new Key("Return"); // MS 0x1C UNIX 0xFF0D
public static final Key LCONTROL = new Key("Left Control"); // MS 0x1D UNIX 0xFFE3
public static final Key A = new Key("A"); // MS 0x1E UNIX 0x061 UPPER 0x041
public static final Key S = new Key("S"); // MS 0x1F UNIX 0x073 UPPER 0x053
public static final Key D = new Key("D"); // MS 0x20 UNIX 0x064 UPPER 0x044
public static final Key F = new Key("F"); // MS 0x21 UNIX 0x066 UPPER 0x046
public static final Key G = new Key("G"); // MS 0x22 UNIX 0x067 UPPER 0x047
public static final Key H = new Key("H"); // MS 0x23 UNIX 0x068 UPPER 0x048
public static final Key J = new Key("J"); // MS 0x24 UNIX 0x06A UPPER 0x04A
public static final Key K = new Key("K"); // MS 0x25 UNIX 0x06B UPPER 0x04B
public static final Key L = new Key("L"); // MS 0x26 UNIX 0x06C UPPER 0x04C
public static final Key SEMICOLON = new Key(";"); // MS 0x27 UNIX 0x03b COLON 0x03a
public static final Key APOSTROPHE = new Key("'"); // MS 0x28 UNIX 0x027 QUOTEDBL 0x022
public static final Key GRAVE = new Key("~"); // MS 0x29 UNIX 0x060 TILDE 0x07e
public static final Key LSHIFT = new Key("Left Shift"); // MS 0x2A UNIX 0xFFE1
public static final Key BACKSLASH = new Key("\\"); // MS 0x2B UNIX 0x05c BAR 0x07c
public static final Key Z = new Key("Z"); // MS 0x2C UNIX 0x07A UPPER 0x05A
public static final Key X = new Key("X"); // MS 0x2D UNIX 0x078 UPPER 0x058
public static final Key C = new Key("C"); // MS 0x2E UNIX 0x063 UPPER 0x043
public static final Key V = new Key("V"); // MS 0x2F UNIX 0x076 UPPER 0x056
public static final Key B = new Key("B"); // MS 0x30 UNIX 0x062 UPPER 0x042
public static final Key N = new Key("N"); // MS 0x31 UNIX 0x06E UPPER 0x04E
public static final Key M = new Key("M"); // MS 0x32 UNIX 0x06D UPPER 0x04D
public static final Key COMMA = new Key(","); // MS 0x33 UNIX 0x02c LESS 0x03c
public static final Key PERIOD = new Key("."); // MS 0x34 UNIX 0x02e GREATER 0x03e
public static final Key SLASH = new Key("/"); // MS 0x35 UNIX 0x02f QUESTION 0x03f
public static final Key RSHIFT = new Key("Right Shift"); // MS 0x36 UNIX 0xFFE2
public static final Key MULTIPLY = new Key("Multiply"); // MS 0x37 UNIX 0xFFAA
public static final Key LALT = new Key("Left Alt"); // MS 0x38 UNIX 0xFFE9
public static final Key SPACE = new Key(" "); // MS 0x39 UNIX 0x020
public static final Key CAPITAL = new Key("Caps Lock"); // MS 0x3A UNIX 0xFFE5 SHIFTLOCK 0xFFE6
public static final Key F1 = new Key("F1"); // MS 0x3B UNIX 0xFFBE
public static final Key F2 = new Key("F2"); // MS 0x3C UNIX 0xFFBF
public static final Key F3 = new Key("F3"); // MS 0x3D UNIX 0xFFC0
public static final Key F4 = new Key("F4"); // MS 0x3E UNIX 0xFFC1
public static final Key F5 = new Key("F5"); // MS 0x3F UNIX 0xFFC2
public static final Key F6 = new Key("F6"); // MS 0x40 UNIX 0xFFC3
public static final Key F7 = new Key("F7"); // MS 0x41 UNIX 0xFFC4
public static final Key F8 = new Key("F8"); // MS 0x42 UNIX 0xFFC5
public static final Key F9 = new Key("F9"); // MS 0x43 UNIX 0xFFC6
public static final Key F10 = new Key("F10"); // MS 0x44 UNIX 0xFFC7
public static final Key NUMLOCK = new Key("Num Lock"); // MS 0x45 UNIX 0xFF7F
public static final Key SCROLL = new Key("Scroll Lock"); // MS 0x46 UNIX 0xFF14
public static final Key NUMPAD7 = new Key("Num 7"); // MS 0x47 UNIX 0xFFB7 HOME 0xFF95
public static final Key NUMPAD8 = new Key("Num 8"); // MS 0x48 UNIX 0xFFB8 UP 0xFF97
public static final Key NUMPAD9 = new Key("Num 9"); // MS 0x49 UNIX 0xFFB9 PRIOR 0xFF9A
public static final Key SUBTRACT = new Key("Num -"); // MS 0x4A UNIX 0xFFAD
public static final Key NUMPAD4 = new Key("Num 4"); // MS 0x4B UNIX 0xFFB4 LEFT 0xFF96
public static final Key NUMPAD5 = new Key("Num 5"); // MS 0x4C UNIX 0xFFB5
public static final Key NUMPAD6 = new Key("Num 6"); // MS 0x4D UNIX 0xFFB6 RIGHT 0xFF98
public static final Key ADD = new Key("Num +"); // MS 0x4E UNIX 0xFFAB
public static final Key NUMPAD1 = new Key("Num 1"); // MS 0x4F UNIX 0xFFB1 END 0xFF9C
public static final Key NUMPAD2 = new Key("Num 2"); // MS 0x50 UNIX 0xFFB2 DOWN 0xFF99
public static final Key NUMPAD3 = new Key("Num 3"); // MS 0x51 UNIX 0xFFB3 NEXT 0xFF9B
public static final Key NUMPAD0 = new Key("Num 0"); // MS 0x52 UNIX 0xFFB0 INSERT 0xFF9E
public static final Key DECIMAL = new Key("Num ."); // MS 0x53 UNIX 0xFFAE DELETE 0xFF9F
public static final Key F11 = new Key("F11"); // MS 0x57 UNIX 0xFFC8
public static final Key F12 = new Key("F12"); // MS 0x58 UNIX 0xFFC9
public static final Key F13 = new Key("F13"); // MS 0x64 UNIX 0xFFCA
public static final Key F14 = new Key("F14"); // MS 0x65 UNIX 0xFFCB
public static final Key F15 = new Key("F15"); // MS 0x66 UNIX 0xFFCC
public static final Key KANA = new Key("Kana"); // MS 0x70 UNIX 0xFF2D
public static final Key CONVERT = new Key("Convert"); // MS 0x79 Japanese keyboard
public static final Key NOCONVERT = new Key("Noconvert"); // MS 0x7B Japanese keyboard
public static final Key YEN = new Key("Yen"); // MS 0x7D UNIX 0x0a5
public static final Key NUMPADEQUAL = new Key("Num ="); // MS 0x8D UNIX 0xFFBD
public static final Key CIRCUMFLEX = new Key("Circumflex"); // MS 0x90 Japanese keyboard
public static final Key AT = new Key("At"); // MS 0x91 UNIX 0x040
public static final Key COLON = new Key("Colon"); // MS 0x92 UNIX 0x03a
public static final Key UNDERLINE = new Key("Underline"); // MS 0x93 NEC PC98
public static final Key KANJI = new Key("Kanji"); // MS 0x94 UNIX 0xFF21
public static final Key STOP = new Key("Stop"); // MS 0x95 UNIX 0xFF69
public static final Key AX = new Key("Ax"); // MS 0x96 Japan AX
public static final Key UNLABELED = new Key("Unlabeled"); // MS 0x97 J3100
public static final Key NUMPADENTER = new Key("Num Enter"); // MS 0x9C UNIX 0xFF8D
public static final Key RCONTROL = new Key("Right Control"); // MS 0x9D UNIX 0xFFE4
public static final Key NUMPADCOMMA = new Key("Num ,"); // MS 0xB3 UNIX 0xFFAC
public static final Key DIVIDE = new Key("Num /"); // MS 0xB5 UNIX 0xFFAF
public static final Key SYSRQ = new Key("SysRq"); // MS 0xB7 UNIX 0xFF15 PRINT 0xFF61
public static final Key RALT = new Key("Right Alt"); // MS 0xB8 UNIX 0xFFEA
public static final Key PAUSE = new Key("Pause"); // MS 0xC5 UNIX 0xFF13 BREAK 0xFF6B
public static final Key HOME = new Key("Home"); // MS 0xC7 UNIX 0xFF50
public static final Key UP = new Key("Up"); // MS 0xC8 UNIX 0xFF52
public static final Key PAGEUP = new Key("Pg Up"); // MS 0xC9 UNIX 0xFF55
public static final Key LEFT = new Key("Left"); // MS 0xCB UNIX 0xFF51
public static final Key RIGHT = new Key("Right"); // MS 0xCD UNIX 0xFF53
public static final Key END = new Key("End"); // MS 0xCF UNIX 0xFF57
public static final Key DOWN = new Key("Down"); // MS 0xD0 UNIX 0xFF54
public static final Key PAGEDOWN = new Key("Pg Down"); // MS 0xD1 UNIX 0xFF56
public static final Key INSERT = new Key("Insert"); // MS 0xD2 UNIX 0xFF63
public static final Key DELETE = new Key("Delete"); // MS 0xD3 UNIX 0xFFFF
public static final Key LWIN = new Key("Left Windows"); // MS 0xDB UNIX META 0xFFE7 SUPER 0xFFEB HYPER 0xFFED
public static final Key RWIN = new Key("Right Windows"); // MS 0xDC UNIX META 0xFFE8 SUPER 0xFFEC HYPER 0xFFEE
public static final Key APPS = new Key("Apps"); // MS 0xDD UNIX 0xFF67
public static final Key POWER = new Key("Power"); // MS 0xDE Sun 0x1005FF76 SHIFT 0x1005FF7D
public static final Key SLEEP = new Key("Sleep"); // MS 0xDF No UNIX keysym
public static final Key UNKNOWN = new Key("Unknown");
} // class StandardKeyboard.KeyID
} // class Axis.Identifier
/**
* POV enum for different positions.
*/
public static class POV {
/**
* Standard value for center HAT position
*/
public static final float OFF = 0.0f;
/**
* Synonmous with OFF
*/
public static final float CENTER = OFF;
/**
* Standard value for up-left HAT position
*/
public static final float UP_LEFT = 0.125f;
/**
* Standard value for up HAT position
*/
public static final float UP = 0.25f;
/**
* Standard value for up-right HAT position
*/
public static final float UP_RIGHT = 0.375f;
/**
* Standard value for right HAT position
*/
public static final float RIGHT = 0.50f;
/**
* Standard value for down-right HAT position
*/
public static final float DOWN_RIGHT = 0.625f;
/**
* Standard value for down HAT position
*/
public static final float DOWN = 0.75f;
/**
* Standard value for down-left HAT position
*/
public static final float DOWN_LEFT = 0.875f;
/**
* Standard value for left HAT position
*/
public static final float LEFT = 1.0f;
} // class Axis.POV
} // interface Axis

View file

@ -61,21 +61,21 @@ public interface Controller {
public abstract Type getType();
/**
* Returns the axes on this controller, in order of assignment priority.
* Returns the components on this controller, in order of assignment priority.
* For example, the button controller on a mouse returns an array containing
* the primary or leftmost mouse button, followed by the secondary or
* rightmost mouse button (if present), followed by the middle mouse button
* (if present).
* The array returned is an empty array if this controller contains no axes
* The array returned is an empty array if this controller contains no components
* (such as a logical grouping of child controllers).
*/
public abstract Axis[] getAxes();
public abstract Component[] getComponents();
/**
* Returns a single axis based on its type, or null
* if no axis with the specified type could be found.
*/
public abstract Axis getAxis(Axis.Identifier id);
public abstract Component getComponent(Component.Identifier id);
/**
* Returns the rumblers for sending feedback to this controller, or an
@ -89,6 +89,17 @@ public interface Controller {
*/
public abstract boolean poll();
/**
* Initialized the controller event queue to a new size. Existing events
* in the queue are lost.
*/
public abstract void setEventQueueSize(int size);
/**
* Get the device event queue
*/
public abstract EventQueue getEventQueue();
/**
* Returns the port type for this Controller.
*/
@ -129,76 +140,64 @@ public interface Controller {
}
/**
* Mouse controller.
* Unkown controller type.
*/
public static final Type UNKNOWN = new Type("unknown");
public static final Type UNKNOWN = new Type("Unknown");
/**
* Mouse controller.
*/
public static final Type MOUSE = new Type("mouse");
public static final Type MOUSE = new Type("Mouse");
/**
* A mouse ball or the ball part of a trackball controller.
* Note that a mouse wheel is considered part of a ball controller.
* A keyboard controller
*/
public static final Type BALL = new Type("ball");
/**
* A group of buttons on a pad (mouse buttons, for
* example) or a keyboard.
*/
public static final Type BUTTONS = new Type("buttons");
/**
* A keyboard controller (same as BUTTONS)
* @see #BUTTONS
*/
public static final Type KEYBOARD = BUTTONS;
public static final Type KEYBOARD = new Type("Keyboard");
/**
* Fingerstick controller; note that this may be sometimes treated as a
* type of mouse or stick.
*/
public static final Type FINGERSTICK = new Type("fingerstick");
public static final Type FINGERSTICK = new Type("Fingerstick");
/**
* Gamepad controller.
*/
public static final Type GAMEPAD = new Type("gamepad");
public static final Type GAMEPAD = new Type("Gamepad");
/**
* Headtracker controller.
*/
public static final Type HEADTRACKER = new Type("headtracker");
public static final Type HEADTRACKER = new Type("Headtracker");
/**
* Rudder controller.
*/
public static final Type RUDDER = new Type("rudder");
public static final Type RUDDER = new Type("Rudder");
/**
* Stick controller, such as a joystick or flightstick.
*/
public static final Type STICK = new Type("stick");
public static final Type STICK = new Type("Stick");
/**
* A trackball controller; note that this may sometimes be treated as a
* type of mouse.
*/
public static final Type TRACKBALL = new Type("trackball");
public static final Type TRACKBALL = new Type("Trackball");
/**
* A trackpad, such as a tablet, touchpad, or glidepad;
* note that this may sometimes be treated as a type of mouse.
*/
public static final Type TRACKPAD = new Type("trackpad");
public static final Type TRACKPAD = new Type("Trackpad");
/**
* A wheel controller, such as a steering wheel (note
* that a mouse wheel is considered part of a ball control, not a
* that a mouse wheel is considered part of a mouse, not a
* wheel controller).
*/
public static final Type WHEEL = new Type("wheel");
public static final Type WHEEL = new Type("Wheel");
} // class Controller.Type
/**
@ -249,5 +248,16 @@ public interface Controller {
* Serial port
*/
public static final PortType SERIAL = new PortType("Serial port");
/**
* i8042
*/
public static final PortType I8042 = new PortType("i8042 (PS/2)");
/**
* Parallel port
*/
public static final PortType PARALLEL = new PortType("Parallel port");
} // class Controller.PortType
} // interface Controller

View file

@ -38,8 +38,12 @@
*****************************************************************************/
package net.java.games.input;
import java.io.File;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A ControllerEnvironment represents a collection of controllers that are
@ -49,9 +53,9 @@ import java.util.Iterator;
* In this reference implementation, this class can also be used to register
* controllers with the default environment as "plug-ins". A plug-in is
* created by subclassing ControllerEnvironment with a class that has a public
* no-argument constructor, implements the org.java.games.util.plugins.Plugin
* no-argument constructor, implements the net.java.games.util.plugins.Plugin
* interface and has a name ending in "Plugin".
* (See org.java.games.input.DirectInputEnvironmentPlugin in the DXplugin
* (See net.java.games.input.DirectInputEnvironmentPlugin in the DXplugin
* part of the source tree for an example.)
*
* When the DefaultControllerEnvrionment is instanced it uses the plugin library
@ -61,12 +65,16 @@ import java.util.Iterator;
* Java app.
*
* For more information on the organization of plugins within the controller
* root directories, see org.java.games.util.plugins.Plugins (Note the
* root directories, see net.java.games.util.plugins.Plugins (Note the
* plural -- "Plugins" not "Plugin" which is just a marker interface.)
*
*/
public abstract class ControllerEnvironment {
static void log(String msg) {
Logger.getLogger(ControllerEnvironment.class.getName()).info(msg);
}
/**
* The default controller environment
*/
@ -76,12 +84,17 @@ public abstract class ControllerEnvironment {
/**
* List of controller listeners
*/
protected final ArrayList controllerListeners = new ArrayList();
protected final ArrayList<ControllerListener> controllerListeners = new ArrayList<>();
/**
* Protected constructor for subclassing.
*/
protected ControllerEnvironment() {
if(System.getProperty("jinput.loglevel") != null) {
String loggerName = ControllerEnvironment.class.getPackage().getName();
Level level = Level.parse(System.getProperty("jinput.loglevel"));
Logger.getLogger(loggerName).setLevel(level);
}
}
/**
@ -98,6 +111,13 @@ public abstract class ControllerEnvironment {
controllerListeners.add(l);
}
/**
* Returns the isSupported status of this environment.
* What makes an environment supported or not is up to the
* particular plugin, but may include OS or available hardware.
*/
public abstract boolean isSupported();
/**
* Removes a listener for controller state change events.
*/
@ -112,9 +132,9 @@ public abstract class ControllerEnvironment {
*/
protected void fireControllerAdded(Controller c) {
ControllerEvent ev = new ControllerEvent(c);
Iterator it = controllerListeners.iterator();
Iterator<ControllerListener> it = controllerListeners.iterator();
while (it.hasNext()) {
((ControllerListener)it.next()).controllerAdded(ev);
it.next().controllerAdded(ev);
}
}
@ -124,9 +144,9 @@ public abstract class ControllerEnvironment {
*/
protected void fireControllerRemoved(Controller c) {
ControllerEvent ev = new ControllerEvent(c);
Iterator it = controllerListeners.iterator();
Iterator<ControllerListener> it = controllerListeners.iterator();
while (it.hasNext()) {
((ControllerListener)it.next()).controllerRemoved(ev);
it.next().controllerRemoved(ev);
}
}
@ -137,4 +157,4 @@ public abstract class ControllerEnvironment {
public static ControllerEnvironment getDefaultEnvironment() {
return defaultEnvironment;
}
} // ControllerEnvironment
}

View file

@ -0,0 +1,214 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*/
package net.java.games.input;
import net.java.games.util.plugins.Plugins;
import java.io.File;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.logging.Logger;
/**
* The default controller environment.
*
* @version %I% %G%
* @author Michael Martak
*/
class DefaultControllerEnvironment extends ControllerEnvironment {
static String libPath;
private static Logger log = Logger.getLogger(DefaultControllerEnvironment.class.getName());
/**
* Static utility method for loading native libraries.
* It will try to load from either the path given by
* the net.java.games.input.librarypath property
* or through System.loadLibrary().
*
*/
static void loadLibrary(final String lib_name) {
AccessController.doPrivileged((PrivilegedAction<String>) () -> {
String lib_path = System.getProperty("net.java.games.input.librarypath");
if (lib_path != null)
System.load(lib_path + File.separator + System.mapLibraryName(lib_name));
else
System.loadLibrary(lib_name);
return null;
});
}
static String getPrivilegedProperty(final String property) {
return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(property));
}
static String getPrivilegedProperty(final String property, final String default_value) {
return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(property, default_value));
}
/**
* List of all controllers in this environment
*/
private ArrayList<Controller> controllers;
private Collection<String> loadedPluginNames = new ArrayList<>();
/**
* Public no-arg constructor.
*/
public DefaultControllerEnvironment() {
}
/**
* Returns a list of all controllers available to this environment,
* or an empty array if there are no controllers in this environment.
*/
public Controller[] getControllers() {
if (controllers == null) {
// Controller list has not been scanned.
controllers = new ArrayList<>();
AccessController.doPrivileged((PrivilegedAction<Void>) () -> scanControllers());
//Check the properties for specified controller classes
String pluginClasses = getPrivilegedProperty("jinput.plugins", "") + " " + getPrivilegedProperty("net.java.games.input.plugins", "");
if(!getPrivilegedProperty("jinput.useDefaultPlugin", "true").toLowerCase().trim().equals("false") && !getPrivilegedProperty("net.java.games.input.useDefaultPlugin", "true").toLowerCase().trim().equals("false")) {
String osName = getPrivilegedProperty("os.name", "").trim();
if(osName.equals("Linux")) {
pluginClasses = pluginClasses + " net.java.games.input.LinuxEnvironmentPlugin";
} else if(osName.equals("Mac OS X")) {
pluginClasses = pluginClasses + " net.java.games.input.OSXEnvironmentPlugin";
} else if(osName.equals("Windows XP") || osName.equals("Windows Vista") || osName.equals("Windows 7") || osName.equals("Windows 8") || osName.equals("Windows 8.1") || osName.equals("Windows 10")) {
pluginClasses = pluginClasses + " net.java.games.input.DirectAndRawInputEnvironmentPlugin";
} else if(osName.equals("Windows 98") || osName.equals("Windows 2000")) {
pluginClasses = pluginClasses + " net.java.games.input.DirectInputEnvironmentPlugin";
} else if (osName.startsWith("Windows")) {
log.warning("Found unknown Windows version: " + osName);
log.warning("Attempting to use default windows plug-in.");
pluginClasses = pluginClasses + " net.java.games.input.DirectAndRawInputEnvironmentPlugin";
} else {
log.warning("Trying to use default plugin, OS name " + osName +" not recognised");
}
}
StringTokenizer pluginClassTok = new StringTokenizer(pluginClasses, " \t\n\r\f,;:");
while(pluginClassTok.hasMoreTokens()) {
String className = pluginClassTok.nextToken();
try {
if(!loadedPluginNames.contains(className)) {
log.fine("Loading: " + className);
Class<?> ceClass = Class.forName(className);
ControllerEnvironment ce = (ControllerEnvironment) ceClass.getDeclaredConstructor().newInstance();
if(ce.isSupported()) {
addControllers(ce.getControllers());
loadedPluginNames.add(ce.getClass().getName());
} else {
log(ceClass.getName() + " is not supported");
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
Controller[] ret = new Controller[controllers.size()];
Iterator<Controller> it = controllers.iterator();
int i = 0;
while (it.hasNext()) {
ret[i] = it.next();
i++;
}
return ret;
}
/* This is jeff's new plugin code using Jeff's Plugin manager */
private Void scanControllers() {
String pluginPathName = getPrivilegedProperty("jinput.controllerPluginPath");
if(pluginPathName == null) {
pluginPathName = "controller";
}
scanControllersAt(getPrivilegedProperty("java.home") +
File.separator + "lib"+File.separator + pluginPathName);
scanControllersAt(getPrivilegedProperty("user.dir")+
File.separator + pluginPathName);
return null;
}
private void scanControllersAt(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
try {
Plugins plugins = new Plugins(file);
@SuppressWarnings("unchecked")
Class<ControllerEnvironment>[] envClasses = plugins.getExtends(ControllerEnvironment.class);
for(int i=0;i<envClasses.length;i++){
try {
ControllerEnvironment.log("ControllerEnvironment "+
envClasses[i].getName()
+" loaded by "+envClasses[i].getClassLoader());
ControllerEnvironment ce = envClasses[i].getDeclaredConstructor().newInstance();
if(ce.isSupported()) {
addControllers(ce.getControllers());
loadedPluginNames.add(ce.getClass().getName());
} else {
log(envClasses[i].getName() + " is not supported");
}
} catch (Throwable e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Add the array of controllers to our list of controllers.
*/
private void addControllers(Controller[] c) {
for (int i = 0; i < c.length; i++) {
controllers.add(c[i]);
}
}
public boolean isSupported() {
return true;
}
}

View file

@ -0,0 +1,76 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
public final class Event {
private Component component;
private float value;
private long nanos;
public final void set(Event other) {
this.set(other.getComponent(), other.getValue(), other.getNanos());
}
public final void set(Component component, float value, long nanos) {
this.component = component;
this.value = value;
this.nanos = nanos;
}
public final Component getComponent() {
return component;
}
public final float getValue() {
return value;
}
/**
* Return the time the event happened, in nanoseconds.
* The time is relative and therefore can only be used
* to compare with other event times.
*/
public final long getNanos() {
return nanos;
}
public final String toString() {
return "Event: component = " + component + " | value = " + value;
}
}

View file

@ -0,0 +1,95 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
/**
* A FIFO queue for input events.
*/
public final class EventQueue {
private final Event[] queue;
private int head;
private int tail;
/**
* This is an internal method and should not be called by applications using the API
*/
public EventQueue(int size) {
queue = new Event[size + 1];
for (int i = 0; i < queue.length; i++)
queue[i] = new Event();
}
/**
* This is an internal method and should not be called by applications using the API
*/
final synchronized void add(Event event) {
queue[tail].set(event);
tail = increase(tail);
}
/**
* Check if the queue is full
* @return true if the queue is full
*/
final synchronized boolean isFull() {
return increase(tail) == head;
}
/**
* This is an internal method and should not be called by applications using the API
*/
private final int increase(int x) {
return (x + 1)%queue.length;
}
/**
* Populates the provided event with the details of the event on the head of the queue.
*
* @param event The event to populate
* @return false if there were no events left on the queue, otherwise true.
*/
public final synchronized boolean getNextEvent(Event event) {
if (head == tail)
return false;
event.set(queue[head]);
head = increase(head);
return true;
}
}

View file

@ -0,0 +1,69 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
/**
* A Keyboard is a type of controller consisting of a single controller,
* they keypad, which contains several axes (the keys). By default, all keys
* are set to receive polling data.
*/
public abstract class Keyboard extends AbstractController {
/**
* Protected constructor.
* Subclasses should initialize the array of axes to an array of keys.
* @param name The name of the keyboard
*/
protected Keyboard(String name, Component[] keys, Controller[] children, Rumbler[] rumblers) {
super(name, keys, children, rumblers);
}
/**
* Returns the type of the Controller.
*/
public Type getType() {
return Type.KEYBOARD;
}
public final boolean isKeyDown(Component.Identifier.Key key_id) {
Component key = getComponent(key_id);
if (key == null)
return false;
return key.getPollData() != 0;
}
} // class Keyboard

View file

@ -0,0 +1,186 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.util.List;
import java.util.ArrayList;
/**
* A Mouse is a type of controller consisting of two child controllers,
* a ball and a button pad. This includes devices such as touch pads,
* trackballs, and fingersticks.
*/
public abstract class Mouse extends AbstractController {
protected Mouse(String name, Component[] components, Controller[] children, Rumbler[] rumblers) {
super(name, components, children, rumblers);
}
/**
* Returns the type of the Controller.
*/
public Type getType() {
return Type.MOUSE;
}
/**
* Returns the x-axis for the mouse ball, never null.
*/
public Component getX() {
return getComponent(Component.Identifier.Axis.X);
}
/**
* Returns the y-axis for the mouse ball, never null.
*/
public Component getY() {
return getComponent(Component.Identifier.Axis.Y);
}
/**
* Returns the mouse wheel, or null if no mouse wheel is present.
*/
public Component getWheel() {
return getComponent(Component.Identifier.Axis.Z);
}
/**
* Returns the left or primary mouse button, never null.
*/
public Component getPrimaryButton() {
Component primaryButton = getComponent(Component.Identifier.Button.LEFT);
if(primaryButton==null) {
primaryButton = getComponent(Component.Identifier.Button._1);
}
return primaryButton;
}
/**
* Returns the right or secondary mouse button, null if the mouse is
* a single-button mouse.
*/
public Component getSecondaryButton() {
Component secondaryButton = getComponent(Component.Identifier.Button.RIGHT);
if(secondaryButton==null) {
secondaryButton = getComponent(Component.Identifier.Button._2);
}
return secondaryButton;
}
/**
* Returns the middle or tertiary mouse button, null if the mouse has
* fewer than three buttons.
*/
public Component getTertiaryButton() {
Component tertiaryButton = getComponent(Component.Identifier.Button.MIDDLE);
if(tertiaryButton==null) {
tertiaryButton = getComponent(Component.Identifier.Button._3);
}
return tertiaryButton;
}
/**
* Returns the left mouse button.
*/
public Component getLeft() {
return getComponent(Component.Identifier.Button.LEFT);
}
/**
* Returns the right, null if the mouse is a single-button mouse.
*/
public Component getRight() {
return getComponent(Component.Identifier.Button.RIGHT);
}
/**
* Returns the middle, null if the mouse has fewer than three buttons.
*/
public Component getMiddle() {
return getComponent(Component.Identifier.Button.MIDDLE);
}
/**
* Returns the side or 4th mouse button, null if the mouse has
* fewer than 4 buttons.
*/
public Component getSide() {
return getComponent(Component.Identifier.Button.SIDE);
}
/**
* Returns the extra or 5th mouse button, null if the mouse has
* fewer than 5 buttons.
*/
public Component getExtra() {
return getComponent(Component.Identifier.Button.EXTRA);
}
/**
* Returns the forward mouse button, null if the mouse hasn't
* got one.
*/
public Component getForward() {
return getComponent(Component.Identifier.Button.FORWARD);
}
/**
* Returns the back mouse button, null if the mouse hasn't
* got one.
*/
public Component getBack() {
return getComponent(Component.Identifier.Button.BACK);
}
/**
* Returns forth mouse button, null if the mouse hasn't
* got one.
*/
public Component getButton3() {
return getComponent(Component.Identifier.Button._3);
}
/**
* Returns fifth mouse button, null if the mouse hasn't
* got one.
*/
public Component getButton4() {
return getComponent(Component.Identifier.Button._4);
}
} // class Mouse

View file

@ -1,10 +1,4 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
@ -35,7 +29,7 @@
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
*/
package net.java.games.input;
import java.io.File;
@ -44,8 +38,6 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
@ -79,7 +71,7 @@ class PluginClassLoader extends ClassLoader {
* Overrides findClass to first look in the parent class loader,
* then try loading the class from the plugin file system.
*/
protected Class findClass(String name)
protected Class<?> findClass(String name)
throws ClassNotFoundException {
// Try loading the class from the file system.
byte[] b = loadClassData(name);
@ -125,7 +117,7 @@ class PluginClassLoader extends ClassLoader {
if (!file.exists()) {
throw new ClassNotFoundException(name);
}
FileInputStream fileInputStream = new FileInputStream(file);
try(FileInputStream fileInputStream = new FileInputStream(file)) {
assert file.length() <= Integer.MAX_VALUE;
int length = (int) file.length();
byte[] bytes = new byte[length];
@ -133,6 +125,7 @@ class PluginClassLoader extends ClassLoader {
assert length == length2;
return bytes;
}
}
/**
* Scans through the plugin directory for JAR files and
@ -149,7 +142,7 @@ class PluginClassLoader extends ClassLoader {
JarFile jarfile = new JarFile(jarFiles[i]);
JarEntry jarentry = jarfile.getJarEntry(name + ".class");
if (jarentry != null) {
InputStream jarInputStream = jarfile.getInputStream(jarentry);
try(InputStream jarInputStream = jarfile.getInputStream(jarentry)) {
assert jarentry.getSize() <= Integer.MAX_VALUE;
int length = (int) jarentry.getSize();
assert length >= 0;
@ -159,6 +152,7 @@ class PluginClassLoader extends ClassLoader {
return bytes;
}
}
}
throw new FileNotFoundException(name);
}

View file

@ -49,4 +49,19 @@ public interface Rumbler {
*/
public abstract void rumble(float intensity);
/**
* Get the string name of the axis the rumbler is attached to
*
* @return The axis name
*/
public String getAxisName();
/**
* Get the axis identifier the rumbler is attached to
*
* @return The axis identifier
*/
public Component.Identifier getAxisIdentifier();
} // interface Rumbler

View file

@ -0,0 +1,102 @@
/*
* Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* -Redistribution 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.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS
* LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A
* RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
* IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT
* OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
* PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use in the
* design, construction, operation or maintenance of any nuclear facility.
*/
package net.java.games.input;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* The version and build number of this implementation.
* Version numbers for a release are of the form: w.x.y, where:
* <ul>
* <li>
* w - the major version number of the release. This number should
* start at 1. Typically, a bump in the major version number
* signifies that the release breaks backwards compatibility
* with some older release.
* </li>
* <li>
* x - minor version number. This number starts at 0. A bump in
* the minor version number signifies a release that has significant
* new functionality.
* </li>
* <li>
* y - minor-minor version number number. This number starts at 0. A
* bump in the minor-minor version number signifies that new bug
* fixes have been added to the build.
* </li>
* </ul>
*
* For example, the following are all valid version strings:
* <ul>
* <li>1.1.2</li>
* <li>1.3.5-SNAPSHOT</li>
* <li>4.7.1-M2</li>
* </ul>
*
*/
public final class Version {
/**
* Private constructor - no need for user to create
* an instance of this class.
*/
private Version() {
}
/**
* Returns the verison string and build number of
* this implementation. See the class descritpion
* for the version string format.
*
* @return The version string of this implementation.
*/
public static String getVersion() {
String version = "Unversioned";
try {
Properties p = new Properties();
InputStream is = Version.class.getResourceAsStream("/META-INF/maven/net.java.jinput/coreapi/pom.properties");
if(is != null) {
p.load(is);
version = p.getProperty("version", "");
}
} catch(IOException e) {
// ignore
}
return version;
}
}

View file

@ -0,0 +1,14 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<body>
Top level package for JInput.
<h2>Package Specification</h2>
Use -Djinput.useDefaultPlugin=false (or net.java.games.input.useDefaultPlugin=false) to disable automatic loading of the default plugin for the platform.<BR/>
Use -Djinput.plugins (or net.java.games.input.plugins) and specifiy a list of class name to over ride the plugins system. This will force the classes passed to be loaded first, then plugins will be searched for in the default manner (./controller/*.jar)<BR/>
Use -Djinput.controllerPluginPath to change the path the plugins mechanism will use to search for plugin Jars.
Use -Djinput.loglevel to change the logging level using Java util logging level strings.
</body>
</html>

6
docs/_config.yml Normal file
View file

@ -0,0 +1,6 @@
title: JInput
description: Java library for access to input devices.
show_downloads: true
google_analytics:
theme: jekyll-theme-architect
jinput_version: 2.0.9

93
docs/index.md Normal file
View file

@ -0,0 +1,93 @@
---
layout: default
---
[![Maven Central](https://img.shields.io/maven-central/v/net.java.jinput/coreapi.svg)](https://maven-badges.herokuapp.com/maven-central/net.java.jinput/coreapi)
[![Javadocs](http://www.javadoc.io/badge/net.java.jinput/coreapi.svg)](http://www.javadoc.io/doc/net.java.jinput/coreapi)
# Welcome to the Java Input API Project!
<p>The JInput Project hosts an implementation of an API for game controller
discovery and polled input. It is part of a suite of open-source technologies
initiated by the Game Technology Group at Sun Microsystems with intention of
making the development of high performance games in Java a reality.</p>
<p>The API itself is pure Java and presents a platform-neutral
completely portable model of controller discovery and polling.
It can handle arbitrary controllers and returns both human and
machine understandable descriptions of the inputs available.</p>
<p>The implementation hosted here also includes plug-ins to allow
the API to adapt to various specific platforms. These plug-ins
often contain a native code portion to interface to the host system.
</p>
## Getting Started
### Maven
Include the dependency in your project:
```xml
<dependency>
<groupId>net.java.jinput</groupId>
<artifactId>jinput</artifactId>
<version>{{site.jinput_version}}</version>
</dependency>
<dependency>
<groupId>net.java.jinput</groupId>
<artifactId>jinput</artifactId>
<version>{{site.jinput_version}}</version>
<classifier>natives-all</classifier>
</dependency>
```
You'll also need to add the build plugin in your `build/plugins` section of your pom
```xml
<plugin>
<groupId>com.googlecode.mavennatives</groupId>
<artifactId>maven-nativedependencies-plugin</artifactId>
</plugin>
```
A full pom might look like [this one](https://github.com/jinput/jinput/blob/master/examples/example.pom.xml)
### Without maven
The jar file with the java code in should be in maven central, you'll need the [jinput.jar](http://repo1.maven.org/maven2/net/java/jinput/jinput/{{site.jinput_version}}/jinput-{{site.jinput_version}}.jar) and [jinput-natives-all.jar](http://repo1.maven.org/maven2/net/java/jinput/jinput/{{site.jinput_version}}/jinput-{{site.jinput_version}}-natives-all.jar) that contains the native binaries.
## Running
Add the jinput jar to your classpath, if you are using maven and have the native dependencies plugin working, it will have unpacked the native binaries to `target/natives`, you must specify the `java.library.path` property to point to this directy.
Example
```
java -cp ~/.m2/repository/net/java/jinput/jinput/{{site.jinput_version}}/jinput-{{site.jinput_version}}.jar:target/examples-pom-{{site.jinput_version}}.jar -Djava.library.path=target/natives net.java.games.input.example.ReadFirstMouse
```
More generally
```
java -cp <path to jinput.jar>:<your own jars> -Djava.library.path=<path to natives> <main class>
```
## Usage
```java
/* Create an event object for the underlying plugin to populate */
Event event = new Event();
/* Get the available controllers */
Controller[] controllers = ControllerEnvironment.getDefaultEnvironment().getControllers();
for (int i = 0; i < controllers.length; i++) {
/* Remember to poll each one */
controllers[i].poll();
/* Get the controllers event queue */
EventQueue queue = controllers[i].getEventQueue();
/* For each object in the queue */
while (queue.getNextEvent(event)) {
/* Get event component */
Component comp = event.getComponent();
/* Process event (your awesome code) */
...
}
}
```
[More examples here](https://github.com/jinput/jinput/tree/master/examples/src/main/java/net/java/games/input/example).

77
examples/example.pom.xml Normal file
View file

@ -0,0 +1,77 @@
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>net.java.jinput</groupId>
<artifactId>examples-pom</artifactId>
<packaging>jar</packaging>
<name>JInput - example pom</name>
<version>2.0.9</version>
<repositories>
<repository>
<id>central-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases><enabled>false</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>net.java.jinput</groupId>
<artifactId>jinput</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>net.java.jinput</groupId>
<artifactId>jinput</artifactId>
<version>${project.version}</version>
<classifier>natives-all</classifier>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.googlecode.mavennatives</groupId>
<artifactId>maven-nativedependencies-plugin</artifactId>
<version>0.0.7</version>
<executions>
<execution>
<id>unpacknatives</id>
<goals>
<goal>copy</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>-Djava.library.path=${project.build.directory}/natives</argument>
<argument>-Djinput.loglevel=OFF</argument>
<argument>net.java.games.input.example.ReadAllEvents</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</project>

78
examples/pom.xml Normal file
View file

@ -0,0 +1,78 @@
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>examples</artifactId>
<packaging>jar</packaging>
<name>JInput - examples</name>
<parent>
<groupId>net.java.jinput</groupId>
<artifactId>jinput-parent</artifactId>
<version>2.0.10-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<repositories>
<repository>
<id>central-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases><enabled>false</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jinput</artifactId>
<version>${project.version}</version>
<type>pom</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.googlecode.mavennatives</groupId>
<artifactId>maven-nativedependencies-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>ReadAllEvents</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>-Djava.library.path=${project.build.directory}/natives</argument>
<argument>-Djinput.loglevel=OFF</argument>
<argument>net.java.games.input.example.ReadAllEvents</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View file

@ -0,0 +1,92 @@
package net.java.games.input.example;
import net.java.games.input.Component;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
import net.java.games.input.Event;
import net.java.games.input.EventQueue;
/**
* This class shows how to use the event queue system in JInput. It will show
* how to get the controllers, how to get the event queue for a controller, and
* how to read and process events from the queue.
*
* @author Endolf
*/
public class ReadAllEvents {
public ReadAllEvents() {
while (true) {
/* Get the available controllers */
Controller[] controllers = ControllerEnvironment
.getDefaultEnvironment().getControllers();
if (controllers.length == 0) {
System.out.println("Found no controllers.");
System.exit(0);
}
for (int i = 0; i < controllers.length; i++) {
/* Remember to poll each one */
controllers[i].poll();
/* Get the controllers event queue */
EventQueue queue = controllers[i].getEventQueue();
/* Create an event object for the underlying plugin to populate */
Event event = new Event();
/* For each object in the queue */
while (queue.getNextEvent(event)) {
/*
* Create a string buffer and put in it, the controller name,
* the time stamp of the event, the name of the component
* that changed and the new value.
*
* Note that the timestamp is a relative thing, not
* absolute, we can tell what order events happened in
* across controllers this way. We can not use it to tell
* exactly *when* an event happened just the order.
*/
StringBuffer buffer = new StringBuffer(controllers[i]
.getName());
buffer.append(" at ");
buffer.append(event.getNanos()).append(", ");
Component comp = event.getComponent();
buffer.append(comp.getName()).append(" changed to ");
float value = event.getValue();
/*
* Check the type of the component and display an
* appropriate value
*/
if (comp.isAnalog()) {
buffer.append(value);
} else {
if (value == 1.0f) {
buffer.append("On");
} else {
buffer.append("Off");
}
}
System.out.println(buffer.toString());
}
}
/*
* Sleep for 20 milliseconds, in here only so the example doesn't
* thrash the system.
*/
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ReadAllEvents();
}
}

View file

@ -0,0 +1,85 @@
package net.java.games.input.example;
import net.java.games.input.Component;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
/**
* This class shows how to read the values in a polling loop for the first mouse
* detected. It will show how to get the available controllers, how to check the
* type of the controller, how to read the components of the controller, and how
* to get the data from the component.
*
* @author Endolf
*/
public class ReadFirstMouse {
public ReadFirstMouse() {
/* Get the available controllers */
Controller[] controllers = ControllerEnvironment
.getDefaultEnvironment().getControllers();
/*
* Loop through the controllers, check the type of each one, and save
* the first mouse we find.
*/
Controller firstMouse = null;
for (int i = 0; i < controllers.length && firstMouse == null; i++) {
if (controllers[i].getType() == Controller.Type.MOUSE) {
// Found a mouse
firstMouse = controllers[i];
}
}
if (firstMouse == null) {
// Couldn't find a mouse
System.out.println("Found no mouse");
System.exit(0);
}
System.out.println("First mouse is: " + firstMouse.getName());
while (true) {
/* Poll the controller */
firstMouse.poll();
/* Get all the axis and buttons */
Component[] components = firstMouse.getComponents();
StringBuffer buffer = new StringBuffer();
/* For each component, get it's name, and it's current value */
for (int i = 0; i < components.length; i++) {
if (i > 0) {
buffer.append(", ");
}
buffer.append(components[i].getName());
buffer.append(": ");
if (components[i].isAnalog()) {
/* Get the value at the last poll of this component */
buffer.append(components[i].getPollData());
} else {
if (components[i].getPollData() == 1.0f) {
buffer.append("On");
} else {
buffer.append("Off");
}
}
}
System.out.println(buffer.toString());
/*
* Sleep for 20 millis, this is just so the example doesn't thrash
* the system.
*/
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ReadFirstMouse();
}
}

View file

@ -1,103 +0,0 @@
<?xml version="1.0"?>
<!-- Written to assume that classpath is rooted in the current directory. -->
<!-- So this should be OK if you make this script in the root of a filesystem. -->
<!-- If not, you may prefer to adjust the basedir, or move some directories around. -->
<!-- The idea is that both Ant and NetBeans have to know what the package root is -->
<!-- for the classes in your application. -->
<project name="Direct Input Plugin" basedir="." default="all">
<!-- Don't worry if you don't know the Ant syntax completely or need help on some tasks! -->
<!-- The standard Ant documentation is bundled. See Help | Help Sets | Ant 1.4.1 Manual. -->
<target name="init">
<!-- You can set up any variables you want used throughout the script here. -->
<property name="hello" value="world"/>
<mkdir dir="classes"/>
<mkdir dir="bin"/>
<!-- To use e.g. Jikes, uncomment this line. -->
<!-- (Or make the same change in Tools | Options | Ant Settings | Properties.) -->
<!-- <property name="build.compiler" value="jikes"/> -->
<!-- You might like to set up some overridable paths, etc.: -->
<!-- <property name="mylib" value="../lib/mylib.jar"/> -->
</target>
<target name="compile" depends="init">
<!-- Both srcdir and destdir should be package roots. -->
<!-- They could be different of course; in that case NetBeans can also be set -->
<!-- up to compile to a different filesystem in the same way; see Compiler Types: -->
<javac srcdir="src/java" destdir="classes" debug="true" deprecation="true" source="1.4">
<!-- To add something to the classpath: -->
<classpath>
<pathelement location="lib/controller.jar"/>
<pathelement location="lib/jutils.jar"/>
</classpath>
<!-- To exclude some files: -->
<!--
<exclude name="com/foo/SomeFile.java"/>
<exclude name="com/foo/somepackage/"/>
-->
</javac>
<exec dir="." executable="gcc" os="Windows 2000">
<arg line=" -D_STRICT_ANSI -D_JNI_IMPLEMENTATION_"/>
<arg line=" -I'${java.home}/../include' -I'${java.home}/../include/win32' -Ic:/dx9/include"/>
<arg line=" -o bin/dxinput.dll src/native/input.cpp -Wl,--export-all-symbols"/>
<arg line=" -shared -Wl,--kill-at -ldxguid -ldinput -ldinput8"/>
</exec>
<copy file="bin/dxinput.dll" todir="../../coreAPI/src/tests/controller" />
</target>
<target name="jar" depends="init,compile">
<!-- To make a standalone app: -->
<!-- 1. Create a myapp.mf manifest somewhere. -->
<!-- 2. Put in it: -->
<!-- Manifest-Version: 1.0 -->
<!-- Main-Class: com.foo.Main -->
<!-- 3. Pass to <jar>: manifest="myapp.mf" -->
<jar jarfile="bin/dxinput.jar" compress="true" basedir="classes">
<exclude name="**/*.java"/>
<exclude name="**/*.form"/>
<exclude name="dxinput.mf"/>
<exclude name="dxinput.jar"/>
<exclude name="apidoc"/>
</jar>
<copy file="bin/dxinput.jar" todir="../../coreAPI/src/tests/controller" />
</target>
<target name="all" depends="compile,jar" description="Build everything.">
<echo message="Application built. Hello ${hello}!"/>
</target>
<target name="test" depends="init,all" description="Try running it.">
<echo message="Test by running test on the build.xml for input"/>
</target>
<target name="javadoc" depends="init" description="Javadoc for my API.">
<mkdir dir="apidocs"/>
<javadoc packagenames="net.*"
destdir="apidocs"
additionalparam="-source 1.4">
<sourcepath>
<pathelement location="src/java"/>
</sourcepath>
<classpath>
<pathelement location="lib/controller.jar"/>
<pathelement location="lib/jutils.jar"/>
</classpath>
</javadoc>
</target>
<target name="clean" depends="init" description="Clean all build products.">
<delete>
<fileset dir="classes">
<include name="**/*.class"/>
</fileset>
</delete>
<delete file="bin/dxinput.jar" failonerror="no"/>
<delete file="bin/dxinput.dll" failonerror="no"/>
<delete file="../../coreAPI/src/tests/controller/dxinput.jar" failonerror="no" />
<delete file="../../coreAPI/src/test/controller/dxinput.dll" failonerror="no"/>
<delete dir="../../docs/input/win32/apidoc" failonerror="no"/>
</target>
</project>

View file

@ -1,211 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import net.java.games.input.AbstractAxis;
import net.java.games.input.Axis;
/**
*
* @author martak
* @version
*/
class DirectInputAxis extends AbstractAxis {
/**
* DIDFT_ constants and macros defined in dinput.h
*/
private static final int DIDFT_ALL = 0x00000000;
private static final int DIDFT_RELAXIS = 0x00000001;
private static final int DIDFT_ABSAXIS = 0x00000002;
private static final int DIDFT_AXIS = 0x00000003;
private static final int DIDFT_PSHBUTTON = 0x00000004;
private static final int DIDFT_TGLBUTTON = 0x00000008;
private static final int DIDFT_BUTTON = 0x0000000C;
private static final int DIDFT_POV = 0x00000010;
private static final int DIDFT_COLLECTION = 0x00000040;
private static final int DIDFT_NODATA = 0x00000080;
private static final int DIDFT_ANYINSTANCE = 0x00FFFF00;
private static final int DIDFT_INSTANCEMASK = DIDFT_ANYINSTANCE;
private static final int DIDFT_FFACTUATOR = 0x01000000;
private static final int DIDFT_FFEFFECTTRIGGER = 0x02000000;
private static final int DIDFT_OUTPUT = 0x10000000;
private static final int DIDFT_NOCOLLECTION = 0x00FFFF00;
private static int DIDFT_MAKEINSTANCE(int n) {
return ((n&0xffff) << 8);
}
private static int DIDFT_GETTYPE(int n) {
return (n&0xFF);
}
private static int DIDFT_GETINSTANCE(int n) {
return ((n >> 8)&0xffff);
}
private static int DIDFT_ENUMCOLLECTION(int n) {
return ((n&0xFFFF) << 8);
}
private DirectInputDevice device;
/**
* DIJOYSTATE structure defined in dinput.h:
*
* <pre>
* typedef struct DIJOYSTATE {
* LONG lX;
* LONG lY;
* LONG lZ;
* LONG lRx;
* LONG lRy;
* LONG lRz;
* LONG rglSlider[2];
* DWORD rgdwPOV[4];
* BYTE rgbButtons[32];
* } DIJOYSTATE, *LPDIJOYSTATE;
*
* 80 bytes total
* </pre>
*/
private int offset;
private int type;
private int instance;
private int bitmask = 0xffffffff;
private int bitshift = 0;
private DirectInputAxis(DirectInputDevice device, Axis.Identifier id,
int didft, String name) {
super(name, id);
this.device = device;
this.type = DIDFT_GETTYPE(didft);
this.instance = DIDFT_GETINSTANCE(didft);
if (id == Axis.Identifier.X) {
offset = 0;
} else if (id == Axis.Identifier.Y) {
offset = 1;
} else if (id == Axis.Identifier.Z) {
offset = 2;
} else if (id == Axis.Identifier.RX) {
offset = 3;
} else if (id == Axis.Identifier.RY) {
offset = 4;
} else if (id == Axis.Identifier.RZ) {
offset = 5;
} else if (id == Axis.Identifier.SLIDER) {
//System.out.println("Slider on "+name+" instance = "+instance);
offset = 6 + (instance>>2);
} else if (id == Axis.Identifier.POV) {
//System.out.println("POV on "+name+" instance = "+instance);
offset = 8 + instance;
} else if (id == Axis.Identifier.BUTTON) {
//System.out.println("Button on "+name+" instance = "+instance);
offset = 12 + (instance/4);
bitshift = (instance%4)*8;
bitmask=0xff;
}
}
/** Returns the data from the last time the control has been polled.
* If this axis is a button, the value returned will be either 0.0f or 1.0f.
* If this axis is normalized, the value returned will be between -1.0f and
* 1.0f.
* @return A float between -1.0 and 1.0
*/
public float getPollData() {
int data = ((device.data[offset] >> bitshift)&bitmask);
if ((type&DIDFT_BUTTON) != 0 ) {
return (float)((data&0x80)>>7);
} else if ((type&DIDFT_AXIS)!=0){ // all axes are set for -32768 to 32738
return ((float)data)/32768;
} else if ((type&DIDFT_POV)!=0) {
if (data == -1) {
return Axis.POV.OFF;
} else if (data == 0.0) {
return Axis.POV.UP;
} else if (data == 9000) {
return Axis.POV.RIGHT;
} else if (data == 18000) {
return Axis.POV.DOWN;
} else if (data == 27000) {
return Axis.POV.LEFT;
} else {
System.err.print("Unexpected value for DX8 HAT: "+data);
return Axis.POV.OFF;
}
} else { // return raw value
return (float)data;
}
}
/** Returns <code>true</code> if data returned from <code>poll</code>
* is relative to the last call, or <code>false</code> if data
* is absolute.
* @return true if data has chnaged since last poll, else false
*/
public boolean isRelative() {
return (type & DIDFT_RELAXIS) != 0;
}
/** Returns whether or not the axis is analog, or false if it is digital.
* @return true if analog, false if digital
*/
public boolean isAnalog() {
return (type & DIDFT_AXIS) != 0;
}
/** Returns whether or not data polled from this axis is normalized
* between the values of -1.0f and 1.0f.
* @return true if data is normalized, false if not.
*/
public boolean isNormalized() {
return (type & (DIDFT_BUTTON|DIDFT_AXIS|DIDFT_POV)) != 0;
}
/** Creates a new DirectInputAxis (factory method).
* This is a function used internally during set up
* @return The new DirectInputAxis object.
* @param device The device to attach this axis to.
*
* @param didft The identifier for the axis as provided by DX8.
* @param name A name to give the new axis.
* @param id The identifier for the device
*/
public static DirectInputAxis createAxis(DirectInputDevice device,
Axis.Identifier id, int didft, String name) {
return new DirectInputAxis(device, id, didft, name);
}
}

View file

@ -1,207 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import net.java.games.input.AbstractController;
import net.java.games.input.Axis;
import net.java.games.input.Controller;
import java.util.ArrayList;
import java.util.Iterator;
/**
*
* @author martak
* @version
*/
class DirectInputDevice extends AbstractController {
/**
* DIDEVTYPE_ constants from dinput.h header file
** JPK NOTE: This changed in DI8. In general this
* is fragile anda way shoudl be found to tie these mroe directly
* to the header files.
*/
/* Mike's <=DX7 types
private static final int DIDEVTYPEJOYSTICK_UNKNOWN = 1;
private static final int DIDEVTYPEJOYSTICK_TRADITIONAL = 2;
private static final int DIDEVTYPEJOYSTICK_FLIGHTSTICK = 3;
private static final int DIDEVTYPEJOYSTICK_GAMEPAD = 4;
private static final int DIDEVTYPEJOYSTICK_RUDDER = 5;
private static final int DIDEVTYPEJOYSTICK_WHEEL = 6;
private static final int DIDEVTYPEJOYSTICK_HEADTRACKER = 7;
*/
/**
* Pointer to the IDirectInputDevice for this device
*/
private long lpDevice;
/**
* Type of device
*/
private Type type;
/**
* Do we need to poll data?
*/
private boolean polled = true;
/**
* Data when polling, as per the DIJOYSTATE structure in dinput.h;
* @see DirectInputAxis for a breakdown of this structure
*/
int[] data = new int[32];
/**
* Private constructor
* @param lpDevice A pointer to the IDirectInputDevice for the device.
* @param subtype The subtype of device, as defined in the DIDEVTYPE
* constants above
* @param productName The product name for the device
* @param instanceName The name of the device
*/
private DirectInputDevice(long lpDevice, int subtype, String productName,
String instanceName,boolean polled) {
super(productName + " " + instanceName);
this.lpDevice = lpDevice;
this.polled = polled;
System.out.println("Creating "+productName+" polling = "+polled);
switch(subtype) {
/*
case DIDEVTYPEJOYSTICK_GAMEPAD:
type = Type.GAMEPAD; break;
case DIDEVTYPEJOYSTICK_RUDDER:
type = Type.RUDDER; break;
case DIDEVTYPEJOYSTICK_WHEEL:
type = Type.WHEEL; break;
case DIDEVTYPEJOYSTICK_HEADTRACKER:
type = Type.HEADTRACKER; break;
case DIDEVTYPEJOYSTICK_TRADITIONAL: // fall through
case DIDEVTYPEJOYSTICK_FLIGHTSTICK: // fall through
*/
default:
type = Type.STICK; break;
}
axes = initDirectInputAxes();
}
/**
* Used instead of overriding initAxes because it needs the
* pointer to the IDirectInputDevice
*/
private Axis[] initDirectInputAxes() {
ArrayList list = new ArrayList();
enumObjects(lpDevice, list);
Axis[] ret = new Axis[list.size()];
Iterator it = list.iterator();
int i = 0;
while (it.hasNext()) {
ret[i] = (Axis)it.next();
i++;
}
return ret;
}
/**
* Callback called by enumObjects to add a new axis into the list
* @param list This in which to add the new axis
* @param id The identifier for the axis, based on GUID
* @param didft The combination of DIDFT_ flags that make up the type and
* instance number of the axis.
* @param name The name to call the axis.
*/
private void addAxis(ArrayList list, Axis.Identifier id, int didft,
String name) {
list.add(DirectInputAxis.createAxis(this, id, didft, name));
}
/** Polls axes for data. Returns false if the controller is no longer valid.
* Polling reflects the current state of the device when polled, and is
* unbuffered.
* @return False if the co troller is no longer valid, else true.
*/
public boolean poll() {
return pollNative(lpDevice, data, polled);
}
/** Returns the type of Controller.
* @return The type of the controller.
*/
public Type getType() {
return type;
}
/** Returns the zero-based port number for this Controller.
* @return The port number.
*/
public int getPortNumber() {
// REMIND : We may be able to parse this from the name string
return 0;
}
/**
* Polls the device; native method. The data from the poll is stored in
* the data array.
*/
private native boolean pollNative(long lpDevice, int[] data,
boolean polled);
/**
* Enumerates the axes on the device
*/
private native boolean enumObjects(long lpDevice, ArrayList list);
/** Creates a new DirectInputDevice (factory method)
* This is a function used internally during set up
* @param polled Whether this device's driver should actually be
* polled during a call to Poll or whether it is an
* interrupt driven device that should ignore poll
* requests.
* @param lpDevice A pointer to the IDirectInputDevice for the device.
* @param subtype The subtype of device, as defined in the DIDEVTYPE
* constants above
* @param productName The product name for the device
* @param instanceName The name of the device
* @return The new DirectInputDevice object
*/
public static DirectInputDevice createDevice(long lpDevice, int subtype,
String productName, String instanceName, boolean polled) {
return new DirectInputDevice(lpDevice, subtype, productName,
instanceName,polled);
}
} // class DirectInputDevice

View file

@ -1,183 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Iterator;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
//import sun.security.action.LoadLibraryAction;
import net.java.games.util.plugins.Plugin;
/** DirectInput implementation of controller environment
* @author martak
* @version 1.0
*/
public class DirectInputEnvironmentPlugin extends ControllerEnvironment
implements Plugin
{
static {
/** Mikes old code, causes it to be laoded by wrong loader
java.security.AccessController.doPrivileged(
new LoadLibraryAction("jinput"));
*/
System.loadLibrary("dxinput");
}
/**
* DIDEVTYPE_ constants from dinput.h header file
* JPK NOTE: changed in DX8 so had to be changed. This is
* fragile, we should find a way to set them from
* the C side sowe can stay up to date with header
*/
/** DX7 and earlier
private static final int DIDEVTYPE_DEVICE = 1;
private static final int DIDEVTYPE_MOUSE = 2;
private static final int DIDEVTYPE_KEYBOARD = 3;
private static final int DIDEVTYPE_JOYSTICK = 4;
private static final int DIDEVTYPE_HID = 0x00010000;
private static int GET_DIDEVICE_TYPE(int dwDevType) {
return (int)((byte)dwDevType);
}
private static int GET_DIDEVICE_SUBTYPE(int dwDevType) {
return (int)((byte)((((short)dwDevType) >> 8) & 0xFF));
}
**/
/* DX8 and 9 */
private static final int DI8DEVTYPE_DEVICE = 0x11;
private static final int DI8DEVTYPE_MOUSE = 0x12;
private static final int DI8DEVTYPE_KEYBOARD = 0x13;
private static final int DI8DEVTYPE_JOYSTICK = 0x14;
private static final int DI8DEVTYPE_GAMEPAD = 0x15;
private static final int DI8DEVTYPE_DRIVING = 0x16;
private static final int DI8DEVTYPE_FLIGHT = 0x17;
private static final int DI8DEVTYPE_1STPERSON = 0x18;
private static final int DI8DEVTYPE_DEVICECTRL = 0x19;
private static final int DI8DEVTYPE_SCREENPOINTER = 0x1A;
private static final int DI8DEVTYPE_REMOTE = 0x1B;
private static final int DI8DEVTYPE_SUPPLEMENTAL = 0x1C;
private static int GET_DIDEVICE_TYPE(int dwDevType) {
return (dwDevType&0xFF);
}
private static int GET_DIDEVICE_SUBTYPE(int dwDevType) {
return (int)((byte)((((short)dwDevType) >> 8) & 0xFF));
}
// Pointer to DirectInput instance
private long lpDirectInput;
// Permanent array of controllers
private Controller[] controllers;
/** Creates new DirectInputEnvironment */
public DirectInputEnvironmentPlugin() {
lpDirectInput = directInputCreate();
enumControllers();
}
/** Returns a list of all controllers available to this environment,
* or an empty array if there are no controllers in this environment.
* @return An array of controllers that may be empty.
*/
public Controller[] getControllers() {
return controllers;
}
private void enumControllers() {
// If direct input fails, create an empty array
if (lpDirectInput == 0) {
controllers = new Controller[] {};
return;
}
// Create temporary controller array
ArrayList tempDevices = new ArrayList();
// Eumerate devices
enumDevices(lpDirectInput, tempDevices);
// Set up permanent controller array
controllers = new Controller[tempDevices.size()];
Iterator it = tempDevices.iterator();
int i = 0;
while (it.hasNext()) {
controllers[i] = (Controller)it.next();
i++;
}
}
/**
* Creates a new device, adding it to the list supplied.
* @param lpDevice A pointer to the IDirectInputDevice for the device.
* @param type The type of device to create, as defined by the constants
* in dinput.h (see DI8DEVTYPE constants above).
* @param productName The product name for the device
* @param instanceName The name of the device
*/
private void addDevice(ArrayList list, long lpDevice,
int type, String productName, String instanceName, boolean polled) {
Controller c;
int category = GET_DIDEVICE_TYPE(type);
int subtype = GET_DIDEVICE_SUBTYPE(type);
//System.out.println("Category = "+category);
if (category == DI8DEVTYPE_MOUSE) {
c = DirectInputMouse.createMouse(lpDevice, subtype, productName,
instanceName);
} else if (category == DI8DEVTYPE_KEYBOARD) {
c = DirectInputKeyboard.createKeyboard(lpDevice, subtype,
productName, instanceName);
} else {
assert category == DI8DEVTYPE_JOYSTICK;
c = DirectInputDevice.createDevice(lpDevice, subtype, productName,
instanceName,polled);
}
if (c != null) {
list.add(c);
}
}
/**
* Returns the direct input instance, or 0 if failed to initialize
*/
private native long directInputCreate();
/**
* Enumerates all devices, calling createDevice for each one
*/
private native boolean enumDevices(long lpDirectInput, ArrayList list);
} // class DirectInputEnvironment

View file

@ -1,208 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import net.java.games.input.AbstractAxis;
import net.java.games.input.Axis;
import net.java.games.input.StandardKeyboard;
/**
* DirectInput keyboard implementation.
* @author martak
* @version
*/
class DirectInputKeyboard extends StandardKeyboard {
/**
* DIDEVTYPE_ constants from dinput.h header file
*/
private static final int DIDEVTYPEKEYBOARD_UNKNOWN = 0;
private static final int DIDEVTYPEKEYBOARD_PCXT = 1;
private static final int DIDEVTYPEKEYBOARD_OLIVETTI = 2;
private static final int DIDEVTYPEKEYBOARD_PCAT = 3;
private static final int DIDEVTYPEKEYBOARD_PCENH = 4;
private static final int DIDEVTYPEKEYBOARD_NOKIA1050 = 5;
private static final int DIDEVTYPEKEYBOARD_NOKIA9140 = 6;
private static final int DIDEVTYPEKEYBOARD_NEC98 = 7;
private static final int DIDEVTYPEKEYBOARD_NEC98LAPTOP = 8;
private static final int DIDEVTYPEKEYBOARD_NEC98106 = 9;
private static final int DIDEVTYPEKEYBOARD_JAPAN106 = 10;
private static final int DIDEVTYPEKEYBOARD_JAPANAX = 11;
private static final int DIDEVTYPEKEYBOARD_J3100 = 12;
/**
* Key index crosstable; maps indices into the data array to virtual keys
* in the key array in StandardKeyboard.
* For example, the key F11 is at index 84 in the array of keys in
* StandardKeyboard, yet it is data element 87 (0x57) in our data array.
* <p>
* To access the data element of a particular key (F11), we use the
* crosstable as follows:
* <p><code>
* KeyID f11 = StandardKey.KeyID.F11;
* int keyIndex = f11.getKeyIndex(); // returns 84
* int crossIndex = CROSSTABLE[keyIndex]; // returns 0x57 (87)
* </code>
* To find a key given the data element index (87), we do a simple search
* through the crosstable starting at that index (index 87/0x57 = 0x65) and
* looking backwards until we find our key itself, or a lower number
* (meaning the key was not found). We can only take advantage of this
* algorithm only because on Windows, our crosstable is in increasing order.
*/
private final static int[] CROSSTABLE = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, // _9
0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, // Y
0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, // D
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, // BACKSLASH
0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, // RSHIFT
0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, // F7
0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, // NUMPAD5
0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x57, 0x58, 0x64, 0x65, // F14
0x66, 0x70, 0x79, 0x7B, 0x7D, 0x8D, 0x90, 0x91, 0x92, 0x93, 0x94, // KANJI
0x95, 0x96, 0x97, 0x9C, 0x9D, 0xB3, 0xB5, 0xB7, 0xB8, 0xC5, 0xC7, // HOME
0xC8, 0xC9, 0xCB, 0xCD, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xDB, 0xDC, // RWIN
0xDD, 0xDE, 0xDF // SLEEP
};
/**
* Pointer to the IDirectInputDevice for this device
*/
private long lpDevice;
/**
* Subtype of keyboard, defined by DIDEVTYPE constants
*/
private int subtype;
/**
* Polling key data
*/
private byte[] keyData = new byte[256];
/**
* Private constructor
* @param lpDevice A pointer to the IDirectInputDevice for the device.
* @param subtype The subtype of keyboard, as defined in the DIDEVTYPE
* constants above
* @param productName The product name for the device
* @param instanceName The name of the device
*/
private DirectInputKeyboard(long lpDevice, int subtype, String productName,
String instanceName) {
super(productName + " (" + instanceName + ")");
this.lpDevice = lpDevice;
this.subtype = subtype;
}
/**
* Callback to rename a given key by index, name
* @param index the index in the data array
* @param name the name of the key
*/
private void renameKey(int index, String name) {
int keyIndex = index;
if (keyIndex > CROSSTABLE.length) {
keyIndex = CROSSTABLE.length - 1;
}
for (; CROSSTABLE[keyIndex] > index; keyIndex--)
;
if (CROSSTABLE[keyIndex] == index) {
Axis[] axes = getAxes();
AbstractAxis key = (AbstractAxis)axes[index];
if (name != null && name.length() > 0) {
//System.out.println("Renaming key " + key.getName() +
// " to " + name + " index=" +
// index + " keyIndex=" + keyIndex + " CROSSTAB=" +
// CROSSTABLE[keyIndex]);
key.setName(name);
}
} else {
//System.out.println("Key not found " + name + " index=" + index +
// " keyIndex=" + keyIndex + " CROSSTAB=" +
// CROSSTABLE[keyIndex]);
}
}
/** Polls axes for data. Returns false if the controller is no longer valid.
* Polling reflects the current state of the device when polled.
* @return False if the KB is no longer valid, true otherwise.
*/
public boolean poll() {
return pollNative(lpDevice, keyData);
}
/** Returns whether or not the given key has been pressed since the last
* call to poll.
* @param key The key whose state to check.
* @return true if this key has changed state since last read of its state, false otherwise.
*/
protected boolean isKeyPressed(Key key) {
KeyID id = (KeyID)key.getIdentifier();
int keyIndex = id.getKeyIndex();
int crossIndex = CROSSTABLE[keyIndex];
return ((keyData[crossIndex] & 0x80) != 0);
}
/**
* Polls the device; native method
*/
private native boolean pollNative(long lpDevice, byte[] keyData);
/**
* Renames the keys with the name provided by DirectInput
*/
private native boolean renameKeys(long lpDevice);
/** Creates a new DirectInputKeyboard (factory method)
* This is a function used internally during set up.
* @param lpDevice A pointer to the IDirectInputDevice for the device.
* @param subtype The subtype of keyboard, as defined in the DIDEVTYPE
* constants above
* @param productName The product name for the keyboard
* @param instanceName The name of the keyboard
* @return The new DirectInputKeyboard object.
*/
public static DirectInputKeyboard createKeyboard(long lpDevice,
int subtype, String productName, String instanceName) {
DirectInputKeyboard ret = new DirectInputKeyboard(lpDevice, subtype,
productName, instanceName);
ret.renameKeys(lpDevice);
return ret;
}
} // class DirectInputKeyboard

View file

@ -1,311 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import net.java.games.input.AbstractAxis;
import net.java.games.input.Axis;
import net.java.games.input.Mouse;
/**
* DirectInput mouse implementation.
* @author martak
* @version
*/
class DirectInputMouse extends Mouse {
/**
* DIDEVTYPE_ constants from dinput.h header file
*/
private static final int DIDEVTYPEMOUSE_UNKNOWN = 1;
private static final int DIDEVTYPEMOUSE_TRADITIONAL = 2;
private static final int DIDEVTYPEMOUSE_FINGERSTICK = 3;
private static final int DIDEVTYPEMOUSE_TOUCHPAD = 4;
private static final int DIDEVTYPEMOUSE_TRACKBALL = 5;
/**
* Pointer to the IDirectInputDevice for this device
*/
private long lpDevice;
/**
* Type of mouse
*/
private Type type;
/**
* Mouse data
*/
private byte[] mouseData = new byte[16];
/**
* Private constructor
* @param lpDevice A pointer to the IDirectInputDevice for the device.
* @param subtype The subtype of mouse, as defined in the DIDEVTYPE
* constants above
* @param productName The product name for the device
* @param instanceName The name of the device
*/
private DirectInputMouse(long lpDevice, int subtype, String productName,
String instanceName) {
super(productName + " " + instanceName);
buttons = new ButtonsImpl();
ball = new BallImpl();
this.lpDevice = lpDevice;
switch(subtype) {
case DIDEVTYPEMOUSE_FINGERSTICK:
type = Type.FINGERSTICK; break;
case DIDEVTYPEMOUSE_TOUCHPAD:
type = Type.TRACKPAD; break;
case DIDEVTYPEMOUSE_TRACKBALL:
type = Type.TRACKBALL; break;
case DIDEVTYPEMOUSE_TRADITIONAL: // fall through
case DIDEVTYPEMOUSE_UNKNOWN: // fall through
default:
type = Type.MOUSE; break;
}
renameAxes(lpDevice);
}
/**
* Callback to rename a given axis by type, name
*/
private void renameAxis(Axis.Identifier id, String name) {
AbstractAxis axis;
if (id instanceof ButtonID) {
axis = (AbstractAxis)getButtons().getAxis(id);
} else {
axis = (AbstractAxis)getBall().getAxis(id);
}
axis.setName(name);
//System.out.println("Renaming " + name);
}
/** Polls axes for data. Returns false if the controller is no longer valid.
* Polling reflects the current state of the device when polled.
* @return false if the mosue is no lonegr valid, true otherwise.
*/
public boolean poll() {
return pollNative(lpDevice, mouseData);
}
/** Returns the type of the Controller.
* @return The device type of the controller (logically this
* shoudl be some form of "mouse" .)
*/
public Type getType() {
return type;
}
/** Creates a new DirectInputMouse (factory method)
* This is a function used internally during set up.
* @param lpDevice A pointer to the IDirectInputDevice for the device.
* @param subtype The subtype of mouse, as defined in the DIDEVTYPE
* constants above
* @param productName The product name for the keyboard
* @param instanceName The name of the keyboard
* @return The new DirectInputMouse object.
*/
public static DirectInputMouse createMouse(long lpDevice, int subtype,
String productName, String instanceName) {
return new DirectInputMouse(lpDevice, subtype, productName,
instanceName);
}
/**
* Implementation class representing the mouse ball
*/
class BallImpl extends Ball {
/**
* Public constructor
*/
public BallImpl() {
super(DirectInputMouse.this.getName() + " ball");
x = new BallAxis(Axis.Identifier.X);
y = new BallAxis(Axis.Identifier.Y);
wheel = new BallAxis(Axis.Identifier.SLIDER);
}
} // class DirectInputMouse.BallImpl
/**
* Implementation class representing the mouse buttons
*/
class ButtonsImpl extends Buttons {
/**
* Public constructor
*/
public ButtonsImpl() {
super(DirectInputMouse.this.getName() + " buttons");
left = new ButtonImpl(ButtonID.LEFT);
right = new ButtonImpl(ButtonID.RIGHT);
middle = new ButtonImpl(ButtonID.MIDDLE);
}
} // class DirectInputMouse.ButtonsImpl
/**
* Polls the device; native method
*/
private native boolean pollNative(long lpDevice, byte[] mouseData);
/**
* Renames the axes with the name provided by DirectInput
*/
private native boolean renameAxes(long lpDevice);
/**
* Mouse button axis implementation
*/
class ButtonImpl extends Button {
/**
* Index into the mouseData array
*/
private final int index;
/** Public constructor
* @param id An ID of a button to create an obejct to represent.
*
*/
public ButtonImpl(ButtonID id) {
super(id.getName(), id);
if (id == ButtonID.LEFT) {
index = 12;
} else if (id == ButtonID.RIGHT) {
index = 13;
} else if (id == ButtonID.MIDDLE) {
index = 14;
} else {
throw new RuntimeException("Unknown button");
}
}
/** Returns the data from the last time the control has been polled.
* If this axis is a button, the value returned will be either 0.0f or 1.0f.
* If this axis is normalized, the value returned will be between -1.0f and
* 1.0f.
* @return state of controller. (Note: DX8 mice actually
* queue state so what is returned is the next state,
* not necessarily the most current one.)
*/
public float getPollData() {
// Mouse button
byte data = mouseData[index];
if ((data & 0x80) != 0) {
return 1.0f;
} else {
return 0.0f;
}
}
/** Returns <code>true</code> if data returned from <code>poll</code>
* is relative to the last call, or <code>false</code> if data
* is absolute.
* @return true if data is relative, otherwise false.
*/
public boolean isRelative() {
return false;
}
} // class DirectInputMouse.ButtonImpl
/**
* Mouse ball axis implementation
*/
class BallAxis extends AbstractAxis {
/**
* Starting index into the mouseData array
*/
private final int index;
/** Public constructor
* @param id An ID for a mouse axis to create an object to represent.
*/
public BallAxis(Identifier id) {
super(id.getName(), id);
if (id == Identifier.X) {
index = 0;
} else if (id == Identifier.Y) {
index = 4;
} else if (id == Identifier.SLIDER) {
index = 8;
} else {
throw new RuntimeException("Unknown mouse axis");
}
}
/** Returns the data from the last time the control has been polled.
* If this axis is a button, the value returned will be either 0.0f or 1.0f.
* If this axis is normalized, the value returned will be between -1.0f and
* 1.0f.
* @return data. (Note that mice queue state in DX8 so what
* is returned is the next stae in the queue, not
* necessarily the most current one.)
*/
public float getPollData() {
int data = ((int)mouseData[index] << 12) |
((int)mouseData[index + 1] << 8) |
((int)mouseData[index + 2] << 4) |
((int)mouseData[index + 3]);
if (data == -1) {
return -1.0f;
} else if (data >= 1) {
return 1.0f;
} else {
return 0.0f;
}
}
/** Returns <code>true</code> if data returned from <code>poll</code>
* is relative to the last call, or <code>false</code> if data
* is absolute.
* @return true if relative, otherwise false.
*/
public boolean isRelative() {
return true;
}
/** Returns whether or not the axis is analog, or false if it is digital.
* @return true if analog, false if digital
*/
public boolean isAnalog() {
return true;
}
} // class DirectInputMouse.MouseBallAxis
} // class DirectInputMouse

View file

@ -1,888 +0,0 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
#ifndef WIN32
#error This is a Windows-only file
#endif
// hard define as DX7
//#define DIRECTINPUT_VERSION 0x0800
#include <windows.h>
#include <jni.h>
#include <dinput.h>
/*
******************************************************************************
* Global variables
******************************************************************************
*/
jclass CLASS_AxisIdentifier = NULL;
jclass CLASS_ButtonIdentifier = NULL;
jclass CLASS_DirectInputEnvironmentPlugin = NULL;
jclass CLASS_DirectInputDevice = NULL;
jclass CLASS_DirectInputKeyboard = NULL;
jclass CLASS_DirectInputMouse = NULL;
jmethodID MID_AddDevice = NULL;
jmethodID MID_AddAxis = NULL;
jmethodID MID_RenameKey = NULL;
jmethodID MID_RenameAxis = NULL;
jfieldID FID_X = NULL;
jfieldID FID_Y = NULL;
jfieldID FID_Z = NULL;
jfieldID FID_RX = NULL;
jfieldID FID_RY = NULL;
jfieldID FID_RZ = NULL;
jfieldID FID_Slider = NULL;
jfieldID FID_Button = NULL;
jfieldID FID_POV = NULL;
jfieldID FID_Left = NULL;
jfieldID FID_Right = NULL;
jfieldID FID_Middle = NULL;
const char* FD_AxisIdentifier = "Lnet/java/games/input/Axis$Identifier;";
const char* FD_ButtonIdentifier = "Lnet/java/games/input/Mouse$ButtonID;";
// Dummy input window. This is needed because DirectX evidently needs a window
// to do anything, such as setting the cooperative level for a device.
const TCHAR* DUMMY_WINDOW_NAME = "InputControllerWindow";
HWND hwndDummy = NULL;
// Buffer size
const DWORD BUFFER_SIZE = 16;
// Class for handing device data to the callback for EnumDevices
class DeviceParamData {
public:
DeviceParamData(LPDIRECTINPUT8 lpdi, JNIEnv* e, jobject o, jobject l) :
lpDirectInput(lpdi), env(e), obj(o), list(l)
{
}
LPDIRECTINPUT8 lpDirectInput;
JNIEnv* env;
jobject obj;
jobject list;
};
// Class for handing device data to the callback for EnumObjects
class ObjectParamData {
public:
ObjectParamData(LPDIRECTINPUTDEVICE8 lpDev, JNIEnv* e, jobject o,
jobject l) :
lpDevice(lpDev), env(e), obj(o), list(l)
{
}
LPDIRECTINPUTDEVICE8 lpDevice;
JNIEnv* env;
jobject obj;
jobject list;
};
void PrintOutput(TCHAR* tszMessage) {
printf("%s\n", tszMessage);
}
void PrintDIError(TCHAR* tszOutput, HRESULT res) {
TCHAR tszMessage[256];
#define CHECK_RESULT(r) case r: \
sprintf(tszMessage, "%s : %s", tszOutput, #r); \
break;
switch (res) {
CHECK_RESULT(DI_OK)
CHECK_RESULT(DI_NOTATTACHED)
CHECK_RESULT(DI_POLLEDDEVICE)
CHECK_RESULT(DI_DOWNLOADSKIPPED)
CHECK_RESULT(DI_EFFECTRESTARTED)
CHECK_RESULT(DI_TRUNCATED)
CHECK_RESULT(DI_TRUNCATEDANDRESTARTED)
CHECK_RESULT(DIERR_OLDDIRECTINPUTVERSION)
CHECK_RESULT(DIERR_BETADIRECTINPUTVERSION)
CHECK_RESULT(DIERR_BADDRIVERVER)
CHECK_RESULT(DIERR_DEVICENOTREG)
CHECK_RESULT(DIERR_NOTFOUND)
//CHECK_RESULT(DIERR_OBJECTNOTFOUND)
CHECK_RESULT(DIERR_INVALIDPARAM)
CHECK_RESULT(DIERR_NOINTERFACE)
CHECK_RESULT(DIERR_GENERIC)
CHECK_RESULT(DIERR_OUTOFMEMORY)
CHECK_RESULT(DIERR_UNSUPPORTED)
CHECK_RESULT(DIERR_NOTINITIALIZED)
CHECK_RESULT(DIERR_ALREADYINITIALIZED)
CHECK_RESULT(DIERR_NOAGGREGATION)
CHECK_RESULT(DIERR_OTHERAPPHASPRIO)
CHECK_RESULT(DIERR_INPUTLOST)
CHECK_RESULT(DIERR_ACQUIRED)
CHECK_RESULT(DIERR_NOTACQUIRED)
//CHECK_RESULT(DIERR_READONLY)
//CHECK_RESULT(DIERR_HANDLEEXISTS)
CHECK_RESULT(DIERR_INSUFFICIENTPRIVS)
CHECK_RESULT(DIERR_DEVICEFULL)
CHECK_RESULT(DIERR_MOREDATA)
CHECK_RESULT(DIERR_NOTDOWNLOADED)
CHECK_RESULT(DIERR_HASEFFECTS)
CHECK_RESULT(DIERR_NOTEXCLUSIVEACQUIRED)
CHECK_RESULT(DIERR_INCOMPLETEEFFECT)
CHECK_RESULT(DIERR_NOTBUFFERED)
CHECK_RESULT(DIERR_EFFECTPLAYING)
CHECK_RESULT(DIERR_UNPLUGGED)
CHECK_RESULT(DIERR_REPORTFULL)
default: sprintf(tszMessage, "Unknown"); break;
}
PrintOutput(tszMessage);
}
/*
******************************************************************************
* DirectInputEnvironmentPlugin
******************************************************************************
*/
/*
* Initialize all class, method, and field IDs
*/
BOOL InitIDs(JNIEnv* env) {
CLASS_AxisIdentifier =
env->FindClass("net/java/games/input/Axis$Identifier");
if (CLASS_AxisIdentifier == NULL) {
return FALSE;
}
FID_X = env->GetStaticFieldID(CLASS_AxisIdentifier, "X",
FD_AxisIdentifier);
if (FID_X == NULL) {
return FALSE;
}
FID_Y = env->GetStaticFieldID(CLASS_AxisIdentifier, "Y",
FD_AxisIdentifier);
if (FID_Y == NULL) {
return FALSE;
}
FID_Z = env->GetStaticFieldID(CLASS_AxisIdentifier, "Z",
FD_AxisIdentifier);
if (FID_Z == NULL) {
return FALSE;
}
FID_RX = env->GetStaticFieldID(CLASS_AxisIdentifier, "RX",
FD_AxisIdentifier);
if (FID_RX == NULL) {
return FALSE;
}
FID_RY = env->GetStaticFieldID(CLASS_AxisIdentifier, "RY",
FD_AxisIdentifier);
if (FID_RY == NULL) {
return FALSE;
}
FID_RZ = env->GetStaticFieldID(CLASS_AxisIdentifier, "RZ",
FD_AxisIdentifier);
if (FID_RZ == NULL) {
return FALSE;
}
FID_Slider = env->GetStaticFieldID(CLASS_AxisIdentifier, "SLIDER",
FD_AxisIdentifier);
if (FID_Slider == NULL) {
return FALSE;
}
FID_Button = env->GetStaticFieldID(CLASS_AxisIdentifier, "BUTTON",
FD_AxisIdentifier);
if (FID_Button == NULL) {
return FALSE;
}
FID_POV = env->GetStaticFieldID(CLASS_AxisIdentifier, "POV",
FD_AxisIdentifier);
if (FID_POV == NULL) {
return FALSE;
}
CLASS_ButtonIdentifier =
env->FindClass("net/java/games/input/Mouse$ButtonID");
if (CLASS_ButtonIdentifier == NULL) {
return FALSE;
}
FID_Left = env->GetStaticFieldID(CLASS_ButtonIdentifier, "LEFT",
FD_ButtonIdentifier);
if (FID_Left == NULL) {
return FALSE;
}
FID_Right = env->GetStaticFieldID(CLASS_ButtonIdentifier, "RIGHT",
FD_ButtonIdentifier);
if (FID_Right == NULL) {
return FALSE;
}
FID_Middle = env->GetStaticFieldID(CLASS_ButtonIdentifier, "MIDDLE",
FD_ButtonIdentifier);
if (FID_Middle == NULL) {
return FALSE;
}
CLASS_DirectInputEnvironmentPlugin =
env->FindClass("net/java/games/input/DirectInputEnvironmentPlugin");
if (CLASS_DirectInputEnvironmentPlugin == NULL) {
return FALSE;
}
MID_AddDevice = env->GetMethodID(CLASS_DirectInputEnvironmentPlugin, "addDevice",
"(Ljava/util/ArrayList;JILjava/lang/String;Ljava/lang/String;Z)V");
if (MID_AddDevice == NULL) {
return FALSE;
}
CLASS_DirectInputDevice =
env->FindClass("net/java/games/input/DirectInputDevice");
if (CLASS_DirectInputDevice == NULL) {
return FALSE;
}
MID_AddAxis = env->GetMethodID(CLASS_DirectInputDevice, "addAxis",
"(Ljava/util/ArrayList;Lnet/java/games/input/Axis$Identifier;ILjava/lang/String;)V");
if (MID_AddAxis == NULL) {
return FALSE;
}
CLASS_DirectInputKeyboard =
env->FindClass("net/java/games/input/DirectInputKeyboard");
if (CLASS_DirectInputKeyboard == NULL) {
return FALSE;
}
MID_RenameKey = env->GetMethodID(CLASS_DirectInputKeyboard, "renameKey",
"(ILjava/lang/String;)V");
if (MID_RenameKey == NULL) {
return FALSE;
}
CLASS_DirectInputMouse =
env->FindClass("net/java/games/input/DirectInputMouse");
if (CLASS_DirectInputMouse == NULL) {
return FALSE;
}
MID_RenameAxis = env->GetMethodID(CLASS_DirectInputMouse, "renameAxis",
"(Lnet/java/games/input/Axis$Identifier;Ljava/lang/String;)V");
if (MID_RenameAxis == NULL) {
return FALSE;
}
return TRUE;
}
/*
* WndProc for our dummy input window
*/
LRESULT CALLBACK DummyWndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hWnd, message, wParam, lParam);
}
/*
* Register the dummy input window class
*/
BOOL RegisterDummyWindow(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)DummyWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = NULL;
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = (LPCSTR)NULL;
wcex.lpszClassName = DUMMY_WINDOW_NAME;
wcex.hIconSm = NULL;
return RegisterClassEx(&wcex);
}
/*
* Class: org_java_games_input_DirectInputEnvironmentPlugin
* Method: directInputCreate
* Signature: ()J
*/
extern "C" JNIEXPORT jlong JNICALL
Java_net_java_games_input_DirectInputEnvironmentPlugin_directInputCreate
(JNIEnv* env, jobject obj)
{
// Get our module handle
HINSTANCE hInst = GetModuleHandle(NULL);
// Register the dummy input window
if (!RegisterDummyWindow(hInst)) {
return (jlong)0;
}
// Create the dummy input window
hwndDummy = CreateWindow(DUMMY_WINDOW_NAME, NULL,
WS_POPUP | WS_ICONIC,
0, 0, 0, 0, NULL, NULL, hInst, NULL);
if (hwndDummy == NULL)
{
return (jlong)0;
}
// Create the IDirectInput object
DWORD dwVersion = DIRECTINPUT_VERSION;
LPDIRECTINPUT8 lpDirectInput = NULL;
HRESULT res;
if (FAILED(res = DirectInput8Create(hInst, DIRECTINPUT_VERSION,
IID_IDirectInput8,(VOID **)&lpDirectInput, NULL))){
PrintDIError("DirectInputCreate", res);
return (jlong)0;
}
// Initialize method, class, and field IDs
if (!InitIDs(env)) {
lpDirectInput->Release();
return (jlong)0;
}
return (jlong)(long)lpDirectInput;
}
/*
* Enumeration callback for devices
*
* returns DIENUM_CONTINUE or DIENUM_STOP
*/
/** mikes old enum callback
BOOL CALLBACK EnumDeviceCallback(LPCDIDEVICEINSTANCE lpddi, LPVOID pvRef)
{
DeviceParamData* pData = (DeviceParamData*)pvRef;
LPDIRECTINPUT8 lpDirectInput = pData->lpDirectInput;
JNIEnv* env = pData->env;
jobject obj = pData->obj;
jobject list = pData->list;
LPDIRECTINPUTDEVICE8 lpDevice = NULL;
LPUNKNOWN pUnknown = NULL;
// Create the device object
HRESULT res = lpDirectInput->CreateDevice(lpddi->guidInstance, &lpDevice,
pUnknown);
if (res != DI_OK) {
PrintDIError("CreateDevice", res);
return DIENUM_STOP;
}
LPDIRECTINPUTDEVICE8 lpDevice2 = NULL;
// Get the IDirectDrawDevice8 interface from the object
res = lpDevice->QueryInterface(IID_IDirectInputDevice8,
(void**)&lpDevice2);
if (res != DI_OK) {
PrintDIError("QueryInterface DID2", res);
lpDevice->Release();
return DIENUM_STOP;
}
// Set the data format
DWORD category = GET_DIDEVICE_TYPE(lpddi->dwDevType);
LPCDIDATAFORMAT lpDataFormat = &c_dfDIJoystick;
if (category == DI8DEVTYPE_MOUSE) {
lpDataFormat = &c_dfDIMouse;
} else if (category == DI8DEVTYPE_KEYBOARD) {
lpDataFormat = &c_dfDIKeyboard;
}
res = lpDevice2->SetDataFormat(lpDataFormat);
if (res != DI_OK) {
PrintDIError("SetDataFormat", res);
lpDevice2->Release();
lpDevice->Release();
return DIENUM_STOP;
}
// If we are the mouse, we have to buffer the data
if (category == DI8DEVTYPE_MOUSE) {
DIPROPDWORD dipropdw;
dipropdw.diph.dwSize = sizeof(DIPROPDWORD);
dipropdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipropdw.diph.dwObj = 0;
dipropdw.diph.dwHow = DIPH_DEVICE;
dipropdw.dwData = BUFFER_SIZE;
res = lpDevice2->SetProperty(DIPROP_BUFFERSIZE, &dipropdw.diph);
if (res != DI_OK) {
PrintDIError("SetProperty", res);
lpDevice2->Release();
lpDevice->Release();
return DIENUM_STOP;
}
}
// Set the cooperative level
res = lpDevice2->SetCooperativeLevel(hwndDummy,
DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
if (res != DI_OK) {
PrintDIError("SetCooperativeLevel", res);
lpDevice2->Release();
lpDevice->Release();
return DIENUM_STOP;
}
// Acquire the device
res = lpDevice2->Acquire();
if (res != DI_OK && res != S_FALSE) {
PrintDIError("Acquire", res);
lpDevice2->Release();
lpDevice->Release();
return DIENUM_STOP;
}
// Set the variables for the Java callback
jint type = (jint)lpddi->dwDevType;
jstring productName = env->NewStringUTF(lpddi->tszProductName);
if (productName == NULL) {
lpDevice2->Release();
lpDevice->Release();
return DIENUM_STOP;
}
jstring instanceName = env->NewStringUTF(lpddi->tszInstanceName);
if (instanceName == NULL) {
lpDevice2->Release();
lpDevice->Release();
return DIENUM_STOP;
}
// Add the device into the list
env->CallVoidMethod(obj, MID_AddDevice, list, (jlong)(long)lpDevice2, type,
productName, instanceName);
return DIENUM_CONTINUE;
}
*/
/** jeff's new enum callback */
BOOL CALLBACK EnumDeviceCallback(LPCDIDEVICEINSTANCE lpddi, LPVOID pvRef)
{
DeviceParamData* pData = (DeviceParamData*)pvRef;
LPDIRECTINPUT8 lpDirectInput = pData->lpDirectInput;
JNIEnv* env = pData->env;
jobject obj = pData->obj;
jobject list = pData->list;
LPDIRECTINPUTDEVICE8 lpDevice = NULL;
LPUNKNOWN pUnknown = NULL;
HRESULT res;
// Create the device object
if (FAILED(res = lpDirectInput->CreateDevice(lpddi->guidInstance, &lpDevice,
pUnknown))){
PrintDIError("CreateDevice", res);
return DIENUM_STOP;
}
/*
LPDIRECTINPUTDEVICE8 lpDevice2 = NULL;
// Get the IDirectDrawDevice8 interface from the object
res = lpDevice->QueryInterface(IID_IDirectInputDevice8,
(void**)&lpDevice2);
if (res != DI_OK) {
PrintDIError("QueryInterface DID2", res);
lpDevice->Release();
return DIENUM_STOP;
}
*/
// Set the data format
LPCDIDATAFORMAT lpDataFormat;
DWORD category = GET_DIDEVICE_TYPE(lpddi->dwDevType)&0xFF;
switch (category){
case DI8DEVTYPE_KEYBOARD:
//printf("found Keyboard\n");
lpDataFormat = &c_dfDIKeyboard;
break;
case DI8DEVTYPE_MOUSE:
//printf("found mouse\n");
lpDataFormat = &c_dfDIMouse;
// set up buffering
DIPROPDWORD dipropdw;
dipropdw.diph.dwSize = sizeof(DIPROPDWORD);
dipropdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipropdw.diph.dwObj = 0;
dipropdw.diph.dwHow = DIPH_DEVICE;
dipropdw.dwData = BUFFER_SIZE;
if (FAILED(
res = lpDevice->SetProperty(DIPROP_BUFFERSIZE,
&dipropdw.diph))) {
PrintDIError("SetProperty", res);
lpDevice->Release();
return DIENUM_STOP;
}
break;
case DI8DEVTYPE_JOYSTICK:
default:
//printf("found stick\n");
lpDataFormat = &c_dfDIJoystick;
break;
}
if (FAILED(res = lpDevice->SetDataFormat(lpDataFormat))){
PrintDIError("SetDataFormat", res);
lpDevice->Release();
return DIENUM_STOP;
}
// Set the cooperative level
if(FAILED(res = lpDevice->SetCooperativeLevel(hwndDummy,
DISCL_NONEXCLUSIVE | DISCL_BACKGROUND))){
PrintDIError("SetCooperativeLevel", res);
lpDevice->Release();
return DIENUM_STOP;
}
// get polling
DIDEVCAPS didc;
// Allocate space for all the device's objects (axes, buttons, POVS)
ZeroMemory( &didc, sizeof(DIDEVCAPS) );
didc.dwSize = sizeof(DIDEVCAPS);
if (FAILED(res=lpDevice->GetCapabilities(&didc))){
PrintDIError("Get Device Capabilities", res);
lpDevice->Release();
return DIENUM_STOP;
}
jboolean polled = JNI_FALSE;
if ((didc.dwFlags)&DIDC_POLLEDDATAFORMAT) {
polled = JNI_TRUE;
}
// Acquire the device
if(FAILED(res = lpDevice->Acquire())){
PrintDIError("Acquire", res);
lpDevice->Release();
return DIENUM_STOP;
}
// Set the variables for the Java callback
jint type = (jint)lpddi->dwDevType&0xffff;
//printf("type == %x\n",type);
jstring productName = env->NewStringUTF(lpddi->tszProductName);
if (productName == NULL) {
lpDevice->Release();
return DIENUM_STOP;
}
jstring instanceName = env->NewStringUTF(lpddi->tszInstanceName);
if (instanceName == NULL) {
lpDevice->Release();
return DIENUM_STOP;
}
// Add the device into the list
env->CallVoidMethod(obj, MID_AddDevice, list, (jlong)(long)lpDevice, type,
productName, instanceName,(jboolean)polled);
return DIENUM_CONTINUE;
}
/*
* Class: org_java_games_input_DirectInputEnvironmentPlugin
* Method: enumDevices
* Signature: (JLjava/util/ArrayList;)Z
*/
extern "C" JNIEXPORT jboolean JNICALL
Java_net_java_games_input_DirectInputEnvironmentPlugin_enumDevices
(JNIEnv* env, jobject obj, jlong lDirectInput, jobject list)
{
LPDIRECTINPUT8 lpDirectInput = (LPDIRECTINPUT8)(long)lDirectInput;
DWORD dwDevType = DI8DEVCLASS_ALL;
DeviceParamData data(lpDirectInput, env, obj, list);
LPVOID pvRef = (LPVOID)&data;
DWORD dwFlags = DIEDFL_ATTACHEDONLY;
HRESULT res;
if(FAILED(res=lpDirectInput->EnumDevices(dwDevType,
EnumDeviceCallback, pvRef, dwFlags))){
PrintDIError("EnumDevices", res);
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
******************************************************************************
* DirectInputDevice
******************************************************************************
*/
/*
* Class: org_java_games_input_DirectInputDevice
* Method: pollNative
* Signature: (J[B)Z
*/
extern "C" JNIEXPORT jboolean JNICALL
Java_net_java_games_input_DirectInputDevice_pollNative
(JNIEnv* env, jobject obj, jlong lDevice, jintArray baData,
jboolean pollme)
{
LPDIRECTINPUTDEVICE8 lpDevice = (LPDIRECTINPUTDEVICE8)(long)lDevice;
// Reacquire the device
HRESULT res = lpDevice->Acquire();
if (res != DI_OK && res != S_FALSE) {
PrintDIError("Acquire", res);
return JNI_FALSE;
}
// Poll the device
if (pollme == JNI_TRUE) {
res = lpDevice->Poll();
if (res != DI_OK) {
PrintDIError("Poll", res);
return JNI_FALSE;
}
}
// Get the device state (data)
DIJOYSTATE data;
res = lpDevice->GetDeviceState(sizeof(data), &data);
if (res != DI_OK) {
PrintDIError("GetDeviceState", res);
return JNI_FALSE;
}
// Copy the data into the byte array
env->SetIntArrayRegion(baData, 0, (jsize)(sizeof(data)/4), (jint*)&data);
return JNI_TRUE;
}
/*
* Enumeration callback for device objects
*
* returns DIENUM_CONTINUE or DIENUM_STOP
*/
BOOL CALLBACK EnumObjectsCallback(LPCDIDEVICEOBJECTINSTANCE lpddoi,
LPVOID pvRef)
{
ObjectParamData* pData = (ObjectParamData*)pvRef;
LPDIRECTINPUTDEVICE8 lpDevice = pData->lpDevice;
JNIEnv* env = pData->env;
jobject obj = pData->obj;
jobject list = pData->list;
jobject identifier = NULL;
HRESULT res;
if (lpddoi->guidType == GUID_XAxis) {
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier, FID_X);
} else if (lpddoi->guidType == GUID_YAxis) {
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier, FID_Y);
} else if (lpddoi->guidType == GUID_ZAxis) {
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier, FID_Z);
} else if (lpddoi->guidType == GUID_RxAxis) {
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier, FID_RX);
} else if (lpddoi->guidType == GUID_RyAxis) {
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier, FID_RY);
} else if (lpddoi->guidType == GUID_RzAxis) {
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier, FID_RZ);
} else if (lpddoi->guidType == GUID_Slider) {
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier, FID_Slider);
} else if (lpddoi->guidType == GUID_Button) {
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier, FID_Button);
} else if (lpddoi->guidType == GUID_POV) {
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier, FID_POV);
} else {
// Do not add this axis into the list, since we don't know what it is
return DIENUM_CONTINUE;
}
if (identifier == NULL) {
return DIENUM_STOP;
}
if (DIDFT_GETTYPE(lpddoi->dwType)&DIDFT_AXIS){
// set axis range
DIPROPRANGE joy_axis_range;
joy_axis_range.lMin = -32768;
joy_axis_range.lMax = 32768;
joy_axis_range.diph.dwSize=sizeof(DIPROPRANGE);
joy_axis_range.diph.dwHeaderSize=sizeof(DIPROPHEADER);
joy_axis_range.diph.dwHow = DIPH_BYID;
joy_axis_range.diph.dwObj=lpddoi->dwType;
if (FAILED(
res=lpDevice->SetProperty(DIPROP_RANGE,&joy_axis_range.diph))){
PrintDIError("SetProperty", res);
}
}
jint didft = (jint)lpddoi->dwType;
jstring name = env->NewStringUTF(lpddoi->tszName);
// Add the axis into our list
env->CallVoidMethod(obj, MID_AddAxis, list, identifier, didft,
name);
return DIENUM_CONTINUE;
}
/*
* Class: org_java_games_input_DirectInputDevice
* Method: enumObjects
* Signature: (JLjava/util/ArrayList;)Z
*/
extern "C" JNIEXPORT jboolean JNICALL
Java_net_java_games_input_DirectInputDevice_enumObjects
(JNIEnv* env, jobject obj, jlong lDevice, jobject list)
{
LPDIRECTINPUTDEVICE8 lpDevice = (LPDIRECTINPUTDEVICE8)(long)lDevice;
ObjectParamData data(lpDevice, env, obj, list);
LPVOID pvRef = (LPVOID)&data;
DWORD dwFlags = DIDFT_ALL;
// Enum objects
HRESULT res = lpDevice->EnumObjects(EnumObjectsCallback, pvRef, dwFlags);
if (res != DI_OK) {
PrintDIError("EnumObjects", res);
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
******************************************************************************
* DirectInputKeyboard
******************************************************************************
*/
/*
* Class: org_java_games_input_DirectInputKeyboard
* Method: pollNative
* Signature: (J[B)Z
*/
extern "C" JNIEXPORT jboolean JNICALL
Java_net_java_games_input_DirectInputKeyboard_pollNative
(JNIEnv* env, jobject obj, jlong lDevice, jbyteArray baData)
{
LPDIRECTINPUTDEVICE8 lpDevice = (LPDIRECTINPUTDEVICE8)(long)lDevice;
// Reacquire the device
HRESULT res = lpDevice->Acquire();
if (res != DI_OK && res != S_FALSE) {
PrintDIError("Acquire", res);
return JNI_FALSE;
}
// Get the device state (data)
char data[256];
res = lpDevice->GetDeviceState(sizeof(data), data);
if (res != DI_OK) {
PrintDIError("GetDeviceState", res);
return JNI_FALSE;
}
env->SetByteArrayRegion(baData, 0, (jsize)sizeof(data), (jbyte*)&data);
return JNI_TRUE;
}
/*
* Enumeration callback to rename keyboard keys
*
* returns DIENUM_CONTINUE or DIENUM_STOP
*/
BOOL CALLBACK RenameKeysCallback(LPCDIDEVICEOBJECTINSTANCE lpddoi,
LPVOID pvRef)
{
ObjectParamData* pData = (ObjectParamData*)pvRef;
//LPDIRECTINPUTDEVICE8 lpDevice = pData->lpDevice;
JNIEnv* env = pData->env;
jobject obj = pData->obj;
jint index = (jint)lpddoi->dwOfs;
jstring name = env->NewStringUTF(lpddoi->tszName);
env->CallVoidMethod(obj, MID_RenameKey, index, name);
return DIENUM_CONTINUE;
}
/*
* Class: org_java_games_input_DirectInputKeyboard
* Method: renameKeys
* Signature: (J)Z
*/
extern "C" JNIEXPORT jboolean JNICALL
Java_net_java_games_input_DirectInputKeyboard_renameKeys
(JNIEnv* env, jobject obj, jlong lDevice)
{
LPDIRECTINPUTDEVICE8 lpDevice = (LPDIRECTINPUTDEVICE8)(long)lDevice;
ObjectParamData data(lpDevice, env, obj, NULL);
LPVOID pvRef = (LPVOID)&data;
DWORD dwFlags = DIDFT_ALL;
// Enum objects
HRESULT res = lpDevice->EnumObjects(RenameKeysCallback, pvRef, dwFlags);
if (res != DI_OK) {
PrintDIError("EnumObjects", res);
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
******************************************************************************
* DirectInputMouse
******************************************************************************
*/
/*
* Class: org_java_games_input_DirectInputMouse
* Method: pollNative
* Signature: (J[B)Z
*/
extern "C" JNIEXPORT jboolean JNICALL
Java_net_java_games_input_DirectInputMouse_pollNative
(JNIEnv* env, jobject obj, jlong lDevice, jbyteArray baData)
{
LPDIRECTINPUTDEVICE8 lpDevice = (LPDIRECTINPUTDEVICE8)(long)lDevice;
// Reacquire the device
HRESULT res = lpDevice->Acquire();
if (res != DI_OK && res != S_FALSE) {
PrintDIError("Acquire", res);
return JNI_FALSE;
}
// Get the data
DIMOUSESTATE data;
res = lpDevice->GetDeviceState(sizeof(data), &data);
if (res != DI_OK) {
PrintDIError("GetDeviceState", res);
return JNI_FALSE;
}
// Set the data in our array
env->SetByteArrayRegion(baData, 0, (jsize)sizeof(data), (jbyte*)&data);
return JNI_TRUE;
}
/*
* Enumeration callback to rename mouse axes
*
* returns DIENUM_CONTINUE or DIENUM_STOP
*/
BOOL CALLBACK RenameAxesCallback(LPCDIDEVICEOBJECTINSTANCE lpddoi,
LPVOID pvRef)
{
ObjectParamData* pData = (ObjectParamData*)pvRef;
//LPDIRECTINPUTDEVICE8 lpDevice = pData->lpDevice;
JNIEnv* env = pData->env;
jobject obj = pData->obj;
jobject identifier;
switch (lpddoi->dwOfs) {
case DIMOFS_X:
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier,
FID_X);
break;
case DIMOFS_Y:
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier,
FID_Y);
break;
case DIMOFS_Z:
identifier = env->GetStaticObjectField(CLASS_AxisIdentifier,
FID_Slider);
break;
case DIMOFS_BUTTON0:
identifier = env->GetStaticObjectField(CLASS_ButtonIdentifier,
FID_Left);
break;
case DIMOFS_BUTTON1:
identifier = env->GetStaticObjectField(CLASS_ButtonIdentifier,
FID_Right);
break;
case DIMOFS_BUTTON2:
identifier = env->GetStaticObjectField(CLASS_ButtonIdentifier,
FID_Middle);
break;
case DIMOFS_BUTTON3:
default:
return DIENUM_CONTINUE; // Not an axis we know
}
jstring name = env->NewStringUTF(lpddoi->tszName);
env->CallVoidMethod(obj, MID_RenameAxis, identifier, name);
return DIENUM_CONTINUE;
}
/*
* Class: org_java_games_input_DirectInputMouse
* Method: renameAxes
* Signature: (J)Z
*/
extern "C" JNIEXPORT jboolean JNICALL
Java_net_java_games_input_DirectInputMouse_renameAxes
(JNIEnv* env, jobject obj, jlong lDevice)
{
LPDIRECTINPUTDEVICE8 lpDevice = (LPDIRECTINPUTDEVICE8)(long)lDevice;
ObjectParamData data(lpDevice, env, obj, NULL);
LPVOID pvRef = (LPVOID)&data;
DWORD dwFlags = DIDFT_ALL;
// Enum objects
HRESULT res = lpDevice->EnumObjects(RenameAxesCallback, pvRef, dwFlags);
if (res != DI_OK) {
PrintDIError("EnumObjects", res);
return JNI_FALSE;
}
return JNI_TRUE;
}

52
plugins/OSX/build.xml Normal file
View file

@ -0,0 +1,52 @@
<?xml version="1.0" ?>
<project name="OS X Plugin, Native code" basedir="." default="compileNativeJinputLib">
<description>OSX JInput Native Plugin</description>
<target name="init">
<mkdir dir="target/natives/arm64"/>
</target>
<target name="compile">
<apply dir="${dstdir}" executable="${compiler}" os="Mac OS X" skipemptyfilesets="true" failonerror="true" dest="${dstdir}">
<arg line="${cflags} -O2 -Wall -c -fPIC -I${sdkroot}/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers -I../../../../common/src/native -I../../generated-sources/natives/"/>
<mapper type="glob" from="*.c" to="*.o"/>
<fileset dir="src/main/native" includes="*.c"/>
<fileset dir="../common/src/native" includes="*.c"/>
</apply>
</target>
<target name="link">
<apply dir="${objdir}" parallel="true" executable="${linker}" os="Mac OS X" failonerror="true" skipemptyfilesets="true">
<arg line="${linkerflags} -dynamiclib -o ${libname} -framework CoreFoundation -framework IOKit -framework CoreServices -L/Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home/lib"/>
<fileset dir="${objdir}" includes="*.o"/>
</apply>
<apply dir="${objdir}" executable="strip" os="Mac OS X" failonerror="true">
<arg line="-S -X"/>
<fileset dir="." includes="${libname}"/>
</apply>
</target>
<target name="compileNativeJinputLib" depends="init">
<property name="arm64_sdkroot" location="/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk"/>
<property name="arm64_flags" value="-isysroot ${arm64_sdkroot} -arch arm64 -mmacosx-version-min=10.5 -I/Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home/include/ -I/Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home/include/darwin/"/>
<antcall target="compile">
<param name="dstdir" location="target/natives/arm64"/>
<param name="compiler" value="gcc"/>
<param name="sdkroot" location="${arm64_sdkroot}"/>
<param name="cflags" value="${arm64_flags}"/>
</antcall>
<antcall target="link">
<param name="objdir" location="target/natives/arm64"/>
<param name="libname" value="libjinput-osx-arm64.jnilib"/>
<param name="linker" value="gcc"/>
<param name="linkerflags" value="${arm64_flags}"/>
</antcall>
<apply dir="target/natives" parallel="true" executable="lipo" os="Mac OS X" failonerror="true" skipemptyfilesets="true" >
<arg value="-create"/>
<srcfile/>
<arg value="-output"/>
<arg path="target/natives/libjinput-osx.jnilib"/>
<fileset file="target/natives/arm64/libjinput-osx-arm64.jnilib"/>
</apply>
</target>
</project>

69
plugins/OSX/pom.xml Normal file
View file

@ -0,0 +1,69 @@
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>osx-plugin</artifactId>
<packaging>jar</packaging>
<name>JInput - OSX Plugin</name>
<parent>
<groupId>net.java.jinput</groupId>
<artifactId>plugins</artifactId>
<version>2.0.10-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>net.java.jinput</groupId>
<artifactId>coreapi</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<!-- <plugin> -->
<!-- <artifactId>maven-javadoc-plugin</artifactId> -->
<!-- </plugin> -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>compile</phase>
<configuration>
<target>
<ant dir="." target="compileNativeJinputLib"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classesDirectory>${project.build.directory}/natives</classesDirectory>
<classifier>natives-osx</classifier>
<includes>
<include>*.jnilib</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,135 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*/
package net.java.games.input;
import java.util.Map;
import java.util.HashMap;
/** Button Usages
* @author elias
* @version 1.0
*/
final class ButtonUsage implements Usage {
private final static Map<Integer, ButtonUsage> map = new HashMap<>();
private final int button_id;
public final static ButtonUsage map(int button_id) {
Integer button_id_obj = button_id;
ButtonUsage existing = map.get(button_id_obj);
if (existing != null)
return existing;
ButtonUsage new_button = new ButtonUsage(button_id);
map.put(button_id_obj, new_button);
return new_button;
}
private ButtonUsage(int button_id) {
this.button_id = button_id;
}
public final Component.Identifier.Button getIdentifier() {
switch (button_id) {
case 1:
return Component.Identifier.Button._0;
case 2:
return Component.Identifier.Button._1;
case 3:
return Component.Identifier.Button._2;
case 4:
return Component.Identifier.Button._3;
case 5:
return Component.Identifier.Button._4;
case 6:
return Component.Identifier.Button._5;
case 7:
return Component.Identifier.Button._6;
case 8:
return Component.Identifier.Button._7;
case 9:
return Component.Identifier.Button._8;
case 10:
return Component.Identifier.Button._9;
case 11:
return Component.Identifier.Button._10;
case 12:
return Component.Identifier.Button._11;
case 13:
return Component.Identifier.Button._12;
case 14:
return Component.Identifier.Button._13;
case 15:
return Component.Identifier.Button._14;
case 16:
return Component.Identifier.Button._15;
case 17:
return Component.Identifier.Button._16;
case 18:
return Component.Identifier.Button._17;
case 19:
return Component.Identifier.Button._18;
case 20:
return Component.Identifier.Button._19;
case 21:
return Component.Identifier.Button._20;
case 22:
return Component.Identifier.Button._21;
case 23:
return Component.Identifier.Button._22;
case 24:
return Component.Identifier.Button._23;
case 25:
return Component.Identifier.Button._24;
case 26:
return Component.Identifier.Button._25;
case 27:
return Component.Identifier.Button._26;
case 28:
return Component.Identifier.Button._27;
case 29:
return Component.Identifier.Button._28;
case 30:
return Component.Identifier.Button._29;
case 31:
return Component.Identifier.Button._30;
case 32:
return Component.Identifier.Button._31;
default:
return null;
}
}
public final String toString() {
return "ButtonUsage (" + button_id + ")";
}
}

View file

@ -0,0 +1,74 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.lang.reflect.Method;
/** HID Element types
* @author elias
* @version 1.0
*/
final class ElementType {
private final static ElementType[] map = new ElementType[514];
public final static ElementType INPUT_MISC = new ElementType(1);
public final static ElementType INPUT_BUTTON = new ElementType(2);
public final static ElementType INPUT_AXIS = new ElementType(3);
public final static ElementType INPUT_SCANCODES = new ElementType(4);
public final static ElementType OUTPUT = new ElementType(129);
public final static ElementType FEATURE = new ElementType(257);
public final static ElementType COLLECTION = new ElementType(513);
private final int type_id;
public final static ElementType map(int type_id) {
if (type_id < 0 || type_id >= map.length)
return null;
return map[type_id];
}
private ElementType(int type_id) {
map[type_id] = this;
this.type_id = type_id;
}
public final String toString() {
return "ElementType (0x" + Integer.toHexString(type_id) + ")";
}
}

View file

@ -0,0 +1,136 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*/
package net.java.games.input;
/** Generic Desktop Usages
* @author elias
* @version 1.0
*/
final class GenericDesktopUsage implements Usage {
private final static GenericDesktopUsage[] map = new GenericDesktopUsage[0xFF];
public final static GenericDesktopUsage POINTER = new GenericDesktopUsage(0x01); /* Physical Collection */
public final static GenericDesktopUsage MOUSE = new GenericDesktopUsage(0x02); /* Application Collection */
/* 0x03 Reserved */
public final static GenericDesktopUsage JOYSTICK = new GenericDesktopUsage(0x04); /* Application Collection */
public final static GenericDesktopUsage GAME_PAD = new GenericDesktopUsage(0x05); /* Application Collection */
public final static GenericDesktopUsage KEYBOARD = new GenericDesktopUsage(0x06); /* Application Collection */
public final static GenericDesktopUsage KEYPAD = new GenericDesktopUsage(0x07); /* Application Collection */
public final static GenericDesktopUsage MULTI_AXIS_CONTROLLER = new GenericDesktopUsage(0x08); /* Application Collection */
/* 0x09 - 0x2F Reserved */
public final static GenericDesktopUsage X = new GenericDesktopUsage(0x30); /* Dynamic Value */
public final static GenericDesktopUsage Y = new GenericDesktopUsage(0x31); /* Dynamic Value */
public final static GenericDesktopUsage Z = new GenericDesktopUsage(0x32); /* Dynamic Value */
public final static GenericDesktopUsage RX = new GenericDesktopUsage(0x33); /* Dynamic Value */
public final static GenericDesktopUsage RY = new GenericDesktopUsage(0x34); /* Dynamic Value */
public final static GenericDesktopUsage RZ = new GenericDesktopUsage(0x35); /* Dynamic Value */
public final static GenericDesktopUsage SLIDER = new GenericDesktopUsage(0x36); /* Dynamic Value */
public final static GenericDesktopUsage DIAL = new GenericDesktopUsage(0x37); /* Dynamic Value */
public final static GenericDesktopUsage WHEEL = new GenericDesktopUsage(0x38); /* Dynamic Value */
public final static GenericDesktopUsage HATSWITCH = new GenericDesktopUsage(0x39); /* Dynamic Value */
public final static GenericDesktopUsage COUNTED_BUFFER = new GenericDesktopUsage(0x3A); /* Logical Collection */
public final static GenericDesktopUsage BYTE_COUNT = new GenericDesktopUsage(0x3B); /* Dynamic Value */
public final static GenericDesktopUsage MOTION_WAKEUP = new GenericDesktopUsage(0x3C); /* One-Shot Control */
public final static GenericDesktopUsage START = new GenericDesktopUsage(0x3D); /* On/Off Control */
public final static GenericDesktopUsage SELECT = new GenericDesktopUsage(0x3E); /* On/Off Control */
/* 0x3F Reserved */
public final static GenericDesktopUsage VX = new GenericDesktopUsage(0x40); /* Dynamic Value */
public final static GenericDesktopUsage VY = new GenericDesktopUsage(0x41); /* Dynamic Value */
public final static GenericDesktopUsage VZ = new GenericDesktopUsage(0x42); /* Dynamic Value */
public final static GenericDesktopUsage VBRX = new GenericDesktopUsage(0x43); /* Dynamic Value */
public final static GenericDesktopUsage VBRY = new GenericDesktopUsage(0x44); /* Dynamic Value */
public final static GenericDesktopUsage VBRZ = new GenericDesktopUsage(0x45); /* Dynamic Value */
public final static GenericDesktopUsage VNO = new GenericDesktopUsage(0x46); /* Dynamic Value */
/* 0x47 - 0x7F Reserved */
public final static GenericDesktopUsage SYSTEM_CONTROL = new GenericDesktopUsage(0x80); /* Application Collection */
public final static GenericDesktopUsage SYSTEM_POWER_DOWN = new GenericDesktopUsage(0x81); /* One-Shot Control */
public final static GenericDesktopUsage SYSTEM_SLEEP = new GenericDesktopUsage(0x82); /* One-Shot Control */
public final static GenericDesktopUsage SYSTEM_WAKE_UP = new GenericDesktopUsage(0x83); /* One-Shot Control */
public final static GenericDesktopUsage SYSTEM_CONTEXT_MENU = new GenericDesktopUsage(0x84); /* One-Shot Control */
public final static GenericDesktopUsage SYSTEM_MAIN_MENU = new GenericDesktopUsage(0x85); /* One-Shot Control */
public final static GenericDesktopUsage SYSTEM_APP_MENU = new GenericDesktopUsage(0x86); /* One-Shot Control */
public final static GenericDesktopUsage SYSTEM_MENU_HELP = new GenericDesktopUsage(0x87); /* One-Shot Control */
public final static GenericDesktopUsage SYSTEM_MENU_EXIT = new GenericDesktopUsage(0x88); /* One-Shot Control */
public final static GenericDesktopUsage SYSTEM_MENU = new GenericDesktopUsage(0x89); /* Selector */
public final static GenericDesktopUsage SYSTEM_MENU_RIGHT = new GenericDesktopUsage(0x8A); /* Re-Trigger Control */
public final static GenericDesktopUsage SYSTEM_MENU_LEFT = new GenericDesktopUsage(0x8B); /* Re-Trigger Control */
public final static GenericDesktopUsage SYSTEM_MENU_UP = new GenericDesktopUsage(0x8C); /* Re-Trigger Control */
public final static GenericDesktopUsage SYSTEM_MENU_DOWN = new GenericDesktopUsage(0x8D); /* Re-Trigger Control */
/* 0x8E - 0x8F Reserved */
public final static GenericDesktopUsage DPAD_UP = new GenericDesktopUsage(0x90); /* On/Off Control */
public final static GenericDesktopUsage DPAD_DOWN = new GenericDesktopUsage(0x91); /* On/Off Control */
public final static GenericDesktopUsage DPAD_RIGHT = new GenericDesktopUsage(0x92); /* On/Off Control */
public final static GenericDesktopUsage DPAD_LEFT = new GenericDesktopUsage(0x93); /* On/Off Control */
/* 0x94 - 0xFFFF Reserved */
private final int usage_id;
public final static GenericDesktopUsage map(int usage_id) {
if (usage_id < 0 || usage_id >= map.length)
return null;
return map[usage_id];
}
private GenericDesktopUsage(int usage_id) {
map[usage_id] = this;
this.usage_id = usage_id;
}
public final String toString() {
return "GenericDesktopUsage (0x" + Integer.toHexString(usage_id) + ")";
}
public final Component.Identifier getIdentifier() {
if (this == GenericDesktopUsage.X) {
return Component.Identifier.Axis.X;
} else if (this == GenericDesktopUsage.Y) {
return Component.Identifier.Axis.Y;
} else if (this == GenericDesktopUsage.Z || this == GenericDesktopUsage.WHEEL) {
return Component.Identifier.Axis.Z;
} else if (this == GenericDesktopUsage.RX) {
return Component.Identifier.Axis.RX;
} else if (this == GenericDesktopUsage.RY) {
return Component.Identifier.Axis.RY;
} else if (this == GenericDesktopUsage.RZ) {
return Component.Identifier.Axis.RZ;
} else if (this == GenericDesktopUsage.SLIDER) {
return Component.Identifier.Axis.SLIDER;
} else if (this == GenericDesktopUsage.HATSWITCH) {
return Component.Identifier.Axis.POV;
} else if (this == GenericDesktopUsage.SELECT) {
return Component.Identifier.Button.SELECT;
} else
return null;
}
}

View file

@ -0,0 +1,242 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*/
package net.java.games.input;
/** Mapping from Keyboard HID usages to Component.Identifier.Key
* @author elias
* @version 1.0
*/
final class KeyboardUsage implements Usage {
private final static KeyboardUsage[] map = new KeyboardUsage[0xFF];
public static final KeyboardUsage ERRORROLLOVER = new KeyboardUsage(0x01); /* ErrorRollOver */
public static final KeyboardUsage POSTFAIL = new KeyboardUsage(0x02); /* POSTFail */
public static final KeyboardUsage ERRORUNDEFINED = new KeyboardUsage(0x03); /* ErrorUndefined */
public static final KeyboardUsage A = new KeyboardUsage(Component.Identifier.Key.A, 0x04); /* a or A */
public static final KeyboardUsage B = new KeyboardUsage(Component.Identifier.Key.B, 0x05); /* b or B */
public static final KeyboardUsage C = new KeyboardUsage(Component.Identifier.Key.C, 0x06); /* c or C */
public static final KeyboardUsage D = new KeyboardUsage(Component.Identifier.Key.D, 0x07); /* d or D */
public static final KeyboardUsage E = new KeyboardUsage(Component.Identifier.Key.E, 0x08); /* e or E */
public static final KeyboardUsage F = new KeyboardUsage(Component.Identifier.Key.F, 0x09); /* f or F */
public static final KeyboardUsage G = new KeyboardUsage(Component.Identifier.Key.G, 0x0A); /* g or G */
public static final KeyboardUsage H = new KeyboardUsage(Component.Identifier.Key.H, 0x0B); /* h or H */
public static final KeyboardUsage I = new KeyboardUsage(Component.Identifier.Key.I, 0x0C); /* i or I */
public static final KeyboardUsage J = new KeyboardUsage(Component.Identifier.Key.J, 0x0D); /* j or J */
public static final KeyboardUsage K = new KeyboardUsage(Component.Identifier.Key.K, 0x0E); /* k or K */
public static final KeyboardUsage L = new KeyboardUsage(Component.Identifier.Key.L, 0x0F); /* l or L */
public static final KeyboardUsage M = new KeyboardUsage(Component.Identifier.Key.M, 0x10); /* m or M */
public static final KeyboardUsage N = new KeyboardUsage(Component.Identifier.Key.N, 0x11); /* n or N */
public static final KeyboardUsage O = new KeyboardUsage(Component.Identifier.Key.O, 0x12); /* o or O */
public static final KeyboardUsage P = new KeyboardUsage(Component.Identifier.Key.P, 0x13); /* p or P */
public static final KeyboardUsage Q = new KeyboardUsage(Component.Identifier.Key.Q, 0x14); /* q or Q */
public static final KeyboardUsage R = new KeyboardUsage(Component.Identifier.Key.R, 0x15); /* r or R */
public static final KeyboardUsage S = new KeyboardUsage(Component.Identifier.Key.S, 0x16); /* s or S */
public static final KeyboardUsage T = new KeyboardUsage(Component.Identifier.Key.T, 0x17); /* t or T */
public static final KeyboardUsage U = new KeyboardUsage(Component.Identifier.Key.U, 0x18); /* u or U */
public static final KeyboardUsage V = new KeyboardUsage(Component.Identifier.Key.V, 0x19); /* v or V */
public static final KeyboardUsage W = new KeyboardUsage(Component.Identifier.Key.W, 0x1A); /* w or W */
public static final KeyboardUsage X = new KeyboardUsage(Component.Identifier.Key.X, 0x1B); /* x or X */
public static final KeyboardUsage Y = new KeyboardUsage(Component.Identifier.Key.Y, 0x1C); /* y or Y */
public static final KeyboardUsage Z = new KeyboardUsage(Component.Identifier.Key.Z, 0x1D); /* z or Z */
public static final KeyboardUsage _1 = new KeyboardUsage(Component.Identifier.Key._1, 0x1E); /* 1 or ! */
public static final KeyboardUsage _2 = new KeyboardUsage(Component.Identifier.Key._2, 0x1F); /* 2 or @ */
public static final KeyboardUsage _3 = new KeyboardUsage(Component.Identifier.Key._3, 0x20); /* 3 or # */
public static final KeyboardUsage _4 = new KeyboardUsage(Component.Identifier.Key._4, 0x21); /* 4 or $ */
public static final KeyboardUsage _5 = new KeyboardUsage(Component.Identifier.Key._5, 0x22); /* 5 or % */
public static final KeyboardUsage _6 = new KeyboardUsage(Component.Identifier.Key._6, 0x23); /* 6 or ^ */
public static final KeyboardUsage _7 = new KeyboardUsage(Component.Identifier.Key._7, 0x24); /* 7 or & */
public static final KeyboardUsage _8 = new KeyboardUsage(Component.Identifier.Key._8, 0x25); /* 8 or * */
public static final KeyboardUsage _9 = new KeyboardUsage(Component.Identifier.Key._9, 0x26); /* 9 or ( */
public static final KeyboardUsage _0 = new KeyboardUsage(Component.Identifier.Key._0, 0x27); /* 0 or ) */
public static final KeyboardUsage ENTER = new KeyboardUsage(Component.Identifier.Key.RETURN, 0x28); /* Return (Enter) */
public static final KeyboardUsage ESCAPE = new KeyboardUsage(Component.Identifier.Key.ESCAPE, 0x29); /* Escape */
public static final KeyboardUsage BACKSPACE = new KeyboardUsage(Component.Identifier.Key.BACK, 0x2A); /* Delete (Backspace) */
public static final KeyboardUsage TAB = new KeyboardUsage(Component.Identifier.Key.TAB, 0x2B); /* Tab */
public static final KeyboardUsage SPACEBAR = new KeyboardUsage(Component.Identifier.Key.SPACE, 0x2C); /* Spacebar */
public static final KeyboardUsage HYPHEN = new KeyboardUsage(Component.Identifier.Key.MINUS, 0x2D); /* - or _ */
public static final KeyboardUsage EQUALSIGN = new KeyboardUsage(Component.Identifier.Key.EQUALS, 0x2E); /* = or + */
public static final KeyboardUsage OPENBRACKET = new KeyboardUsage(Component.Identifier.Key.LBRACKET, 0x2F); /* [ or { */
public static final KeyboardUsage CLOSEBRACKET = new KeyboardUsage(Component.Identifier.Key.RBRACKET, 0x30); /* ] or } */
public static final KeyboardUsage BACKSLASH = new KeyboardUsage(Component.Identifier.Key.BACKSLASH, 0x31); /* \ or | */
public static final KeyboardUsage NONUSPOUNT = new KeyboardUsage(Component.Identifier.Key.PERIOD, 0x32); /* Non-US # or _ */
public static final KeyboardUsage SEMICOLON = new KeyboardUsage(Component.Identifier.Key.SEMICOLON, 0x33); /* ; or : */
public static final KeyboardUsage QUOTE = new KeyboardUsage(Component.Identifier.Key.APOSTROPHE, 0x34); /* ' or " */
public static final KeyboardUsage TILDE = new KeyboardUsage(Component.Identifier.Key.GRAVE, 0x35); /* Grave Accent and Tilde */
public static final KeyboardUsage COMMA = new KeyboardUsage(Component.Identifier.Key.COMMA, 0x36); /* , or < */
public static final KeyboardUsage PERIOD = new KeyboardUsage(Component.Identifier.Key.PERIOD, 0x37); /* . or > */
public static final KeyboardUsage SLASH = new KeyboardUsage(Component.Identifier.Key.SLASH, 0x38); /* / or ? */
public static final KeyboardUsage CAPSLOCK = new KeyboardUsage(Component.Identifier.Key.CAPITAL, 0x39); /* Caps Lock */
public static final KeyboardUsage F1 = new KeyboardUsage(Component.Identifier.Key.F1, 0x3A); /* F1 */
public static final KeyboardUsage F2 = new KeyboardUsage(Component.Identifier.Key.F2, 0x3B); /* F2 */
public static final KeyboardUsage F3 = new KeyboardUsage(Component.Identifier.Key.F3, 0x3C); /* F3 */
public static final KeyboardUsage F4 = new KeyboardUsage(Component.Identifier.Key.F4, 0x3D); /* F4 */
public static final KeyboardUsage F5 = new KeyboardUsage(Component.Identifier.Key.F5, 0x3E); /* F5 */
public static final KeyboardUsage F6 = new KeyboardUsage(Component.Identifier.Key.F6, 0x3F); /* F6 */
public static final KeyboardUsage F7 = new KeyboardUsage(Component.Identifier.Key.F7, 0x40); /* F7 */
public static final KeyboardUsage F8 = new KeyboardUsage(Component.Identifier.Key.F8, 0x41); /* F8 */
public static final KeyboardUsage F9 = new KeyboardUsage(Component.Identifier.Key.F9, 0x42); /* F9 */
public static final KeyboardUsage F10 = new KeyboardUsage(Component.Identifier.Key.F10, 0x43); /* F10 */
public static final KeyboardUsage F11 = new KeyboardUsage(Component.Identifier.Key.F11, 0x44); /* F11 */
public static final KeyboardUsage F12 = new KeyboardUsage(Component.Identifier.Key.F12, 0x45); /* F12 */
public static final KeyboardUsage PRINTSCREEN = new KeyboardUsage(Component.Identifier.Key.SYSRQ, 0x46); /* PrintScreen */
public static final KeyboardUsage SCROLLLOCK = new KeyboardUsage(Component.Identifier.Key.SCROLL, 0x47); /* Scroll Lock */
public static final KeyboardUsage PAUSE = new KeyboardUsage(Component.Identifier.Key.PAUSE, 0x48); /* Pause */
public static final KeyboardUsage INSERT = new KeyboardUsage(Component.Identifier.Key.INSERT, 0x49); /* Insert */
public static final KeyboardUsage HOME = new KeyboardUsage(Component.Identifier.Key.HOME, 0x4A); /* Home */
public static final KeyboardUsage PAGEUP = new KeyboardUsage(Component.Identifier.Key.PAGEUP, 0x4B); /* Page Up */
public static final KeyboardUsage DELETE = new KeyboardUsage(Component.Identifier.Key.DELETE, 0x4C); /* Delete Forward */
public static final KeyboardUsage END = new KeyboardUsage(Component.Identifier.Key.END, 0x4D); /* End */
public static final KeyboardUsage PAGEDOWN = new KeyboardUsage(Component.Identifier.Key.PAGEDOWN, 0x4E); /* Page Down */
public static final KeyboardUsage RIGHTARROW = new KeyboardUsage(Component.Identifier.Key.RIGHT, 0x4F); /* Right Arrow */
public static final KeyboardUsage LEFTARROW = new KeyboardUsage(Component.Identifier.Key.LEFT, 0x50); /* Left Arrow */
public static final KeyboardUsage DOWNARROW = new KeyboardUsage(Component.Identifier.Key.DOWN, 0x51); /* Down Arrow */
public static final KeyboardUsage UPARROW = new KeyboardUsage(Component.Identifier.Key.UP, 0x52); /* Up Arrow */
public static final KeyboardUsage KEYPAD_NUMLOCK = new KeyboardUsage(Component.Identifier.Key.NUMLOCK, 0x53); /* Keypad NumLock or Clear */
public static final KeyboardUsage KEYPAD_SLASH = new KeyboardUsage(Component.Identifier.Key.DIVIDE, 0x54); /* Keypad / */
public static final KeyboardUsage KEYPAD_ASTERICK = new KeyboardUsage(0x55); /* Keypad * */
public static final KeyboardUsage KEYPAD_HYPHEN = new KeyboardUsage(Component.Identifier.Key.SUBTRACT, 0x56); /* Keypad - */
public static final KeyboardUsage KEYPAD_PLUS = new KeyboardUsage(Component.Identifier.Key.ADD, 0x57); /* Keypad + */
public static final KeyboardUsage KEYPAD_ENTER = new KeyboardUsage(Component.Identifier.Key.NUMPADENTER, 0x58); /* Keypad Enter */
public static final KeyboardUsage KEYPAD_1 = new KeyboardUsage(Component.Identifier.Key.NUMPAD1, 0x59); /* Keypad 1 or End */
public static final KeyboardUsage KEYPAD_2 = new KeyboardUsage(Component.Identifier.Key.NUMPAD2, 0x5A); /* Keypad 2 or Down Arrow */
public static final KeyboardUsage KEYPAD_3 = new KeyboardUsage(Component.Identifier.Key.NUMPAD3, 0x5B); /* Keypad 3 or Page Down */
public static final KeyboardUsage KEYPAD_4 = new KeyboardUsage(Component.Identifier.Key.NUMPAD4, 0x5C); /* Keypad 4 or Left Arrow */
public static final KeyboardUsage KEYPAD_5 = new KeyboardUsage(Component.Identifier.Key.NUMPAD5, 0x5D); /* Keypad 5 */
public static final KeyboardUsage KEYPAD_6 = new KeyboardUsage(Component.Identifier.Key.NUMPAD6, 0x5E); /* Keypad 6 or Right Arrow */
public static final KeyboardUsage KEYPAD_7 = new KeyboardUsage(Component.Identifier.Key.NUMPAD7, 0x5F); /* Keypad 7 or Home */
public static final KeyboardUsage KEYPAD_8 = new KeyboardUsage(Component.Identifier.Key.NUMPAD8, 0x60); /* Keypad 8 or Up Arrow */
public static final KeyboardUsage KEYPAD_9 = new KeyboardUsage(Component.Identifier.Key.NUMPAD9, 0x61); /* Keypad 9 or Page Up */
public static final KeyboardUsage KEYPAD_0 = new KeyboardUsage(Component.Identifier.Key.NUMPAD0, 0x62); /* Keypad 0 or Insert */
public static final KeyboardUsage KEYPAD_PERIOD = new KeyboardUsage(Component.Identifier.Key.DECIMAL, 0x63); /* Keypad . or Delete */
public static final KeyboardUsage NONUSBACKSLASH = new KeyboardUsage(Component.Identifier.Key.BACKSLASH, 0x64); /* Non-US \ or | */
public static final KeyboardUsage APPLICATION = new KeyboardUsage(Component.Identifier.Key.APPS, 0x65); /* Application */
public static final KeyboardUsage POWER = new KeyboardUsage(Component.Identifier.Key.POWER, 0x66); /* Power */
public static final KeyboardUsage KEYPAD_EQUALSIGN = new KeyboardUsage(Component.Identifier.Key.NUMPADEQUAL, 0x67); /* Keypad = */
public static final KeyboardUsage F13 = new KeyboardUsage(Component.Identifier.Key.F13, 0x68); /* F13 */
public static final KeyboardUsage F14 = new KeyboardUsage(Component.Identifier.Key.F14, 0x69); /* F14 */
public static final KeyboardUsage F15 = new KeyboardUsage(Component.Identifier.Key.F15, 0x6A); /* F15 */
public static final KeyboardUsage F16 = new KeyboardUsage(0x6B); /* F16 */
public static final KeyboardUsage F17 = new KeyboardUsage(0x6C); /* F17 */
public static final KeyboardUsage F18 = new KeyboardUsage(0x6D); /* F18 */
public static final KeyboardUsage F19 = new KeyboardUsage(0x6E); /* F19 */
public static final KeyboardUsage F20 = new KeyboardUsage(0x6F); /* F20 */
public static final KeyboardUsage F21 = new KeyboardUsage(0x70); /* F21 */
public static final KeyboardUsage F22 = new KeyboardUsage(0x71); /* F22 */
public static final KeyboardUsage F23 = new KeyboardUsage(0x72); /* F23 */
public static final KeyboardUsage F24 = new KeyboardUsage(0x73); /* F24 */
public static final KeyboardUsage EXECUTE = new KeyboardUsage(0x74); /* Execute */
public static final KeyboardUsage HELP = new KeyboardUsage(0x75); /* Help */
public static final KeyboardUsage MENU = new KeyboardUsage(0x76); /* Menu */
public static final KeyboardUsage SELECT = new KeyboardUsage(0x77); /* Select */
public static final KeyboardUsage STOP = new KeyboardUsage(Component.Identifier.Key.STOP, 0x78); /* Stop */
public static final KeyboardUsage AGAIN = new KeyboardUsage(0x79); /* Again */
public static final KeyboardUsage UNDO = new KeyboardUsage(0x7A); /* Undo */
public static final KeyboardUsage CUT = new KeyboardUsage(0x7B); /* Cut */
public static final KeyboardUsage COPY = new KeyboardUsage(0x7C); /* Copy */
public static final KeyboardUsage PASTE = new KeyboardUsage(0x7D); /* Paste */
public static final KeyboardUsage FIND = new KeyboardUsage(0x7E); /* Find */
public static final KeyboardUsage MUTE = new KeyboardUsage(0x7F); /* Mute */
public static final KeyboardUsage VOLUMEUP = new KeyboardUsage(0x80); /* Volume Up */
public static final KeyboardUsage VOLUMEDOWN = new KeyboardUsage(0x81); /* Volume Down */
public static final KeyboardUsage LOCKINGCAPSLOCK = new KeyboardUsage(Component.Identifier.Key.CAPITAL, 0x82); /* Locking Caps Lock */
public static final KeyboardUsage LOCKINGNUMLOCK = new KeyboardUsage(Component.Identifier.Key.NUMLOCK, 0x83); /* Locking Num Lock */
public static final KeyboardUsage LOCKINGSCROLLLOCK = new KeyboardUsage(Component.Identifier.Key.SCROLL, 0x84); /* Locking Scroll Lock */
public static final KeyboardUsage KEYPAD_COMMA = new KeyboardUsage(Component.Identifier.Key.COMMA, 0x85); /* Keypad Comma */
public static final KeyboardUsage KEYPAD_EQUALSSIGNAS400 = new KeyboardUsage(0x86); /* Keypad Equal Sign for AS/400 */
public static final KeyboardUsage INTERNATIONAL1 = new KeyboardUsage(0x87); /* International1 */
public static final KeyboardUsage INTERNATIONAL2 = new KeyboardUsage(0x88); /* International2 */
public static final KeyboardUsage INTERNATIONAL3 = new KeyboardUsage(0x89); /* International3 */
public static final KeyboardUsage INTERNATIONAL4 = new KeyboardUsage(0x8A); /* International4 */
public static final KeyboardUsage INTERNATIONAL5 = new KeyboardUsage(0x8B); /* International5 */
public static final KeyboardUsage INTERNATIONAL6 = new KeyboardUsage(0x8C); /* International6 */
public static final KeyboardUsage INTERNATIONAL7 = new KeyboardUsage(0x8D); /* International7 */
public static final KeyboardUsage INTERNATIONAL8 = new KeyboardUsage(0x8E); /* International8 */
public static final KeyboardUsage INTERNATIONAL9 = new KeyboardUsage(0x8F); /* International9 */
public static final KeyboardUsage LANG1 = new KeyboardUsage(0x90); /* LANG1 */
public static final KeyboardUsage LANG2 = new KeyboardUsage(0x91); /* LANG2 */
public static final KeyboardUsage LANG3 = new KeyboardUsage(0x92); /* LANG3 */
public static final KeyboardUsage LANG4 = new KeyboardUsage(0x93); /* LANG4 */
public static final KeyboardUsage LANG5 = new KeyboardUsage(0x94); /* LANG5 */
public static final KeyboardUsage LANG6 = new KeyboardUsage(0x95); /* LANG6 */
public static final KeyboardUsage LANG7 = new KeyboardUsage(0x96); /* LANG7 */
public static final KeyboardUsage LANG8 = new KeyboardUsage(0x97); /* LANG8 */
public static final KeyboardUsage LANG9 = new KeyboardUsage(0x98); /* LANG9 */
public static final KeyboardUsage ALTERNATEERASE = new KeyboardUsage(0x99); /* AlternateErase */
public static final KeyboardUsage SYSREQORATTENTION = new KeyboardUsage(Component.Identifier.Key.SYSRQ, 0x9A); /* SysReq/Attention */
public static final KeyboardUsage CANCEL = new KeyboardUsage(0x9B); /* Cancel */
public static final KeyboardUsage CLEAR = new KeyboardUsage(0x9C); /* Clear */
public static final KeyboardUsage PRIOR = new KeyboardUsage(Component.Identifier.Key.PAGEUP, 0x9D); /* Prior */
public static final KeyboardUsage RETURN = new KeyboardUsage(Component.Identifier.Key.RETURN, 0x9E); /* Return */
public static final KeyboardUsage SEPARATOR = new KeyboardUsage(0x9F); /* Separator */
public static final KeyboardUsage OUT = new KeyboardUsage(0xA0); /* Out */
public static final KeyboardUsage OPER = new KeyboardUsage(0xA1); /* Oper */
public static final KeyboardUsage CLEARORAGAIN = new KeyboardUsage(0xA2); /* Clear/Again */
public static final KeyboardUsage CRSELORPROPS = new KeyboardUsage(0xA3); /* CrSel/Props */
public static final KeyboardUsage EXSEL = new KeyboardUsage(0xA4); /* ExSel */
/* 0xA5-0xDF Reserved */
public static final KeyboardUsage LEFTCONTROL = new KeyboardUsage(Component.Identifier.Key.LCONTROL, 0xE0); /* Left Control */
public static final KeyboardUsage LEFTSHIFT = new KeyboardUsage(Component.Identifier.Key.LSHIFT, 0xE1); /* Left Shift */
public static final KeyboardUsage LEFTALT = new KeyboardUsage(Component.Identifier.Key.LALT, 0xE2); /* Left Alt */
public static final KeyboardUsage LEFTGUI = new KeyboardUsage(Component.Identifier.Key.LWIN, 0xE3); /* Left GUI */
public static final KeyboardUsage RIGHTCONTROL = new KeyboardUsage(Component.Identifier.Key.RCONTROL, 0xE4); /* Right Control */
public static final KeyboardUsage RIGHTSHIFT = new KeyboardUsage(Component.Identifier.Key.RSHIFT, 0xE5); /* Right Shift */
public static final KeyboardUsage RIGHTALT = new KeyboardUsage(Component.Identifier.Key.RALT, 0xE6); /* Right Alt */
public static final KeyboardUsage RIGHTGUI = new KeyboardUsage(Component.Identifier.Key.RWIN, 0xE7); /* Right GUI */
private final int usage;
private final Component.Identifier.Key identifier;
public final Component.Identifier.Key getIdentifier() {
return identifier;
}
public final static KeyboardUsage map(int usage) {
if (usage < 0 || usage >= map.length)
return null;
return map[usage];
}
private KeyboardUsage(int usage) {
this(Component.Identifier.Key.UNKNOWN, usage);
}
private KeyboardUsage(Component.Identifier.Key id, int usage) {
this.identifier = id;
this.usage = usage;
map[usage] = this;
}
public final String toString() {
return "KeyboardUsage (0x" + Integer.toHexString(usage) + ")";
}
}

View file

@ -0,0 +1,74 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** Represents an OSX AbstractController
* @author elias
* @version 1.0
*/
final class OSXAbstractController extends AbstractController {
private final PortType port;
private final OSXHIDQueue queue;
private final Type type;
protected OSXAbstractController(OSXHIDDevice device, OSXHIDQueue queue, Component[] components, Controller[] children, Rumbler[] rumblers, Type type) {
super(device.getProductName(), components, children, rumblers);
this.queue = queue;
this.type = type;
this.port = device.getPortType();
}
protected final boolean getNextDeviceEvent(Event event) throws IOException {
return OSXControllers.getNextDeviceEvent(event, queue);
}
protected final void setDeviceEventQueueSize(int size) throws IOException {
queue.setQueueDepth(size);
}
public Type getType() {
return type;
}
public final PortType getPortType() {
return port;
}
}

View file

@ -0,0 +1,70 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** Represents an OSX Component
* @author elias
* @version 1.0
*/
class OSXComponent extends AbstractComponent {
private final OSXHIDElement element;
public OSXComponent(Component.Identifier id, OSXHIDElement element) {
super(id.getName(), id);
this.element = element;
}
public final boolean isRelative() {
return element.isRelative();
}
public boolean isAnalog() {
return element.isAnalog();
}
public final OSXHIDElement getElement() {
return element;
}
protected float poll() throws IOException {
return OSXControllers.poll(element);
}
}

View file

@ -0,0 +1,64 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** helper methods for OSX specific Controllers
* @author elias
* @version 1.0
*/
final class OSXControllers {
private final static OSXEvent osx_event = new OSXEvent();
public final static synchronized float poll(OSXHIDElement element) throws IOException {
element.getElementValue(osx_event);
return element.convertValue(osx_event.getValue());
}
/* synchronized to protect osx_event */
public final static synchronized boolean getNextDeviceEvent(Event event, OSXHIDQueue queue) throws IOException {
if (queue.getNextEvent(osx_event)) {
OSXComponent component = queue.mapEvent(osx_event);
event.set(component, component.getElement().convertValue(osx_event.getValue()), osx_event.getNanos());
return true;
} else
return false;
}
}

View file

@ -0,0 +1,261 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*/
package net.java.games.input;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import net.java.games.util.plugins.Plugin;
import java.security.AccessController;
import java.security.PrivilegedAction;
/** OSX HIDManager implementation
* @author elias
* @author gregorypierce
* @version 1.0
*/
public final class OSXEnvironmentPlugin extends ControllerEnvironment implements Plugin {
private static boolean supported = false;
/**
* Static utility method for loading native libraries.
* It will try to load from either the path given by
* the net.java.games.input.librarypath property
* or through System.loadLibrary().
*
*/
static void loadLibrary(final String lib_name) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
try {
String lib_path = System.getProperty("net.java.games.input.librarypath");
if (lib_path != null)
System.load(lib_path + File.separator + System.mapLibraryName(lib_name));
else
System.loadLibrary(lib_name);
} catch (UnsatisfiedLinkError e) {
e.printStackTrace();
supported = false;
}
return null;
});
}
static String getPrivilegedProperty(final String property) {
return AccessController.doPrivileged((PrivilegedAction<String>)() -> System.getProperty(property));
}
static String getPrivilegedProperty(final String property, final String default_value) {
return AccessController.doPrivileged((PrivilegedAction<String>)() -> System.getProperty(property, default_value));
}
static {
String osName = getPrivilegedProperty("os.name", "").trim();
if(osName.equals("Mac OS X")) {
// Could check isMacOSXEqualsOrBetterThan in here too.
supported = true;
loadLibrary("jinput-osx");
}
}
private final static boolean isMacOSXEqualsOrBetterThan(int major_required, int minor_required) {
String os_version = System.getProperty("os.version");
StringTokenizer version_tokenizer = new StringTokenizer(os_version, ".");
int major;
int minor;
try {
String major_str = version_tokenizer.nextToken();
String minor_str = version_tokenizer.nextToken();
major = Integer.parseInt(major_str);
minor = Integer.parseInt(minor_str);
} catch (Exception e) {
log("Exception occurred while trying to determine OS version: " + e);
// Best guess, no
return false;
}
return major > major_required || (major == major_required && minor >= minor_required);
}
private final Controller[] controllers;
public OSXEnvironmentPlugin() {
if(isSupported()) {
this.controllers = enumerateControllers();
} else {
this.controllers = new Controller[0];
}
}
public final Controller[] getControllers() {
return controllers;
}
public boolean isSupported() {
return supported;
}
private final static void addElements(OSXHIDQueue queue, List<OSXHIDElement> elements, List<OSXComponent> components, boolean map_mouse_buttons) throws IOException {
Iterator<OSXHIDElement> it = elements.iterator();
while (it.hasNext()) {
OSXHIDElement element = it.next();
Component.Identifier id = element.getIdentifier();
if (id == null)
continue;
if (map_mouse_buttons) {
if (id == Component.Identifier.Button._0) {
id = Component.Identifier.Button.LEFT;
} else if (id == Component.Identifier.Button._1) {
id = Component.Identifier.Button.RIGHT;
} else if (id == Component.Identifier.Button._2) {
id = Component.Identifier.Button.MIDDLE;
}
}
OSXComponent component = new OSXComponent(id, element);
components.add(component);
queue.addElement(element, component);
}
}
private final static Keyboard createKeyboardFromDevice(OSXHIDDevice device, List<OSXHIDElement> elements) throws IOException {
List<OSXComponent> components = new ArrayList<>();
OSXHIDQueue queue = device.createQueue(AbstractController.EVENT_QUEUE_DEPTH);
try {
addElements(queue, elements, components, false);
} catch (IOException e) {
queue.release();
throw e;
}
Component[] components_array = new Component[components.size()];
components.toArray(components_array);
return new OSXKeyboard(device, queue, components_array, new Controller[]{}, new Rumbler[]{});
}
private final static Mouse createMouseFromDevice(OSXHIDDevice device, List<OSXHIDElement> elements) throws IOException {
List<OSXComponent> components = new ArrayList<>();
OSXHIDQueue queue = device.createQueue(AbstractController.EVENT_QUEUE_DEPTH);
try {
addElements(queue, elements, components, true);
} catch (IOException e) {
queue.release();
throw e;
}
Component[] components_array = new Component[components.size()];
components.toArray(components_array);
Mouse mouse = new OSXMouse(device, queue, components_array, new Controller[]{}, new Rumbler[]{});
if (mouse.getPrimaryButton() != null && mouse.getX() != null && mouse.getY() != null) {
return mouse;
} else {
queue.release();
return null;
}
}
private final static AbstractController createControllerFromDevice(OSXHIDDevice device, List<OSXHIDElement> elements, Controller.Type type) throws IOException {
List<OSXComponent> components = new ArrayList<>();
OSXHIDQueue queue = device.createQueue(AbstractController.EVENT_QUEUE_DEPTH);
try {
addElements(queue, elements, components, false);
} catch (IOException e) {
queue.release();
throw e;
}
Component[] components_array = new Component[components.size()];
components.toArray(components_array);
return new OSXAbstractController(device, queue, components_array, new Controller[]{}, new Rumbler[]{}, type);
}
private final static void createControllersFromDevice(OSXHIDDevice device, List<Controller> controllers) throws IOException {
UsagePair usage_pair = device.getUsagePair();
if (usage_pair == null)
return;
List<OSXHIDElement> elements = device.getElements();
if (usage_pair.getUsagePage() == UsagePage.GENERIC_DESKTOP && (usage_pair.getUsage() == GenericDesktopUsage.MOUSE ||
usage_pair.getUsage() == GenericDesktopUsage.POINTER)) {
Controller mouse = createMouseFromDevice(device, elements);
if (mouse != null)
controllers.add(mouse);
} else if (usage_pair.getUsagePage() == UsagePage.GENERIC_DESKTOP && (usage_pair.getUsage() == GenericDesktopUsage.KEYBOARD ||
usage_pair.getUsage() == GenericDesktopUsage.KEYPAD)) {
controllers.add(createKeyboardFromDevice(device, elements));
} else if (usage_pair.getUsagePage() == UsagePage.GENERIC_DESKTOP && usage_pair.getUsage() == GenericDesktopUsage.JOYSTICK) {
controllers.add(createControllerFromDevice(device, elements, Controller.Type.STICK));
} else if (usage_pair.getUsagePage() == UsagePage.GENERIC_DESKTOP && usage_pair.getUsage() == GenericDesktopUsage.MULTI_AXIS_CONTROLLER) {
controllers.add(createControllerFromDevice(device, elements, Controller.Type.STICK));
} else if (usage_pair.getUsagePage() == UsagePage.GENERIC_DESKTOP && usage_pair.getUsage() == GenericDesktopUsage.GAME_PAD) {
controllers.add(createControllerFromDevice(device, elements, Controller.Type.GAMEPAD));
}
}
private final static Controller[] enumerateControllers() {
List<Controller> controllers = new ArrayList<>();
try {
OSXHIDDeviceIterator it = new OSXHIDDeviceIterator();
try {
while (true) {
OSXHIDDevice device;
try {
device = it.next();
if (device == null)
break;
boolean device_used = false;
try {
int old_size = controllers.size();
createControllersFromDevice(device, controllers);
device_used = old_size != controllers.size();
} catch (IOException e) {
log("Failed to create controllers from device: " + device.getProductName());
}
if (!device_used)
device.release();
} catch (IOException e) {
log("Failed to enumerate device: " + e.getMessage());
}
}
} finally {
it.close();
}
} catch (IOException e) {
log("Failed to enumerate devices: " + e.getMessage());
return new Controller[]{};
}
Controller[] controllers_array = new Controller[controllers.size()];
controllers.toArray(controllers_array);
return controllers_array;
}
}

View file

@ -0,0 +1,73 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
/** OSX Event structure corresponding to IOHIDEventStruct
* @author elias
* @version 1.0
*/
class OSXEvent {
private long type;
private long cookie;
private int value;
private long nanos;
public void set(long type, long cookie, int value, long nanos) {
this.type = type;
this.cookie = cookie;
this.value = value;
this.nanos = nanos;
}
public long getType() {
return type;
}
public long getCookie() {
return cookie;
}
public int getValue() {
return value;
}
public long getNanos() {
return nanos;
}
}

View file

@ -0,0 +1,294 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*/
package net.java.games.input;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Iterator;
import java.util.logging.Logger;
/** OSX HIDManager implementation
* @author elias
* @author gregorypierce
* @version 1.0
*/
final class OSXHIDDevice {
private final static Logger log = Logger.getLogger(OSXHIDDevice.class.getName());
private final static int AXIS_DEFAULT_MIN_VALUE = 0;
private final static int AXIS_DEFAULT_MAX_VALUE = 64*1024;
private final static String kIOHIDTransportKey = "Transport";
private final static String kIOHIDVendorIDKey = "VendorID";
private final static String kIOHIDVendorIDSourceKey = "VendorIDSource";
private final static String kIOHIDProductIDKey = "ProductID";
private final static String kIOHIDVersionNumberKey = "VersionNumber";
private final static String kIOHIDManufacturerKey = "Manufacturer";
private final static String kIOHIDProductKey = "Product";
private final static String kIOHIDSerialNumberKey = "SerialNumber";
private final static String kIOHIDCountryCodeKey = "CountryCode";
private final static String kIOHIDLocationIDKey = "LocationID";
private final static String kIOHIDDeviceUsageKey = "DeviceUsage";
private final static String kIOHIDDeviceUsagePageKey = "DeviceUsagePage";
private final static String kIOHIDDeviceUsagePairsKey = "DeviceUsagePairs";
private final static String kIOHIDPrimaryUsageKey = "PrimaryUsage";
private final static String kIOHIDPrimaryUsagePageKey = "PrimaryUsagePage";
private final static String kIOHIDMaxInputReportSizeKey = "MaxInputReportSize";
private final static String kIOHIDMaxOutputReportSizeKey = "MaxOutputReportSize";
private final static String kIOHIDMaxFeatureReportSizeKey = "MaxFeatureReportSize";
private final static String kIOHIDElementKey = "Elements";
private final static String kIOHIDElementCookieKey = "ElementCookie";
private final static String kIOHIDElementTypeKey = "Type";
private final static String kIOHIDElementCollectionTypeKey = "CollectionType";
private final static String kIOHIDElementUsageKey = "Usage";
private final static String kIOHIDElementUsagePageKey = "UsagePage";
private final static String kIOHIDElementMinKey = "Min";
private final static String kIOHIDElementMaxKey = "Max";
private final static String kIOHIDElementScaledMinKey = "ScaledMin";
private final static String kIOHIDElementScaledMaxKey = "ScaledMax";
private final static String kIOHIDElementSizeKey = "Size";
private final static String kIOHIDElementReportSizeKey = "ReportSize";
private final static String kIOHIDElementReportCountKey = "ReportCount";
private final static String kIOHIDElementReportIDKey = "ReportID";
private final static String kIOHIDElementIsArrayKey = "IsArray";
private final static String kIOHIDElementIsRelativeKey = "IsRelative";
private final static String kIOHIDElementIsWrappingKey = "IsWrapping";
private final static String kIOHIDElementIsNonLinearKey = "IsNonLinear";
private final static String kIOHIDElementHasPreferredStateKey = "HasPreferredState";
private final static String kIOHIDElementHasNullStateKey = "HasNullState";
private final static String kIOHIDElementUnitKey = "Unit";
private final static String kIOHIDElementUnitExponentKey = "UnitExponent";
private final static String kIOHIDElementNameKey = "Name";
private final static String kIOHIDElementValueLocationKey = "ValueLocation";
private final static String kIOHIDElementDuplicateIndexKey = "DuplicateIndex";
private final static String kIOHIDElementParentCollectionKey = "ParentCollection";
private final long device_address;
private final long device_interface_address;
private final Map<String,?> properties;
private boolean released;
public OSXHIDDevice(long device_address, long device_interface_address) throws IOException {
this.device_address = device_address;
this.device_interface_address = device_interface_address;
this.properties = getDeviceProperties();
open();
}
public final Controller.PortType getPortType() {
String transport = (String)properties.get(kIOHIDTransportKey);
if (transport == null)
return Controller.PortType.UNKNOWN;
if (transport.equals("USB")) {
return Controller.PortType.USB;
} else {
return Controller.PortType.UNKNOWN;
}
}
public final String getProductName() {
return (String)properties.get(kIOHIDProductKey);
}
private final OSXHIDElement createElementFromElementProperties(Map<String,?> element_properties) {
/* long size = getLongFromProperties(element_properties, kIOHIDElementSizeKey);
// ignore elements that can't fit into the 32 bit value field of a hid event
if (size > 32)
return null;*/
long element_cookie = getLongFromProperties(element_properties, kIOHIDElementCookieKey);
int element_type_id = getIntFromProperties(element_properties, kIOHIDElementTypeKey);
ElementType element_type = ElementType.map(element_type_id);
int min = (int)getLongFromProperties(element_properties, kIOHIDElementMinKey, AXIS_DEFAULT_MIN_VALUE);
int max = (int)getLongFromProperties(element_properties, kIOHIDElementMaxKey, AXIS_DEFAULT_MAX_VALUE);
/* long scaled_min = getLongFromProperties(element_properties, kIOHIDElementScaledMinKey, Long.MIN_VALUE);
long scaled_max = getLongFromProperties(element_properties, kIOHIDElementScaledMaxKey, Long.MAX_VALUE);*/
UsagePair device_usage_pair = getUsagePair();
boolean default_relative = device_usage_pair != null && (device_usage_pair.getUsage() == GenericDesktopUsage.POINTER || device_usage_pair.getUsage() == GenericDesktopUsage.MOUSE);
boolean is_relative = getBooleanFromProperties(element_properties, kIOHIDElementIsRelativeKey, default_relative);
/* boolean is_wrapping = getBooleanFromProperties(element_properties, kIOHIDElementIsWrappingKey);
boolean is_non_linear = getBooleanFromProperties(element_properties, kIOHIDElementIsNonLinearKey);
boolean has_preferred_state = getBooleanFromProperties(element_properties, kIOHIDElementHasPreferredStateKey);
boolean has_null_state = getBooleanFromProperties(element_properties, kIOHIDElementHasNullStateKey);*/
int usage = getIntFromProperties(element_properties, kIOHIDElementUsageKey);
int usage_page = getIntFromProperties(element_properties, kIOHIDElementUsagePageKey);
UsagePair usage_pair = createUsagePair(usage_page, usage);
if (usage_pair == null || (element_type != ElementType.INPUT_MISC && element_type != ElementType.INPUT_BUTTON && element_type != ElementType.INPUT_AXIS)) {
//log.info("element_type = 0x" + element_type + " | usage = " + usage + " | usage_page = " + usage_page);
return null;
} else {
return new OSXHIDElement(this, usage_pair, element_cookie, element_type, min, max, is_relative);
}
}
@SuppressWarnings("unchecked")
private final void addElements(List<OSXHIDElement> elements, Map<String,?> properties) {
Object[] elements_properties = (Object[])properties.get(kIOHIDElementKey);
if (elements_properties == null)
return;
for (int i = 0; i < elements_properties.length; i++) {
Map<String,?> element_properties = (Map<String,?>)elements_properties[i];
OSXHIDElement element = createElementFromElementProperties(element_properties);
if (element != null) {
elements.add(element);
}
addElements(elements, element_properties);
}
}
public final List<OSXHIDElement> getElements() {
List<OSXHIDElement> elements = new ArrayList<>();
addElements(elements, properties);
return elements;
}
private final static long getLongFromProperties(Map<String,?> properties, String key, long default_value) {
Long long_obj = (Long)properties.get(key);
if (long_obj == null)
return default_value;
return long_obj.longValue();
}
private final static boolean getBooleanFromProperties(Map<String,?> properties, String key, boolean default_value) {
return getLongFromProperties(properties, key, default_value ? 1 : 0) != 0;
}
private final static int getIntFromProperties(Map<String,?> properties, String key) {
return (int)getLongFromProperties(properties, key);
}
private final static long getLongFromProperties(Map<String,?> properties, String key) {
Long long_obj = (Long)properties.get(key);
return long_obj.longValue();
}
private final static UsagePair createUsagePair(int usage_page_id, int usage_id) {
UsagePage usage_page = UsagePage.map(usage_page_id);
if (usage_page != null) {
Usage usage = usage_page.mapUsage(usage_id);
if (usage != null)
return new UsagePair(usage_page, usage);
}
return null;
}
public final UsagePair getUsagePair() {
int usage_page_id = getIntFromProperties(properties, kIOHIDPrimaryUsagePageKey);
int usage_id = getIntFromProperties(properties, kIOHIDPrimaryUsageKey);
return createUsagePair(usage_page_id, usage_id);
}
private final void dumpProperties() {
log.info(toString());
dumpMap("", properties);
}
private final static void dumpArray(String prefix, Object[] array) {
log.info(prefix + "{");
for (int i = 0; i < array.length; i++) {
dumpObject(prefix + "\t", array[i]);
log.info(prefix + ",");
}
log.info(prefix + "}");
}
private final static void dumpMap(String prefix, Map<String,?> map) {
Iterator<String> keys = map.keySet().iterator();
while (keys.hasNext()) {
Object key = keys.next();
Object value = map.get(key);
dumpObject(prefix, key);
dumpObject(prefix + "\t", value);
}
}
@SuppressWarnings("unchecked")
private final static void dumpObject(String prefix, Object obj) {
if (obj instanceof Long) {
Long l = (Long)obj;
log.info(prefix + "0x" + Long.toHexString(l.longValue()));
} else if (obj instanceof Map)
dumpMap(prefix, (Map<String,?>)obj);
else if (obj.getClass().isArray())
dumpArray(prefix, (Object[])obj);
else
log.info(prefix + obj);
}
private final Map<String,?> getDeviceProperties() throws IOException {
return nGetDeviceProperties(device_address);
}
private final static native Map<String,?> nGetDeviceProperties(long device_address) throws IOException;
public final synchronized void release() throws IOException {
try {
close();
} finally {
released = true;
nReleaseDevice(device_address, device_interface_address);
}
}
private final static native void nReleaseDevice(long device_address, long device_interface_address);
public final synchronized void getElementValue(long element_cookie, OSXEvent event) throws IOException {
checkReleased();
nGetElementValue(device_interface_address, element_cookie, event);
}
private final static native void nGetElementValue(long device_interface_address, long element_cookie, OSXEvent event) throws IOException;
public final synchronized OSXHIDQueue createQueue(int queue_depth) throws IOException {
checkReleased();
long queue_address = nCreateQueue(device_interface_address);
return new OSXHIDQueue(queue_address, queue_depth);
}
private final static native long nCreateQueue(long device_interface_address) throws IOException;
private final void open() throws IOException {
nOpen(device_interface_address);
}
private final static native void nOpen(long device_interface_address) throws IOException;
private final void close() throws IOException {
nClose(device_interface_address);
}
private final static native void nClose(long device_interface_address) throws IOException;
private final void checkReleased() throws IOException {
if (released)
throw new IOException();
}
}

View file

@ -0,0 +1,65 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** OSX HIDManager implementation
* @author elias
* @author gregorypierce
* @version 1.0
*/
final class OSXHIDDeviceIterator {
private final long iterator_address;
public OSXHIDDeviceIterator() throws IOException {
this.iterator_address = nCreateIterator();
}
private final static native long nCreateIterator();
public final void close(){
nReleaseIterator(iterator_address);
}
private final static native void nReleaseIterator(long iterator_address);
public final OSXHIDDevice next() throws IOException {
return nNext(iterator_address);
}
private final static native OSXHIDDevice nNext(long iterator_address) throws IOException;
}

View file

@ -0,0 +1,143 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** Represents an OSX HID Element
* @author elias
* @author gregorypierce
* @version 1.0
*/
final class OSXHIDElement {
private final OSXHIDDevice device;
private final UsagePair usage_pair;
private final long element_cookie;
private final ElementType element_type;
private final int min;
private final int max;
private final Component.Identifier identifier;
private final boolean is_relative;
public OSXHIDElement(OSXHIDDevice device, UsagePair usage_pair, long element_cookie, ElementType element_type, int min, int max, boolean is_relative) {
this.device = device;
this.usage_pair = usage_pair;
this.element_cookie = element_cookie;
this.element_type = element_type;
this.min = min;
this.max = max;
this.identifier = computeIdentifier();
this.is_relative = is_relative;
}
private final Component.Identifier computeIdentifier() {
if (usage_pair.getUsagePage() == UsagePage.GENERIC_DESKTOP) {
return ((GenericDesktopUsage)usage_pair.getUsage()).getIdentifier();
} else if (usage_pair.getUsagePage() == UsagePage.BUTTON) {
return ((ButtonUsage)usage_pair.getUsage()).getIdentifier();
} else if (usage_pair.getUsagePage() == UsagePage.KEYBOARD_OR_KEYPAD) {
return ((KeyboardUsage)usage_pair.getUsage()).getIdentifier();
} else
return null;
}
final Component.Identifier getIdentifier() {
return identifier;
}
final long getCookie() {
return element_cookie;
}
final ElementType getType() {
return element_type;
}
final boolean isRelative() {
return is_relative && identifier instanceof Component.Identifier.Axis;
}
final boolean isAnalog() {
return identifier instanceof Component.Identifier.Axis && identifier != Component.Identifier.Axis.POV;
}
private UsagePair getUsagePair() {
return usage_pair;
}
final void getElementValue(OSXEvent event) throws IOException {
device.getElementValue(element_cookie, event);
}
final float convertValue(float value) {
if (identifier == Component.Identifier.Axis.POV) {
switch ((int)value) {
case 0:
return Component.POV.UP;
case 1:
return Component.POV.UP_RIGHT;
case 2:
return Component.POV.RIGHT;
case 3:
return Component.POV.DOWN_RIGHT;
case 4:
return Component.POV.DOWN;
case 5:
return Component.POV.DOWN_LEFT;
case 6:
return Component.POV.LEFT;
case 7:
return Component.POV.UP_LEFT;
case 8:
return Component.POV.OFF;
default:
return Component.POV.OFF;
}
} else if (identifier instanceof Component.Identifier.Axis && !is_relative) {
if (min == max)
return 0;
else if (value > max)
value = max;
else if (value < min)
value = min;
return 2*(value - min)/(max - min) - 1;
} else
return value;
}
}

View file

@ -0,0 +1,135 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*/
package net.java.games.input;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
/**
* @author elias
* @version 1.0
*/
final class OSXHIDQueue {
private final Map<Long,OSXComponent> map = new HashMap<>();
private final long queue_address;
private boolean released;
public OSXHIDQueue(long address, int queue_depth) throws IOException {
this.queue_address = address;
try {
createQueue(queue_depth);
} catch (IOException e) {
release();
throw e;
}
}
public final synchronized void setQueueDepth(int queue_depth) throws IOException {
checkReleased();
stop();
close();
createQueue(queue_depth);
}
private final void createQueue(int queue_depth) throws IOException {
open(queue_depth);
try {
start();
} catch (IOException e) {
close();
throw e;
}
}
public final OSXComponent mapEvent(OSXEvent event) {
return map.get(event.getCookie());
}
private final void open(int queue_depth) throws IOException {
nOpen(queue_address, queue_depth);
}
private final static native void nOpen(long queue_address, int queue_depth) throws IOException;
private final void close() throws IOException {
nClose(queue_address);
}
private final static native void nClose(long queue_address) throws IOException;
private final void start() throws IOException {
nStart(queue_address);
}
private final static native void nStart(long queue_address) throws IOException;
private final void stop() throws IOException {
nStop(queue_address);
}
private final static native void nStop(long queue_address) throws IOException;
public final synchronized void release() throws IOException {
if (!released) {
released = true;
try {
stop();
close();
} finally {
nReleaseQueue(queue_address);
}
}
}
private final static native void nReleaseQueue(long queue_address) throws IOException;
public final void addElement(OSXHIDElement element, OSXComponent component) throws IOException {
nAddElement(queue_address, element.getCookie());
map.put(element.getCookie(), component);
}
private final static native void nAddElement(long queue_address, long cookie) throws IOException;
public final void removeElement(OSXHIDElement element) throws IOException {
nRemoveElement(queue_address, element.getCookie());
map.remove(element.getCookie());
}
private final static native void nRemoveElement(long queue_address, long cookie) throws IOException;
public final synchronized boolean getNextEvent(OSXEvent event) throws IOException {
checkReleased();
return nGetNextEvent(queue_address, event);
}
private final static native boolean nGetNextEvent(long queue_address, OSXEvent event) throws IOException;
private final void checkReleased() throws IOException {
if (released)
throw new IOException("Queue is released");
}
}

View file

@ -0,0 +1,68 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** Represents an OSX Keyboard
* @author elias
* @version 1.0
*/
final class OSXKeyboard extends Keyboard {
private final PortType port;
private final OSXHIDQueue queue;
protected OSXKeyboard(OSXHIDDevice device, OSXHIDQueue queue, Component[] components, Controller[] children, Rumbler[] rumblers) {
super(device.getProductName(), components, children, rumblers);
this.queue = queue;
this.port = device.getPortType();
}
protected final boolean getNextDeviceEvent(Event event) throws IOException {
return OSXControllers.getNextDeviceEvent(event, queue);
}
protected final void setDeviceEventQueueSize(int size) throws IOException {
queue.setQueueDepth(size);
}
public final PortType getPortType() {
return port;
}
}

View file

@ -0,0 +1,68 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** Represents an OSX Mouse
* @author elias
* @version 1.0
*/
final class OSXMouse extends Mouse {
private final PortType port;
private final OSXHIDQueue queue;
protected OSXMouse(OSXHIDDevice device, OSXHIDQueue queue, Component[] components, Controller[] children, Rumbler[] rumblers) {
super(device.getProductName(), components, children, rumblers);
this.queue = queue;
this.port = device.getPortType();
}
protected final boolean getNextDeviceEvent(Event event) throws IOException {
return OSXControllers.getNextDeviceEvent(event, queue);
}
protected final void setDeviceEventQueueSize(int size) throws IOException {
queue.setQueueDepth(size);
}
public final PortType getPortType() {
return port;
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*/
package net.java.games.input;
/** Generic Desktop Usages
* @author elias
* @version 1.0
*/
public interface Usage {
}

View file

@ -0,0 +1,108 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*/
package net.java.games.input;
import java.lang.reflect.Method;
/** HID Usage pages
* @author elias
* @version 1.0
*/
final class UsagePage {
private final static UsagePage[] map = new UsagePage[0xFF];
public final static UsagePage UNDEFINED = new UsagePage(0x00);
public final static UsagePage GENERIC_DESKTOP = new UsagePage(0x01, GenericDesktopUsage.class);
public final static UsagePage SIMULATION = new UsagePage(0x02);
public final static UsagePage VR = new UsagePage(0x03);
public final static UsagePage SPORT = new UsagePage(0x04);
public final static UsagePage GAME = new UsagePage(0x05);
/* Reserved 0x06 */
public final static UsagePage KEYBOARD_OR_KEYPAD = new UsagePage(0x07, KeyboardUsage.class); /* USB Device Class Definition for Human Interface Devices (HID). Note: the usage type for all key codes is Selector (Sel). */
public final static UsagePage LEDS = new UsagePage(0x08);
public final static UsagePage BUTTON = new UsagePage(0x09, ButtonUsage.class);
public final static UsagePage ORDINAL = new UsagePage(0x0A);
public final static UsagePage TELEPHONY = new UsagePage(0x0B);
public final static UsagePage CONSUMER = new UsagePage(0x0C);
public final static UsagePage DIGITIZER = new UsagePage(0x0D);
/* Reserved 0x0E */
public final static UsagePage PID = new UsagePage(0x0F); /* USB Physical Interface Device definitions for force feedback and related devices. */
public final static UsagePage UNICODE = new UsagePage(0x10);
/* Reserved 0x11 - 0x13 */
public final static UsagePage ALPHANUMERIC_DISPLAY = new UsagePage(0x14);
/* Reserved 0x15 - 0x7F */
/* Monitor 0x80 - 0x83 USB Device Class Definition for Monitor Devices */
/* Power 0x84 - 0x87 USB Device Class Definition for Power Devices */
public final static UsagePage POWER_DEVICE = new UsagePage(0x84); /* Power Device Page */
public final static UsagePage BATTERY_SYSTEM = new UsagePage(0x85); /* Battery System Page */
/* Reserved 0x88 - 0x8B */
public final static UsagePage BAR_CODE_SCANNER = new UsagePage(0x8C); /* (Point of Sale) USB Device Class Definition for Bar Code Scanner Devices */
public final static UsagePage SCALE = new UsagePage(0x8D); /* (Point of Sale) USB Device Class Definition for Scale Devices */
/* ReservedPointofSalepages 0x8E - 0X8F */
public final static UsagePage CAMERACONTROL= new UsagePage(0x90); /* USB Device Class Definition for Image Class Devices */
public final static UsagePage ARCADE = new UsagePage(0x91); /* OAAF Definitions for arcade and coinop related Devices */
private final Class<? extends Usage> usage_class;
private final int usage_page_id;
public final static UsagePage map(int page_id) {
if (page_id < 0 || page_id >= map.length)
return null;
return map[page_id];
}
private UsagePage(int page_id, Class<? extends Usage> usage_class) {
map[page_id] = this;
this.usage_class = usage_class;
this.usage_page_id = page_id;
}
private UsagePage(int page_id) {
this(page_id, null);
}
public final String toString() {
return "UsagePage (0x" + Integer.toHexString(usage_page_id) + ")";
}
public final Usage mapUsage(int usage_id) {
if (usage_class == null)
return null;
try {
Method map_method = usage_class.getMethod("map", int.class);
Object result = map_method.invoke(null, usage_id);
return (Usage)result;
} catch (Exception e) {
throw new Error(e);
}
}
}

View file

@ -0,0 +1,76 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
/** Usage/Page pair
* @author elias
* @version 1.0
*/
class UsagePair {
private final UsagePage usage_page;
private final Usage usage;
public UsagePair(UsagePage usage_page, Usage usage) {
this.usage_page = usage_page;
this.usage = usage;
}
public final UsagePage getUsagePage() {
return usage_page;
}
public final Usage getUsage() {
return usage;
}
public final int hashCode() {
return usage.hashCode() ^ usage_page.hashCode();
}
public final boolean equals(Object other) {
if (!(other instanceof UsagePair))
return false;
UsagePair other_pair = (UsagePair)other;
return other_pair.usage.equals(usage) && other_pair.usage_page.equals(usage_page);
}
public final String toString() {
return "UsagePair: (page = " + usage_page + ", usage = " + usage + ")";
}
}

View file

@ -0,0 +1,197 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
#include <CoreServices/CoreServices.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <jni.h>
#include "util.h"
#include "macosxutil.h"
typedef struct {
JNIEnv *env;
jobject map;
} dict_context_t;
typedef struct {
JNIEnv *env;
jobjectArray array;
jsize index;
} array_context_t;
static jobject createObjectFromCFObject(JNIEnv *env, CFTypeRef cfobject);
static jstring createStringFromCFString(JNIEnv *env, CFStringRef cfstring) {
CFIndex unicode_length = CFStringGetLength(cfstring);
CFIndex utf8_length = CFStringGetMaximumSizeForEncoding(unicode_length, kCFStringEncodingUTF8);
// Allocate buffer large enough, plus \0 terminator
char *buffer = (char *)malloc(utf8_length + 1);
if (buffer == NULL)
return NULL;
Boolean result = CFStringGetCString(cfstring, buffer, utf8_length + 1, kCFStringEncodingUTF8);
if (!result) {
free(buffer);
return NULL;
}
jstring str = (*env)->NewStringUTF(env, buffer);
free(buffer);
return str;
}
static jobject createDoubleObjectFromCFNumber(JNIEnv *env, CFNumberRef cfnumber) {
double value;
Boolean result = CFNumberGetValue(cfnumber, kCFNumberDoubleType, &value);
if (!result)
return NULL;
return newJObject(env, "java/lang/Double", "(D)V", (jdouble)value);
}
static jobject createLongObjectFromCFNumber(JNIEnv *env, CFNumberRef cfnumber) {
SInt64 value;
Boolean result = CFNumberGetValue(cfnumber, kCFNumberSInt64Type, &value);
if (!result)
return NULL;
return newJObject(env, "java/lang/Long", "(J)V", (jlong)value);
}
static jobject createNumberFromCFNumber(JNIEnv *env, CFNumberRef cfnumber) {
CFNumberType number_type = CFNumberGetType(cfnumber);
switch (number_type) {
case kCFNumberSInt8Type:
case kCFNumberSInt16Type:
case kCFNumberSInt32Type:
case kCFNumberSInt64Type:
case kCFNumberCharType:
case kCFNumberShortType:
case kCFNumberIntType:
case kCFNumberLongType:
case kCFNumberLongLongType:
case kCFNumberCFIndexType:
return createLongObjectFromCFNumber(env, cfnumber);
case kCFNumberFloat32Type:
case kCFNumberFloat64Type:
case kCFNumberFloatType:
case kCFNumberDoubleType:
return createDoubleObjectFromCFNumber(env, cfnumber);
default:
return NULL;
}
}
static void createArrayEntries(const void *value, void *context) {
array_context_t *array_context = (array_context_t *)context;
jobject jval = createObjectFromCFObject(array_context->env, value);
(*array_context->env)->SetObjectArrayElement(array_context->env, array_context->array, array_context->index++, jval);
(*array_context->env)->DeleteLocalRef(array_context->env, jval);
}
static jobject createArrayFromCFArray(JNIEnv *env, CFArrayRef cfarray) {
jclass Object_class = (*env)->FindClass(env, "java/lang/Object");
if (Object_class == NULL)
return NULL;
CFIndex size = CFArrayGetCount(cfarray);
CFRange range = {0, size};
jobjectArray array = (*env)->NewObjectArray(env, size, Object_class, NULL);
array_context_t array_context;
array_context.env = env;
array_context.array = array;
array_context.index = 0;
CFArrayApplyFunction(cfarray, range, createArrayEntries, &array_context);
return array;
}
static jobject createObjectFromCFObject(JNIEnv *env, CFTypeRef cfobject) {
CFTypeID type_id = CFGetTypeID(cfobject);
if (type_id == CFDictionaryGetTypeID()) {
return createMapFromCFDictionary(env, cfobject);
} else if (type_id == CFArrayGetTypeID()) {
return createArrayFromCFArray(env, cfobject);
} else if (type_id == CFStringGetTypeID()) {
return createStringFromCFString(env, cfobject);
} else if (type_id == CFNumberGetTypeID()) {
return createNumberFromCFNumber(env, cfobject);
} else {
return NULL;
}
}
static void createMapKeys(const void *key, const void *value, void *context) {
dict_context_t *dict_context = (dict_context_t *)context;
jclass Map_class = (*dict_context->env)->GetObjectClass(dict_context->env, dict_context->map);
if (Map_class == NULL)
return;
jmethodID map_put = (*dict_context->env)->GetMethodID(dict_context->env, Map_class, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
if (map_put == NULL)
return;
jobject jkey = createObjectFromCFObject(dict_context->env, key);
jobject jvalue = createObjectFromCFObject(dict_context->env, value);
if (jkey == NULL || jvalue == NULL)
return;
(*dict_context->env)->CallObjectMethod(dict_context->env, dict_context->map, map_put, jkey, jvalue);
(*dict_context->env)->DeleteLocalRef(dict_context->env, jkey);
(*dict_context->env)->DeleteLocalRef(dict_context->env, jvalue);
}
jobject createMapFromCFDictionary(JNIEnv *env, CFDictionaryRef dict) {
jobject map = newJObject(env, "java/util/HashMap", "()V");
if (map == NULL)
return NULL;
dict_context_t dict_context;
dict_context.env = env;
dict_context.map = map;
CFDictionaryApplyFunction(dict, createMapKeys, &dict_context);
return map;
}
void copyEvent(JNIEnv *env, IOHIDEventStruct *event, jobject event_return) {
jclass OSXEvent_class = (*env)->GetObjectClass(env, event_return);
if (OSXEvent_class == NULL) {
return;
}
jmethodID OSXEvent_set = (*env)->GetMethodID(env, OSXEvent_class, "set", "(JJIJ)V");
if (OSXEvent_set == NULL) {
return;
}
Nanoseconds nanos = AbsoluteToNanoseconds(event->timestamp);
uint64_t nanos64= *((uint64_t *)&nanos);
(*env)->CallVoidMethod(env, event_return, OSXEvent_set, (jlong)event->type, (jlong)(intptr_t)event->elementCookie, (jint)event->value, (jlong)nanos64);
}

View file

@ -0,0 +1,48 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <jni.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/hid/IOHIDLib.h>
extern jobject createMapFromCFDictionary(JNIEnv *env, CFDictionaryRef dict);
extern void copyEvent(JNIEnv *env, IOHIDEventStruct *event, jobject event_return);

View file

@ -0,0 +1,118 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
#include <IOKit/IOTypes.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/hid/IOHIDLib.h>
#include <IOKit/hid/IOHIDKeys.h>
#include <CoreFoundation/CoreFoundation.h>
#include "net_java_games_input_OSXHIDDevice.h"
#include "util.h"
#include "macosxutil.h"
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDDevice_nReleaseDevice(JNIEnv *env, jclass unused, jlong device_address, jlong interface_address) {
io_object_t hidDevice = (io_object_t)device_address;
IOHIDDeviceInterface **device_interface = (IOHIDDeviceInterface **)(intptr_t)interface_address;;
(*device_interface)->Release(device_interface);
IOObjectRelease(hidDevice);
}
JNIEXPORT jobject JNICALL Java_net_java_games_input_OSXHIDDevice_nGetDeviceProperties(JNIEnv *env, jclass unused, jlong device_address) {
io_object_t hidDevice = (io_object_t)device_address;
CFMutableDictionaryRef properties;
kern_return_t result = IORegistryEntryCreateCFProperties(hidDevice,
&properties,
kCFAllocatorDefault,
kNilOptions);
if (result != KERN_SUCCESS) {
throwIOException(env, "Failed to create properties for device (%ld)", result);
return NULL;
}
jobject map = createMapFromCFDictionary(env, properties);
CFRelease(properties);
return map;
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDDevice_nOpen
(JNIEnv * env, jclass unused, jlong lpDevice) {
IOHIDDeviceInterface **hidDeviceInterface = (IOHIDDeviceInterface **)(intptr_t)lpDevice;
IOReturn ioReturnValue = (*hidDeviceInterface)->open(hidDeviceInterface, 0);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Device open failed: %d", ioReturnValue);
}
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDDevice_nClose
(JNIEnv * env, jclass unused, jlong lpDevice) {
IOHIDDeviceInterface **hidDeviceInterface = (IOHIDDeviceInterface **)(intptr_t)lpDevice;
IOReturn ioReturnValue = (*hidDeviceInterface)->close(hidDeviceInterface);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Device close failed: %d", ioReturnValue);
}
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDDevice_nGetElementValue
(JNIEnv * env, jclass unused, jlong lpDevice, jlong hidCookie, jobject event_return) {
IOHIDDeviceInterface **hidDeviceInterface = (IOHIDDeviceInterface **)(intptr_t)lpDevice;
IOHIDElementCookie cookie = (IOHIDElementCookie)(intptr_t)hidCookie;
IOHIDEventStruct event;
IOReturn ioReturnValue = (*hidDeviceInterface)->getElementValue(hidDeviceInterface, cookie, &event);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Device getElementValue failed: %d", ioReturnValue);
return;
}
copyEvent(env, &event, event_return);
if (event.longValue != NULL) {
free(event.longValue);
}
}
JNIEXPORT jlong JNICALL Java_net_java_games_input_OSXHIDDevice_nCreateQueue(JNIEnv *env, jclass unused, jlong device_address) {
IOHIDDeviceInterface **hidDeviceInterface = (IOHIDDeviceInterface **)(intptr_t)device_address;
IOHIDQueueInterface **queue = (*hidDeviceInterface)->allocQueue(hidDeviceInterface);
if (queue == NULL) {
throwIOException(env, "Could not allocate queue");
return 0;
}
return (jlong)(intptr_t)queue;
}

View file

@ -0,0 +1,143 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
#include <IOKit/IOTypes.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/hid/IOHIDLib.h>
#include <IOKit/hid/IOHIDKeys.h>
#include <CoreFoundation/CoreFoundation.h>
#include "net_java_games_input_OSXHIDDeviceIterator.h"
#include "util.h"
JNIEXPORT jlong JNICALL Java_net_java_games_input_OSXHIDDeviceIterator_nCreateIterator(JNIEnv *env, jclass unused) {
io_iterator_t hidObjectIterator;
// Set up a matching dictionary to search the I/O Registry by class
// name for all HID class devices
//
CFMutableDictionaryRef hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
// Now search I/O Registry for matching devices.
// IOServiceGetMatchingServices consumes a reference to the dictionary so we don't have to release it
IOReturn ioReturnValue = IOServiceGetMatchingServices(kIOMasterPortDefault, hidMatchDictionary, &hidObjectIterator);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Failed to create iterator (%ld)\n", ioReturnValue);
return 0;
}
if (hidObjectIterator == IO_OBJECT_NULL) {
throwIOException(env, "Failed to create iterator\n");
return 0;
}
return (jlong)hidObjectIterator;
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDDeviceIterator_nReleaseIterator(JNIEnv *env, jclass unused, jlong address) {
io_iterator_t iterator = (io_iterator_t)address;
IOObjectRelease(iterator);
}
static IOHIDDeviceInterface **createHIDDevice(JNIEnv *env, io_object_t hidDevice) {
// io_name_t className;
IOHIDDeviceInterface **hidDeviceInterface;
IOCFPlugInInterface **plugInInterface;
SInt32 score;
/* ioReturnValue = IOObjectGetClass(hidDevice, className);
if (ioReturnValue != kIOReturnSuccess) {
printfJava(env, "Failed to get IOObject class name.");
}
printfJava(env, "Found device type [%s]\n", className);
*/
IOReturn ioReturnValue = IOCreatePlugInInterfaceForService(hidDevice,
kIOHIDDeviceUserClientTypeID,
kIOCFPlugInInterfaceID,
&plugInInterface,
&score);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Couldn't create plugin for device interface (%ld)\n", ioReturnValue);
return NULL;
}
//Call a method of the intermediate plug-in to create the device
//interface
//
HRESULT plugInResult = (*plugInInterface)->QueryInterface(plugInInterface,
CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID),
(LPVOID)&hidDeviceInterface);
(*plugInInterface)->Release(plugInInterface);
if (plugInResult != S_OK) {
throwIOException(env, "Couldn't create HID class device interface (%ld)\n", plugInResult);
return NULL;
}
return hidDeviceInterface;
}
JNIEXPORT jobject JNICALL Java_net_java_games_input_OSXHIDDeviceIterator_nNext(JNIEnv *env, jclass unused, jlong address) {
io_iterator_t iterator = (io_iterator_t)address;
io_object_t hidDevice;
// io_string_t path;
// kern_return_t result;
hidDevice = IOIteratorNext(iterator);
if (hidDevice == MACH_PORT_NULL)
return NULL;
/* IOResult result = IORegistryEntryGetPath(hidDevice, kIOServicePlane, path);
if (result != KERN_SUCCESS) {
IOObjectRelease(hidDevice);
throwIOException("Failed to get device path (%ld)\n", result);
return NULL;
}
*/
IOHIDDeviceInterface **device_interface = createHIDDevice(env, hidDevice);
if (device_interface == NULL) {
IOObjectRelease(hidDevice);
return NULL;
}
jobject device_object = newJObject(env, "net/java/games/input/OSXHIDDevice", "(JJ)V", (jlong)hidDevice, (jlong)(intptr_t)device_interface);
if (device_object == NULL) {
(*device_interface)->Release(device_interface);
IOObjectRelease(hidDevice);
return NULL;
}
return device_object;
}

View file

@ -0,0 +1,135 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
#include <IOKit/IOTypes.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/hid/IOHIDLib.h>
#include <IOKit/hid/IOHIDKeys.h>
#include <CoreFoundation/CoreFoundation.h>
#include "net_java_games_input_OSXHIDQueue.h"
#include "util.h"
#include "macosxutil.h"
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDQueue_nOpen(JNIEnv *env, jclass unused, jlong address, jint queue_depth) {
IOHIDQueueInterface **queue = (IOHIDQueueInterface **)(intptr_t)address;
IOReturn ioReturnValue = (*queue)->create(queue, 0, queue_depth);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Queue open failed: %d\n", ioReturnValue);
return;
}
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDQueue_nStart(JNIEnv *env, jclass unused, jlong address) {
IOHIDQueueInterface **queue = (IOHIDQueueInterface **)(intptr_t)address;
IOReturn ioReturnValue = (*queue)->start(queue);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Queue start failed: %d\n", ioReturnValue);
return;
}
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDQueue_nStop(JNIEnv *env, jclass unused, jlong address) {
IOHIDQueueInterface **queue = (IOHIDQueueInterface **)(intptr_t)address;
IOReturn ioReturnValue = (*queue)->stop(queue);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Queue stop failed: %d\n", ioReturnValue);
return;
}
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDQueue_nClose(JNIEnv *env, jclass unused, jlong address) {
IOHIDQueueInterface **queue = (IOHIDQueueInterface **)(intptr_t)address;
IOReturn ioReturnValue = (*queue)->dispose(queue);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Queue dispose failed: %d\n", ioReturnValue);
return;
}
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDQueue_nReleaseQueue(JNIEnv *env, jclass unused, jlong address) {
IOHIDQueueInterface **queue = (IOHIDQueueInterface **)(intptr_t)address;
IOReturn ioReturnValue = (*queue)->Release(queue);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Queue Release failed: %d\n", ioReturnValue);
return;
}
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDQueue_nAddElement(JNIEnv *env, jclass unused, jlong address, jlong cookie_address) {
IOHIDQueueInterface **queue = (IOHIDQueueInterface **)(intptr_t)address;
IOHIDElementCookie cookie = (IOHIDElementCookie)(intptr_t)cookie_address;
IOReturn ioReturnValue = (*queue)->addElement(queue, cookie, 0);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Queue addElement failed: %d\n", ioReturnValue);
return;
}
}
JNIEXPORT void JNICALL Java_net_java_games_input_OSXHIDQueue_nRemoveElement(JNIEnv *env, jclass unused, jlong address, jlong cookie_address) {
IOHIDQueueInterface **queue = (IOHIDQueueInterface **)(intptr_t)address;
IOHIDElementCookie cookie = (IOHIDElementCookie)(intptr_t)cookie_address;
IOReturn ioReturnValue = (*queue)->removeElement(queue, cookie);
if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Queue removeElement failed: %d\n", ioReturnValue);
return;
}
}
JNIEXPORT jboolean JNICALL Java_net_java_games_input_OSXHIDQueue_nGetNextEvent(JNIEnv *env, jclass unused, jlong address, jobject event_return) {
IOHIDQueueInterface **queue = (IOHIDQueueInterface **)(intptr_t)address;
IOHIDEventStruct event;
AbsoluteTime zeroTime = {0, 0};
IOReturn ioReturnValue = (*queue)->getNextEvent(queue, &event, zeroTime, 0);
if (ioReturnValue == kIOReturnUnderrun) {
return JNI_FALSE;
} else if (ioReturnValue != kIOReturnSuccess) {
throwIOException(env, "Queue getNextEvent failed: %d\n", ioReturnValue);
return JNI_FALSE;
}
copyEvent(env, &event, event_return);
if (event.longValue != NULL) {
free(event.longValue);
}
return JNI_TRUE;
}

51
plugins/awt/build.xml Normal file
View file

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="all" name="AWT Plugin">
<target name="init">
<mkdir dir="classes"/>
<mkdir dir="bin"/>
</target>
<target depends="init" name="compile">
<javac debug="true" deprecation="true" destdir="classes" source="1.4" target="1.4" srcdir="src">
<classpath>
<pathelement location="../../coreAPI/bin/jinput-core.jar"/>
<pathelement location="../../lib/jutils.jar"/>
</classpath>
</javac>
</target>
<target depends="init,compile" name="jar">
<jar jarfile="bin/awtinput.jar" compress="true" basedir="classes">
<include name="**/*.class"/>
</jar>
</target>
<target depends="jar" description="Build everything." name="all">
</target>
<target name="javadoc" depends="init" description="Javadoc for AWT plugin for JInput.">
<mkdir dir="apidocs"/>
<javadoc packagenames="net.java.games.input.*"
destdir="apidocs"
additionalparam="-source 1.4"
link="../../../coreAPI/apidocs">
<sourcepath>
<pathelement location="src"/>
</sourcepath>
<classpath>
<pathelement location="../../coreAPI/bin/jinput-core.jar"/>
<pathelement location="../../lib/jutils.jar"/>
</classpath>
</javadoc>
</target>
<target description="Clean all build products." name="clean">
<delete failonerror="no">
<fileset dir="classes"/>
</delete>
<delete dir="bin/awtinput.jar" failonerror="no"/>
<delete dir="apidoc" failonerror="no"/>
</target>
</project>

32
plugins/awt/pom.xml Normal file
View file

@ -0,0 +1,32 @@
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>awt-plugin</artifactId>
<packaging>jar</packaging>
<name>JInput - AWT Plugin</name>
<parent>
<groupId>net.java.jinput</groupId>
<artifactId>plugins</artifactId>
<version>2.0.10-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>net.java.jinput</groupId>
<artifactId>coreapi</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<!-- <plugin> -->
<!-- <artifactId>maven-javadoc-plugin</artifactId> -->
<!-- </plugin> -->
</plugins>
</build>
</project>

View file

@ -0,0 +1,51 @@
/**
* Copyright (C) 2004 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
import net.java.games.util.plugins.Plugin;
/**
* @author Jeremy
* @author elias
*/
public class AWTEnvironmentPlugin extends ControllerEnvironment implements Plugin {
private final Controller[] controllers;
public AWTEnvironmentPlugin() {
this.controllers = new Controller[]{new AWTKeyboard(), new AWTMouse()};
}
public Controller[] getControllers() {
return controllers;
}
public boolean isSupported() {
return true;
}
}

View file

@ -0,0 +1,289 @@
/**
* Copyright (C) 2004 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.awt.event.KeyEvent;
/**
* @author Jeremy
* @author elias
*/
final class AWTKeyMap {
public final static Component.Identifier.Key mapKeyCode(int key_code) {
switch (key_code) {
case KeyEvent.VK_0:
return Component.Identifier.Key._0;
case KeyEvent.VK_1:
return Component.Identifier.Key._1;
case KeyEvent.VK_2:
return Component.Identifier.Key._2;
case KeyEvent.VK_3:
return Component.Identifier.Key._3;
case KeyEvent.VK_4:
return Component.Identifier.Key._4;
case KeyEvent.VK_5:
return Component.Identifier.Key._5;
case KeyEvent.VK_6:
return Component.Identifier.Key._6;
case KeyEvent.VK_7:
return Component.Identifier.Key._7;
case KeyEvent.VK_8:
return Component.Identifier.Key._8;
case KeyEvent.VK_9:
return Component.Identifier.Key._9;
case KeyEvent.VK_Q:
return Component.Identifier.Key.Q;
case KeyEvent.VK_W:
return Component.Identifier.Key.W;
case KeyEvent.VK_E:
return Component.Identifier.Key.E;
case KeyEvent.VK_R:
return Component.Identifier.Key.R;
case KeyEvent.VK_T:
return Component.Identifier.Key.T;
case KeyEvent.VK_Y:
return Component.Identifier.Key.Y;
case KeyEvent.VK_U:
return Component.Identifier.Key.U;
case KeyEvent.VK_I:
return Component.Identifier.Key.I;
case KeyEvent.VK_O:
return Component.Identifier.Key.O;
case KeyEvent.VK_P:
return Component.Identifier.Key.P;
case KeyEvent.VK_A:
return Component.Identifier.Key.A;
case KeyEvent.VK_S:
return Component.Identifier.Key.S;
case KeyEvent.VK_D:
return Component.Identifier.Key.D;
case KeyEvent.VK_F:
return Component.Identifier.Key.F;
case KeyEvent.VK_G:
return Component.Identifier.Key.G;
case KeyEvent.VK_H:
return Component.Identifier.Key.H;
case KeyEvent.VK_J:
return Component.Identifier.Key.J;
case KeyEvent.VK_K:
return Component.Identifier.Key.K;
case KeyEvent.VK_L:
return Component.Identifier.Key.L;
case KeyEvent.VK_Z:
return Component.Identifier.Key.Z;
case KeyEvent.VK_X:
return Component.Identifier.Key.X;
case KeyEvent.VK_C:
return Component.Identifier.Key.C;
case KeyEvent.VK_V:
return Component.Identifier.Key.V;
case KeyEvent.VK_B:
return Component.Identifier.Key.B;
case KeyEvent.VK_N:
return Component.Identifier.Key.N;
case KeyEvent.VK_M:
return Component.Identifier.Key.M;
case KeyEvent.VK_F1:
return Component.Identifier.Key.F1;
case KeyEvent.VK_F2:
return Component.Identifier.Key.F2;
case KeyEvent.VK_F3:
return Component.Identifier.Key.F3;
case KeyEvent.VK_F4:
return Component.Identifier.Key.F4;
case KeyEvent.VK_F5:
return Component.Identifier.Key.F5;
case KeyEvent.VK_F6:
return Component.Identifier.Key.F6;
case KeyEvent.VK_F7:
return Component.Identifier.Key.F7;
case KeyEvent.VK_F8:
return Component.Identifier.Key.F8;
case KeyEvent.VK_F9:
return Component.Identifier.Key.F9;
case KeyEvent.VK_F10:
return Component.Identifier.Key.F10;
case KeyEvent.VK_F11:
return Component.Identifier.Key.F11;
case KeyEvent.VK_F12:
return Component.Identifier.Key.F12;
case KeyEvent.VK_ESCAPE:
return Component.Identifier.Key.ESCAPE;
case KeyEvent.VK_MINUS:
return Component.Identifier.Key.MINUS;
case KeyEvent.VK_EQUALS:
return Component.Identifier.Key.EQUALS;
case KeyEvent.VK_BACK_SPACE:
return Component.Identifier.Key.BACKSLASH;
case KeyEvent.VK_TAB:
return Component.Identifier.Key.TAB;
case KeyEvent.VK_OPEN_BRACKET:
return Component.Identifier.Key.LBRACKET;
case KeyEvent.VK_CLOSE_BRACKET:
return Component.Identifier.Key.RBRACKET;
case KeyEvent.VK_SEMICOLON:
return Component.Identifier.Key.SEMICOLON;
case KeyEvent.VK_QUOTE:
return Component.Identifier.Key.APOSTROPHE;
case KeyEvent.VK_NUMBER_SIGN:
return Component.Identifier.Key.GRAVE;
case KeyEvent.VK_BACK_SLASH:
return Component.Identifier.Key.BACKSLASH;
case KeyEvent.VK_PERIOD:
return Component.Identifier.Key.PERIOD;
case KeyEvent.VK_SLASH:
return Component.Identifier.Key.SLASH;
case KeyEvent.VK_MULTIPLY:
return Component.Identifier.Key.MULTIPLY;
case KeyEvent.VK_SPACE:
return Component.Identifier.Key.SPACE;
case KeyEvent.VK_CAPS_LOCK:
return Component.Identifier.Key.CAPITAL;
case KeyEvent.VK_NUM_LOCK:
return Component.Identifier.Key.NUMLOCK;
case KeyEvent.VK_SCROLL_LOCK:
return Component.Identifier.Key.SCROLL;
case KeyEvent.VK_NUMPAD7:
return Component.Identifier.Key.NUMPAD7;
case KeyEvent.VK_NUMPAD8:
return Component.Identifier.Key.NUMPAD8;
case KeyEvent.VK_NUMPAD9:
return Component.Identifier.Key.NUMPAD9;
case KeyEvent.VK_SUBTRACT:
return Component.Identifier.Key.SUBTRACT;
case KeyEvent.VK_NUMPAD4:
return Component.Identifier.Key.NUMPAD4;
case KeyEvent.VK_NUMPAD5:
return Component.Identifier.Key.NUMPAD5;
case KeyEvent.VK_NUMPAD6:
return Component.Identifier.Key.NUMPAD6;
case KeyEvent.VK_ADD:
return Component.Identifier.Key.ADD;
case KeyEvent.VK_NUMPAD1:
return Component.Identifier.Key.NUMPAD1;
case KeyEvent.VK_NUMPAD2:
return Component.Identifier.Key.NUMPAD2;
case KeyEvent.VK_NUMPAD3:
return Component.Identifier.Key.NUMPAD3;
case KeyEvent.VK_NUMPAD0:
return Component.Identifier.Key.NUMPAD0;
case KeyEvent.VK_DECIMAL:
return Component.Identifier.Key.DECIMAL;
case KeyEvent.VK_KANA:
return Component.Identifier.Key.KANA;
case KeyEvent.VK_CONVERT:
return Component.Identifier.Key.CONVERT;
case KeyEvent.VK_NONCONVERT:
return Component.Identifier.Key.NOCONVERT;
case KeyEvent.VK_CIRCUMFLEX:
return Component.Identifier.Key.CIRCUMFLEX;
case KeyEvent.VK_AT:
return Component.Identifier.Key.AT;
case KeyEvent.VK_COLON:
return Component.Identifier.Key.COLON;
case KeyEvent.VK_UNDERSCORE:
return Component.Identifier.Key.UNDERLINE;
case KeyEvent.VK_KANJI:
return Component.Identifier.Key.KANJI;
case KeyEvent.VK_STOP:
return Component.Identifier.Key.STOP;
case KeyEvent.VK_DIVIDE:
return Component.Identifier.Key.DIVIDE;
case KeyEvent.VK_PAUSE:
return Component.Identifier.Key.PAUSE;
case KeyEvent.VK_HOME:
return Component.Identifier.Key.HOME;
case KeyEvent.VK_UP:
return Component.Identifier.Key.UP;
case KeyEvent.VK_PAGE_UP:
return Component.Identifier.Key.PAGEUP;
case KeyEvent.VK_LEFT:
return Component.Identifier.Key.LEFT;
case KeyEvent.VK_RIGHT:
return Component.Identifier.Key.RIGHT;
case KeyEvent.VK_END:
return Component.Identifier.Key.END;
case KeyEvent.VK_DOWN:
return Component.Identifier.Key.DOWN;
case KeyEvent.VK_PAGE_DOWN:
return Component.Identifier.Key.PAGEDOWN;
case KeyEvent.VK_INSERT:
return Component.Identifier.Key.INSERT;
case KeyEvent.VK_DELETE:
return Component.Identifier.Key.DELETE;
default:
return Component.Identifier.Key.UNKNOWN;
}
}
public final static Component.Identifier.Key map(KeyEvent event) {
int key_code = event.getKeyCode();
int key_location = event.getKeyLocation();
switch (key_code) {
case KeyEvent.VK_CONTROL:
if (key_location == KeyEvent.KEY_LOCATION_RIGHT)
return Component.Identifier.Key.RCONTROL;
else
return Component.Identifier.Key.LCONTROL;
case KeyEvent.VK_SHIFT:
if (key_location == KeyEvent.KEY_LOCATION_RIGHT)
return Component.Identifier.Key.RSHIFT;
else
return Component.Identifier.Key.LSHIFT;
case KeyEvent.VK_ALT:
if (key_location == KeyEvent.KEY_LOCATION_RIGHT)
return Component.Identifier.Key.RALT;
else
return Component.Identifier.Key.LALT;
//this is 1.5 only
/* case KeyEvent.VK_WINDOWS:
if (key_location == KeyEvent.KEY_LOCATION_RIGHT)
return Component.Identifier.Key.RWIN;
else
return Component.Identifier.Key.LWIN;*/
case KeyEvent.VK_ENTER:
if (key_location == KeyEvent.KEY_LOCATION_NUMPAD)
return Component.Identifier.Key.NUMPADENTER;
else
return Component.Identifier.Key.RETURN;
case KeyEvent.VK_COMMA:
if (key_location == KeyEvent.KEY_LOCATION_NUMPAD)
return Component.Identifier.Key.NUMPADCOMMA;
else
return Component.Identifier.Key.COMMA;
default:
return mapKeyCode(key_code);
}
}
}

View file

@ -0,0 +1,170 @@
/*
* Copyright (C) 2004 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* @author Jeremy
* @author elias
*/
final class AWTKeyboard extends Keyboard implements AWTEventListener {
private final List<KeyEvent> awt_events = new ArrayList<>();
private Event[] processed_events;
private int processed_events_index;
protected AWTKeyboard() {
super("AWTKeyboard", createComponents(), new Controller[]{}, new Rumbler[]{});
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
resizeEventQueue(EVENT_QUEUE_DEPTH);
}
private final static Component[] createComponents() {
List<Component> components = new ArrayList<>();
Field[] vkey_fields = KeyEvent.class.getFields();
for (int i = 0; i < vkey_fields.length; i++) {
Field vkey_field = vkey_fields[i];
try {
if (Modifier.isStatic(vkey_field.getModifiers()) && vkey_field.getType() == int.class &&
vkey_field.getName().startsWith("VK_")) {
int vkey_code = vkey_field.getInt(null);
Component.Identifier.Key key_id = AWTKeyMap.mapKeyCode(vkey_code);
if (key_id != Component.Identifier.Key.UNKNOWN)
components.add(new Key(key_id));
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
components.add(new Key(Component.Identifier.Key.RCONTROL));
components.add(new Key(Component.Identifier.Key.LCONTROL));
components.add(new Key(Component.Identifier.Key.RSHIFT));
components.add(new Key(Component.Identifier.Key.LSHIFT));
components.add(new Key(Component.Identifier.Key.RALT));
components.add(new Key(Component.Identifier.Key.LALT));
components.add(new Key(Component.Identifier.Key.NUMPADENTER));
components.add(new Key(Component.Identifier.Key.RETURN));
components.add(new Key(Component.Identifier.Key.NUMPADCOMMA));
components.add(new Key(Component.Identifier.Key.COMMA));
return components.toArray(new Component[]{});
}
private final void resizeEventQueue(int size) {
processed_events = new Event[size];
for (int i = 0; i < processed_events.length; i++)
processed_events[i] = new Event();
processed_events_index = 0;
}
protected final void setDeviceEventQueueSize(int size) throws IOException {
resizeEventQueue(size);
}
public final synchronized void eventDispatched(AWTEvent event) {
if (event instanceof KeyEvent)
awt_events.add((KeyEvent)event);
}
public final synchronized void pollDevice() throws IOException {
for (int i = 0; i < awt_events.size(); i++) {
processEvent(awt_events.get(i));
}
awt_events.clear();
}
private final void processEvent(KeyEvent event) {
Component.Identifier.Key key_id = AWTKeyMap.map(event);
if (key_id == null)
return;
Key key = (Key)getComponent(key_id);
if (key == null)
return;
long nanos = event.getWhen()*1000000L;
if (event.getID() == KeyEvent.KEY_PRESSED) {
//the key was pressed
addEvent(key, 1, nanos);
} else if (event.getID() == KeyEvent.KEY_RELEASED) {
KeyEvent nextPress = (KeyEvent)Toolkit.getDefaultToolkit().getSystemEventQueue().peekEvent(KeyEvent.KEY_PRESSED);
if ((nextPress == null) || (nextPress.getWhen() != event.getWhen())) {
//the key came really came up
addEvent(key, 0, nanos);
}
}
}
private final void addEvent(Key key, float value, long nanos) {
key.setValue(value);
if (processed_events_index < processed_events.length)
processed_events[processed_events_index++].set(key, value, nanos);
}
protected final synchronized boolean getNextDeviceEvent(Event event) throws IOException {
if (processed_events_index == 0)
return false;
processed_events_index--;
event.set(processed_events[0]);
Event tmp = processed_events[0];
processed_events[0] = processed_events[processed_events_index];
processed_events[processed_events_index] = tmp;
return true;
}
private final static class Key extends AbstractComponent {
private float value;
public Key(Component.Identifier.Key key_id) {
super(key_id.getName(), key_id);
}
public final void setValue(float value) {
this.value = value;
}
protected final float poll() {
return value;
}
public final boolean isAnalog() {
return false;
}
public final boolean isRelative() {
return false;
}
}
}

View file

@ -0,0 +1,221 @@
/*
* Copyright (C) 2004 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
/**
* @author Jeremy
* @author elias
*/
final class AWTMouse extends Mouse implements AWTEventListener {
private final static int EVENT_X = 1;
private final static int EVENT_Y = 2;
private final static int EVENT_BUTTON = 4;
private final List<AWTEvent> awt_events = new ArrayList<>();
private final List<AWTEvent> processed_awt_events = new ArrayList<>();
private int event_state = EVENT_X;
protected AWTMouse() {
super("AWTMouse", createComponents(), new Controller[]{}, new Rumbler[]{});
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK);
}
private final static Component[] createComponents() {
return new Component[]{new Axis(Component.Identifier.Axis.X),
new Axis(Component.Identifier.Axis.Y),
new Axis(Component.Identifier.Axis.Z),
new Button(Component.Identifier.Button.LEFT),
new Button(Component.Identifier.Button.MIDDLE),
new Button(Component.Identifier.Button.RIGHT)};
}
private final void processButtons(int button_enum, float value) {
Button button = getButton(button_enum);
if (button != null)
button.setValue(value);
}
private final Button getButton(int button_enum) {
switch (button_enum) {
case MouseEvent.BUTTON1:
return (Button)getLeft();
case MouseEvent.BUTTON2:
return (Button)getMiddle();
case MouseEvent.BUTTON3:
return (Button)getRight();
case MouseEvent.NOBUTTON:
default:
// Unknown button
return null;
}
}
private final void processEvent(AWTEvent event) throws IOException {
if (event instanceof MouseWheelEvent) {
MouseWheelEvent mwe = (MouseWheelEvent)event;
Axis wheel = (Axis)getWheel();
wheel.setValue(wheel.poll() + mwe.getWheelRotation());
} else if (event instanceof MouseEvent) {
MouseEvent me = (MouseEvent)event;
Axis x = (Axis)getX();
Axis y = (Axis)getY();
x.setValue(me.getX());
y.setValue(me.getY());
switch (me.getID()) {
case MouseEvent.MOUSE_PRESSED:
processButtons(me.getButton(), 1f);
break;
case MouseEvent.MOUSE_RELEASED:
processButtons(me.getButton(), 0f);
break;
default:
break;
}
}
}
public final synchronized void pollDevice() throws IOException {
Axis wheel = (Axis)getWheel();
wheel.setValue(0);
for (int i = 0; i < awt_events.size(); i++) {
AWTEvent event = awt_events.get(i);
processEvent(event);
processed_awt_events.add(event);
}
awt_events.clear();
}
protected final synchronized boolean getNextDeviceEvent(Event event) throws IOException {
while (true) {
if (processed_awt_events.isEmpty())
return false;
AWTEvent awt_event = processed_awt_events.get(0);
if (awt_event instanceof MouseWheelEvent) {
MouseWheelEvent awt_wheel_event = (MouseWheelEvent)awt_event;
long nanos = awt_wheel_event.getWhen()*1000000L;
event.set(getWheel(), awt_wheel_event.getWheelRotation(), nanos);
processed_awt_events.remove(0);
} else if (awt_event instanceof MouseEvent) {
MouseEvent mouse_event = (MouseEvent)awt_event;
long nanos = mouse_event.getWhen()*1000000L;
switch (event_state) {
case EVENT_X:
event_state = EVENT_Y;
event.set(getX(), mouse_event.getX(), nanos);
return true;
case EVENT_Y:
event_state = EVENT_BUTTON;
event.set(getY(), mouse_event.getY(), nanos);
return true;
case EVENT_BUTTON:
processed_awt_events.remove(0);
event_state = EVENT_X;
Button button = getButton(mouse_event.getButton());
if (button != null) {
switch (mouse_event.getID()) {
case MouseEvent.MOUSE_PRESSED:
event.set(button, 1f, nanos);
return true;
case MouseEvent.MOUSE_RELEASED:
event.set(button, 0f, nanos);
return true;
default:
break;
}
}
break;
default:
throw new RuntimeException("Unknown event state: " + event_state);
}
}
}
}
public final synchronized void eventDispatched(AWTEvent event) {
awt_events.add(event);
}
final static class Axis extends AbstractComponent {
private float value;
public Axis(Component.Identifier.Axis axis_id) {
super(axis_id.getName(), axis_id);
}
public final boolean isRelative() {
return false;
}
public final boolean isAnalog() {
return true;
}
protected final void setValue(float value) {
this.value = value;
}
protected final float poll() throws IOException {
return value;
}
}
final static class Button extends AbstractComponent {
private float value;
public Button(Component.Identifier.Button button_id) {
super(button_id.getName(), button_id);
}
protected final void setValue(float value) {
this.value = value;
}
protected final float poll() throws IOException {
return value;
}
public final boolean isAnalog() {
return false;
}
public final boolean isRelative() {
return false;
}
}
}

View file

@ -0,0 +1,118 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <jni.h>
#include "util.h"
static jstring sprintfJavaString(JNIEnv *env, const char *format, va_list ap) {
#define BUFFER_SIZE 4000
char buffer[BUFFER_SIZE];
jstring str;
#ifdef _MSC_VER
vsnprintf_s(buffer, BUFFER_SIZE, _TRUNCATE, format, ap);
#else
vsnprintf(buffer, BUFFER_SIZE, format, ap);
#endif
buffer[BUFFER_SIZE - 1] = '\0';
str = (*env)->NewStringUTF(env, buffer);
return str;
}
void printfJava(JNIEnv *env, const char *format, ...) {
jstring str;
jclass org_lwjgl_LWJGLUtil_class;
jmethodID log_method;
va_list ap;
va_start(ap, format);
str = sprintfJavaString(env, format, ap);
va_end(ap);
org_lwjgl_LWJGLUtil_class = (*env)->FindClass(env, "net/java/games/input/ControllerEnvironment");
if (org_lwjgl_LWJGLUtil_class == NULL)
return;
log_method = (*env)->GetStaticMethodID(env, org_lwjgl_LWJGLUtil_class, "log", "(Ljava/lang/String;)V");
if (log_method == NULL)
return;
(*env)->CallStaticVoidMethod(env, org_lwjgl_LWJGLUtil_class, log_method, str);
}
static void throwException(JNIEnv * env, const char *exception_name, const char *format, va_list ap) {
jstring str;
jobject exception;
if ((*env)->ExceptionCheck(env) == JNI_TRUE)
return; // The JVM crashes if we try to throw two exceptions from one native call
str = sprintfJavaString(env, format, ap);
exception = newJObject(env, exception_name, "(Ljava/lang/String;)V", str);
(*env)->Throw(env, exception);
}
void throwRuntimeException(JNIEnv * env, const char *format, ...) {
va_list ap;
va_start(ap, format);
throwException(env, "java/lang/RuntimeException", format, ap);
va_end(ap);
}
void throwIOException(JNIEnv * env, const char *format, ...) {
va_list ap;
va_start(ap, format);
throwException(env, "java/io/IOException", format, ap);
va_end(ap);
}
jobject newJObject(JNIEnv * env, const char *class_name, const char *constructor_signature, ...) {
va_list ap;
jclass clazz;
jmethodID constructor;
jobject obj;
clazz = (*env)->FindClass(env, class_name);
if (clazz == NULL)
return NULL;
constructor = (*env)->GetMethodID(env, clazz, "<init>", constructor_signature);
if (constructor == NULL)
return NULL;
va_start(ap, constructor_signature);
obj = (*env)->NewObjectV(env, clazz, constructor, ap);
va_end(ap);
return obj;
}

View file

@ -0,0 +1,53 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <jni.h>
#ifdef _MSC_VER
#include <Basetsd.h>
#else
#include <inttypes.h>
#endif
extern void printfJava(JNIEnv *env, const char *format, ...);
extern void throwRuntimeException(JNIEnv * env, const char *format, ...);
extern void throwIOException(JNIEnv * env, const char *format, ...);
extern jobject newJObject(JNIEnv * env, const char *class_name, const char *constructor_signature, ...);

45
plugins/linux/build.xml Normal file
View file

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="compileNativeJinputLib" name="Linux Plugin">
<property name="libname64" value="libjinput-linux64.so"/>
<property name="libname32" value="libjinput-linux.so"/>
<target name="init">
<mkdir dir="target/natives"/>
</target>
<target name="createNativeDefinitions.java">
<exec dir="src/main/native" executable="gawk" os="Linux" output="../java/net/java/games/input/NativeDefinitions.java">
<arg line="-f"/>
<arg line="getDefinitions"/>
<arg line="/usr/include/linux/input.h"/>
</exec>
</target>
<target depends="init" name="compileNativeJinputLib">
<exec executable="uname" outputproperty="hwplatform">
<arg value="-m"/>
</exec>
<condition property="libname" value="${libname64}" else="${libname32}">
<equals arg1="${hwplatform}" arg2="x86_64"/>
</condition>
<apply dir="target/natives" executable="cc" os="Linux" dest="target/natives" skipemptyfilesets="true" failonerror="true">
<arg line="-O2 -Wall -c -fPIC"/>
<arg value="-I${java.home}/include"/>
<arg value="-I${java.home}/include/linux"/>
<arg value="-I${java.home}/../include"/>
<arg value="-I${java.home}/../include/linux"/>
<arg value="-I../../../common/src/native"/>
<arg value="-I../generated-sources/natives"/>
<mapper type="glob" from="*.c" to="*.o"/>
<fileset dir="src/main/native" includes="*.c"/>
<fileset dir="../common/src/native" includes="*.c"/>
</apply>
<apply dir="target/natives" parallel="true" executable="cc" os="Linux" failonerror="true">
<arg line="-shared -O2 -Wall -o ${libname}"/>
<fileset dir="target/natives" includes="*.o"/>
</apply>
<apply dir="target/natives" parallel="true" executable="strip" os="Linux" failonerror="true">
<fileset file="target/natives/${libname}"/>
</apply>
</target>
</project>

69
plugins/linux/pom.xml Normal file
View file

@ -0,0 +1,69 @@
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>linux-plugin</artifactId>
<packaging>jar</packaging>
<name>JInput - Linux Plugin</name>
<parent>
<groupId>net.java.jinput</groupId>
<artifactId>plugins</artifactId>
<version>2.0.10-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>net.java.jinput</groupId>
<artifactId>coreapi</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>compile</phase>
<configuration>
<target>
<ant dir="." target="compileNativeJinputLib"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classesDirectory>${project.build.directory}/natives</classesDirectory>
<classifier>natives-linux</classifier>
<includes>
<include>*.so</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View file

@ -0,0 +1,69 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
/**
* @author elias
*/
final class LinuxAbsInfo {
private int value;
private int minimum;
private int maximum;
private int fuzz;
private int flat;
public final void set(int value, int min, int max, int fuzz, int flat) {
this.value = value;
this.minimum = min;
this.maximum = max;
this.fuzz = fuzz;
this.flat = flat;
}
public final String toString() {
return "AbsInfo: value = " + value + " | min = " + minimum + " | max = " + maximum + " | fuzz = " + fuzz + " | flat = " + flat;
}
public final int getValue() {
return value;
}
final int getMax() {
return maximum;
}
final int getMin() {
return minimum;
}
final int getFlat() {
return flat;
}
final int getFuzz() {
return fuzz;
}
}

View file

@ -0,0 +1,74 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** Represents a Linux controller
* @author elias
* @version 1.0
*/
final class LinuxAbstractController extends AbstractController {
private final PortType port;
private final LinuxEventDevice device;
private final Type type;
protected LinuxAbstractController(LinuxEventDevice device, Component[] components, Controller[] children, Rumbler[] rumblers, Type type) throws IOException {
super(device.getName(), components, children, rumblers);
this.device = device;
this.port = device.getPortType();
this.type = type;
}
public final PortType getPortType() {
return port;
}
public final void pollDevice() throws IOException {
device.pollKeyStates();
}
protected final boolean getNextDeviceEvent(Event event) throws IOException {
return LinuxControllers.getNextDeviceEvent(event, device);
}
public Type getType() {
return type;
}
}

View file

@ -0,0 +1,62 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
/**
* @author elias
*/
final class LinuxAxisDescriptor {
private int type;
private int code;
public final void set(int type, int code) {
this.type = type;
this.code = code;
}
public final int getType() {
return type;
}
public final int getCode() {
return code;
}
public final int hashCode() {
return type ^ code;
}
public final boolean equals(Object other) {
if (!(other instanceof LinuxAxisDescriptor))
return false;
LinuxAxisDescriptor descriptor = (LinuxAxisDescriptor)other;
return descriptor.type == type && descriptor.code == code;
}
public final String toString() {
return "LinuxAxis: type = 0x" + Integer.toHexString(type) + ", code = 0x" + Integer.toHexString(code);
}
}

View file

@ -0,0 +1,32 @@
package net.java.games.input;
import java.io.IOException;
public class LinuxCombinedController extends AbstractController {
private LinuxAbstractController eventController;
private LinuxJoystickAbstractController joystickController;
LinuxCombinedController(LinuxAbstractController eventController, LinuxJoystickAbstractController joystickController) {
super(eventController.getName(), joystickController.getComponents(), eventController.getControllers(), eventController.getRumblers());
this.eventController = eventController;
this.joystickController = joystickController;
}
protected boolean getNextDeviceEvent(Event event) throws IOException {
return joystickController.getNextDeviceEvent(event);
}
public final PortType getPortType() {
return eventController.getPortType();
}
public final void pollDevice() throws IOException {
eventController.pollDevice();
joystickController.pollDevice();
}
public Type getType() {
return eventController.getType();
}
}

View file

@ -0,0 +1,78 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** Represents a linux Axis
* @author elias
* @version 1.0
*/
class LinuxComponent extends AbstractComponent {
private final LinuxEventComponent component;
public LinuxComponent(LinuxEventComponent component) {
super(component.getIdentifier().getName(), component.getIdentifier());
this.component = component;
}
public final boolean isRelative() {
return component.isRelative();
}
public final boolean isAnalog() {
return component.isAnalog();
}
protected float poll() throws IOException {
return convertValue(LinuxControllers.poll(component), component.getDescriptor());
}
float convertValue(float value, LinuxAxisDescriptor descriptor) {
return getComponent().convertValue(value);
}
public final float getDeadZone() {
return component.getDeadZone();
}
public final LinuxEventComponent getComponent() {
return component;
}
}

View file

@ -0,0 +1,42 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.io.IOException;
/**
* @author elias
*/
final class LinuxConstantFF extends LinuxForceFeedbackEffect {
public LinuxConstantFF(LinuxEventDevice device) throws IOException {
super(device);
}
protected final int upload(int id, float intensity) throws IOException {
int scaled_intensity = Math.round(intensity*0x7fff);
return getDevice().uploadConstantEffect(id, 0, 0, 0, 0, 0, scaled_intensity, 0, 0, 0, 0);
}
}

View file

@ -0,0 +1,81 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** helper methods for Linux specific Controllers
* @author elias
* @version 1.0
*/
final class LinuxControllers {
private final static LinuxEvent linux_event = new LinuxEvent();
/* Declared synchronized to protect linux_event */
public final static synchronized boolean getNextDeviceEvent(Event event, LinuxEventDevice device) throws IOException {
while (device.getNextEvent(linux_event)) {
LinuxAxisDescriptor descriptor = linux_event.getDescriptor();
LinuxComponent component = device.mapDescriptor(descriptor);
if (component != null) {
float value = component.convertValue(linux_event.getValue(), descriptor);
event.set(component, value, linux_event.getNanos());
return true;
}
}
return false;
}
private final static LinuxAbsInfo abs_info = new LinuxAbsInfo();
/* Declared synchronized to protect abs_info */
public final static synchronized float poll(LinuxEventComponent event_component) throws IOException {
int native_type = event_component.getDescriptor().getType();
switch (native_type) {
case NativeDefinitions.EV_KEY:
int native_code = event_component.getDescriptor().getCode();
float state = event_component.getDevice().isKeySet(native_code) ? 1f : 0f;
return state;
case NativeDefinitions.EV_ABS:
event_component.getAbsInfo(abs_info);
return abs_info.getValue();
default:
throw new RuntimeException("Unkown native_type: " + native_type);
}
}
}

View file

@ -0,0 +1,39 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/**
* @author elias
*/
interface LinuxDevice {
void close() throws IOException;
}

View file

@ -0,0 +1,62 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.io.IOException;
abstract class LinuxDeviceTask {
public final static int INPROGRESS = 1;
public final static int COMPLETED = 2;
public final static int FAILED = 3;
private Object result;
private IOException exception;
private int state = INPROGRESS;
public final void doExecute() {
try {
result = execute();
state = COMPLETED;
} catch (IOException e) {
exception = e;
state = FAILED;
}
}
public final IOException getException() {
return exception;
}
public final Object getResult() {
return result;
}
public final int getState() {
return state;
}
protected abstract Object execute() throws IOException;
}

View file

@ -0,0 +1,91 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
/**
* Linux doesn't have proper support for force feedback
* from different threads since it relies on PIDs
* to determine ownership of a particular effect slot.
* Therefore we have to hack around this by
* making sure everything related to FF
* (including the final device close that performs
* and implicit deletion of all the process' effects)
* is run on a single thread.
*/
final class LinuxDeviceThread extends Thread {
private final List<LinuxDeviceTask> tasks = new ArrayList<>();
public LinuxDeviceThread() {
setDaemon(true);
start();
}
public synchronized final void run() {
while (true) {
if (!tasks.isEmpty()) {
LinuxDeviceTask task = tasks.remove(0);
task.doExecute();
synchronized (task) {
task.notify();
}
} else {
try {
wait();
} catch (InterruptedException e) {
// ignore
}
}
}
}
public final Object execute(LinuxDeviceTask task) throws IOException {
synchronized (this) {
tasks.add(task);
notify();
}
synchronized (task) {
while (task.getState() == LinuxDeviceTask.INPROGRESS) {
try {
task.wait();
} catch (InterruptedException e) {
// ignore
}
}
}
switch (task.getState()) {
case LinuxDeviceTask.COMPLETED:
return task.getResult();
case LinuxDeviceTask.FAILED:
throw task.getException();
default:
throw new RuntimeException("Invalid task state: " + task.getState());
}
}
}

View file

@ -0,0 +1,477 @@
/*
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import net.java.games.util.plugins.Plugin;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
import java.io.File;
import java.io.FilenameFilter;
import java.security.AccessController;
import java.security.PrivilegedAction;
/** Environment plugin for linux
* @author elias
* @author Jeremy Booth (jeremy@newdawnsoftware.com)
*/
public final class LinuxEnvironmentPlugin extends ControllerEnvironment implements Plugin {
private final static String LIBNAME = "jinput-linux";
private final static String POSTFIX64BIT = "64";
private static boolean supported = false;
private final Controller[] controllers;
private final List<LinuxDevice> devices = new ArrayList<LinuxDevice>();
private final static LinuxDeviceThread device_thread = new LinuxDeviceThread();
/**
* Static utility method for loading native libraries.
* It will try to load from either the path given by
* the net.java.games.input.librarypath property
* or through System.loadLibrary().
*
*/
static void loadLibrary(final String lib_name) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
String lib_path = System.getProperty("net.java.games.input.librarypath");
try {
if(lib_path != null)
System.load(lib_path + File.separator + System.mapLibraryName(lib_name));
else
System.loadLibrary(lib_name);
} catch(UnsatisfiedLinkError e) {
log("Failed to load library: " + e.getMessage());
e.printStackTrace();
supported = false;
}
return null;
});
}
static String getPrivilegedProperty(final String property) {
return AccessController.doPrivileged((PrivilegedAction<String>)() -> System.getProperty(property));
}
static String getPrivilegedProperty(final String property, final String default_value) {
return AccessController.doPrivileged((PrivilegedAction<String>)() -> System.getProperty(property, default_value));
}
static {
String osName = getPrivilegedProperty("os.name", "").trim();
if(osName.equals("Linux")) {
supported = true;
if("i386".equals(getPrivilegedProperty("os.arch"))) {
loadLibrary(LIBNAME);
} else {
loadLibrary(LIBNAME + POSTFIX64BIT);
}
}
}
public final static Object execute(LinuxDeviceTask task) throws IOException {
return device_thread.execute(task);
}
public LinuxEnvironmentPlugin() {
if(isSupported()) {
this.controllers = enumerateControllers();
log("Linux plugin claims to have found " + controllers.length + " controllers");
AccessController.doPrivileged((PrivilegedAction<Void>)() -> {
Runtime.getRuntime().addShutdownHook(new ShutdownHook());
return null;
});
} else {
controllers = new Controller[0];
}
}
/** Returns a list of all controllers available to this environment,
* or an empty array if there are no controllers in this environment.
* @return Returns a list of all controllers available to this environment,
* or an empty array if there are no controllers in this environment.
*/
public final Controller[] getControllers() {
return controllers;
}
private final static Component[] createComponents(List<LinuxEventComponent> event_components, LinuxEventDevice device) {
LinuxEventComponent[][] povs = new LinuxEventComponent[4][2];
List<LinuxComponent> components = new ArrayList<>();
for(int i = 0; i < event_components.size(); i++) {
LinuxEventComponent event_component = event_components.get(i);
Component.Identifier identifier = event_component.getIdentifier();
if(identifier == Component.Identifier.Axis.POV) {
int native_code = event_component.getDescriptor().getCode();
switch(native_code) {
case NativeDefinitions.ABS_HAT0X:
povs[0][0] = event_component;
break;
case NativeDefinitions.ABS_HAT0Y:
povs[0][1] = event_component;
break;
case NativeDefinitions.ABS_HAT1X:
povs[1][0] = event_component;
break;
case NativeDefinitions.ABS_HAT1Y:
povs[1][1] = event_component;
break;
case NativeDefinitions.ABS_HAT2X:
povs[2][0] = event_component;
break;
case NativeDefinitions.ABS_HAT2Y:
povs[2][1] = event_component;
break;
case NativeDefinitions.ABS_HAT3X:
povs[3][0] = event_component;
break;
case NativeDefinitions.ABS_HAT3Y:
povs[3][1] = event_component;
break;
default:
log("Unknown POV instance: " + native_code);
break;
}
} else if(identifier != null) {
LinuxComponent component = new LinuxComponent(event_component);
components.add(component);
device.registerComponent(event_component.getDescriptor(), component);
}
}
for(int i = 0; i < povs.length; i++) {
LinuxEventComponent x = povs[i][0];
LinuxEventComponent y = povs[i][1];
if(x != null && y != null) {
LinuxComponent controller_component = new LinuxPOV(x, y);
components.add(controller_component);
device.registerComponent(x.getDescriptor(), controller_component);
device.registerComponent(y.getDescriptor(), controller_component);
}
}
Component[] components_array = new Component[components.size()];
components.toArray(components_array);
return components_array;
}
private final static Mouse createMouseFromDevice(LinuxEventDevice device, Component[] components) throws IOException {
Mouse mouse = new LinuxMouse(device, components, new Controller[]{}, device.getRumblers());
if(mouse.getX() != null && mouse.getY() != null && mouse.getPrimaryButton() != null)
return mouse;
else
return null;
}
private final static Keyboard createKeyboardFromDevice(LinuxEventDevice device, Component[] components) throws IOException {
Keyboard keyboard = new LinuxKeyboard(device, components, new Controller[]{}, device.getRumblers());
return keyboard;
}
private final static Controller createJoystickFromDevice(LinuxEventDevice device, Component[] components, Controller.Type type) throws IOException {
Controller joystick = new LinuxAbstractController(device, components, new Controller[]{}, device.getRumblers(), type);
return joystick;
}
private final static Controller createControllerFromDevice(LinuxEventDevice device) throws IOException {
List<LinuxEventComponent> event_components = device.getComponents();
Component[] components = createComponents(event_components, device);
Controller.Type type = device.getType();
if(type == Controller.Type.MOUSE) {
return createMouseFromDevice(device, components);
} else if(type == Controller.Type.KEYBOARD) {
return createKeyboardFromDevice(device, components);
} else if(type == Controller.Type.STICK || type == Controller.Type.GAMEPAD) {
return createJoystickFromDevice(device, components, type);
} else
return null;
}
private final Controller[] enumerateControllers() {
List<Controller> controllers = new ArrayList<>();
List<Controller> eventControllers = new ArrayList<>();
List<Controller> jsControllers = new ArrayList<>();
enumerateEventControllers(eventControllers);
enumerateJoystickControllers(jsControllers);
for(int i = 0; i < eventControllers.size(); i++) {
for(int j = 0; j < jsControllers.size(); j++) {
Controller evController = eventControllers.get(i);
Controller jsController = jsControllers.get(j);
// compare
// Check if the nodes have the same name
if(evController.getName().equals(jsController.getName())) {
// Check they have the same component count
Component[] evComponents = evController.getComponents();
Component[] jsComponents = jsController.getComponents();
if(evComponents.length == jsComponents.length) {
boolean foundADifference = false;
// check the component pairs are of the same type
for(int k = 0; k < evComponents.length; k++) {
// Check the type of the component is the same
if(!(evComponents[k].getIdentifier() == jsComponents[k].getIdentifier())) {
foundADifference = true;
}
}
if(!foundADifference) {
controllers.add(new LinuxCombinedController((LinuxAbstractController) eventControllers.remove(i), (LinuxJoystickAbstractController) jsControllers.remove(j)));
i--;
j--;
break;
}
}
}
}
}
controllers.addAll(eventControllers);
controllers.addAll(jsControllers);
Controller[] controllers_array = new Controller[controllers.size()];
controllers.toArray(controllers_array);
return controllers_array;
}
private final static Component.Identifier.Button getButtonIdentifier(int index) {
switch(index) {
case 0:
return Component.Identifier.Button._0;
case 1:
return Component.Identifier.Button._1;
case 2:
return Component.Identifier.Button._2;
case 3:
return Component.Identifier.Button._3;
case 4:
return Component.Identifier.Button._4;
case 5:
return Component.Identifier.Button._5;
case 6:
return Component.Identifier.Button._6;
case 7:
return Component.Identifier.Button._7;
case 8:
return Component.Identifier.Button._8;
case 9:
return Component.Identifier.Button._9;
case 10:
return Component.Identifier.Button._10;
case 11:
return Component.Identifier.Button._11;
case 12:
return Component.Identifier.Button._12;
case 13:
return Component.Identifier.Button._13;
case 14:
return Component.Identifier.Button._14;
case 15:
return Component.Identifier.Button._15;
case 16:
return Component.Identifier.Button._16;
case 17:
return Component.Identifier.Button._17;
case 18:
return Component.Identifier.Button._18;
case 19:
return Component.Identifier.Button._19;
case 20:
return Component.Identifier.Button._20;
case 21:
return Component.Identifier.Button._21;
case 22:
return Component.Identifier.Button._22;
case 23:
return Component.Identifier.Button._23;
case 24:
return Component.Identifier.Button._24;
case 25:
return Component.Identifier.Button._25;
case 26:
return Component.Identifier.Button._26;
case 27:
return Component.Identifier.Button._27;
case 28:
return Component.Identifier.Button._28;
case 29:
return Component.Identifier.Button._29;
case 30:
return Component.Identifier.Button._30;
case 31:
return Component.Identifier.Button._31;
default:
return null;
}
}
private final static Controller createJoystickFromJoystickDevice(LinuxJoystickDevice device) {
List<AbstractComponent> components = new ArrayList<>();
byte[] axisMap = device.getAxisMap();
char[] buttonMap = device.getButtonMap();
LinuxJoystickAxis[] hatBits = new LinuxJoystickAxis[6];
for(int i = 0; i < device.getNumButtons(); i++) {
Component.Identifier button_id = LinuxNativeTypesMap.getButtonID(buttonMap[i]);
if(button_id != null) {
LinuxJoystickButton button = new LinuxJoystickButton(button_id);
device.registerButton(i, button);
components.add(button);
}
}
for(int i = 0; i < device.getNumAxes(); i++) {
Component.Identifier.Axis axis_id;
axis_id = (Component.Identifier.Axis) LinuxNativeTypesMap.getAbsAxisID(axisMap[i]);
LinuxJoystickAxis axis = new LinuxJoystickAxis(axis_id);
device.registerAxis(i, axis);
if(axisMap[i] == NativeDefinitions.ABS_HAT0X) {
hatBits[0] = axis;
} else if(axisMap[i] == NativeDefinitions.ABS_HAT0Y) {
hatBits[1] = axis;
axis = new LinuxJoystickPOV(Component.Identifier.Axis.POV, hatBits[0], hatBits[1]);
device.registerPOV((LinuxJoystickPOV) axis);
components.add(axis);
} else if(axisMap[i] == NativeDefinitions.ABS_HAT1X) {
hatBits[2] = axis;
} else if(axisMap[i] == NativeDefinitions.ABS_HAT1Y) {
hatBits[3] = axis;
axis = new LinuxJoystickPOV(Component.Identifier.Axis.POV, hatBits[2], hatBits[3]);
device.registerPOV((LinuxJoystickPOV) axis);
components.add(axis);
} else if(axisMap[i] == NativeDefinitions.ABS_HAT2X) {
hatBits[4] = axis;
} else if(axisMap[i] == NativeDefinitions.ABS_HAT2Y) {
hatBits[5] = axis;
axis = new LinuxJoystickPOV(Component.Identifier.Axis.POV, hatBits[4], hatBits[5]);
device.registerPOV((LinuxJoystickPOV) axis);
components.add(axis);
} else {
components.add(axis);
}
}
return new LinuxJoystickAbstractController(device, components.toArray(new Component[]{}), new Controller[]{}, new Rumbler[]{});
}
private final void enumerateJoystickControllers(List<Controller> controllers) {
File[] joystick_device_files = enumerateJoystickDeviceFiles("/dev/input");
if(joystick_device_files == null || joystick_device_files.length == 0) {
joystick_device_files = enumerateJoystickDeviceFiles("/dev");
if(joystick_device_files == null)
return;
}
for(int i = 0; i < joystick_device_files.length; i++) {
File event_file = joystick_device_files[i];
try {
String path = getAbsolutePathPrivileged(event_file);
LinuxJoystickDevice device = new LinuxJoystickDevice(path);
Controller controller = createJoystickFromJoystickDevice(device);
if(controller != null) {
controllers.add(controller);
devices.add(device);
} else
device.close();
} catch(IOException e) {
log("Failed to open device (" + event_file + "): " + e.getMessage());
}
}
}
private final static File[] enumerateJoystickDeviceFiles(final String dev_path) {
final File dev = new File(dev_path);
return listFilesPrivileged(dev, new FilenameFilter() {
public final boolean accept(File dir, String name) {
return name.startsWith("js");
}
});
}
private static String getAbsolutePathPrivileged(final File file) {
return AccessController.doPrivileged((PrivilegedAction<String>) () -> file.getAbsolutePath());
}
private static File[] listFilesPrivileged(final File dir, final FilenameFilter filter) {
return AccessController.doPrivileged((PrivilegedAction<File[]>) () -> {
File[] files = dir.listFiles(filter);
if(files == null) {
log("dir " + dir.getName() + " exists: " + dir.exists() + ", is writable: " + dir.isDirectory());
files = new File[]{};
} else {
Arrays.sort(files, Comparator.comparing(File::getName));
}
return files;
});
}
private final void enumerateEventControllers(List<Controller> controllers) {
final File dev = new File("/dev/input");
File[] event_device_files = listFilesPrivileged(dev, (File dir, String name) -> name.startsWith("event"));
if(event_device_files == null)
return;
for(int i = 0; i < event_device_files.length; i++) {
File event_file = event_device_files[i];
try {
String path = getAbsolutePathPrivileged(event_file);
LinuxEventDevice device = new LinuxEventDevice(path);
try {
Controller controller = createControllerFromDevice(device);
if(controller != null) {
controllers.add(controller);
devices.add(device);
} else
device.close();
} catch(IOException e) {
log("Failed to create Controller: " + e.getMessage());
device.close();
}
} catch(IOException e) {
log("Failed to open device (" + event_file + "): " + e.getMessage());
}
}
}
private final class ShutdownHook extends Thread {
public final void run() {
for(int i = 0; i < devices.size(); i++) {
try {
LinuxDevice device = devices.get(i);
device.close();
} catch(IOException e) {
log("Failed to close device: " + e.getMessage());
}
}
}
}
public boolean isSupported() {
return supported;
}
}

View file

@ -0,0 +1,53 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
/**
* @author elias
*/
final class LinuxEvent {
private long nanos;
private final LinuxAxisDescriptor descriptor = new LinuxAxisDescriptor();
private int value;
public final void set(long seconds, long microseconds, int type, int code, int value) {
this.nanos = (seconds*1000000 + microseconds)*1000;
this.descriptor.set(type, code);
this.value = value;
}
public final int getValue() {
return value;
}
public final LinuxAxisDescriptor getDescriptor() {
return descriptor;
}
public final long getNanos() {
return nanos;
}
}

View file

@ -0,0 +1,115 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.io.IOException;
/**
* @author elias
* @author Jeremy Booth (jeremy@newdawnsoftware.com)
*/
final class LinuxEventComponent {
private final LinuxEventDevice device;
private final Component.Identifier identifier;
private final Controller.Type button_trait;
private final boolean is_relative;
private final LinuxAxisDescriptor descriptor;
private final int min;
private final int max;
private final int flat;
public LinuxEventComponent(LinuxEventDevice device, Component.Identifier identifier, boolean is_relative, int native_type, int native_code) throws IOException {
this.device = device;
this.identifier = identifier;
if (native_type == NativeDefinitions.EV_KEY)
this.button_trait = LinuxNativeTypesMap.guessButtonTrait(native_code);
else
this.button_trait = Controller.Type.UNKNOWN;
this.is_relative = is_relative;
this.descriptor = new LinuxAxisDescriptor();
descriptor.set(native_type, native_code);
if (native_type == NativeDefinitions.EV_ABS) {
LinuxAbsInfo abs_info = new LinuxAbsInfo();
getAbsInfo(abs_info);
this.min = abs_info.getMin();
this.max = abs_info.getMax();
this.flat = abs_info.getFlat();
} else {
this.min = Integer.MIN_VALUE;
this.max = Integer.MAX_VALUE;
this.flat = 0;
}
}
public final LinuxEventDevice getDevice() {
return device;
}
public final void getAbsInfo(LinuxAbsInfo abs_info) throws IOException {
assert descriptor.getType() == NativeDefinitions.EV_ABS;
device.getAbsInfo(descriptor.getCode(), abs_info);
}
public final Controller.Type getButtonTrait() {
return button_trait;
}
public final Component.Identifier getIdentifier() {
return identifier;
}
public final LinuxAxisDescriptor getDescriptor() {
return descriptor;
}
public final boolean isRelative() {
return is_relative;
}
public final boolean isAnalog() {
return identifier instanceof Component.Identifier.Axis && identifier != Component.Identifier.Axis.POV;
}
final float convertValue(float value) {
if (identifier instanceof Component.Identifier.Axis && !is_relative) {
// Some axes have min = max = 0
if (min == max)
return 0;
if (value > max)
value = max;
else if (value < min)
value = min;
return 2*(value - min)/(max - min) - 1;
} else {
return value;
}
}
final float getDeadZone() {
return flat/(2f*(max - min));
}
}

View file

@ -0,0 +1,367 @@
/*
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/**
* @author elias
*/
final class LinuxEventDevice implements LinuxDevice {
private final Map<LinuxAxisDescriptor, LinuxComponent> component_map = new HashMap<>();
private final Rumbler[] rumblers;
private final long fd;
private final String name;
private final LinuxInputID input_id;
private final List<LinuxEventComponent> components;
private final Controller.Type type;
/* Closed state variable that protects the validity of the file descriptor.
* Access to the closed state must be synchronized
*/
private boolean closed;
/* Access to the key_states array could be synchronized, but
* it doesn't hurt to have multiple threads read/write from/to it
*/
private final byte[] key_states = new byte[NativeDefinitions.KEY_MAX/8 + 1];
public LinuxEventDevice(String filename) throws IOException {
long fd;
boolean detect_rumblers = true;
try {
fd = nOpen(filename, true);
} catch (IOException e) {
fd = nOpen(filename, false);
detect_rumblers = false;
}
this.fd = fd;
try {
this.name = getDeviceName();
this.input_id = getDeviceInputID();
this.components = getDeviceComponents();
if (detect_rumblers)
this.rumblers = enumerateRumblers();
else
this.rumblers = new Rumbler[]{};
this.type = guessType();
} catch (IOException e) {
close();
throw e;
}
}
private final static native long nOpen(String filename, boolean rw) throws IOException;
public final Controller.Type getType() {
return type;
}
private final static int countComponents(List<LinuxEventComponent> components, Class<?> id_type, boolean relative) {
int count = 0;
for (int i = 0; i < components.size(); i++) {
LinuxEventComponent component = components.get(i);
if (id_type.isInstance(component.getIdentifier()) && relative == component.isRelative())
count++;
}
return count;
}
private final Controller.Type guessType() throws IOException {
List<LinuxEventComponent> components = getComponents();
if (components.size() == 0)
return Controller.Type.UNKNOWN;
int num_rel_axes = countComponents(components, Component.Identifier.Axis.class, true);
int num_abs_axes = countComponents(components, Component.Identifier.Axis.class, false);
int num_keys = countComponents(components, Component.Identifier.Key.class, false);
int mouse_traits = 0;
int keyboard_traits = 0;
int joystick_traits = 0;
int gamepad_traits = 0;
if (name.toLowerCase().indexOf("mouse") != -1)
mouse_traits++;
if (name.toLowerCase().indexOf("keyboard") != -1)
keyboard_traits++;
if (name.toLowerCase().indexOf("joystick") != -1)
joystick_traits++;
if (name.toLowerCase().indexOf("gamepad") != -1)
gamepad_traits++;
int num_keyboard_button_traits = 0;
int num_mouse_button_traits = 0;
int num_joystick_button_traits = 0;
int num_gamepad_button_traits = 0;
// count button traits
for (int i = 0; i < components.size(); i++) {
LinuxEventComponent component = components.get(i);
if (component.getButtonTrait() == Controller.Type.MOUSE)
num_mouse_button_traits++;
else if (component.getButtonTrait() == Controller.Type.KEYBOARD)
num_keyboard_button_traits++;
else if (component.getButtonTrait() == Controller.Type.GAMEPAD)
num_gamepad_button_traits++;
else if (component.getButtonTrait() == Controller.Type.STICK)
num_joystick_button_traits++;
}
if ((num_mouse_button_traits >= num_keyboard_button_traits) && (num_mouse_button_traits >= num_joystick_button_traits) && (num_mouse_button_traits >= num_gamepad_button_traits)) {
mouse_traits++;
} else if ((num_keyboard_button_traits >= num_mouse_button_traits) && (num_keyboard_button_traits >= num_joystick_button_traits) && (num_keyboard_button_traits >= num_gamepad_button_traits)) {
keyboard_traits++;
} else if ((num_joystick_button_traits >= num_keyboard_button_traits) && (num_joystick_button_traits >= num_mouse_button_traits) && (num_joystick_button_traits >= num_gamepad_button_traits)) {
joystick_traits++;
} else if ((num_gamepad_button_traits >= num_keyboard_button_traits) && (num_gamepad_button_traits >= num_mouse_button_traits) && (num_gamepad_button_traits >= num_joystick_button_traits)) {
gamepad_traits++;
}
if (num_rel_axes >= 2) {
mouse_traits++;
}
if (num_abs_axes >= 2) {
joystick_traits++;
gamepad_traits++;
}
if ((mouse_traits >= keyboard_traits) && (mouse_traits >= joystick_traits) && (mouse_traits >= gamepad_traits)) {
return Controller.Type.MOUSE;
} else if ((keyboard_traits >= mouse_traits) && (keyboard_traits >= joystick_traits) && (keyboard_traits >= gamepad_traits)) {
return Controller.Type.KEYBOARD;
} else if ((joystick_traits >= mouse_traits) && (joystick_traits >= keyboard_traits) && (joystick_traits >= gamepad_traits)) {
return Controller.Type.STICK;
} else if ((gamepad_traits >= mouse_traits) && (gamepad_traits >= keyboard_traits) && (gamepad_traits >= joystick_traits)) {
return Controller.Type.GAMEPAD;
} else
return null;
}
private final Rumbler[] enumerateRumblers() {
List<Rumbler> rumblers = new ArrayList<>();
try {
int num_effects = getNumEffects();
if (num_effects <= 0)
return rumblers.toArray(new Rumbler[]{});
byte[] ff_bits = getForceFeedbackBits();
if (isBitSet(ff_bits, NativeDefinitions.FF_RUMBLE) && num_effects > rumblers.size()) {
rumblers.add(new LinuxRumbleFF(this));
}
} catch (IOException e) {
LinuxEnvironmentPlugin.log("Failed to enumerate rumblers: " + e.getMessage());
}
return rumblers.toArray(new Rumbler[]{});
}
public final Rumbler[] getRumblers() {
return rumblers;
}
public final synchronized int uploadRumbleEffect(int id, int trigger_button, int direction, int trigger_interval, int replay_length, int replay_delay, int strong_magnitude, int weak_magnitude) throws IOException {
checkClosed();
return nUploadRumbleEffect(fd, id, direction, trigger_button, trigger_interval, replay_length, replay_delay, strong_magnitude, weak_magnitude);
}
private final static native int nUploadRumbleEffect(long fd, int id, int direction, int trigger_button, int trigger_interval, int replay_length, int replay_delay, int strong_magnitude, int weak_magnitude) throws IOException;
public final synchronized int uploadConstantEffect(int id, int trigger_button, int direction, int trigger_interval, int replay_length, int replay_delay, int constant_level, int constant_env_attack_length, int constant_env_attack_level, int constant_env_fade_length, int constant_env_fade_level) throws IOException {
checkClosed();
return nUploadConstantEffect(fd, id, direction, trigger_button, trigger_interval, replay_length, replay_delay, constant_level, constant_env_attack_length, constant_env_attack_level, constant_env_fade_length, constant_env_fade_level);
}
private final static native int nUploadConstantEffect(long fd, int id, int direction, int trigger_button, int trigger_interval, int replay_length, int replay_delay, int constant_level, int constant_env_attack_length, int constant_env_attack_level, int constant_env_fade_length, int constant_env_fade_level) throws IOException;
final void eraseEffect(int id) throws IOException {
nEraseEffect(fd, id);
}
private final static native void nEraseEffect(long fd, int ff_id) throws IOException;
public final synchronized void writeEvent(int type, int code, int value) throws IOException {
checkClosed();
nWriteEvent(fd, type, code, value);
}
private final static native void nWriteEvent(long fd, int type, int code, int value) throws IOException;
public final void registerComponent(LinuxAxisDescriptor desc, LinuxComponent component) {
component_map.put(desc, component);
}
public final LinuxComponent mapDescriptor(LinuxAxisDescriptor desc) {
return component_map.get(desc);
}
public final Controller.PortType getPortType() throws IOException {
return input_id.getPortType();
}
public final LinuxInputID getInputID() {
return input_id;
}
private final LinuxInputID getDeviceInputID() throws IOException {
return nGetInputID(fd);
}
private final static native LinuxInputID nGetInputID(long fd) throws IOException;
public final int getNumEffects() throws IOException {
return nGetNumEffects(fd);
}
private final static native int nGetNumEffects(long fd) throws IOException;
private final int getVersion() throws IOException {
return nGetVersion(fd);
}
private final static native int nGetVersion(long fd) throws IOException;
public final synchronized boolean getNextEvent(LinuxEvent linux_event) throws IOException {
checkClosed();
return nGetNextEvent(fd, linux_event);
}
private final static native boolean nGetNextEvent(long fd, LinuxEvent linux_event) throws IOException;
public final synchronized void getAbsInfo(int abs_axis, LinuxAbsInfo abs_info) throws IOException {
checkClosed();
nGetAbsInfo(fd, abs_axis, abs_info);
}
private final static native void nGetAbsInfo(long fd, int abs_axis, LinuxAbsInfo abs_info) throws IOException;
private final void addKeys(List<LinuxEventComponent> components) throws IOException {
byte[] bits = getKeysBits();
for (int i = 0; i < bits.length*8; i++) {
if (isBitSet(bits, i)) {
Component.Identifier id = LinuxNativeTypesMap.getButtonID(i);
components.add(new LinuxEventComponent(this, id, false, NativeDefinitions.EV_KEY, i));
}
}
}
private final void addAbsoluteAxes(List<LinuxEventComponent> components) throws IOException {
byte[] bits = getAbsoluteAxesBits();
for (int i = 0; i < bits.length*8; i++) {
if (isBitSet(bits, i)) {
Component.Identifier id = LinuxNativeTypesMap.getAbsAxisID(i);
components.add(new LinuxEventComponent(this, id, false, NativeDefinitions.EV_ABS, i));
}
}
}
private final void addRelativeAxes(List<LinuxEventComponent> components) throws IOException {
byte[] bits = getRelativeAxesBits();
for (int i = 0; i < bits.length*8; i++) {
if (isBitSet(bits, i)) {
Component.Identifier id = LinuxNativeTypesMap.getRelAxisID(i);
components.add(new LinuxEventComponent(this, id, true, NativeDefinitions.EV_REL, i));
}
}
}
public final List<LinuxEventComponent> getComponents() {
return components;
}
private final List<LinuxEventComponent> getDeviceComponents() throws IOException {
List<LinuxEventComponent> components = new ArrayList<>();
byte[] evtype_bits = getEventTypeBits();
if (isBitSet(evtype_bits, NativeDefinitions.EV_KEY))
addKeys(components);
if (isBitSet(evtype_bits, NativeDefinitions.EV_ABS))
addAbsoluteAxes(components);
if (isBitSet(evtype_bits, NativeDefinitions.EV_REL))
addRelativeAxes(components);
return components;
}
private final byte[] getForceFeedbackBits() throws IOException {
byte[] bits = new byte[NativeDefinitions.FF_MAX/8 + 1];
nGetBits(fd, NativeDefinitions.EV_FF, bits);
return bits;
}
private final byte[] getKeysBits() throws IOException {
byte[] bits = new byte[NativeDefinitions.KEY_MAX/8 + 1];
nGetBits(fd, NativeDefinitions.EV_KEY, bits);
return bits;
}
private final byte[] getAbsoluteAxesBits() throws IOException {
byte[] bits = new byte[NativeDefinitions.ABS_MAX/8 + 1];
nGetBits(fd, NativeDefinitions.EV_ABS, bits);
return bits;
}
private final byte[] getRelativeAxesBits() throws IOException {
byte[] bits = new byte[NativeDefinitions.REL_MAX/8 + 1];
nGetBits(fd, NativeDefinitions.EV_REL, bits);
return bits;
}
private final byte[] getEventTypeBits() throws IOException {
byte[] bits = new byte[NativeDefinitions.EV_MAX/8 + 1];
nGetBits(fd, 0, bits);
return bits;
}
private final static native void nGetBits(long fd, int ev_type, byte[] evtype_bits) throws IOException;
public final synchronized void pollKeyStates() throws IOException {
nGetKeyStates(fd, key_states);
}
private final static native void nGetKeyStates(long fd, byte[] states) throws IOException;
public final boolean isKeySet(int bit) {
return isBitSet(key_states, bit);
}
public final static boolean isBitSet(byte[] bits, int bit) {
return (bits[bit/8] & (1<<(bit%8))) != 0;
}
public final String getName() {
return name;
}
private final String getDeviceName() throws IOException {
return nGetName(fd);
}
private final static native String nGetName(long fd) throws IOException;
public synchronized final void close() throws IOException {
if (closed)
return;
closed = true;
LinuxEnvironmentPlugin.execute(new LinuxDeviceTask() {
protected final Object execute() throws IOException {
nClose(fd);
return null;
}
});
}
private final static native void nClose(long fd) throws IOException;
private final void checkClosed() throws IOException {
if (closed)
throw new IOException("Device is closed");
}
@SuppressWarnings("deprecation")
protected void finalize() throws IOException {
close();
}
}

View file

@ -0,0 +1,110 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
import java.io.IOException;
/**
* @author elias
*/
abstract class LinuxForceFeedbackEffect implements Rumbler {
private final LinuxEventDevice device;
private final int ff_id;
private final WriteTask write_task = new WriteTask();
private final UploadTask upload_task = new UploadTask();
public LinuxForceFeedbackEffect(LinuxEventDevice device) throws IOException {
this.device = device;
this.ff_id = upload_task.doUpload(-1, 0);
}
protected abstract int upload(int id, float intensity) throws IOException;
protected final LinuxEventDevice getDevice() {
return device;
}
public synchronized final void rumble(float intensity) {
try {
if (intensity > 0) {
upload_task.doUpload(ff_id, intensity);
write_task.write(1);
} else {
write_task.write(0);
}
} catch (IOException e) {
LinuxEnvironmentPlugin.log("Failed to rumble: " + e);
}
}
/*
* Erase doesn't seem to be implemented on Logitech joysticks,
* so we'll rely on the kernel cleaning up on device close
*/
/*
public final void erase() throws IOException {
device.eraseEffect(ff_id);
}
*/
public final String getAxisName() {
return null;
}
public final Component.Identifier getAxisIdentifier() {
return null;
}
private final class UploadTask extends LinuxDeviceTask {
private int id;
private float intensity;
public final int doUpload(int id, float intensity) throws IOException {
this.id = id;
this.intensity = intensity;
LinuxEnvironmentPlugin.execute(this);
return this.id;
}
protected final Object execute() throws IOException {
this.id = upload(id, intensity);
return null;
}
}
private final class WriteTask extends LinuxDeviceTask {
private int value;
public final void write(int value) throws IOException {
this.value = value;
LinuxEnvironmentPlugin.execute(this);
}
protected final Object execute() throws IOException {
device.writeEvent(NativeDefinitions.EV_FF, ff_id, value);
return null;
}
}
}

View file

@ -0,0 +1,52 @@
/**
* Copyright (C) 2003 Jeremy Booth (jeremy@newdawnsoftware.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 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.
* 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
*/
package net.java.games.input;
/**
* @author elias
*/
final class LinuxInputID {
private final int bustype;
private final int vendor;
private final int product;
private final int version;
public LinuxInputID(int bustype, int vendor, int product, int version) {
this.bustype = bustype;
this.vendor = vendor;
this.product = product;
this.version = version;
}
public final Controller.PortType getPortType() {
return LinuxNativeTypesMap.getPortType(bustype);
}
public final String toString() {
return "LinuxInputID: bustype = 0x" + Integer.toHexString(bustype) + " | vendor = 0x" + Integer.toHexString(vendor) +
" | product = 0x" + Integer.toHexString(product) + " | version = 0x" + Integer.toHexString(version);
}
}

View file

@ -0,0 +1,70 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** Represents a Linux controller
* @author elias
* @version 1.0
*/
final class LinuxJoystickAbstractController extends AbstractController {
private final LinuxJoystickDevice device;
protected LinuxJoystickAbstractController(LinuxJoystickDevice device, Component[] components, Controller[] children, Rumbler[] rumblers) {
super(device.getName(), components, children, rumblers);
this.device = device;
}
protected final void setDeviceEventQueueSize(int size) throws IOException {
device.setBufferSize(size);
}
public final void pollDevice() throws IOException {
device.poll();
}
protected final boolean getNextDeviceEvent(Event event) throws IOException {
return device.getNextEvent(event);
}
public Type getType() {
return Controller.Type.STICK;
}
}

View file

@ -0,0 +1,76 @@
/*
* %W% %E%
*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*****************************************************************************
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materails provided with the distribution.
*
* Neither the name Sun Microsystems, Inc. or the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANT OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMEN, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
* A RESULT OF USING, MODIFYING OR DESTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES. HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OUR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for us in
* the design, construction, operation or maintenance of any nuclear facility
*
*****************************************************************************/
package net.java.games.input;
import java.io.IOException;
/** Represents a linux Axis
* @author elias
* @version 1.0
*/
class LinuxJoystickAxis extends AbstractComponent {
private float value;
private boolean analog;
public LinuxJoystickAxis(Component.Identifier.Axis axis_id) {
this(axis_id, true);
}
public LinuxJoystickAxis(Component.Identifier.Axis axis_id, boolean analog) {
super(axis_id.getName(), axis_id);
this.analog = analog;
}
public final boolean isRelative() {
return false;
}
public final boolean isAnalog() {
return analog;
}
final void setValue(float value) {
this.value = value;
resetHasPolled();
}
protected final float poll() throws IOException {
return value;
}
}

Some files were not shown because too many files have changed in this diff Show more