Merge lp:~mixxxdevelopers/mixxx/features_controllerAbstraction into lp:~mixxxdevelopers/mixxx/trunk

Proposed by RJ Skerry-Ryan
Status: Superseded
Proposed branch: lp:~mixxxdevelopers/mixxx/features_controllerAbstraction
Merge into: lp:~mixxxdevelopers/mixxx/trunk
Diff against target: 21632 lines (+11597/-8152)
153 files modified
mixxx/SConstruct (+1/-1)
mixxx/build/depends.py (+23/-22)
mixxx/build/features.py (+47/-34)
mixxx/lib/hidapi-0.7.0/LICENSE-orig.txt (+9/-0)
mixxx/lib/hidapi-0.7.0/LICENSE.txt (+13/-0)
mixxx/lib/hidapi-0.7.0/hidapi/hidapi.h (+383/-0)
mixxx/lib/hidapi-0.7.0/linux/.gitignore (+13/-0)
mixxx/lib/hidapi-0.7.0/linux/Makefile (+36/-0)
mixxx/lib/hidapi-0.7.0/linux/README.txt (+63/-0)
mixxx/lib/hidapi-0.7.0/linux/hid-libusb.c (+1386/-0)
mixxx/lib/hidapi-0.7.0/linux/hid.c (+595/-0)
mixxx/lib/hidapi-0.7.0/mac/.gitignore (+13/-0)
mixxx/lib/hidapi-0.7.0/mac/Makefile (+32/-0)
mixxx/lib/hidapi-0.7.0/mac/hid.c (+1122/-0)
mixxx/lib/hidapi-0.7.0/windows/.gitignore (+11/-0)
mixxx/lib/hidapi-0.7.0/windows/Makefile (+14/-0)
mixxx/lib/hidapi-0.7.0/windows/Makefile.mingw (+32/-0)
mixxx/lib/hidapi-0.7.0/windows/ddk_build/.gitignore (+2/-0)
mixxx/lib/hidapi-0.7.0/windows/ddk_build/hidapi.def (+17/-0)
mixxx/lib/hidapi-0.7.0/windows/ddk_build/makefile (+49/-0)
mixxx/lib/hidapi-0.7.0/windows/ddk_build/sources (+23/-0)
mixxx/lib/hidapi-0.7.0/windows/hid.c (+873/-0)
mixxx/lib/hidapi-0.7.0/windows/hidapi.sln (+29/-0)
mixxx/lib/hidapi-0.7.0/windows/hidapi.vcproj (+201/-0)
mixxx/lib/hidapi-0.7.0/windows/hidtest.vcproj (+196/-0)
mixxx/res/controllers/American-Audio-VMS4-scripts.js (+1/-1)
mixxx/res/controllers/EKS Otus.js (+95/-0)
mixxx/res/controllers/Eks Otus.cntrlr.xml (+13/-0)
mixxx/res/controllers/Stanton-SCS1d-scripts.js (+87/-104)
mixxx/res/controllers/Stanton-SCS3d-scripts.js (+23/-26)
mixxx/res/controllers/common-controller-scripts.js (+47/-14)
mixxx/res/mixxx.qrc (+1/-0)
mixxx/src/SConscript (+10/-10)
mixxx/src/controlbeat.cpp (+2/-1)
mixxx/src/controlbeat.h (+1/-2)
mixxx/src/controlgroupdelegate.cpp (+1/-1)
mixxx/src/controllers/controller-preset.cpp (+147/-0)
mixxx/src/controllers/controller.cpp (+153/-0)
mixxx/src/controllers/controller.h (+128/-0)
mixxx/src/controllers/controllerengine.cpp (+1132/-0)
mixxx/src/controllers/controllerengine.h (+136/-0)
mixxx/src/controllers/controllerenumerator.cpp (+28/-0)
mixxx/src/controllers/controllerenumerator.h (+36/-0)
mixxx/src/controllers/controllermanager.cpp (+315/-0)
mixxx/src/controllers/controllermanager.h (+86/-0)
mixxx/src/controllers/defs_controllers.h (+22/-0)
mixxx/src/controllers/dlgprefcontroller.cpp (+168/-0)
mixxx/src/controllers/dlgprefcontroller.h (+67/-0)
mixxx/src/controllers/dlgprefcontrollerdlg.ui (+140/-0)
mixxx/src/controllers/dlgprefnocontrollers.cpp (+25/-0)
mixxx/src/controllers/dlgprefnocontrollers.h (+33/-0)
mixxx/src/controllers/dlgprefnocontrollersdlg.ui (+46/-0)
mixxx/src/controllers/hidcontroller.cpp (+249/-0)
mixxx/src/controllers/hidcontroller.h (+75/-0)
mixxx/src/controllers/hidenumerator.cpp (+59/-0)
mixxx/src/controllers/hidenumerator.h (+31/-0)
mixxx/src/controllers/midi/hss1394controller.cpp (+211/-0)
mixxx/src/controllers/midi/hss1394controller.h (+66/-0)
mixxx/src/controllers/midi/hss1394enumerator.cpp (+60/-0)
mixxx/src/controllers/midi/hss1394enumerator.h (+31/-0)
mixxx/src/controllers/midi/midicontroller-preset.cpp (+468/-0)
mixxx/src/controllers/midi/midicontroller.cpp (+404/-0)
mixxx/src/controllers/midi/midicontroller.h (+91/-0)
mixxx/src/controllers/midi/midienumerator.cpp (+24/-0)
mixxx/src/controllers/midi/midienumerator.h (+37/-0)
mixxx/src/controllers/midi/midimessage.h (+89/-0)
mixxx/src/controllers/midi/midioutputhandler.cpp (+74/-0)
mixxx/src/controllers/midi/midioutputhandler.h (+51/-0)
mixxx/src/controllers/midi/portmidicontroller.cpp (+245/-0)
mixxx/src/controllers/midi/portmidicontroller.h (+67/-0)
mixxx/src/controllers/midi/portmidienumerator.cpp (+133/-0)
mixxx/src/controllers/midi/portmidienumerator.h (+32/-0)
mixxx/src/controllers/qtscript-bytearray/bytearrayclass.cpp (+284/-0)
mixxx/src/controllers/qtscript-bytearray/bytearrayclass.h (+91/-0)
mixxx/src/controllers/qtscript-bytearray/bytearrayprototype.cpp (+129/-0)
mixxx/src/controllers/qtscript-bytearray/bytearrayprototype.h (+76/-0)
mixxx/src/controllogpotmeter.cpp (+2/-1)
mixxx/src/controllogpotmeter.h (+1/-1)
mixxx/src/controlobject.cpp (+6/-8)
mixxx/src/controlobject.h (+4/-4)
mixxx/src/controlobjectthread.cpp (+2/-1)
mixxx/src/controlobjectthread.h (+3/-3)
mixxx/src/controlpotmeter.cpp (+2/-1)
mixxx/src/controlpotmeter.h (+1/-1)
mixxx/src/controlpushbutton.cpp (+4/-4)
mixxx/src/controlpushbutton.h (+2/-1)
mixxx/src/controlttrotary.cpp (+2/-1)
mixxx/src/controlttrotary.h (+2/-2)
mixxx/src/controlvaluedelegate.cpp (+1/-1)
mixxx/src/dlgmidilearning.cpp (+0/-210)
mixxx/src/dlgmidilearning.h (+0/-56)
mixxx/src/dlgmidilearning.ui (+0/-241)
mixxx/src/dlgpreferences.cpp (+160/-31)
mixxx/src/dlgpreferences.h (+28/-21)
mixxx/src/dlgprefmidibindings.cpp (+0/-508)
mixxx/src/dlgprefmidibindings.h (+0/-92)
mixxx/src/dlgprefmidibindingsdlg.ui (+0/-324)
mixxx/src/dlgprefnomidi.cpp (+0/-25)
mixxx/src/dlgprefnomidi.h (+0/-33)
mixxx/src/dlgprefnomididlg.ui (+0/-46)
mixxx/src/engine/ratecontrol.cpp (+2/-0)
mixxx/src/library/schemamanager.cpp (+2/-2)
mixxx/src/main.cpp (+2/-2)
mixxx/src/midi/hss1394enumerator.cpp (+0/-66)
mixxx/src/midi/hss1394enumerator.h (+0/-38)
mixxx/src/midi/midichanneldelegate.cpp (+0/-77)
mixxx/src/midi/midichanneldelegate.h (+0/-36)
mixxx/src/midi/mididevice.cpp (+0/-373)
mixxx/src/midi/mididevice.h (+0/-115)
mixxx/src/midi/mididevicedummy.h (+0/-42)
mixxx/src/midi/midideviceenumerator.cpp (+0/-28)
mixxx/src/midi/midideviceenumerator.h (+0/-38)
mixxx/src/midi/mididevicehss1394.cpp (+0/-233)
mixxx/src/midi/mididevicehss1394.h (+0/-66)
mixxx/src/midi/mididevicemanager.cpp (+0/-217)
mixxx/src/midi/mididevicemanager.h (+0/-54)
mixxx/src/midi/midideviceportmidi.cpp (+0/-325)
mixxx/src/midi/midideviceportmidi.h (+0/-60)
mixxx/src/midi/midiinputmapping.h (+0/-10)
mixxx/src/midi/midiinputmappingtablemodel.cpp (+0/-229)
mixxx/src/midi/midiinputmappingtablemodel.h (+0/-42)
mixxx/src/midi/midiledhandler.cpp (+0/-119)
mixxx/src/midi/midiledhandler.h (+0/-44)
mixxx/src/midi/midimapping.cpp (+0/-1178)
mixxx/src/midi/midimapping.h (+0/-175)
mixxx/src/midi/midimessage.cpp (+0/-111)
mixxx/src/midi/midimessage.h (+0/-114)
mixxx/src/midi/midinodelegate.cpp (+0/-75)
mixxx/src/midi/midinodelegate.h (+0/-36)
mixxx/src/midi/midioptiondelegate.cpp (+0/-158)
mixxx/src/midi/midioptiondelegate.h (+0/-39)
mixxx/src/midi/midioutputmapping.h (+0/-10)
mixxx/src/midi/midioutputmappingtablemodel.cpp (+0/-263)
mixxx/src/midi/midioutputmappingtablemodel.h (+0/-44)
mixxx/src/midi/midiscriptengine.cpp (+0/-1342)
mixxx/src/midi/midiscriptengine.h (+0/-145)
mixxx/src/midi/midistatusdelegate.cpp (+0/-121)
mixxx/src/midi/midistatusdelegate.h (+0/-39)
mixxx/src/midi/portmidienumerator.cpp (+0/-135)
mixxx/src/midi/portmidienumerator.h (+0/-37)
mixxx/src/mixxx.cpp (+27/-25)
mixxx/src/mixxx.h (+2/-3)
mixxx/src/mixxx.rc (+2/-2)
mixxx/src/mixxxkeyboard.cpp (+2/-2)
mixxx/src/recording/recordingmanager.cpp (+1/-0)
mixxx/src/skin/propertybinder.cpp (+2/-0)
mixxx/src/softtakeover.cpp (+2/-2)
mixxx/src/softtakeover.h (+1/-1)
mixxx/src/test/controllerengine_test.cpp (+104/-25)
mixxx/src/widget/wwidget.cpp (+0/-20)
mixxx/src/widget/wwidget.h (+0/-2)
mixxx/src/xmlparse.cpp (+23/-0)
mixxx/src/xmlparse.h (+2/-0)
To merge this branch: bzr merge lp:~mixxxdevelopers/mixxx/features_controllerAbstraction
Reviewer Review Type Date Requested Status
RJ Skerry-Ryan Needs Fixing
Review via email: mp+98121@code.launchpad.net

This proposal has been superseded by a proposal from 2012-04-07.

Commit message

Abstracts the controller subsystem to support multiple protocols. MIDI subsystem partially rewritten, directories, classes and threads reorganized. Adds full HID controller support. Removes MIDI mapping GUI for now.

To post a comment you must log in.
Revision history for this message
William Good (bkgood) wrote :

Maybe I missed the discussion on this but while I agree that the GUI mapping support totally sucks do we really want to remove it without replacing it?

Revision history for this message
RJ Skerry-Ryan (rryan) wrote :

For 1.11 I think we're just going to remove it. The general reasoning is
that since we haven't really had anyone complaining about how hard it is to
use like about 2 years of it being there.. the only conclusion must be that
close to nobody uses it.

Code-wise it was very complicated too and really screwed up the MIDI
mapping implementation since they were deeply intertwined. I'd rather nuke
it in 1.11 and come up with a really nice one for 1.12 or create an
external mapping program.

On Sun, Mar 18, 2012 at 9:26 PM, Bill Good <email address hidden> wrote:

> Maybe I missed the discussion on this but while I agree that the GUI
> mapping support totally sucks do we really want to remove it without
> replacing it?
> --
>
> https://code.launchpad.net/~mixxxdevelopers/mixxx/features_controllerAbstraction/+merge/98121
> You proposed lp:~mixxxdevelopers/mixxx/features_controllerAbstraction for
> merging.
>

Revision history for this message
Sean M. Pappalardo (pegasus-renegadetech) wrote :

We could add back the MIDI mapping wizard if you like, since there's already a message signal and a learning flag in place in MidiController. MC just needs a slot to get data from the wizard, then the wizard would need to be adjusted to work with these signals/slots. I'll check into this further.

Revision history for this message
RJ Skerry-Ryan (rryan) wrote :
Download full text (3.9 KiB)

Hey Sean,

I realize you haven't put the finishing touches on the branch yet. I'm sorry in advance because this review is going to seem a little brutal but I'm convinced that we need to do things right. The main problem I saw with the MIDI subsystem in 1.10 is that everything was totally commingled. This made it impossible to write unit tests for a given class because we had swiss-army-knife classes that did everything. We need to move away from this.

I want to get you this feedback as soon as possible, so here it is. I may have more comments to share later.

* Please make sure to remove commented code referring to non-existing stuff (e.g. all commented lines you left in build/depends.py that refer to old files that don't exist anymore)

* Make sure to delete "res/controllers/Stanton SCS.1m VUMETERS ONLY.xml"

* Please delete src/controllers/OLDmidi soon because it makes reviewing your branch hard (the diff is gigantic).

* In defs_controllers.h, make helper functions instead of these macros. (DEFAULT_DEVICE_PRESET, DEFAULT_MIDI_DEVICE_PRESET in particular. Ideally PRESETS_PATH and LPRESETS_PATH as well).

* Please add "virtual" to every destructor declaration.

* It's good that the old MidiMapping class died because it was a mutable-shared-state-logic-monster. That said, storing the mappings in the controller is almost as bad.
   - Let's pull all mappings out into a Mapping/MidiMapping class. This class should be plain-old-data, not a QObject (e.g. no signals/slots) and no methods except the minimum needed for Controller to look up the script files, MidiController to look up a mapped control in receive() and to look up output mappings where it creates the MidiOutputHandlers.

* Take all serialization/deserialization code and put it into a MappingParser/MidiMappingParser helper class which creates a Mapping/MidiMapping class from a given path.

* Delete loadPreset / savePreset / buildDomElement methods in Controller/MidiController .. replace them with a setMapping() command. A controller that doesn't have a mapping yet can be considered invalid.

* Controllers shouldn't be concerned with saving a preset. Instead that should be the controller preferences dialog or the ControllerManager's job to deserialize the mapping and call Controller::setMapping().

* Need to remove all methods that deal with a char*/length data buffer e.g. Controller::send, Controller::receivePointer. Instead we should be using QByteArray for everything.

* Remove length argument from Controller::sendBa since a QByteArray knows its own length. Also, rename sendBa to send(). Also make the argument a const QByteArray.

* I'd prefer we get rid of the Controller::send(QList<int>) method and instead require people to use QByteArrays but I'm not sure if this is easy from scripts so maybe we can let it be. Please change the implementation of Controller::send(QList<int>, int) to build a QByteArray and call send(QByteArray).

* In ControllerManager, please remove the m_pPMEnumerator, m_pHSSEnumerator, m_pHIDEnumerator, and m_pOSCEnumerator declarations. Instead use a QList of ControllerEnumerator* objects. Add an "addControllerEnumerator()" method to ControllerManager, an...

Read more...

review: Needs Fixing
Revision history for this message
Sean M. Pappalardo (pegasus-renegadetech) wrote :

> * Please make sure to remove commented code referring to non-existing stuff
> * Make sure to delete "res/controllers/Stanton SCS.1m VUMETERS ONLY.xml"
> * Please delete src/controllers/OLDmidi soon because it makes reviewing your

These are among the reasons why I didn't propose a merge yet, silly. :)

> * In defs_controllers.h, make helper functions instead of these macros.

What benefit would that give? The macros are straightforward and fast.

> * Please add "virtual" to every destructor declaration.

As a matter of course? What will that do? I only do it to destructors that will be reimplemented.

> shared-state-logic-monster. That said, storing the mappings in the controller
> is almost as bad.

I do this because I view a Controller as a device, with all properties particular to that device (e.g. a mapping) contained in the one object. Then due to the time-sensitive nature of MIDI processing, I imagine local object data is faster to access.

> * Take all serialization/deserialization code and put it into a
> MappingParser/MidiMappingParser helper class which creates a
> Mapping/MidiMapping class from a given path.

That sounds like overkill. If we do in fact make a MidiMapping class, shouldn't the same class that holds the data be responsible for all operations on that data?

> * Need to remove all methods that deal with a char*/length data buffer e.g.
> Controller::send, Controller::receivePointer. Instead we should be using
> QByteArray for everything.

Not all of them can be removed without duplicating code or complicating the classes, since the device APIs send and expect data this way. If we try, know that interfacing raw bytes between JS and C++ is a very delicate issue. I've had numerous problems with bytes getting mangled in the past.
Plus I imagine primitive data types to be slightly faster. Here again, what would be the benefit of switching to QByteArrays?

> * I'd prefer we get rid of the Controller::send(QList<int>) method and instead
> require people to use QByteArrays

We can't. This is how QtScript passes data byte arrays to C++.

> * In ControllerManager, please remove the m_pPMEnumerator, m_pHSSEnumerator,
> m_pHIDEnumerator, and m_pOSCEnumerator declarations.

Thanks for the suggested methods. This was bothering me too but I couldn't think of a neat way to fix it.

> * midi-mappings-scripts.js You're changing the names of a lot of common script
> stuff. Won't this break MIDI-scripts in the wild?

Yes, but the only things that will be incompatible are MidiButtonState and MidiLedState. A README telling to search-n-replace will fix them right up. I left backwards-compatible calls for everything else.

Revision history for this message
Owen Williams (ywwg) wrote :

We should think long and hard before breaking people's scripts, even if a simple search-and-replace will fix it. I'd prefer to leave scripts stable and only limit breakage to major releases (2.0, etc). I'm not super-familiar with this branch, but is this breakage necessary?

Revision history for this message
RJ Skerry-Ryan (rryan) wrote :
Download full text (5.5 KiB)

On Mon, Mar 19, 2012 at 4:14 PM, Sean M. Pappalardo
<email address hidden>wrote:

> > * Please make sure to remove commented code referring to non-existing
> stuff
> > * Make sure to delete "res/controllers/Stanton SCS.1m VUMETERS ONLY.xml"
> > * Please delete src/controllers/OLDmidi soon because it makes reviewing
> your
>
> These are among the reasons why I didn't propose a merge yet, silly. :)
>
> > * In defs_controllers.h, make helper functions instead of these macros.
>
> What benefit would that give? The macros are straightforward and fast.
>

Macros should only be used for constants. They're no faster than an inline
function. These particular macros refer to member variables of a class and
have logic in them. This obscures the logic within the class they are used
in because it is hidden behind what looks like a constant. If they have
member variables then they're specific to a class so why not make them a
private inline helper function of that class?

>
> > * Please add "virtual" to every destructor declaration.
>
> As a matter of course? What will that do? I only do it to destructors that
> will be reimplemented.
>
>
It's just something that every class should have. It should be as automatic
as making your member variables private. Some day in the future someone
will subclass your class -- guaranteed. Be nice to them -- it might even be
your future self. :)

> > shared-state-logic-monster. That said, storing the mappings in the
> controller
> > is almost as bad.
>
> I do this because I view a Controller as a device, with all properties
> particular to that device (e.g. a mapping) contained in the one object.
> Then due to the time-sensitive nature of MIDI processing, I imagine local
> object data is faster to access.
>
>
It's fine for the controller to have a mapping. That mapping should be
encapsulated into one class so you can pass them around and vary the
implementation of the mapping independent of the class that consumes the
mapping (the Controller).

Accessing a member variable versus the member variable of another class is
possibly the difference in 1 or two assembly instructions -- if any
difference. If you care about this in the name of speed then I'm surprised
you use so many virtual functions (they are about 2x slower than a regular
function call). This sort of difference is totally meaningless from a Mixxx
performance perspective. We're talking picoseconds here!

Don't let tens or hundreds of assembly instructions get in the way of
writing good code. For the long-term health of the project it's worth it to
structure the project in small, bite-sized and testable classes. This is
extra work, I know.

> > * Take all serialization/deserialization code and put it into a
> > MappingParser/MidiMappingParser helper class which creates a
> > Mapping/MidiMapping class from a given path.
>
> That sounds like overkill. If we do in fact make a MidiMapping class,
> shouldn't the same class that holds the data be responsible for all
> operations on that data?
>

The mapping parsing / serializing code is long enough to warrant living in
its own utility class. It is long and obscures the purpose of whatever
class it lives in (origin...

Read more...

Revision history for this message
Sean M. Pappalardo (pegasus-renegadetech) wrote :

> Macros should only be used for constants.

My bad, I forgot there were member variables in two of them. Don't know what I was thinking when I did that.

> difference. If you care about this in the name of speed then I'm surprised
> you use so many virtual functions (they are about 2x slower than a regular
> function call).

:O I had no idea! Is that 2x slowdown a matter of picoseconds too?

> The mapping parsing / serializing code is long enough to warrant living in
> its own utility class. It is long and obscures the purpose of whatever
> class it lives in (originally MidiMapping, now *Controller).

What bothers me about separating it is that there is no generic ControllerMapping class (at least not yet,) so MidiMappings are specific to MIDI controllers, so why not make them an integral part? I see your point though and will make the change.

> 1.10. Can we keep the ButtonState and LedState as they are for MIDI and
> mark them deprecated?

Actually, leaving them without the "Midi" prefix should be fine, since non-MIDI controllers will need to set the values differently anyway.

Revision history for this message
Sean M. Pappalardo (pegasus-renegadetech) wrote :

LOL, I removed the OLDmidi directory and the diff got bigger. (Not surprised.)

RJ, while I work on the rest, I need you to take a look at ControllerEngine::connectControl() and figure out why using COTs breaks automatic reactions. They work fine in trunk so I have no idea.

Revision history for this message
Sean M. Pappalardo (pegasus-renegadetech) wrote :

Hello again. Looking at your class-separation requests more closely now, I still have reservations:

> - Let's pull all mappings out into a Mapping/MidiMapping class. This class
> should be plain-old-data, not a QObject (e.g. no signals/slots) and no methods

I'm sorry, I can't see the benefit of doing that. It would just add complexity and make it harder for *Controller to be expanded in the future such as when the GUI signals it to add/delete/change mappings. (Besides, a preset is just two QLists. Specific *Controllers add two QHashes for mappings.)

> * Take all serialization/deserialization code and put it into a
> MappingParser/MidiMappingParser helper class

Here too, moving those functions to another class would add needless complexity because they have to access data that's specific to a Controller. I understand the desire to have classes not be too long, but don't let that get in the way of logical design. In this case, everything that's in *Controller is specific to that type of device. (Yes, that includes the parsing code, since it's specific to the mapping storage format, which is specific to the device type.) Trying to separate it across multiple classes would cause us to have shared-state logic monsters again and make it much more difficult to follow for those new to the code. Since it sounds like you're interested in visual separation, I have moved the functions that handle XML into separate .cpp files and have simply #included these in the main *Controller ones.

> * Controllers shouldn't be concerned with saving a preset. Instead that should
> be the controller preferences dialog or the ControllerManager's job

The ControllerManager _is_ in charge of saving presets. The Controllers just contain the code to do so, because it's specific to each Controller type (as stated above,) and the Manager isn't concerned with those details (or it would be micro-managing.)

In short, there's nothing else that can be factored out.

If your concerns are motivated by unit-testing issues, why can't we just write separate tests for different aspects of a class?

Revision history for this message
RJ Skerry-Ryan (rryan) wrote :
Download full text (3.4 KiB)

On Apr 7, 2012 7:38 AM, "Sean M. Pappalardo" <email address hidden> wrote:
>
> Hello again. Looking at your class-separation requests more closely now,
I still have reservations:
>
> > - Let's pull all mappings out into a Mapping/MidiMapping class. This
class
> > should be plain-old-data, not a QObject (e.g. no signals/slots) and no
methods
>
> I'm sorry, I can't see the benefit of doing that. It would just add
complexity and make it harder for *Controller to be expanded in the future
such as when the GUI signals it to add/delete/change mappings. (Besides, a
preset is just two QLists. Specific *Controllers add two QHashes for
mappings.)

The benefit is encapsulation of the mapping implementation.

Add/delete/change of a mapping from the GUI is the reason the old midi
system is so terrible. The only way to load a mapping going forward will be
to call Controller::loadMapping(ControllerMapping).

>
> > * Take all serialization/deserialization code and put it into a
> > MappingParser/MidiMappingParser helper class
>
> Here too, moving those functions to another class would add needless
complexity because they have to access data that's specific to a
Controller. I understand the desire to have classes not be too long, but
don't let that get in the way of logical design. In this case, everything
that's in *Controller is specific to that type of device. (Yes, that
includes the parsing code, since it's specific to the mapping storage
format, which is specific to the device type.) Trying to separate it across
multiple classes would cause us to have shared-state logic monsters again
and make it much more difficult to follow for those new to the code. Since
it sounds like you're interested in visual separation, I have moved the
functions that handle XML into separate .cpp files and have simply
#included these in the main *Controller ones.

Putting this in a separate helper will allow us to test it and it will
simplify the ControllerMapping class considerably.

>
> > * Controllers shouldn't be concerned with saving a preset. Instead that
should
> > be the controller preferences dialog or the ControllerManager's job
>
> The ControllerManager _is_ in charge of saving presets. The Controllers
just contain the code to do so, because it's specific to each Controller
type (as stated above,) and the Manager isn't concerned with those details
(or it would be micro-managi

I think saving presets should be owned by the controller preferences dialog
and not even be part of the controller manager actually.

>
> In short, there's nothing else that can be factored out.
>
> If your concerns are motivated by unit-testing issues, why can't we just
write separate tests for different aspects of a class?

Well the general reason why this is is that you can't isolate the logic you
aim to test when it's all mixed together in one class.

I feel bad coming down hard but these issues are non-negotiable. In the
past I haven't held the MIDI subsystem to as high a standard as say the
engine but now that you are rewriting it I'd like to change that. "It
works" is not good enough for infrastructure code (which this is going to
be more than ever as we add more controller types) so...

Read more...

2818. By Sean M. Pappalardo

Improvements to soft-takeover algorithm. It works really well now.

2819. By Sean M. Pappalardo

WIP: class-ifying the ControllerPresets and ControllerPresetFileHandlers. Currently broken, committing so RJ can take a look.

2820. By RJ Skerry-Ryan

* Add HidControllerPreset and HidControllerPresetFileHandler
  (necessary to keep ControllerPreset and ControllerPresetFileHandler
  abstract)

* Many fixes here and there to get things building.

* Add ControllerPresetVisitor, a visitor to get a Controller subclass
  the real type of the preset being loaded to it.

2821. By RJ Skerry-Ryan

Check for null handlers and presets.

2822. By RJ Skerry-Ryan

Minor errors, use QSet instead of QList for faster contains() checking.

2823. By RJ Skerry-Ryan

Constify a lot of stuff. Switch to having the controller be in charge of saving the preset because it knows the true type of the preset. If I didn't do this then I would have had to make ControllerPresetFileHandler a ControllerPresetVisitor as well, which isn't worth the extra lines of code. Fix some broken/unfinished code so the branch builds.

2824. By RJ Skerry-Ryan

Cleanup lint / style fixes in ControllerManager.

2825. By RJ Skerry-Ryan

error messages for preset mismatches.

2826. By RJ Skerry-Ryan

Tons of cleanups across the whole controllers/ hierarchy.

2827. By RJ Skerry-Ryan

Merging from lp:mixxx

2828. By Sean M. Pappalardo

- Removed all old MIDI code from dlgpreferences
- Fixed compilation with HID enabled after RJ's codefest.
- Replaced the dialog's ability to signal a controller preset load
- Removed the ConfigObject creation in ControllerEngine by passing it to Controller which passes the path the CE needs.
- ControllerManager and ControllerEngine now look for presets and script files in both res/ and the user directory
- Made MidiController::close() destroy the outputHandlers and set the *MidiControllers to call it within their close() functions.
- Added directory copy from midi/ to controllers/ in upgrade.cpp. Also improved the version number processing.

2829. By Sean M. Pappalardo

- Removed more old commented MIDI dialog code
- Cleaned up MixxxControl and added more properties. Perhaps it will become the center of Control 2.0 eventually?
- Converted the Controller subsystem to use MixxxControls instead of ConfigKeys. It's a bit cleaner.
- WIP: Trying to set up a DlgMappableController as a subclass of DlgController but it's showing the UI from the superclass. Help!
- WIP: DlgControllerLearning. I just comitted it so RJ can build to take a look at the above issue.

2830. By RJ Skerry-Ryan

Add IOKit and CoreFoundation frameworks. Fixes build on OS X

2831. By Sean M. Pappalardo

Fixed DlgMappableController selection and display. I can't get the table to expand to full window width so I'll need help with that.

2832. By Sean M. Pappalardo

- DlgMappableController successfully subclasses DlgController now
- Controller learning (MIDI) works now, though I can't test for sure since I won't be near a MIDI controller for weeks. NEED SOMEONE TO TEST PLEASE!!
- Made control descriptions easier to read, added count
- Sorted control descriptions by group
- Got number of decks and samplers from the global COs
- Disabled a bunch of not-yet-implemented stuff in the mapping pane.

2833. By Sean M. Pappalardo

Neatened up MIDI message display in learning dialog and prevented controls from affecting Mixxx during learning.

2834. By Sean M. Pappalardo

Made the Clear All button work.

2835. By RJ Skerry-Ryan

Get rid of fputs in upgrade.cpp

2836. By RJ Skerry-Ryan

Mass reformat tabs in SConscript to spaces. Remove all license blocks from src/controllers. Fix lint here and there. Remove unused code from MixxxControl.

2837. By RJ Skerry-Ryan

Rewrite SoftTakeover to use ControlObjects instead of MixxxControl.

2838. By RJ Skerry-Ryan

Move SoftTakeover to src/controllers/. Add more virtual destructors and fix style issues here and there.

2839. By RJ Skerry-Ryan

Remove more licenses. Fix more lint.

2840. By RJ Skerry-Ryan

Move HID code to src/controllers/hid.

2841. By RJ Skerry-Ryan

Move MixxxControl to src/controllers.

2842. By RJ Skerry-Ryan

Get rid of passing ControllerProcessor timerEvent()'s directly in favor of just calling a Controller::poll() method when the controller needs to poll (if it has polling enabled).

2843. By RJ Skerry-Ryan

Delete ControllerProcessor since it was just a wrapper around a QTimer essentially.

2844. By RJ Skerry-Ryan

Prevent changing visibility for a few methods. Mass re-format some class definitions to conform to mixxx indentation style.

2845. By RJ Skerry-Ryan

Comments, formatting.

2846. By RJ Skerry-Ryan

Remove redundant/unused code here and there.

2847. By RJ Skerry-Ryan

Parent DeviceChannelListener to its HSS1394Controller.

2848. By RJ Skerry-Ryan

* Remove polling declaration from ControllerEnumerator and put it in
  the Controllers themselves.

* Make all variables of Controller private and make sub-classes access
  via accessors.

2849. By RJ Skerry-Ryan

Remove dups option from MidiOutputHandler since it wasn't used anywhere.

2850. By RJ Skerry-Ryan

Add locking to protect m_controllers list in ControllerManager. Other misc cleanups.

2851. By RJ Skerry-Ryan

Make DlgPrefController vars private.

2852. By RJ Skerry-Ryan

Make DlgPrefController not call open() or close() on controllers anymore. Switch HidReader to use QAtomicInt instead of bool flag.

2853. By RJ Skerry-Ryan

Oops. Fix a bug I wrote in preset loading.

2854. By RJ Skerry-Ryan

Sean -- please take a look at the comment I left. Not sure what the desired behavior is here.

2855. By Sean M. Pappalardo

loadPreset takes a filename, not device name

2856. By RJ Skerry-Ryan

Clear pointer on delete.

2857. By Sean M. Pappalardo

Merging from trunk

Unmerged revisions

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'mixxx/SConstruct'
2--- mixxx/SConstruct 2011-11-08 07:39:27 +0000
3+++ mixxx/SConstruct 2012-04-07 14:24:23 +0000
4@@ -33,11 +33,11 @@
5 toolchain = ARGUMENTS.get('toolchain', None)
6
7 available_features = [features.HifiEq,
8- features.MIDIScript,
9 features.Mad,
10 features.CoreAudio,
11 features.MediaFoundation,
12 features.HSS1394,
13+ features.HID,
14 features.VinylControl,
15 features.Shoutcast,
16 features.Profiling,
17
18=== modified file 'mixxx/build/depends.py'
19--- mixxx/build/depends.py 2012-03-28 02:39:59 +0000
20+++ mixxx/build/depends.py 2012-04-07 14:24:23 +0000
21@@ -29,7 +29,7 @@
22 raise Exception('Did not find PortMidi or its development headers.')
23
24 def sources(self, build):
25- return ['midi/portmidienumerator.cpp', 'midi/midideviceportmidi.cpp']
26+ return ['controllers/midi/portmidienumerator.cpp', 'controllers/midi/portmidicontroller.cpp']
27
28 class OpenGL(Dependence):
29
30@@ -158,6 +158,7 @@
31 build.env.Append(LIBS = 'QtSql4')
32 build.env.Append(LIBS = 'QtGui4')
33 build.env.Append(LIBS = 'QtCore4')
34+ build.env.Append(LIBS = 'QtScript4')
35 build.env.Append(LIBS = 'QtWebKit4')
36 build.env.Append(LIBS = 'QtNetwork4')
37 build.env.Append(LIBS = 'QtOpenGL4')
38@@ -168,6 +169,7 @@
39 '$QTDIR/include/QtGui',
40 '$QTDIR/include/QtXml',
41 '$QTDIR/include/QtNetwork',
42+ '$QTDIR/include/QtScript',
43 '$QTDIR/include/QtSql',
44 '$QTDIR/include/QtOpenGL',
45 '$QTDIR/include/QtWebKit',
46@@ -284,9 +286,9 @@
47 "dlgpreferences.cpp",
48 "dlgprefsound.cpp",
49 "dlgprefsounditem.cpp",
50- "dlgprefmidibindings.cpp",
51+ "controllers/dlgprefcontroller.cpp",
52+ "controllers/dlgprefnocontrollers.cpp",
53 "dlgprefplaylist.cpp",
54- "dlgprefnomidi.cpp",
55 "dlgprefcontrols.cpp",
56 "dlgprefbpm.cpp",
57 "dlgprefreplaygain.cpp",
58@@ -295,7 +297,6 @@
59 "dlgabout.cpp",
60 "dlgprefeq.cpp",
61 "dlgprefcrossfader.cpp",
62- "dlgmidilearning.cpp",
63 "dlgtrackinfo.cpp",
64 "dlgprepare.cpp",
65 "dlgautodj.cpp",
66@@ -343,24 +344,23 @@
67 "analyserbpm.cpp",
68 "analyserwaveform.cpp",
69
70- "midi/mididevice.cpp",
71- "midi/mididevicemanager.cpp",
72- "midi/midideviceenumerator.cpp",
73- "midi/midimapping.cpp",
74- "midi/midiinputmappingtablemodel.cpp",
75- "midi/midioutputmappingtablemodel.cpp",
76- "midi/midichanneldelegate.cpp",
77- "midi/midistatusdelegate.cpp",
78- "midi/midinodelegate.cpp",
79- "midi/midioptiondelegate.cpp",
80- "midi/midimessage.cpp",
81- "midi/midiledhandler.cpp",
82+ "controllers/controller.cpp",
83+ "controllers/controllermanager.cpp",
84+ "controllers/controllerenumerator.cpp",
85+ "controllers/controllerengine.cpp",
86+
87+ "controllers/qtscript-bytearray/bytearrayclass.cpp",
88+ "controllers/qtscript-bytearray/bytearrayprototype.cpp",
89+
90+ # MIDI controllers
91+ "controllers/midi/midienumerator.cpp",
92+ "controllers/midi/midicontroller.cpp",
93+ "controllers/midi/midioutputhandler.cpp",
94+
95+ "mixxxcontrol.cpp",
96 "softtakeover.cpp",
97
98 "main.cpp",
99- "controlgroupdelegate.cpp",
100- "controlvaluedelegate.cpp",
101- "mixxxcontrol.cpp",
102 "mixxx.cpp",
103 "errordialoghandler.cpp",
104 "upgrade.cpp",
105@@ -541,9 +541,11 @@
106 # the code for the QT UI forms
107 build.env.Uic4('dlgpreferencesdlg.ui')
108 build.env.Uic4('dlgprefsounddlg.ui')
109- build.env.Uic4('dlgprefmidibindingsdlg.ui')
110+
111+ build.env.Uic4('controllers/dlgprefcontrollerdlg.ui')
112+ build.env.Uic4('controllers/dlgprefnocontrollersdlg.ui')
113+
114 build.env.Uic4('dlgprefplaylistdlg.ui')
115- build.env.Uic4('dlgprefnomididlg.ui')
116 build.env.Uic4('dlgprefcontrolsdlg.ui')
117 build.env.Uic4('dlgprefeqdlg.ui')
118 build.env.Uic4('dlgprefcrossfaderdlg.ui')
119@@ -555,7 +557,6 @@
120 build.env.Uic4('dlgprefnovinyldlg.ui')
121 build.env.Uic4('dlgprefrecorddlg.ui')
122 build.env.Uic4('dlgaboutdlg.ui')
123- build.env.Uic4('dlgmidilearning.ui')
124 build.env.Uic4('dlgtrackinfo.ui')
125 build.env.Uic4('dlgprepare.ui')
126 build.env.Uic4('dlgautodj.ui')
127
128=== modified file 'mixxx/build/features.py'
129--- mixxx/build/features.py 2012-04-02 03:30:43 +0000
130+++ mixxx/build/features.py 2012-04-07 14:24:23 +0000
131@@ -44,11 +44,53 @@
132 build.env.Append(CPPDEFINES = '__HSS1394__')
133
134 def sources(self, build):
135- sources = SCons.Split("""midi/mididevicehss1394.cpp
136- midi/hss1394enumerator.cpp
137- """)
138- return sources
139-
140+ sources = SCons.Split("""controllers/midi/hss1394controller.cpp
141+ controllers/midi/hss1394enumerator.cpp
142+ """)
143+ return sources
144+
145+class HID(Feature):
146+ def description(self):
147+ return "HID controller support"
148+
149+ def enabled(self, build):
150+ build.flags['hid'] = util.get_flags(build.env, 'hid', 1)
151+ if int(build.flags['hid']):
152+ return True
153+ return False
154+
155+ def add_options(self, build, vars):
156+ vars.Add('hid', 'Set to 1 to enable HID controller support.', 1)
157+
158+ def configure(self, build, conf):
159+ if not self.enabled(build):
160+ return
161+ if build.platform_is_linux and (not conf.CheckLib(['libusb-1.0', 'usb-1.0']) or not conf.CheckHeader('libusb-1.0/libusb.h')):
162+ raise Exception('Did not find the libusb 1.0 development library or its header file, exiting!')
163+ return
164+ elif build.platform_is_windows:
165+ if not conf.CheckLib(['hidapi', 'libhidapi']):
166+ raise Exception('Did not find HIDAPI development library, exiting!')
167+ return
168+
169+ build.env.Append(CPPDEFINES = '__HID__')
170+
171+ def sources(self, build):
172+ build.env.Append(CPPPATH=['#lib/hidapi-0.7.0/hidapi'])
173+ if build.platform_is_linux:
174+ build.env.ParseConfig('pkg-config libusb-1.0 --silence-errors --cflags --libs')
175+ sources = SCons.Split("""controllers/hidcontroller.cpp
176+ controllers/hidenumerator.cpp
177+ """)
178+ if build.platform_is_windows:
179+ # This doesn't work. You need to build it in MSVS like all the other dependencies
180+ # sources.append("#lib/hidapi-0.7.0/windows/hid.c")
181+ return sources
182+ elif build.platform_is_osx:
183+ sources.append("#lib/hidapi-0.7.0/mac/hid.c")
184+ else:
185+ sources.append("#lib/hidapi-0.7.0/linux/hid-libusb.c")
186+ return sources
187
188 class Mad(Feature):
189 def description(self):
190@@ -138,35 +180,6 @@
191 build.env.Append(CPPDEFINES='__MEDIAFOUNDATION__')
192 return
193
194-class MIDIScript(Feature):
195- def description(self):
196- return "MIDI Scripting"
197-
198- def enabled(self, build):
199- build.flags['midiscript'] = util.get_flags(build.env, 'midiscript', 0)
200- if int(build.flags['midiscript']):
201- return True
202- return False
203-
204- def add_options(self, build, vars):
205- vars.Add('midiscript', 'Set to 1 to enable MIDI Scripting support.', 1)
206-
207- def configure(self, build, conf):
208- if not self.enabled(build):
209- return
210- if build.platform_is_windows:
211- build.env.Append(LIBS = 'QtScript4')
212- elif build.platform_is_linux:
213- build.env.Append(LIBS = 'QtScript')
214- elif build.platform_is_osx:
215- # TODO(XXX) put in logic here to add a -framework QtScript
216- pass
217- build.env.Append(CPPPATH = '$QTDIR/include/QtScript')
218- build.env.Append(CPPDEFINES = '__MIDISCRIPT__')
219-
220- def sources(self, build):
221- return ["midi/midiscriptengine.cpp"]
222-
223 class LADSPA(Feature):
224
225 def description(self):
226
227=== added directory 'mixxx/lib/hidapi-0.7.0'
228=== added file 'mixxx/lib/hidapi-0.7.0/LICENSE-orig.txt'
229--- mixxx/lib/hidapi-0.7.0/LICENSE-orig.txt 1970-01-01 00:00:00 +0000
230+++ mixxx/lib/hidapi-0.7.0/LICENSE-orig.txt 2012-04-07 14:24:23 +0000
231@@ -0,0 +1,9 @@
232+ HIDAPI - Multi-Platform library for
233+ communication with HID devices.
234+
235+ Copyright 2009, Alan Ott, Signal 11 Software.
236+ All Rights Reserved.
237+
238+ This software may be used by anyone for any reason so
239+ long as the copyright notice in the source files
240+ remains intact.
241
242=== added file 'mixxx/lib/hidapi-0.7.0/LICENSE.txt'
243--- mixxx/lib/hidapi-0.7.0/LICENSE.txt 1970-01-01 00:00:00 +0000
244+++ mixxx/lib/hidapi-0.7.0/LICENSE.txt 2012-04-07 14:24:23 +0000
245@@ -0,0 +1,13 @@
246+HIDAPI can be used under one of three licenses.
247+
248+1. The GNU Public License, version 3.0, in LICENSE-gpl3.txt
249+2. A BSD-Style License, in LICENSE-bsd.txt.
250+3. The more liberal original HIDAPI license. LICENSE-orig.txt
251+
252+The license chosen is at the discretion of the user of HIDAPI. For example:
253+1. An author of GPL software would likely use HIDAPI under the terms of the
254+GPL.
255+
256+2. An author of commercial closed-source software would likely use HIDAPI
257+under the terms of the BSD-style license or the original HIDAPI license.
258+
259
260=== added directory 'mixxx/lib/hidapi-0.7.0/hidapi'
261=== added file 'mixxx/lib/hidapi-0.7.0/hidapi/hidapi.h'
262--- mixxx/lib/hidapi-0.7.0/hidapi/hidapi.h 1970-01-01 00:00:00 +0000
263+++ mixxx/lib/hidapi-0.7.0/hidapi/hidapi.h 2012-04-07 14:24:23 +0000
264@@ -0,0 +1,383 @@
265+/*******************************************************
266+ HIDAPI - Multi-Platform library for
267+ communication with HID devices.
268+
269+ Alan Ott
270+ Signal 11 Software
271+
272+ 8/22/2009
273+
274+ Copyright 2009, All Rights Reserved.
275+
276+ At the discretion of the user of this library,
277+ this software may be licensed under the terms of the
278+ GNU Public License v3, a BSD-Style license, or the
279+ original HIDAPI license as outlined in the LICENSE.txt,
280+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
281+ files located at the root of the source distribution.
282+ These files may also be found in the public source
283+ code repository located at:
284+ http://github.com/signal11/hidapi .
285+********************************************************/
286+
287+/** @file
288+ * @defgroup API hidapi API
289+ */
290+
291+#ifndef HIDAPI_H__
292+#define HIDAPI_H__
293+
294+#include <wchar.h>
295+
296+#ifdef _WIN32
297+ #define HID_API_EXPORT __declspec(dllexport)
298+ #define HID_API_CALL
299+#else
300+ #define HID_API_EXPORT /**< API export macro */
301+ #define HID_API_CALL /**< API call macro */
302+#endif
303+
304+#define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/
305+
306+#ifdef __cplusplus
307+extern "C" {
308+#endif
309+ struct hid_device_;
310+ typedef struct hid_device_ hid_device; /**< opaque hidapi structure */
311+
312+ /** hidapi info structure */
313+ struct hid_device_info {
314+ /** Platform-specific device path */
315+ char *path;
316+ /** Device Vendor ID */
317+ unsigned short vendor_id;
318+ /** Device Product ID */
319+ unsigned short product_id;
320+ /** Serial Number */
321+ wchar_t *serial_number;
322+ /** Device Release Number in binary-coded decimal,
323+ also known as Device Version Number */
324+ unsigned short release_number;
325+ /** Manufacturer String */
326+ wchar_t *manufacturer_string;
327+ /** Product string */
328+ wchar_t *product_string;
329+ /** Usage Page for this Device/Interface
330+ (Windows/Mac only). */
331+ unsigned short usage_page;
332+ /** Usage for this Device/Interface
333+ (Windows/Mac only).*/
334+ unsigned short usage;
335+ /** The USB interface which this logical device
336+ represents. Valid on both Linux implementations
337+ in all cases, and valid on the Windows implementation
338+ only if the device contains more than one interface. */
339+ int interface_number;
340+
341+ /** Pointer to the next device */
342+ struct hid_device_info *next;
343+ };
344+
345+
346+ /** @brief Initialize the HIDAPI library.
347+
348+ This function initializes the HIDAPI library. Calling it is not
349+ strictly necessary, as it will be called automatically by
350+ hid_enumerate() and any of the hid_open_*() functions if it is
351+ needed. This function should be called at the beginning of
352+ execution however, if there is a chance of HIDAPI handles
353+ being opened by different threads simultaneously.
354+
355+ @ingroup API
356+
357+ @returns
358+ This function returns 0 on success and -1 on error.
359+ */
360+ int HID_API_EXPORT HID_API_CALL hid_init(void);
361+
362+ /** @brief Finalize the HIDAPI library.
363+
364+ This function frees all of the static data associated with
365+ HIDAPI. It should be called at the end of execution to avoid
366+ memory leaks.
367+
368+ @ingroup API
369+
370+ @returns
371+ This function returns 0 on success and -1 on error.
372+ */
373+ int HID_API_EXPORT HID_API_CALL hid_exit(void);
374+
375+ /** @brief Enumerate the HID Devices.
376+
377+ This function returns a linked list of all the HID devices
378+ attached to the system which match vendor_id and product_id.
379+ If @p vendor_id and @p product_id are both set to 0, then
380+ all HID devices will be returned.
381+
382+ @ingroup API
383+ @param vendor_id The Vendor ID (VID) of the types of device
384+ to open.
385+ @param product_id The Product ID (PID) of the types of
386+ device to open.
387+
388+ @returns
389+ This function returns a pointer to a linked list of type
390+ struct #hid_device, containing information about the HID devices
391+ attached to the system, or NULL in the case of failure. Free
392+ this linked list by calling hid_free_enumeration().
393+ */
394+ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id);
395+
396+ /** @brief Free an enumeration Linked List
397+
398+ This function frees a linked list created by hid_enumerate().
399+
400+ @ingroup API
401+ @param devs Pointer to a list of struct_device returned from
402+ hid_enumerate().
403+ */
404+ void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs);
405+
406+ /** @brief Open a HID device using a Vendor ID (VID), Product ID
407+ (PID) and optionally a serial number.
408+
409+ If @p serial_number is NULL, the first device with the
410+ specified VID and PID is opened.
411+
412+ @ingroup API
413+ @param vendor_id The Vendor ID (VID) of the device to open.
414+ @param product_id The Product ID (PID) of the device to open.
415+ @param serial_number The Serial Number of the device to open
416+ (Optionally NULL).
417+
418+ @returns
419+ This function returns a pointer to a #hid_device object on
420+ success or NULL on failure.
421+ */
422+ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number);
423+
424+ /** @brief Open a HID device by its path name.
425+
426+ The path name be determined by calling hid_enumerate(), or a
427+ platform-specific path name can be used (eg: /dev/hidraw0 on
428+ Linux).
429+
430+ @ingroup API
431+ @param path The path name of the device to open
432+
433+ @returns
434+ This function returns a pointer to a #hid_device object on
435+ success or NULL on failure.
436+ */
437+ HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path);
438+
439+ /** @brief Write an Output report to a HID device.
440+
441+ The first byte of @p data[] must contain the Report ID. For
442+ devices which only support a single report, this must be set
443+ to 0x0. The remaining bytes contain the report data. Since
444+ the Report ID is mandatory, calls to hid_write() will always
445+ contain one more byte than the report contains. For example,
446+ if a hid report is 16 bytes long, 17 bytes must be passed to
447+ hid_write(), the Report ID (or 0x0, for devices with a
448+ single report), followed by the report data (16 bytes). In
449+ this example, the length passed in would be 17.
450+
451+ hid_write() will send the data on the first OUT endpoint, if
452+ one exists. If it does not, it will send the data through
453+ the Control Endpoint (Endpoint 0).
454+
455+ @ingroup API
456+ @param device A device handle returned from hid_open().
457+ @param data The data to send, including the report number as
458+ the first byte.
459+ @param length The length in bytes of the data to send.
460+
461+ @returns
462+ This function returns the actual number of bytes written and
463+ -1 on error.
464+ */
465+ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length);
466+
467+ /** @brief Read an Input report from a HID device with timeout.
468+
469+ Input reports are returned
470+ to the host through the INTERRUPT IN endpoint. The first byte will
471+ contain the Report number if the device uses numbered reports.
472+
473+ @ingroup API
474+ @param device A device handle returned from hid_open().
475+ @param data A buffer to put the read data into.
476+ @param length The number of bytes to read. For devices with
477+ multiple reports, make sure to read an extra byte for
478+ the report number.
479+ @param milliseconds timeout in milliseconds or -1 for blocking wait.
480+
481+ @returns
482+ This function returns the actual number of bytes read and
483+ -1 on error.
484+ */
485+ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds);
486+
487+ /** @brief Read an Input report from a HID device.
488+
489+ Input reports are returned
490+ to the host through the INTERRUPT IN endpoint. The first byte will
491+ contain the Report number if the device uses numbered reports.
492+
493+ @ingroup API
494+ @param device A device handle returned from hid_open().
495+ @param data A buffer to put the read data into.
496+ @param length The number of bytes to read. For devices with
497+ multiple reports, make sure to read an extra byte for
498+ the report number.
499+
500+ @returns
501+ This function returns the actual number of bytes read and
502+ -1 on error.
503+ */
504+ int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length);
505+
506+ /** @brief Set the device handle to be non-blocking.
507+
508+ In non-blocking mode calls to hid_read() will return
509+ immediately with a value of 0 if there is no data to be
510+ read. In blocking mode, hid_read() will wait (block) until
511+ there is data to read before returning.
512+
513+ Nonblocking can be turned on and off at any time.
514+
515+ @ingroup API
516+ @param device A device handle returned from hid_open().
517+ @param nonblock enable or not the nonblocking reads
518+ - 1 to enable nonblocking
519+ - 0 to disable nonblocking.
520+
521+ @returns
522+ This function returns 0 on success and -1 on error.
523+ */
524+ int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock);
525+
526+ /** @brief Send a Feature report to the device.
527+
528+ Feature reports are sent over the Control endpoint as a
529+ Set_Report transfer. The first byte of @p data[] must
530+ contain the Report ID. For devices which only support a
531+ single report, this must be set to 0x0. The remaining bytes
532+ contain the report data. Since the Report ID is mandatory,
533+ calls to hid_send_feature_report() will always contain one
534+ more byte than the report contains. For example, if a hid
535+ report is 16 bytes long, 17 bytes must be passed to
536+ hid_send_feature_report(): the Report ID (or 0x0, for
537+ devices which do not use numbered reports), followed by the
538+ report data (16 bytes). In this example, the length passed
539+ in would be 17.
540+
541+ @ingroup API
542+ @param device A device handle returned from hid_open().
543+ @param data The data to send, including the report number as
544+ the first byte.
545+ @param length The length in bytes of the data to send, including
546+ the report number.
547+
548+ @returns
549+ This function returns the actual number of bytes written and
550+ -1 on error.
551+ */
552+ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length);
553+
554+ /** @brief Get a feature report from a HID device.
555+
556+ Make sure to set the first byte of @p data[] to the Report
557+ ID of the report to be read. Make sure to allow space for
558+ this extra byte in @p data[].
559+
560+ @ingroup API
561+ @param device A device handle returned from hid_open().
562+ @param data A buffer to put the read data into, including
563+ the Report ID. Set the first byte of @p data[] to the
564+ Report ID of the report to be read.
565+ @param length The number of bytes to read, including an
566+ extra byte for the report ID. The buffer can be longer
567+ than the actual report.
568+
569+ @returns
570+ This function returns the number of bytes read and
571+ -1 on error.
572+ */
573+ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length);
574+
575+ /** @brief Close a HID device.
576+
577+ @ingroup API
578+ @param device A device handle returned from hid_open().
579+ */
580+ void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device);
581+
582+ /** @brief Get The Manufacturer String from a HID device.
583+
584+ @ingroup API
585+ @param device A device handle returned from hid_open().
586+ @param string A wide string buffer to put the data into.
587+ @param maxlen The length of the buffer in multiples of wchar_t.
588+
589+ @returns
590+ This function returns 0 on success and -1 on error.
591+ */
592+ int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
593+
594+ /** @brief Get The Product String from a HID device.
595+
596+ @ingroup API
597+ @param device A device handle returned from hid_open().
598+ @param string A wide string buffer to put the data into.
599+ @param maxlen The length of the buffer in multiples of wchar_t.
600+
601+ @returns
602+ This function returns 0 on success and -1 on error.
603+ */
604+ int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen);
605+
606+ /** @brief Get The Serial Number String from a HID device.
607+
608+ @ingroup API
609+ @param device A device handle returned from hid_open().
610+ @param string A wide string buffer to put the data into.
611+ @param maxlen The length of the buffer in multiples of wchar_t.
612+
613+ @returns
614+ This function returns 0 on success and -1 on error.
615+ */
616+ int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen);
617+
618+ /** @brief Get a string from a HID device, based on its string index.
619+
620+ @ingroup API
621+ @param device A device handle returned from hid_open().
622+ @param string_index The index of the string to get.
623+ @param string A wide string buffer to put the data into.
624+ @param maxlen The length of the buffer in multiples of wchar_t.
625+
626+ @returns
627+ This function returns 0 on success and -1 on error.
628+ */
629+ int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen);
630+
631+ /** @brief Get a string describing the last error which occurred.
632+
633+ @ingroup API
634+ @param device A device handle returned from hid_open().
635+
636+ @returns
637+ This function returns a string containing the last error
638+ which occurred or NULL if none has occurred.
639+ */
640+ HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device);
641+
642+#ifdef __cplusplus
643+}
644+#endif
645+
646+#endif
647+
648
649=== added directory 'mixxx/lib/hidapi-0.7.0/linux'
650=== added file 'mixxx/lib/hidapi-0.7.0/linux/.gitignore'
651--- mixxx/lib/hidapi-0.7.0/linux/.gitignore 1970-01-01 00:00:00 +0000
652+++ mixxx/lib/hidapi-0.7.0/linux/.gitignore 2012-04-07 14:24:23 +0000
653@@ -0,0 +1,13 @@
654+Debug
655+Release
656+*.exp
657+*.ilk
658+*.lib
659+*.suo
660+*.vcproj.*
661+*.ncb
662+*.suo
663+*.dll
664+*.pdb
665+*.o
666+hidtest
667\ No newline at end of file
668
669=== added file 'mixxx/lib/hidapi-0.7.0/linux/Makefile'
670--- mixxx/lib/hidapi-0.7.0/linux/Makefile 1970-01-01 00:00:00 +0000
671+++ mixxx/lib/hidapi-0.7.0/linux/Makefile 2012-04-07 14:24:23 +0000
672@@ -0,0 +1,36 @@
673+###########################################
674+# Simple Makefile for HIDAPI test program
675+#
676+# Alan Ott
677+# Signal 11 Software
678+# 2010-06-01
679+###########################################
680+
681+all: hidtest
682+
683+CC ?= gcc
684+CFLAGS ?= -Wall -g
685+
686+CXX ?= g++
687+CXXFLAGS ?= -Wall -g
688+
689+COBJS = hid-libusb.o
690+CPPOBJS = ../hidtest/hidtest.o
691+OBJS = $(COBJS) $(CPPOBJS)
692+LIBS = `pkg-config libusb-1.0 libudev --libs`
693+INCLUDES ?= -I../hidapi `pkg-config libusb-1.0 --cflags`
694+
695+
696+hidtest: $(OBJS)
697+ $(CXX) $(CXXFLAGS) $(LDFLAGS) $^ $(LIBS) -o hidtest
698+
699+$(COBJS): %.o: %.c
700+ $(CC) $(CFLAGS) -c $(INCLUDES) $< -o $@
701+
702+$(CPPOBJS): %.o: %.cpp
703+ $(CXX) $(CXXFLAGS) -c $(INCLUDES) $< -o $@
704+
705+clean:
706+ rm -f $(OBJS) hidtest
707+
708+.PHONY: clean
709
710=== added file 'mixxx/lib/hidapi-0.7.0/linux/README.txt'
711--- mixxx/lib/hidapi-0.7.0/linux/README.txt 1970-01-01 00:00:00 +0000
712+++ mixxx/lib/hidapi-0.7.0/linux/README.txt 2012-04-07 14:24:23 +0000
713@@ -0,0 +1,63 @@
714+
715+There are two implementations of HIDAPI for Linux. One (hid.c) uses the
716+Linux hidraw driver, and the other (hid-libusb.c) uses libusb. Which one you
717+use depends on your application. Complete functionality of the hidraw
718+version depends on patches to the Linux kernel which are not currently in
719+the mainline. These patches have to do with sending and receiving feature
720+reports. The libusb implementation uses libusb to talk directly to the
721+device, bypassing any Linux HID driver. The disadvantage of the libusb
722+version is that it will only work with USB devices, while the hidraw
723+implementation will work with Bluetooth devices as well.
724+
725+To use HIDAPI, simply drop either hid.c or hid-libusb.c into your
726+application and build using the build parameters in the Makefile.
727+
728+By default, on Linux, the Makefile in this directory is configured to use
729+the libusb implementation. To switch to the hidraw implementation, simply
730+change hid-libusb.c to hid.c in the Makefile.
731+
732+
733+Libusb Implementation notes
734+----------------------------
735+For the libusb implementation, libusb-1.0 must be installed. Libusb 1.0 is
736+different than the legacy libusb 0.1 which is installed on many systems. To
737+install libusb-1.0 on Ubuntu and other Debian-based systems, run:
738+ sudo apt-get install libusb-1.0-0-dev
739+
740+
741+Hidraw Implementation notes
742+----------------------------
743+For the hidraw implementation, libudev headers and libraries are required to
744+build hidapi programs. To install libudev libraries on Ubuntu,
745+and other Debian-based systems, run:
746+ sudo apt-get install libudev-dev
747+
748+On Redhat-based systems, run the following as root:
749+ yum install libudev-devel
750+
751+Unfortunately, the hidraw driver, which the linux version of hidapi is based
752+on, contains bugs in kernel versions < 2.6.36, which the client application
753+should be aware of.
754+
755+Bugs (hidraw implementation only):
756+-----------------------------------
757+On Kernel versions < 2.6.34, if your device uses numbered reports, an extra
758+byte will be returned at the beginning of all reports returned from read()
759+for hidraw devices. This is worked around in the libary. No action should be
760+necessary in the client library.
761+
762+On Kernel versions < 2.6.35, reports will only be sent using a Set_Report
763+transfer on the CONTROL endpoint. No data will ever be sent on an Interrupt
764+Out endpoint if one exists. This is fixed in 2.6.35. In 2.6.35, OUTPUT
765+reports will be sent to the device on the first INTERRUPT OUT endpoint if it
766+exists; If it does not exist, OUTPUT reports will be sent on the CONTROL
767+endpoint.
768+
769+On Kernel versions < 2.6.36, add an extra byte containing the report number
770+to sent reports if numbered reports are used, and the device does not
771+contain an INTERRPUT OUT endpoint for OUTPUT transfers. For example, if
772+your device uses numbered reports and wants to send {0x2 0xff 0xff 0xff} to
773+the device (0x2 is the report number), you must send {0x2 0x2 0xff 0xff
774+0xff}. If your device has the optional Interrupt OUT endpoint, this does not
775+apply (but really on 2.6.35 only, because 2.6.34 won't use the interrupt
776+out endpoint).
777
778=== added file 'mixxx/lib/hidapi-0.7.0/linux/hid-libusb.c'
779--- mixxx/lib/hidapi-0.7.0/linux/hid-libusb.c 1970-01-01 00:00:00 +0000
780+++ mixxx/lib/hidapi-0.7.0/linux/hid-libusb.c 2012-04-07 14:24:23 +0000
781@@ -0,0 +1,1386 @@
782+/*******************************************************
783+ HIDAPI - Multi-Platform library for
784+ communication with HID devices.
785+
786+ Alan Ott
787+ Signal 11 Software
788+
789+ 8/22/2009
790+ Linux Version - 6/2/2010
791+ Libusb Version - 8/13/2010
792+
793+ Copyright 2009, All Rights Reserved.
794+
795+ At the discretion of the user of this library,
796+ this software may be licensed under the terms of the
797+ GNU Public License v3, a BSD-Style license, or the
798+ original HIDAPI license as outlined in the LICENSE.txt,
799+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
800+ files located at the root of the source distribution.
801+ These files may also be found in the public source
802+ code repository located at:
803+ http://github.com/signal11/hidapi .
804+********************************************************/
805+
806+#define _GNU_SOURCE // needed for wcsdup() before glibc 2.10
807+
808+/* C */
809+#include <stdio.h>
810+#include <string.h>
811+#include <stdlib.h>
812+#include <ctype.h>
813+#include <locale.h>
814+#include <errno.h>
815+
816+/* Unix */
817+#include <unistd.h>
818+#include <sys/types.h>
819+#include <sys/stat.h>
820+#include <sys/ioctl.h>
821+#include <sys/utsname.h>
822+#include <fcntl.h>
823+#include <pthread.h>
824+#include <wchar.h>
825+
826+/* GNU / LibUSB */
827+#include "libusb.h"
828+#include "iconv.h"
829+
830+#include "hidapi.h"
831+
832+#ifdef __cplusplus
833+extern "C" {
834+#endif
835+
836+#ifdef DEBUG_PRINTF
837+#define LOG(...) fprintf(stderr, __VA_ARGS__)
838+#else
839+#define LOG(...) do {} while (0)
840+#endif
841+
842+
843+/* Uncomment to enable the retrieval of Usage and Usage Page in
844+hid_enumerate(). Warning, this is very invasive as it requires the detach
845+and re-attach of the kernel driver. See comments inside hid_enumerate().
846+Linux/libusb HIDAPI programs are encouraged to use the interface number
847+instead to differentiate between interfaces on a composite HID device. */
848+/*#define INVASIVE_GET_USAGE*/
849+
850+/* Linked List of input reports received from the device. */
851+struct input_report {
852+ uint8_t *data;
853+ size_t len;
854+ struct input_report *next;
855+};
856+
857+
858+struct hid_device_ {
859+ /* Handle to the actual device. */
860+ libusb_device_handle *device_handle;
861+
862+ /* Endpoint information */
863+ int input_endpoint;
864+ int output_endpoint;
865+ int input_ep_max_packet_size;
866+
867+ /* The interface number of the HID */
868+ int interface;
869+
870+ /* Indexes of Strings */
871+ int manufacturer_index;
872+ int product_index;
873+ int serial_index;
874+
875+ /* Whether blocking reads are used */
876+ int blocking; /* boolean */
877+
878+ /* Read thread objects */
879+ pthread_t thread;
880+ pthread_mutex_t mutex; /* Protects input_reports */
881+ pthread_cond_t condition;
882+ pthread_barrier_t barrier; /* Ensures correct startup sequence */
883+ int shutdown_thread;
884+ struct libusb_transfer *transfer;
885+
886+ /* List of received input reports. */
887+ struct input_report *input_reports;
888+};
889+
890+static int initialized = 0;
891+
892+uint16_t get_usb_code_for_current_locale(void);
893+static int return_data(hid_device *dev, unsigned char *data, size_t length);
894+
895+static hid_device *new_hid_device(void)
896+{
897+ hid_device *dev = calloc(1, sizeof(hid_device));
898+ dev->device_handle = NULL;
899+ dev->input_endpoint = 0;
900+ dev->output_endpoint = 0;
901+ dev->input_ep_max_packet_size = 0;
902+ dev->interface = 0;
903+ dev->manufacturer_index = 0;
904+ dev->product_index = 0;
905+ dev->serial_index = 0;
906+ dev->blocking = 1;
907+ dev->shutdown_thread = 0;
908+ dev->transfer = NULL;
909+ dev->input_reports = NULL;
910+
911+ pthread_mutex_init(&dev->mutex, NULL);
912+ pthread_cond_init(&dev->condition, NULL);
913+ pthread_barrier_init(&dev->barrier, NULL, 2);
914+
915+ return dev;
916+}
917+
918+static void free_hid_device(hid_device *dev)
919+{
920+ /* Clean up the thread objects */
921+ pthread_barrier_destroy(&dev->barrier);
922+ pthread_cond_destroy(&dev->condition);
923+ pthread_mutex_destroy(&dev->mutex);
924+
925+ /* Free the device itself */
926+ free(dev);
927+}
928+
929+#if 0
930+//TODO: Implement this funciton on Linux.
931+static void register_error(hid_device *device, const char *op)
932+{
933+
934+}
935+#endif
936+
937+#ifdef INVASIVE_GET_USAGE
938+/* Get bytes from a HID Report Descriptor.
939+ Only call with a num_bytes of 0, 1, 2, or 4. */
940+static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur)
941+{
942+ /* Return if there aren't enough bytes. */
943+ if (cur + num_bytes >= len)
944+ return 0;
945+
946+ if (num_bytes == 0)
947+ return 0;
948+ else if (num_bytes == 1) {
949+ return rpt[cur+1];
950+ }
951+ else if (num_bytes == 2) {
952+ return (rpt[cur+2] * 256 + rpt[cur+1]);
953+ }
954+ else if (num_bytes == 4) {
955+ return (rpt[cur+4] * 0x01000000 +
956+ rpt[cur+3] * 0x00010000 +
957+ rpt[cur+2] * 0x00000100 +
958+ rpt[cur+1] * 0x00000001);
959+ }
960+ else
961+ return 0;
962+}
963+
964+/* Retrieves the device's Usage Page and Usage from the report
965+ descriptor. The algorithm is simple, as it just returns the first
966+ Usage and Usage Page that it finds in the descriptor.
967+ The return value is 0 on success and -1 on failure. */
968+static int get_usage(uint8_t *report_descriptor, size_t size,
969+ unsigned short *usage_page, unsigned short *usage)
970+{
971+ int i = 0;
972+ int size_code;
973+ int data_len, key_size;
974+ int usage_found = 0, usage_page_found = 0;
975+
976+ while (i < size) {
977+ int key = report_descriptor[i];
978+ int key_cmd = key & 0xfc;
979+
980+ //printf("key: %02hhx\n", key);
981+
982+ if ((key & 0xf0) == 0xf0) {
983+ /* This is a Long Item. The next byte contains the
984+ length of the data section (value) for this key.
985+ See the HID specification, version 1.11, section
986+ 6.2.2.3, titled "Long Items." */
987+ if (i+1 < size)
988+ data_len = report_descriptor[i+1];
989+ else
990+ data_len = 0; /* malformed report */
991+ key_size = 3;
992+ }
993+ else {
994+ /* This is a Short Item. The bottom two bits of the
995+ key contain the size code for the data section
996+ (value) for this key. Refer to the HID
997+ specification, version 1.11, section 6.2.2.2,
998+ titled "Short Items." */
999+ size_code = key & 0x3;
1000+ switch (size_code) {
1001+ case 0:
1002+ case 1:
1003+ case 2:
1004+ data_len = size_code;
1005+ break;
1006+ case 3:
1007+ data_len = 4;
1008+ break;
1009+ default:
1010+ /* Can't ever happen since size_code is & 0x3 */
1011+ data_len = 0;
1012+ break;
1013+ };
1014+ key_size = 1;
1015+ }
1016+
1017+ if (key_cmd == 0x4) {
1018+ *usage_page = get_bytes(report_descriptor, size, data_len, i);
1019+ usage_page_found = 1;
1020+ //printf("Usage Page: %x\n", (uint32_t)*usage_page);
1021+ }
1022+ if (key_cmd == 0x8) {
1023+ *usage = get_bytes(report_descriptor, size, data_len, i);
1024+ usage_found = 1;
1025+ //printf("Usage: %x\n", (uint32_t)*usage);
1026+ }
1027+
1028+ if (usage_page_found && usage_found)
1029+ return 0; /* success */
1030+
1031+ /* Skip over this key and it's associated data */
1032+ i += data_len + key_size;
1033+ }
1034+
1035+ return -1; /* failure */
1036+}
1037+#endif // INVASIVE_GET_USAGE
1038+
1039+
1040+/* Get the first language the device says it reports. This comes from
1041+ USB string #0. */
1042+static uint16_t get_first_language(libusb_device_handle *dev)
1043+{
1044+ uint16_t buf[32];
1045+ int len;
1046+
1047+ /* Get the string from libusb. */
1048+ len = libusb_get_string_descriptor(dev,
1049+ 0x0, /* String ID */
1050+ 0x0, /* Language */
1051+ (unsigned char*)buf,
1052+ sizeof(buf));
1053+ if (len < 4)
1054+ return 0x0;
1055+
1056+ return buf[1]; // First two bytes are len and descriptor type.
1057+}
1058+
1059+static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
1060+{
1061+ uint16_t buf[32];
1062+ int len;
1063+ int i;
1064+
1065+ /* Get the string from libusb. */
1066+ len = libusb_get_string_descriptor(dev,
1067+ 0x0, /* String ID */
1068+ 0x0, /* Language */
1069+ (unsigned char*)buf,
1070+ sizeof(buf));
1071+ if (len < 4)
1072+ return 0x0;
1073+
1074+
1075+ len /= 2; /* language IDs are two-bytes each. */
1076+ /* Start at index 1 because there are two bytes of protocol data. */
1077+ for (i = 1; i < len; i++) {
1078+ if (buf[i] == lang)
1079+ return 1;
1080+ }
1081+
1082+ return 0;
1083+}
1084+
1085+
1086+/* This function returns a newly allocated wide string containing the USB
1087+ device string numbered by the index. The returned string must be freed
1088+ by using free(). */
1089+static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
1090+{
1091+ char buf[512];
1092+ int len;
1093+ wchar_t *str = NULL;
1094+ wchar_t wbuf[256];
1095+
1096+ /* iconv variables */
1097+ iconv_t ic;
1098+ size_t inbytes;
1099+ size_t outbytes;
1100+ size_t res;
1101+ char *inptr;
1102+ char *outptr;
1103+
1104+ /* Determine which language to use. */
1105+ uint16_t lang;
1106+ lang = get_usb_code_for_current_locale();
1107+ if (!is_language_supported(dev, lang))
1108+ lang = get_first_language(dev);
1109+
1110+ /* Get the string from libusb. */
1111+ len = libusb_get_string_descriptor(dev,
1112+ idx,
1113+ lang,
1114+ (unsigned char*)buf,
1115+ sizeof(buf));
1116+ if (len < 0)
1117+ return NULL;
1118+
1119+ buf[sizeof(buf)-1] = '\0';
1120+
1121+ if (len+1 < sizeof(buf))
1122+ buf[len+1] = '\0';
1123+
1124+ /* Initialize iconv. */
1125+ ic = iconv_open("UTF-32", "UTF-16");
1126+ if (ic == (iconv_t)-1)
1127+ return NULL;
1128+
1129+ /* Convert to UTF-32 (wchar_t on glibc systems).
1130+ Skip the first character (2-bytes). */
1131+ inptr = buf+2;
1132+ inbytes = len-2;
1133+ outptr = (char*) wbuf;
1134+ outbytes = sizeof(wbuf);
1135+ res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
1136+ if (res == (size_t)-1)
1137+ goto err;
1138+
1139+ /* Write the terminating NULL. */
1140+ wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
1141+ if (outbytes >= sizeof(wbuf[0]))
1142+ *((wchar_t*)outptr) = 0x00000000;
1143+
1144+ /* Allocate and copy the string. */
1145+ str = wcsdup(wbuf+1);
1146+
1147+err:
1148+ iconv_close(ic);
1149+
1150+ return str;
1151+}
1152+
1153+static char *make_path(libusb_device *dev, int interface_number)
1154+{
1155+ char str[64];
1156+ snprintf(str, sizeof(str), "%04x:%04x:%02x",
1157+ libusb_get_bus_number(dev),
1158+ libusb_get_device_address(dev),
1159+ interface_number);
1160+ str[sizeof(str)-1] = '\0';
1161+
1162+ return strdup(str);
1163+}
1164+
1165+
1166+int HID_API_EXPORT hid_init(void)
1167+{
1168+ if (!initialized) {
1169+ if (libusb_init(NULL))
1170+ return -1;
1171+ initialized = 1;
1172+ }
1173+
1174+ return 0;
1175+}
1176+
1177+int HID_API_EXPORT hid_exit(void)
1178+{
1179+ if (initialized) {
1180+ libusb_exit(NULL);
1181+ initialized = 0;
1182+ }
1183+
1184+ return 0;
1185+}
1186+
1187+struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
1188+{
1189+ libusb_device **devs;
1190+ libusb_device *dev;
1191+ libusb_device_handle *handle;
1192+ ssize_t num_devs;
1193+ int i = 0;
1194+
1195+ struct hid_device_info *root = NULL; // return object
1196+ struct hid_device_info *cur_dev = NULL;
1197+
1198+ setlocale(LC_ALL,"");
1199+
1200+ if (!initialized)
1201+ hid_init();
1202+
1203+ num_devs = libusb_get_device_list(NULL, &devs);
1204+ if (num_devs < 0)
1205+ return NULL;
1206+ while ((dev = devs[i++]) != NULL) {
1207+ struct libusb_device_descriptor desc;
1208+ struct libusb_config_descriptor *conf_desc = NULL;
1209+ int j, k;
1210+ int interface_num = 0;
1211+
1212+ int res = libusb_get_device_descriptor(dev, &desc);
1213+ unsigned short dev_vid = desc.idVendor;
1214+ unsigned short dev_pid = desc.idProduct;
1215+
1216+ /* HID's are defined at the interface level. */
1217+ if (desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE)
1218+ continue;
1219+
1220+ res = libusb_get_active_config_descriptor(dev, &conf_desc);
1221+ if (res < 0)
1222+ libusb_get_config_descriptor(dev, 0, &conf_desc);
1223+ if (conf_desc) {
1224+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {
1225+ const struct libusb_interface *intf = &conf_desc->interface[j];
1226+ for (k = 0; k < intf->num_altsetting; k++) {
1227+ const struct libusb_interface_descriptor *intf_desc;
1228+ intf_desc = &intf->altsetting[k];
1229+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
1230+ interface_num = intf_desc->bInterfaceNumber;
1231+
1232+ /* Check the VID/PID against the arguments */
1233+ if ((vendor_id == 0x0 && product_id == 0x0) ||
1234+ (vendor_id == dev_vid && product_id == dev_pid)) {
1235+ struct hid_device_info *tmp;
1236+
1237+ /* VID/PID match. Create the record. */
1238+ tmp = calloc(1, sizeof(struct hid_device_info));
1239+ if (cur_dev) {
1240+ cur_dev->next = tmp;
1241+ }
1242+ else {
1243+ root = tmp;
1244+ }
1245+ cur_dev = tmp;
1246+
1247+ /* Fill out the record */
1248+ cur_dev->next = NULL;
1249+ cur_dev->path = make_path(dev, interface_num);
1250+
1251+ res = libusb_open(dev, &handle);
1252+
1253+ if (res >= 0) {
1254+ /* Serial Number */
1255+ if (desc.iSerialNumber > 0)
1256+ cur_dev->serial_number =
1257+ get_usb_string(handle, desc.iSerialNumber);
1258+
1259+ /* Manufacturer and Product strings */
1260+ if (desc.iManufacturer > 0)
1261+ cur_dev->manufacturer_string =
1262+ get_usb_string(handle, desc.iManufacturer);
1263+ if (desc.iProduct > 0)
1264+ cur_dev->product_string =
1265+ get_usb_string(handle, desc.iProduct);
1266+
1267+#ifdef INVASIVE_GET_USAGE
1268+ /*
1269+ This section is removed because it is too
1270+ invasive on the system. Getting a Usage Page
1271+ and Usage requires parsing the HID Report
1272+ descriptor. Getting a HID Report descriptor
1273+ involves claiming the interface. Claiming the
1274+ interface involves detaching the kernel driver.
1275+ Detaching the kernel driver is hard on the system
1276+ because it will unclaim interfaces (if another
1277+ app has them claimed) and the re-attachment of
1278+ the driver will sometimes change /dev entry names.
1279+ It is for these reasons that this section is
1280+ #if 0. For composite devices, use the interface
1281+ field in the hid_device_info struct to distinguish
1282+ between interfaces. */
1283+ int detached = 0;
1284+ unsigned char data[256];
1285+
1286+ /* Usage Page and Usage */
1287+ res = libusb_kernel_driver_active(handle, interface_num);
1288+ if (res == 1) {
1289+ res = libusb_detach_kernel_driver(handle, interface_num);
1290+ if (res < 0)
1291+ LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
1292+ else
1293+ detached = 1;
1294+ }
1295+ res = libusb_claim_interface(handle, interface_num);
1296+ if (res >= 0) {
1297+ /* Get the HID Report Descriptor. */
1298+ res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
1299+ if (res >= 0) {
1300+ unsigned short page=0, usage=0;
1301+ /* Parse the usage and usage page
1302+ out of the report descriptor. */
1303+ get_usage(data, res, &page, &usage);
1304+ cur_dev->usage_page = page;
1305+ cur_dev->usage = usage;
1306+ }
1307+ else
1308+ LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);
1309+
1310+ /* Release the interface */
1311+ res = libusb_release_interface(handle, interface_num);
1312+ if (res < 0)
1313+ LOG("Can't release the interface.\n");
1314+ }
1315+ else
1316+ LOG("Can't claim interface %d\n", res);
1317+
1318+ /* Re-attach kernel driver if necessary. */
1319+ if (detached) {
1320+ res = libusb_attach_kernel_driver(handle, interface_num);
1321+ if (res < 0)
1322+ LOG("Couldn't re-attach kernel driver.\n");
1323+ }
1324+#endif /*******************/
1325+
1326+ libusb_close(handle);
1327+ }
1328+ /* VID/PID */
1329+ cur_dev->vendor_id = dev_vid;
1330+ cur_dev->product_id = dev_pid;
1331+
1332+ /* Release Number */
1333+ cur_dev->release_number = desc.bcdDevice;
1334+
1335+ /* Interface Number */
1336+ cur_dev->interface_number = interface_num;
1337+ }
1338+ }
1339+ } /* altsettings */
1340+ } /* interfaces */
1341+ libusb_free_config_descriptor(conf_desc);
1342+ }
1343+ }
1344+
1345+ libusb_free_device_list(devs, 1);
1346+
1347+ return root;
1348+}
1349+
1350+void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
1351+{
1352+ struct hid_device_info *d = devs;
1353+ while (d) {
1354+ struct hid_device_info *next = d->next;
1355+ free(d->path);
1356+ free(d->serial_number);
1357+ free(d->manufacturer_string);
1358+ free(d->product_string);
1359+ free(d);
1360+ d = next;
1361+ }
1362+}
1363+
1364+hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number)
1365+{
1366+ struct hid_device_info *devs, *cur_dev;
1367+ const char *path_to_open = NULL;
1368+ hid_device *handle = NULL;
1369+
1370+ devs = hid_enumerate(vendor_id, product_id);
1371+ cur_dev = devs;
1372+ while (cur_dev) {
1373+ if (cur_dev->vendor_id == vendor_id &&
1374+ cur_dev->product_id == product_id) {
1375+ if (serial_number) {
1376+ if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
1377+ path_to_open = cur_dev->path;
1378+ break;
1379+ }
1380+ }
1381+ else {
1382+ path_to_open = cur_dev->path;
1383+ break;
1384+ }
1385+ }
1386+ cur_dev = cur_dev->next;
1387+ }
1388+
1389+ if (path_to_open) {
1390+ /* Open the device */
1391+ handle = hid_open_path(path_to_open);
1392+ }
1393+
1394+ hid_free_enumeration(devs);
1395+
1396+ return handle;
1397+}
1398+
1399+static void read_callback(struct libusb_transfer *transfer)
1400+{
1401+ hid_device *dev = transfer->user_data;
1402+
1403+ if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
1404+
1405+ struct input_report *rpt = malloc(sizeof(*rpt));
1406+ rpt->data = malloc(transfer->actual_length);
1407+ memcpy(rpt->data, transfer->buffer, transfer->actual_length);
1408+ rpt->len = transfer->actual_length;
1409+ rpt->next = NULL;
1410+
1411+ pthread_mutex_lock(&dev->mutex);
1412+
1413+ /* Attach the new report object to the end of the list. */
1414+ if (dev->input_reports == NULL) {
1415+ /* The list is empty. Put it at the root. */
1416+ dev->input_reports = rpt;
1417+ pthread_cond_signal(&dev->condition);
1418+ }
1419+ else {
1420+ /* Find the end of the list and attach. */
1421+ struct input_report *cur = dev->input_reports;
1422+ int num_queued = 0;
1423+ while (cur->next != NULL) {
1424+ cur = cur->next;
1425+ num_queued++;
1426+ }
1427+ cur->next = rpt;
1428+
1429+ /* Pop one off if we've reached 30 in the queue. This
1430+ way we don't grow forever if the user never reads
1431+ anything from the device. */
1432+ if (num_queued > 30) {
1433+ return_data(dev, NULL, 0);
1434+ }
1435+ }
1436+ pthread_mutex_unlock(&dev->mutex);
1437+ }
1438+ else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
1439+ dev->shutdown_thread = 1;
1440+ return;
1441+ }
1442+ else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
1443+ dev->shutdown_thread = 1;
1444+ return;
1445+ }
1446+ else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
1447+ //LOG("Timeout (normal)\n");
1448+ }
1449+ else {
1450+ LOG("Unknown transfer code: %d\n", transfer->status);
1451+ }
1452+
1453+ /* Re-submit the transfer object. */
1454+ libusb_submit_transfer(transfer);
1455+}
1456+
1457+
1458+static void *read_thread(void *param)
1459+{
1460+ hid_device *dev = param;
1461+ unsigned char *buf;
1462+ const size_t length = dev->input_ep_max_packet_size;
1463+
1464+ /* Set up the transfer object. */
1465+ buf = malloc(length);
1466+ dev->transfer = libusb_alloc_transfer(0);
1467+ libusb_fill_interrupt_transfer(dev->transfer,
1468+ dev->device_handle,
1469+ dev->input_endpoint,
1470+ buf,
1471+ length,
1472+ read_callback,
1473+ dev,
1474+ 5000/*timeout*/);
1475+
1476+ /* Make the first submission. Further submissions are made
1477+ from inside read_callback() */
1478+ libusb_submit_transfer(dev->transfer);
1479+
1480+ // Notify the main thread that the read thread is up and running.
1481+ pthread_barrier_wait(&dev->barrier);
1482+
1483+ /* Handle all the events. */
1484+ while (!dev->shutdown_thread) {
1485+ int res;
1486+ res = libusb_handle_events(NULL);
1487+ if (res < 0) {
1488+ /* There was an error. Break out of this loop. */
1489+ break;
1490+ }
1491+ }
1492+
1493+ /* Cancel any transfer that may be pending. This call will fail
1494+ if no transfers are pending, but that's OK. */
1495+ if (libusb_cancel_transfer(dev->transfer) == 0) {
1496+ /* The transfer was cancelled, so wait for its completion. */
1497+ libusb_handle_events(NULL);
1498+ }
1499+
1500+ /* Now that the read thread is stopping, Wake any threads which are
1501+ waiting on data (in hid_read_timeout()). Do this under a mutex to
1502+ make sure that a thread which is about to go to sleep waiting on
1503+ the condition acutally will go to sleep before the condition is
1504+ signaled. */
1505+ pthread_mutex_lock(&dev->mutex);
1506+ pthread_cond_broadcast(&dev->condition);
1507+ pthread_mutex_unlock(&dev->mutex);
1508+
1509+ /* The dev->transfer->buffer and dev->transfer objects are cleaned up
1510+ in hid_close(). They are not cleaned up here because this thread
1511+ could end either due to a disconnect or due to a user
1512+ call to hid_close(). In both cases the objects can be safely
1513+ cleaned up after the call to pthread_join() (in hid_close()), but
1514+ since hid_close() calls libusb_cancel_transfer(), on these objects,
1515+ they can not be cleaned up here. */
1516+
1517+ return NULL;
1518+}
1519+
1520+
1521+hid_device * HID_API_EXPORT hid_open_path(const char *path)
1522+{
1523+ hid_device *dev = NULL;
1524+
1525+ dev = new_hid_device();
1526+
1527+ libusb_device **devs;
1528+ libusb_device *usb_dev;
1529+ ssize_t num_devs;
1530+ int res;
1531+ int d = 0;
1532+ int good_open = 0;
1533+
1534+ setlocale(LC_ALL,"");
1535+
1536+ if (!initialized)
1537+ hid_init();
1538+
1539+ num_devs = libusb_get_device_list(NULL, &devs);
1540+ while ((usb_dev = devs[d++]) != NULL) {
1541+ struct libusb_device_descriptor desc;
1542+ struct libusb_config_descriptor *conf_desc = NULL;
1543+ int i,j,k;
1544+ libusb_get_device_descriptor(usb_dev, &desc);
1545+
1546+ if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)
1547+ continue;
1548+ for (j = 0; j < conf_desc->bNumInterfaces; j++) {
1549+ const struct libusb_interface *intf = &conf_desc->interface[j];
1550+ for (k = 0; k < intf->num_altsetting; k++) {
1551+ const struct libusb_interface_descriptor *intf_desc;
1552+ intf_desc = &intf->altsetting[k];
1553+ if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
1554+ char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);
1555+ if (!strcmp(dev_path, path)) {
1556+ /* Matched Paths. Open this device */
1557+
1558+ // OPEN HERE //
1559+ res = libusb_open(usb_dev, &dev->device_handle);
1560+ if (res < 0) {
1561+ LOG("can't open device\n");
1562+ free(dev_path);
1563+ break;
1564+ }
1565+ good_open = 1;
1566+
1567+ /* Detach the kernel driver, but only if the
1568+ device is managed by the kernel */
1569+ if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
1570+ res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);
1571+ if (res < 0) {
1572+ libusb_close(dev->device_handle);
1573+ LOG("Unable to detach Kernel Driver\n");
1574+ free(dev_path);
1575+ good_open = 0;
1576+ break;
1577+ }
1578+ }
1579+
1580+ res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
1581+ if (res < 0) {
1582+ LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
1583+ free(dev_path);
1584+ libusb_close(dev->device_handle);
1585+ good_open = 0;
1586+ break;
1587+ }
1588+
1589+ /* Store off the string descriptor indexes */
1590+ dev->manufacturer_index = desc.iManufacturer;
1591+ dev->product_index = desc.iProduct;
1592+ dev->serial_index = desc.iSerialNumber;
1593+
1594+ /* Store off the interface number */
1595+ dev->interface = intf_desc->bInterfaceNumber;
1596+
1597+ /* Find the INPUT and OUTPUT endpoints. An
1598+ OUTPUT endpoint is not required. */
1599+ for (i = 0; i < intf_desc->bNumEndpoints; i++) {
1600+ const struct libusb_endpoint_descriptor *ep
1601+ = &intf_desc->endpoint[i];
1602+
1603+ /* Determine the type and direction of this
1604+ endpoint. */
1605+ int is_interrupt =
1606+ (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
1607+ == LIBUSB_TRANSFER_TYPE_INTERRUPT;
1608+ int is_output =
1609+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
1610+ == LIBUSB_ENDPOINT_OUT;
1611+ int is_input =
1612+ (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
1613+ == LIBUSB_ENDPOINT_IN;
1614+
1615+ /* Decide whether to use it for intput or output. */
1616+ if (dev->input_endpoint == 0 &&
1617+ is_interrupt && is_input) {
1618+ /* Use this endpoint for INPUT */
1619+ dev->input_endpoint = ep->bEndpointAddress;
1620+ dev->input_ep_max_packet_size = ep->wMaxPacketSize;
1621+ }
1622+ if (dev->output_endpoint == 0 &&
1623+ is_interrupt && is_output) {
1624+ /* Use this endpoint for OUTPUT */
1625+ dev->output_endpoint = ep->bEndpointAddress;
1626+ }
1627+ }
1628+
1629+ pthread_create(&dev->thread, NULL, read_thread, dev);
1630+
1631+ // Wait here for the read thread to be initialized.
1632+ pthread_barrier_wait(&dev->barrier);
1633+
1634+ }
1635+ free(dev_path);
1636+ }
1637+ }
1638+ }
1639+ libusb_free_config_descriptor(conf_desc);
1640+
1641+ }
1642+
1643+ libusb_free_device_list(devs, 1);
1644+
1645+ // If we have a good handle, return it.
1646+ if (good_open) {
1647+ return dev;
1648+ }
1649+ else {
1650+ // Unable to open any devices.
1651+ free_hid_device(dev);
1652+ return NULL;
1653+ }
1654+}
1655+
1656+
1657+int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
1658+{
1659+ int res;
1660+ int report_number = data[0];
1661+ int skipped_report_id = 0;
1662+
1663+ if (report_number == 0x0) {
1664+ data++;
1665+ length--;
1666+ skipped_report_id = 1;
1667+ }
1668+
1669+
1670+ if (dev->output_endpoint <= 0) {
1671+ /* No interrput out endpoint. Use the Control Endpoint */
1672+ res = libusb_control_transfer(dev->device_handle,
1673+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
1674+ 0x09/*HID Set_Report*/,
1675+ (2/*HID output*/ << 8) | report_number,
1676+ dev->interface,
1677+ (unsigned char *)data, length,
1678+ 1000/*timeout millis*/);
1679+
1680+ if (res < 0)
1681+ return -1;
1682+
1683+ if (skipped_report_id)
1684+ length++;
1685+
1686+ return length;
1687+ }
1688+ else {
1689+ /* Use the interrupt out endpoint */
1690+ int actual_length;
1691+ res = libusb_interrupt_transfer(dev->device_handle,
1692+ dev->output_endpoint,
1693+ (unsigned char*)data,
1694+ length,
1695+ &actual_length, 1000);
1696+
1697+ if (res < 0)
1698+ return -1;
1699+
1700+ if (skipped_report_id)
1701+ actual_length++;
1702+
1703+ return actual_length;
1704+ }
1705+}
1706+
1707+/* Helper function, to simplify hid_read().
1708+ This should be called with dev->mutex locked. */
1709+static int return_data(hid_device *dev, unsigned char *data, size_t length)
1710+{
1711+ /* Copy the data out of the linked list item (rpt) into the
1712+ return buffer (data), and delete the liked list item. */
1713+ struct input_report *rpt = dev->input_reports;
1714+ size_t len = (length < rpt->len)? length: rpt->len;
1715+ if (len > 0)
1716+ memcpy(data, rpt->data, len);
1717+ dev->input_reports = rpt->next;
1718+ free(rpt->data);
1719+ free(rpt);
1720+ return len;
1721+}
1722+
1723+static void cleanup_mutex(void *param)
1724+{
1725+ hid_device *dev = param;
1726+ pthread_mutex_unlock(&dev->mutex);
1727+}
1728+
1729+
1730+int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
1731+{
1732+ int bytes_read = -1;
1733+
1734+#if 0
1735+ int transferred;
1736+ int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);
1737+ LOG("transferred: %d\n", transferred);
1738+ return transferred;
1739+#endif
1740+
1741+ pthread_mutex_lock(&dev->mutex);
1742+ pthread_cleanup_push(&cleanup_mutex, dev);
1743+
1744+ /* There's an input report queued up. Return it. */
1745+ if (dev->input_reports) {
1746+ /* Return the first one */
1747+ bytes_read = return_data(dev, data, length);
1748+ goto ret;
1749+ }
1750+
1751+ if (dev->shutdown_thread) {
1752+ /* This means the device has been disconnected.
1753+ An error code of -1 should be returned. */
1754+ bytes_read = -1;
1755+ goto ret;
1756+ }
1757+
1758+ if (milliseconds == -1) {
1759+ /* Blocking */
1760+ while (!dev->input_reports && !dev->shutdown_thread) {
1761+ pthread_cond_wait(&dev->condition, &dev->mutex);
1762+ }
1763+ if (dev->input_reports) {
1764+ bytes_read = return_data(dev, data, length);
1765+ }
1766+ }
1767+ else if (milliseconds > 0) {
1768+ /* Non-blocking, but called with timeout. */
1769+ int res;
1770+ struct timespec ts;
1771+ clock_gettime(CLOCK_REALTIME, &ts);
1772+ ts.tv_sec += milliseconds / 1000;
1773+ ts.tv_nsec += (milliseconds % 1000) * 1000000;
1774+ if (ts.tv_nsec >= 1000000000L) {
1775+ ts.tv_sec++;
1776+ ts.tv_nsec -= 1000000000L;
1777+ }
1778+
1779+ while (!dev->input_reports && !dev->shutdown_thread) {
1780+ res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);
1781+ if (res == 0) {
1782+ if (dev->input_reports) {
1783+ bytes_read = return_data(dev, data, length);
1784+ break;
1785+ }
1786+
1787+ /* If we're here, there was a spurious wake up
1788+ or the read thread was shutdown. Run the
1789+ loop again (ie: don't break). */
1790+ }
1791+ else if (res == ETIMEDOUT) {
1792+ /* Timed out. */
1793+ bytes_read = 0;
1794+ break;
1795+ }
1796+ else {
1797+ /* Error. */
1798+ bytes_read = -1;
1799+ break;
1800+ }
1801+ }
1802+ }
1803+ else {
1804+ /* Purely non-blocking */
1805+ bytes_read = 0;
1806+ }
1807+
1808+ret:
1809+ pthread_mutex_unlock(&dev->mutex);
1810+ pthread_cleanup_pop(0);
1811+
1812+ return bytes_read;
1813+}
1814+
1815+int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
1816+{
1817+ return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0);
1818+}
1819+
1820+int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
1821+{
1822+ dev->blocking = !nonblock;
1823+
1824+ return 0;
1825+}
1826+
1827+
1828+int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
1829+{
1830+ int res = -1;
1831+ int skipped_report_id = 0;
1832+ int report_number = data[0];
1833+
1834+ if (report_number == 0x0) {
1835+ data++;
1836+ length--;
1837+ skipped_report_id = 1;
1838+ }
1839+
1840+ res = libusb_control_transfer(dev->device_handle,
1841+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
1842+ 0x09/*HID set_report*/,
1843+ (3/*HID feature*/ << 8) | report_number,
1844+ dev->interface,
1845+ (unsigned char *)data, length,
1846+ 1000/*timeout millis*/);
1847+
1848+ if (res < 0)
1849+ return -1;
1850+
1851+ /* Account for the report ID */
1852+ if (skipped_report_id)
1853+ length++;
1854+
1855+ return length;
1856+}
1857+
1858+int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
1859+{
1860+ int res = -1;
1861+ int skipped_report_id = 0;
1862+ int report_number = data[0];
1863+
1864+ if (report_number == 0x0) {
1865+ /* Offset the return buffer by 1, so that the report ID
1866+ will remain in byte 0. */
1867+ data++;
1868+ length--;
1869+ skipped_report_id = 1;
1870+ }
1871+ res = libusb_control_transfer(dev->device_handle,
1872+ LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN,
1873+ 0x01/*HID get_report*/,
1874+ (3/*HID feature*/ << 8) | report_number,
1875+ dev->interface,
1876+ (unsigned char *)data, length,
1877+ 1000/*timeout millis*/);
1878+
1879+ if (res < 0)
1880+ return -1;
1881+
1882+ if (skipped_report_id)
1883+ res++;
1884+
1885+ return res;
1886+}
1887+
1888+
1889+void HID_API_EXPORT hid_close(hid_device *dev)
1890+{
1891+ if (!dev)
1892+ return;
1893+
1894+ /* Cause read_thread() to stop. */
1895+ dev->shutdown_thread = 1;
1896+ libusb_cancel_transfer(dev->transfer);
1897+
1898+ /* Wait for read_thread() to end. */
1899+ pthread_join(dev->thread, NULL);
1900+
1901+ /* Clean up the Transfer objects allocated in read_thread(). */
1902+ free(dev->transfer->buffer);
1903+ libusb_free_transfer(dev->transfer);
1904+
1905+ /* release the interface */
1906+ libusb_release_interface(dev->device_handle, dev->interface);
1907+
1908+ /* Close the handle */
1909+ libusb_close(dev->device_handle);
1910+
1911+ /* Clear out the queue of received reports. */
1912+ pthread_mutex_lock(&dev->mutex);
1913+ while (dev->input_reports) {
1914+ return_data(dev, NULL, 0);
1915+ }
1916+ pthread_mutex_unlock(&dev->mutex);
1917+
1918+ free_hid_device(dev);
1919+}
1920+
1921+
1922+int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
1923+{
1924+ return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen);
1925+}
1926+
1927+int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
1928+{
1929+ return hid_get_indexed_string(dev, dev->product_index, string, maxlen);
1930+}
1931+
1932+int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
1933+{
1934+ return hid_get_indexed_string(dev, dev->serial_index, string, maxlen);
1935+}
1936+
1937+int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
1938+{
1939+ wchar_t *str;
1940+
1941+ str = get_usb_string(dev->device_handle, string_index);
1942+ if (str) {
1943+ wcsncpy(string, str, maxlen);
1944+ string[maxlen-1] = L'\0';
1945+ free(str);
1946+ return 0;
1947+ }
1948+ else
1949+ return -1;
1950+}
1951+
1952+
1953+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
1954+{
1955+ return NULL;
1956+}
1957+
1958+
1959+struct lang_map_entry {
1960+ const char *name;
1961+ const char *string_code;
1962+ uint16_t usb_code;
1963+};
1964+
1965+#define LANG(name,code,usb_code) { name, code, usb_code }
1966+static struct lang_map_entry lang_map[] = {
1967+ LANG("Afrikaans", "af", 0x0436),
1968+ LANG("Albanian", "sq", 0x041C),
1969+ LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),
1970+ LANG("Arabic - Bahrain", "ar_bh", 0x3C01),
1971+ LANG("Arabic - Algeria", "ar_dz", 0x1401),
1972+ LANG("Arabic - Egypt", "ar_eg", 0x0C01),
1973+ LANG("Arabic - Iraq", "ar_iq", 0x0801),
1974+ LANG("Arabic - Jordan", "ar_jo", 0x2C01),
1975+ LANG("Arabic - Kuwait", "ar_kw", 0x3401),
1976+ LANG("Arabic - Lebanon", "ar_lb", 0x3001),
1977+ LANG("Arabic - Libya", "ar_ly", 0x1001),
1978+ LANG("Arabic - Morocco", "ar_ma", 0x1801),
1979+ LANG("Arabic - Oman", "ar_om", 0x2001),
1980+ LANG("Arabic - Qatar", "ar_qa", 0x4001),
1981+ LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401),
1982+ LANG("Arabic - Syria", "ar_sy", 0x2801),
1983+ LANG("Arabic - Tunisia", "ar_tn", 0x1C01),
1984+ LANG("Arabic - Yemen", "ar_ye", 0x2401),
1985+ LANG("Armenian", "hy", 0x042B),
1986+ LANG("Azeri - Latin", "az_az", 0x042C),
1987+ LANG("Azeri - Cyrillic", "az_az", 0x082C),
1988+ LANG("Basque", "eu", 0x042D),
1989+ LANG("Belarusian", "be", 0x0423),
1990+ LANG("Bulgarian", "bg", 0x0402),
1991+ LANG("Catalan", "ca", 0x0403),
1992+ LANG("Chinese - China", "zh_cn", 0x0804),
1993+ LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04),
1994+ LANG("Chinese - Macau SAR", "zh_mo", 0x1404),
1995+ LANG("Chinese - Singapore", "zh_sg", 0x1004),
1996+ LANG("Chinese - Taiwan", "zh_tw", 0x0404),
1997+ LANG("Croatian", "hr", 0x041A),
1998+ LANG("Czech", "cs", 0x0405),
1999+ LANG("Danish", "da", 0x0406),
2000+ LANG("Dutch - Netherlands", "nl_nl", 0x0413),
2001+ LANG("Dutch - Belgium", "nl_be", 0x0813),
2002+ LANG("English - Australia", "en_au", 0x0C09),
2003+ LANG("English - Belize", "en_bz", 0x2809),
2004+ LANG("English - Canada", "en_ca", 0x1009),
2005+ LANG("English - Caribbean", "en_cb", 0x2409),
2006+ LANG("English - Ireland", "en_ie", 0x1809),
2007+ LANG("English - Jamaica", "en_jm", 0x2009),
2008+ LANG("English - New Zealand", "en_nz", 0x1409),
2009+ LANG("English - Phillippines", "en_ph", 0x3409),
2010+ LANG("English - Southern Africa", "en_za", 0x1C09),
2011+ LANG("English - Trinidad", "en_tt", 0x2C09),
2012+ LANG("English - Great Britain", "en_gb", 0x0809),
2013+ LANG("English - United States", "en_us", 0x0409),
2014+ LANG("Estonian", "et", 0x0425),
2015+ LANG("Farsi", "fa", 0x0429),
2016+ LANG("Finnish", "fi", 0x040B),
2017+ LANG("Faroese", "fo", 0x0438),
2018+ LANG("French - France", "fr_fr", 0x040C),
2019+ LANG("French - Belgium", "fr_be", 0x080C),
2020+ LANG("French - Canada", "fr_ca", 0x0C0C),
2021+ LANG("French - Luxembourg", "fr_lu", 0x140C),
2022+ LANG("French - Switzerland", "fr_ch", 0x100C),
2023+ LANG("Gaelic - Ireland", "gd_ie", 0x083C),
2024+ LANG("Gaelic - Scotland", "gd", 0x043C),
2025+ LANG("German - Germany", "de_de", 0x0407),
2026+ LANG("German - Austria", "de_at", 0x0C07),
2027+ LANG("German - Liechtenstein", "de_li", 0x1407),
2028+ LANG("German - Luxembourg", "de_lu", 0x1007),
2029+ LANG("German - Switzerland", "de_ch", 0x0807),
2030+ LANG("Greek", "el", 0x0408),
2031+ LANG("Hebrew", "he", 0x040D),
2032+ LANG("Hindi", "hi", 0x0439),
2033+ LANG("Hungarian", "hu", 0x040E),
2034+ LANG("Icelandic", "is", 0x040F),
2035+ LANG("Indonesian", "id", 0x0421),
2036+ LANG("Italian - Italy", "it_it", 0x0410),
2037+ LANG("Italian - Switzerland", "it_ch", 0x0810),
2038+ LANG("Japanese", "ja", 0x0411),
2039+ LANG("Korean", "ko", 0x0412),
2040+ LANG("Latvian", "lv", 0x0426),
2041+ LANG("Lithuanian", "lt", 0x0427),
2042+ LANG("F.Y.R.O. Macedonia", "mk", 0x042F),
2043+ LANG("Malay - Malaysia", "ms_my", 0x043E),
2044+ LANG("Malay – Brunei", "ms_bn", 0x083E),
2045+ LANG("Maltese", "mt", 0x043A),
2046+ LANG("Marathi", "mr", 0x044E),
2047+ LANG("Norwegian - Bokml", "no_no", 0x0414),
2048+ LANG("Norwegian - Nynorsk", "no_no", 0x0814),
2049+ LANG("Polish", "pl", 0x0415),
2050+ LANG("Portuguese - Portugal", "pt_pt", 0x0816),
2051+ LANG("Portuguese - Brazil", "pt_br", 0x0416),
2052+ LANG("Raeto-Romance", "rm", 0x0417),
2053+ LANG("Romanian - Romania", "ro", 0x0418),
2054+ LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818),
2055+ LANG("Russian", "ru", 0x0419),
2056+ LANG("Russian - Republic of Moldova", "ru_mo", 0x0819),
2057+ LANG("Sanskrit", "sa", 0x044F),
2058+ LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A),
2059+ LANG("Serbian - Latin", "sr_sp", 0x081A),
2060+ LANG("Setsuana", "tn", 0x0432),
2061+ LANG("Slovenian", "sl", 0x0424),
2062+ LANG("Slovak", "sk", 0x041B),
2063+ LANG("Sorbian", "sb", 0x042E),
2064+ LANG("Spanish - Spain (Traditional)", "es_es", 0x040A),
2065+ LANG("Spanish - Argentina", "es_ar", 0x2C0A),
2066+ LANG("Spanish - Bolivia", "es_bo", 0x400A),
2067+ LANG("Spanish - Chile", "es_cl", 0x340A),
2068+ LANG("Spanish - Colombia", "es_co", 0x240A),
2069+ LANG("Spanish - Costa Rica", "es_cr", 0x140A),
2070+ LANG("Spanish - Dominican Republic", "es_do", 0x1C0A),
2071+ LANG("Spanish - Ecuador", "es_ec", 0x300A),
2072+ LANG("Spanish - Guatemala", "es_gt", 0x100A),
2073+ LANG("Spanish - Honduras", "es_hn", 0x480A),
2074+ LANG("Spanish - Mexico", "es_mx", 0x080A),
2075+ LANG("Spanish - Nicaragua", "es_ni", 0x4C0A),
2076+ LANG("Spanish - Panama", "es_pa", 0x180A),
2077+ LANG("Spanish - Peru", "es_pe", 0x280A),
2078+ LANG("Spanish - Puerto Rico", "es_pr", 0x500A),
2079+ LANG("Spanish - Paraguay", "es_py", 0x3C0A),
2080+ LANG("Spanish - El Salvador", "es_sv", 0x440A),
2081+ LANG("Spanish - Uruguay", "es_uy", 0x380A),
2082+ LANG("Spanish - Venezuela", "es_ve", 0x200A),
2083+ LANG("Southern Sotho", "st", 0x0430),
2084+ LANG("Swahili", "sw", 0x0441),
2085+ LANG("Swedish - Sweden", "sv_se", 0x041D),
2086+ LANG("Swedish - Finland", "sv_fi", 0x081D),
2087+ LANG("Tamil", "ta", 0x0449),
2088+ LANG("Tatar", "tt", 0X0444),
2089+ LANG("Thai", "th", 0x041E),
2090+ LANG("Turkish", "tr", 0x041F),
2091+ LANG("Tsonga", "ts", 0x0431),
2092+ LANG("Ukrainian", "uk", 0x0422),
2093+ LANG("Urdu", "ur", 0x0420),
2094+ LANG("Uzbek - Cyrillic", "uz_uz", 0x0843),
2095+ LANG("Uzbek – Latin", "uz_uz", 0x0443),
2096+ LANG("Vietnamese", "vi", 0x042A),
2097+ LANG("Xhosa", "xh", 0x0434),
2098+ LANG("Yiddish", "yi", 0x043D),
2099+ LANG("Zulu", "zu", 0x0435),
2100+ LANG(NULL, NULL, 0x0),
2101+};
2102+
2103+uint16_t get_usb_code_for_current_locale(void)
2104+{
2105+ char *locale;
2106+ char search_string[64];
2107+ char *ptr;
2108+
2109+ /* Get the current locale. */
2110+ locale = setlocale(0, NULL);
2111+ if (!locale)
2112+ return 0x0;
2113+
2114+ /* Make a copy of the current locale string. */
2115+ strncpy(search_string, locale, sizeof(search_string));
2116+ search_string[sizeof(search_string)-1] = '\0';
2117+
2118+ /* Chop off the encoding part, and make it lower case. */
2119+ ptr = search_string;
2120+ while (*ptr) {
2121+ *ptr = tolower(*ptr);
2122+ if (*ptr == '.') {
2123+ *ptr = '\0';
2124+ break;
2125+ }
2126+ ptr++;
2127+ }
2128+
2129+ /* Find the entry which matches the string code of our locale. */
2130+ struct lang_map_entry *lang = lang_map;
2131+ while (lang->string_code) {
2132+ if (!strcmp(lang->string_code, search_string)) {
2133+ return lang->usb_code;
2134+ }
2135+ lang++;
2136+ }
2137+
2138+ /* There was no match. Find with just the language only. */
2139+ /* Chop off the variant. Chop it off at the '_'. */
2140+ ptr = search_string;
2141+ while (*ptr) {
2142+ *ptr = tolower(*ptr);
2143+ if (*ptr == '_') {
2144+ *ptr = '\0';
2145+ break;
2146+ }
2147+ ptr++;
2148+ }
2149+
2150+#if 0 // TODO: Do we need this?
2151+ /* Find the entry which matches the string code of our language. */
2152+ lang = lang_map;
2153+ while (lang->string_code) {
2154+ if (!strcmp(lang->string_code, search_string)) {
2155+ return lang->usb_code;
2156+ }
2157+ lang++;
2158+ }
2159+#endif
2160+
2161+ /* Found nothing. */
2162+ return 0x0;
2163+}
2164+
2165+#ifdef __cplusplus
2166+}
2167+#endif
2168
2169=== added file 'mixxx/lib/hidapi-0.7.0/linux/hid.c'
2170--- mixxx/lib/hidapi-0.7.0/linux/hid.c 1970-01-01 00:00:00 +0000
2171+++ mixxx/lib/hidapi-0.7.0/linux/hid.c 2012-04-07 14:24:23 +0000
2172@@ -0,0 +1,595 @@
2173+/*******************************************************
2174+ HIDAPI - Multi-Platform library for
2175+ communication with HID devices.
2176+
2177+ Alan Ott
2178+ Signal 11 Software
2179+
2180+ 8/22/2009
2181+ Linux Version - 6/2/2009
2182+
2183+ Copyright 2009, All Rights Reserved.
2184+
2185+ At the discretion of the user of this library,
2186+ this software may be licensed under the terms of the
2187+ GNU Public License v3, a BSD-Style license, or the
2188+ original HIDAPI license as outlined in the LICENSE.txt,
2189+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
2190+ files located at the root of the source distribution.
2191+ These files may also be found in the public source
2192+ code repository located at:
2193+ http://github.com/signal11/hidapi .
2194+********************************************************/
2195+
2196+/* C */
2197+#include <stdio.h>
2198+#include <string.h>
2199+#include <stdlib.h>
2200+#include <locale.h>
2201+#include <errno.h>
2202+
2203+/* Unix */
2204+#include <unistd.h>
2205+#include <sys/types.h>
2206+#include <sys/stat.h>
2207+#include <sys/ioctl.h>
2208+#include <sys/utsname.h>
2209+#include <fcntl.h>
2210+#include <poll.h>
2211+
2212+/* Linux */
2213+#include <linux/hidraw.h>
2214+#include <linux/version.h>
2215+#include <libudev.h>
2216+
2217+#include "hidapi.h"
2218+
2219+/* Definitions from linux/hidraw.h. Since these are new, some distros
2220+ may not have header files which contain them. */
2221+#ifndef HIDIOCSFEATURE
2222+#define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len)
2223+#endif
2224+#ifndef HIDIOCGFEATURE
2225+#define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len)
2226+#endif
2227+
2228+struct hid_device_ {
2229+ int device_handle;
2230+ int blocking;
2231+ int uses_numbered_reports;
2232+};
2233+
2234+
2235+static __u32 kernel_version = 0;
2236+
2237+hid_device *new_hid_device()
2238+{
2239+ hid_device *dev = calloc(1, sizeof(hid_device));
2240+ dev->device_handle = -1;
2241+ dev->blocking = 1;
2242+ dev->uses_numbered_reports = 0;
2243+
2244+ return dev;
2245+}
2246+
2247+static void register_error(hid_device *device, const char *op)
2248+{
2249+
2250+}
2251+
2252+/* Get an attribute value from a udev_device and return it as a whar_t
2253+ string. The returned string must be freed with free() when done.*/
2254+static wchar_t *copy_udev_string(struct udev_device *dev, const char *udev_name)
2255+{
2256+ const char *str;
2257+ wchar_t *ret = NULL;
2258+ str = udev_device_get_sysattr_value(dev, udev_name);
2259+ if (str) {
2260+ /* Convert the string from UTF-8 to wchar_t */
2261+ size_t wlen = mbstowcs(NULL, str, 0);
2262+ ret = calloc(wlen+1, sizeof(wchar_t));
2263+ mbstowcs(ret, str, wlen+1);
2264+ ret[wlen] = 0x0000;
2265+ }
2266+
2267+ return ret;
2268+}
2269+
2270+/* uses_numbered_reports() returns 1 if report_descriptor describes a device
2271+ which contains numbered reports. */
2272+static int uses_numbered_reports(__u8 *report_descriptor, __u32 size) {
2273+ int i = 0;
2274+ int size_code;
2275+ int data_len, key_size;
2276+
2277+ while (i < size) {
2278+ int key = report_descriptor[i];
2279+
2280+ /* Check for the Report ID key */
2281+ if (key == 0x85/*Report ID*/) {
2282+ /* This device has a Report ID, which means it uses
2283+ numbered reports. */
2284+ return 1;
2285+ }
2286+
2287+ //printf("key: %02hhx\n", key);
2288+
2289+ if ((key & 0xf0) == 0xf0) {
2290+ /* This is a Long Item. The next byte contains the
2291+ length of the data section (value) for this key.
2292+ See the HID specification, version 1.11, section
2293+ 6.2.2.3, titled "Long Items." */
2294+ if (i+1 < size)
2295+ data_len = report_descriptor[i+1];
2296+ else
2297+ data_len = 0; /* malformed report */
2298+ key_size = 3;
2299+ }
2300+ else {
2301+ /* This is a Short Item. The bottom two bits of the
2302+ key contain the size code for the data section
2303+ (value) for this key. Refer to the HID
2304+ specification, version 1.11, section 6.2.2.2,
2305+ titled "Short Items." */
2306+ size_code = key & 0x3;
2307+ switch (size_code) {
2308+ case 0:
2309+ case 1:
2310+ case 2:
2311+ data_len = size_code;
2312+ break;
2313+ case 3:
2314+ data_len = 4;
2315+ break;
2316+ default:
2317+ /* Can't ever happen since size_code is & 0x3 */
2318+ data_len = 0;
2319+ break;
2320+ };
2321+ key_size = 1;
2322+ }
2323+
2324+ /* Skip over this key and it's associated data */
2325+ i += data_len + key_size;
2326+ }
2327+
2328+ /* Didn't find a Report ID key. Device doesn't use numbered reports. */
2329+ return 0;
2330+}
2331+
2332+static int get_device_string(hid_device *dev, const char *key, wchar_t *string, size_t maxlen)
2333+{
2334+ struct udev *udev;
2335+ struct udev_device *udev_dev, *parent;
2336+ struct stat s;
2337+ int ret = -1;
2338+
2339+ setlocale(LC_ALL,"");
2340+
2341+ /* Create the udev object */
2342+ udev = udev_new();
2343+ if (!udev) {
2344+ printf("Can't create udev\n");
2345+ return -1;
2346+ }
2347+
2348+ /* Get the dev_t (major/minor numbers) from the file handle. */
2349+ fstat(dev->device_handle, &s);
2350+ /* Open a udev device from the dev_t. 'c' means character device. */
2351+ udev_dev = udev_device_new_from_devnum(udev, 'c', s.st_rdev);
2352+ if (udev_dev) {
2353+ const char *str;
2354+ /* Find the parent USB Device */
2355+ parent = udev_device_get_parent_with_subsystem_devtype(
2356+ udev_dev,
2357+ "usb",
2358+ "usb_device");
2359+ if (parent) {
2360+ str = udev_device_get_sysattr_value(parent, key);
2361+ if (str) {
2362+ /* Convert the string from UTF-8 to wchar_t */
2363+ ret = mbstowcs(string, str, maxlen);
2364+ goto end;
2365+ }
2366+ }
2367+ }
2368+
2369+end:
2370+ udev_device_unref(udev_dev);
2371+ // parent doesn't need to be (and can't be) unref'd.
2372+ // I'm not sure why, but it'll throw double-free() errors.
2373+ udev_unref(udev);
2374+
2375+ return ret;
2376+}
2377+
2378+int HID_API_EXPORT hid_init(void)
2379+{
2380+ /* Nothing to do for this in the Linux/hidraw implementation. */
2381+ return 0;
2382+}
2383+
2384+int HID_API_EXPORT hid_exit(void)
2385+{
2386+ /* Nothing to do for this in the Linux/hidraw implementation. */
2387+ return 0;
2388+}
2389+
2390+struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
2391+{
2392+ struct udev *udev;
2393+ struct udev_enumerate *enumerate;
2394+ struct udev_list_entry *devices, *dev_list_entry;
2395+
2396+ struct hid_device_info *root = NULL; // return object
2397+ struct hid_device_info *cur_dev = NULL;
2398+
2399+ setlocale(LC_ALL,"");
2400+
2401+ /* Create the udev object */
2402+ udev = udev_new();
2403+ if (!udev) {
2404+ printf("Can't create udev\n");
2405+ return NULL;
2406+ }
2407+
2408+ /* Create a list of the devices in the 'hidraw' subsystem. */
2409+ enumerate = udev_enumerate_new(udev);
2410+ udev_enumerate_add_match_subsystem(enumerate, "hidraw");
2411+ udev_enumerate_scan_devices(enumerate);
2412+ devices = udev_enumerate_get_list_entry(enumerate);
2413+ /* For each item, see if it matches the vid/pid, and if so
2414+ create a udev_device record for it */
2415+ udev_list_entry_foreach(dev_list_entry, devices) {
2416+ const char *sysfs_path;
2417+ const char *dev_path;
2418+ const char *str;
2419+ struct udev_device *hid_dev; // The device's HID udev node.
2420+ struct udev_device *dev; // The actual hardware device.
2421+ struct udev_device *intf_dev; // The device's interface (in the USB sense).
2422+ unsigned short dev_vid;
2423+ unsigned short dev_pid;
2424+
2425+ /* Get the filename of the /sys entry for the device
2426+ and create a udev_device object (dev) representing it */
2427+ sysfs_path = udev_list_entry_get_name(dev_list_entry);
2428+ hid_dev = udev_device_new_from_syspath(udev, sysfs_path);
2429+ dev_path = udev_device_get_devnode(hid_dev);
2430+
2431+ /* The device pointed to by hid_dev contains information about
2432+ the hidraw device. In order to get information about the
2433+ USB device, get the parent device with the
2434+ subsystem/devtype pair of "usb"/"usb_device". This will
2435+ be several levels up the tree, but the function will find
2436+ it.*/
2437+ dev = udev_device_get_parent_with_subsystem_devtype(
2438+ hid_dev,
2439+ "usb",
2440+ "usb_device");
2441+ if (!dev) {
2442+ /* Unable to find parent usb device. */
2443+ goto next;
2444+ }
2445+
2446+ /* Get the VID/PID of the device */
2447+ str = udev_device_get_sysattr_value(dev,"idVendor");
2448+ dev_vid = (str)? strtol(str, NULL, 16): 0x0;
2449+ str = udev_device_get_sysattr_value(dev, "idProduct");
2450+ dev_pid = (str)? strtol(str, NULL, 16): 0x0;
2451+
2452+ /* Check the VID/PID against the arguments */
2453+ if ((vendor_id == 0x0 && product_id == 0x0) ||
2454+ (vendor_id == dev_vid && product_id == dev_pid)) {
2455+ struct hid_device_info *tmp;
2456+ size_t len;
2457+
2458+ /* VID/PID match. Create the record. */
2459+ tmp = malloc(sizeof(struct hid_device_info));
2460+ if (cur_dev) {
2461+ cur_dev->next = tmp;
2462+ }
2463+ else {
2464+ root = tmp;
2465+ }
2466+ cur_dev = tmp;
2467+
2468+ /* Fill out the record */
2469+ cur_dev->next = NULL;
2470+ str = dev_path;
2471+ if (str) {
2472+ len = strlen(str);
2473+ cur_dev->path = calloc(len+1, sizeof(char));
2474+ strncpy(cur_dev->path, str, len+1);
2475+ cur_dev->path[len] = '\0';
2476+ }
2477+ else
2478+ cur_dev->path = NULL;
2479+
2480+ /* Serial Number */
2481+ cur_dev->serial_number
2482+ = copy_udev_string(dev, "serial");
2483+
2484+ /* Manufacturer and Product strings */
2485+ cur_dev->manufacturer_string
2486+ = copy_udev_string(dev, "manufacturer");
2487+ cur_dev->product_string
2488+ = copy_udev_string(dev, "product");
2489+
2490+ /* VID/PID */
2491+ cur_dev->vendor_id = dev_vid;
2492+ cur_dev->product_id = dev_pid;
2493+
2494+ /* Release Number */
2495+ str = udev_device_get_sysattr_value(dev, "bcdDevice");
2496+ cur_dev->release_number = (str)? strtol(str, NULL, 16): 0x0;
2497+
2498+ /* Interface Number */
2499+ cur_dev->interface_number = -1;
2500+ /* Get a handle to the interface's udev node. */
2501+ intf_dev = udev_device_get_parent_with_subsystem_devtype(
2502+ hid_dev,
2503+ "usb",
2504+ "usb_interface");
2505+ if (intf_dev) {
2506+ str = udev_device_get_sysattr_value(intf_dev, "bInterfaceNumber");
2507+ cur_dev->interface_number = (str)? strtol(str, NULL, 16): -1;
2508+ }
2509+ }
2510+ else
2511+ goto next;
2512+
2513+ next:
2514+ udev_device_unref(hid_dev);
2515+ /* dev and intf_dev don't need to be (and can't be)
2516+ unref()d. It will cause a double-free() error. I'm not
2517+ sure why. */
2518+ }
2519+ /* Free the enumerator and udev objects. */
2520+ udev_enumerate_unref(enumerate);
2521+ udev_unref(udev);
2522+
2523+ return root;
2524+}
2525+
2526+void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
2527+{
2528+ struct hid_device_info *d = devs;
2529+ while (d) {
2530+ struct hid_device_info *next = d->next;
2531+ free(d->path);
2532+ free(d->serial_number);
2533+ free(d->manufacturer_string);
2534+ free(d->product_string);
2535+ free(d);
2536+ d = next;
2537+ }
2538+}
2539+
2540+hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number)
2541+{
2542+ struct hid_device_info *devs, *cur_dev;
2543+ const char *path_to_open = NULL;
2544+ hid_device *handle = NULL;
2545+
2546+ devs = hid_enumerate(vendor_id, product_id);
2547+ cur_dev = devs;
2548+ while (cur_dev) {
2549+ if (cur_dev->vendor_id == vendor_id &&
2550+ cur_dev->product_id == product_id) {
2551+ if (serial_number) {
2552+ if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
2553+ path_to_open = cur_dev->path;
2554+ break;
2555+ }
2556+ }
2557+ else {
2558+ path_to_open = cur_dev->path;
2559+ break;
2560+ }
2561+ }
2562+ cur_dev = cur_dev->next;
2563+ }
2564+
2565+ if (path_to_open) {
2566+ /* Open the device */
2567+ handle = hid_open_path(path_to_open);
2568+ }
2569+
2570+ hid_free_enumeration(devs);
2571+
2572+ return handle;
2573+}
2574+
2575+hid_device * HID_API_EXPORT hid_open_path(const char *path)
2576+{
2577+ hid_device *dev = NULL;
2578+
2579+ dev = new_hid_device();
2580+
2581+ if (kernel_version == 0) {
2582+ struct utsname name;
2583+ int major, minor, release;
2584+ int ret;
2585+ uname(&name);
2586+ ret = sscanf(name.release, "%d.%d.%d", &major, &minor, &release);
2587+ if (ret == 3) {
2588+ kernel_version = major << 16 | minor << 8 | release;
2589+ //printf("Kernel Version: %d\n", kernel_version);
2590+ }
2591+ else {
2592+ printf("Couldn't sscanf() version string %s\n", name.release);
2593+ }
2594+ }
2595+
2596+ // OPEN HERE //
2597+ dev->device_handle = open(path, O_RDWR);
2598+
2599+ // If we have a good handle, return it.
2600+ if (dev->device_handle > 0) {
2601+
2602+ /* Get the report descriptor */
2603+ int res, desc_size = 0;
2604+ struct hidraw_report_descriptor rpt_desc;
2605+
2606+ memset(&rpt_desc, 0x0, sizeof(rpt_desc));
2607+
2608+ /* Get Report Descriptor Size */
2609+ res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size);
2610+ if (res < 0)
2611+ perror("HIDIOCGRDESCSIZE");
2612+
2613+
2614+ /* Get Report Descriptor */
2615+ rpt_desc.size = desc_size;
2616+ res = ioctl(dev->device_handle, HIDIOCGRDESC, &rpt_desc);
2617+ if (res < 0) {
2618+ perror("HIDIOCGRDESC");
2619+ } else {
2620+ /* Determine if this device uses numbered reports. */
2621+ dev->uses_numbered_reports =
2622+ uses_numbered_reports(rpt_desc.value,
2623+ rpt_desc.size);
2624+ }
2625+
2626+ return dev;
2627+ }
2628+ else {
2629+ // Unable to open any devices.
2630+ free(dev);
2631+ return NULL;
2632+ }
2633+}
2634+
2635+
2636+int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
2637+{
2638+ int bytes_written;
2639+
2640+ bytes_written = write(dev->device_handle, data, length);
2641+
2642+ return bytes_written;
2643+}
2644+
2645+
2646+int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
2647+{
2648+ int bytes_read;
2649+
2650+ if (milliseconds != 0) {
2651+ /* milliseconds is -1 or > 0. In both cases, we want to
2652+ call poll() and wait for data to arrive. -1 means
2653+ INFINITE. */
2654+ int ret;
2655+ struct pollfd fds;
2656+
2657+ fds.fd = dev->device_handle;
2658+ fds.events = POLLIN;
2659+ fds.revents = 0;
2660+ ret = poll(&fds, 1, milliseconds);
2661+ if (ret == -1 || ret == 0)
2662+ /* Error or timeout */
2663+ return ret;
2664+ }
2665+
2666+ bytes_read = read(dev->device_handle, data, length);
2667+ if (bytes_read < 0 && errno == EAGAIN)
2668+ bytes_read = 0;
2669+
2670+ if (bytes_read >= 0 &&
2671+ kernel_version < KERNEL_VERSION(2,6,34) &&
2672+ dev->uses_numbered_reports) {
2673+ /* Work around a kernel bug. Chop off the first byte. */
2674+ memmove(data, data+1, bytes_read);
2675+ bytes_read--;
2676+ }
2677+
2678+ return bytes_read;
2679+}
2680+
2681+int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
2682+{
2683+ return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
2684+}
2685+
2686+int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
2687+{
2688+ int flags, res;
2689+
2690+ flags = fcntl(dev->device_handle, F_GETFL, 0);
2691+ if (flags >= 0) {
2692+ if (nonblock)
2693+ res = fcntl(dev->device_handle, F_SETFL, flags | O_NONBLOCK);
2694+ else
2695+ res = fcntl(dev->device_handle, F_SETFL, flags & ~O_NONBLOCK);
2696+ }
2697+ else
2698+ return -1;
2699+
2700+ if (res < 0) {
2701+ return -1;
2702+ }
2703+ else {
2704+ dev->blocking = !nonblock;
2705+ return 0; /* Success */
2706+ }
2707+}
2708+
2709+
2710+int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
2711+{
2712+ int res;
2713+
2714+ res = ioctl(dev->device_handle, HIDIOCSFEATURE(length), data);
2715+ if (res < 0)
2716+ perror("ioctl (SFEATURE)");
2717+
2718+ return res;
2719+}
2720+
2721+int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
2722+{
2723+ int res;
2724+
2725+ res = ioctl(dev->device_handle, HIDIOCGFEATURE(length), data);
2726+ if (res < 0)
2727+ perror("ioctl (GFEATURE)");
2728+
2729+
2730+ return res;
2731+}
2732+
2733+
2734+void HID_API_EXPORT hid_close(hid_device *dev)
2735+{
2736+ if (!dev)
2737+ return;
2738+ close(dev->device_handle);
2739+ free(dev);
2740+}
2741+
2742+
2743+int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
2744+{
2745+ return get_device_string(dev, "manufacturer", string, maxlen);
2746+}
2747+
2748+int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
2749+{
2750+ return get_device_string(dev, "product", string, maxlen);
2751+}
2752+
2753+int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
2754+{
2755+ return get_device_string(dev, "serial", string, maxlen);
2756+}
2757+
2758+int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
2759+{
2760+ return -1;
2761+}
2762+
2763+
2764+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
2765+{
2766+ return NULL;
2767+}
2768
2769=== added directory 'mixxx/lib/hidapi-0.7.0/mac'
2770=== added file 'mixxx/lib/hidapi-0.7.0/mac/.gitignore'
2771--- mixxx/lib/hidapi-0.7.0/mac/.gitignore 1970-01-01 00:00:00 +0000
2772+++ mixxx/lib/hidapi-0.7.0/mac/.gitignore 2012-04-07 14:24:23 +0000
2773@@ -0,0 +1,13 @@
2774+Debug
2775+Release
2776+*.exp
2777+*.ilk
2778+*.lib
2779+*.suo
2780+*.vcproj.*
2781+*.ncb
2782+*.suo
2783+*.dll
2784+*.pdb
2785+*.o
2786+hidtest
2787\ No newline at end of file
2788
2789=== added file 'mixxx/lib/hidapi-0.7.0/mac/Makefile'
2790--- mixxx/lib/hidapi-0.7.0/mac/Makefile 1970-01-01 00:00:00 +0000
2791+++ mixxx/lib/hidapi-0.7.0/mac/Makefile 2012-04-07 14:24:23 +0000
2792@@ -0,0 +1,32 @@
2793+###########################################
2794+# Simple Makefile for HIDAPI test program
2795+#
2796+# Alan Ott
2797+# Signal 11 Software
2798+# 2010-07-03
2799+###########################################
2800+
2801+all: hidtest
2802+
2803+CC=gcc
2804+CXX=g++
2805+COBJS=hid.o
2806+CPPOBJS=../hidtest/hidtest.o
2807+OBJS=$(COBJS) $(CPPOBJS)
2808+CFLAGS+=-I../hidapi -Wall -g -c
2809+LIBS=-framework IOKit -framework CoreFoundation
2810+
2811+
2812+hidtest: $(OBJS)
2813+ g++ -Wall -g $^ $(LIBS) -o hidtest
2814+
2815+$(COBJS): %.o: %.c
2816+ $(CC) $(CFLAGS) $< -o $@
2817+
2818+$(CPPOBJS): %.o: %.cpp
2819+ $(CXX) $(CFLAGS) $< -o $@
2820+
2821+clean:
2822+ rm -f *.o hidtest $(CPPOBJS)
2823+
2824+.PHONY: clean
2825
2826=== added file 'mixxx/lib/hidapi-0.7.0/mac/hid.c'
2827--- mixxx/lib/hidapi-0.7.0/mac/hid.c 1970-01-01 00:00:00 +0000
2828+++ mixxx/lib/hidapi-0.7.0/mac/hid.c 2012-04-07 14:24:23 +0000
2829@@ -0,0 +1,1122 @@
2830+/*******************************************************
2831+ HIDAPI - Multi-Platform library for
2832+ communication with HID devices.
2833+
2834+ Alan Ott
2835+ Signal 11 Software
2836+
2837+ 2010-07-03
2838+
2839+ Copyright 2010, All Rights Reserved.
2840+
2841+ At the discretion of the user of this library,
2842+ this software may be licensed under the terms of the
2843+ GNU Public License v3, a BSD-Style license, or the
2844+ original HIDAPI license as outlined in the LICENSE.txt,
2845+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
2846+ files located at the root of the source distribution.
2847+ These files may also be found in the public source
2848+ code repository located at:
2849+ http://github.com/signal11/hidapi .
2850+********************************************************/
2851+
2852+/* See Apple Technical Note TN2187 for details on IOHidManager. */
2853+
2854+#include <IOKit/hid/IOHIDManager.h>
2855+#include <IOKit/hid/IOHIDKeys.h>
2856+#include <CoreFoundation/CoreFoundation.h>
2857+#include <wchar.h>
2858+#include <locale.h>
2859+#include <pthread.h>
2860+#include <sys/time.h>
2861+#include <unistd.h>
2862+
2863+#include "hidapi.h"
2864+
2865+/* Barrier implementation because Mac OSX doesn't have pthread_barrier.
2866+ It also doesn't have clock_gettime(). So much for POSIX and SUSv2.
2867+ This implementation came from Brent Priddy and was posted on
2868+ StackOverflow. It is used with his permission. */
2869+typedef int pthread_barrierattr_t;
2870+typedef struct pthread_barrier {
2871+ pthread_mutex_t mutex;
2872+ pthread_cond_t cond;
2873+ int count;
2874+ int trip_count;
2875+} pthread_barrier_t;
2876+
2877+static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
2878+{
2879+ if(count == 0) {
2880+ errno = EINVAL;
2881+ return -1;
2882+ }
2883+
2884+ if(pthread_mutex_init(&barrier->mutex, 0) < 0) {
2885+ return -1;
2886+ }
2887+ if(pthread_cond_init(&barrier->cond, 0) < 0) {
2888+ pthread_mutex_destroy(&barrier->mutex);
2889+ return -1;
2890+ }
2891+ barrier->trip_count = count;
2892+ barrier->count = 0;
2893+
2894+ return 0;
2895+}
2896+
2897+static int pthread_barrier_destroy(pthread_barrier_t *barrier)
2898+{
2899+ pthread_cond_destroy(&barrier->cond);
2900+ pthread_mutex_destroy(&barrier->mutex);
2901+ return 0;
2902+}
2903+
2904+static int pthread_barrier_wait(pthread_barrier_t *barrier)
2905+{
2906+ pthread_mutex_lock(&barrier->mutex);
2907+ ++(barrier->count);
2908+ if(barrier->count >= barrier->trip_count)
2909+ {
2910+ barrier->count = 0;
2911+ pthread_cond_broadcast(&barrier->cond);
2912+ pthread_mutex_unlock(&barrier->mutex);
2913+ return 1;
2914+ }
2915+ else
2916+ {
2917+ pthread_cond_wait(&barrier->cond, &(barrier->mutex));
2918+ pthread_mutex_unlock(&barrier->mutex);
2919+ return 0;
2920+ }
2921+}
2922+
2923+static int return_data(hid_device *dev, unsigned char *data, size_t length);
2924+
2925+/* Linked List of input reports received from the device. */
2926+struct input_report {
2927+ uint8_t *data;
2928+ size_t len;
2929+ struct input_report *next;
2930+};
2931+
2932+struct hid_device_ {
2933+ IOHIDDeviceRef device_handle;
2934+ int blocking;
2935+ int uses_numbered_reports;
2936+ int disconnected;
2937+ CFStringRef run_loop_mode;
2938+ CFRunLoopRef run_loop;
2939+ CFRunLoopSourceRef source;
2940+ uint8_t *input_report_buf;
2941+ CFIndex max_input_report_len;
2942+ struct input_report *input_reports;
2943+
2944+ pthread_t thread;
2945+ pthread_mutex_t mutex; /* Protects input_reports */
2946+ pthread_cond_t condition;
2947+ pthread_barrier_t barrier; /* Ensures correct startup sequence */
2948+ pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */
2949+ int shutdown_thread;
2950+
2951+ hid_device *next;
2952+};
2953+
2954+/* Static list of all the devices open. This way when a device gets
2955+ disconnected, its hid_device structure can be marked as disconnected
2956+ from hid_device_removal_callback(). */
2957+static hid_device *device_list = NULL;
2958+static pthread_mutex_t device_list_mutex = PTHREAD_MUTEX_INITIALIZER;
2959+
2960+static hid_device *new_hid_device(void)
2961+{
2962+ hid_device *dev = calloc(1, sizeof(hid_device));
2963+ dev->device_handle = NULL;
2964+ dev->blocking = 1;
2965+ dev->uses_numbered_reports = 0;
2966+ dev->disconnected = 0;
2967+ dev->run_loop_mode = NULL;
2968+ dev->run_loop = NULL;
2969+ dev->source = NULL;
2970+ dev->input_report_buf = NULL;
2971+ dev->input_reports = NULL;
2972+ dev->shutdown_thread = 0;
2973+ dev->next = NULL;
2974+
2975+ /* Thread objects */
2976+ pthread_mutex_init(&dev->mutex, NULL);
2977+ pthread_cond_init(&dev->condition, NULL);
2978+ pthread_barrier_init(&dev->barrier, NULL, 2);
2979+ pthread_barrier_init(&dev->shutdown_barrier, NULL, 2);
2980+
2981+ /* Add the new record to the device_list. */
2982+ pthread_mutex_lock(&device_list_mutex);
2983+ if (!device_list)
2984+ device_list = dev;
2985+ else {
2986+ hid_device *d = device_list;
2987+ while (d) {
2988+ if (!d->next) {
2989+ d->next = dev;
2990+ break;
2991+ }
2992+ d = d->next;
2993+ }
2994+ }
2995+ pthread_mutex_unlock(&device_list_mutex);
2996+
2997+ return dev;
2998+}
2999+
3000+static void free_hid_device(hid_device *dev)
3001+{
3002+ if (!dev)
3003+ return;
3004+
3005+ /* Delete any input reports still left over. */
3006+ struct input_report *rpt = dev->input_reports;
3007+ while (rpt) {
3008+ struct input_report *next = rpt->next;
3009+ free(rpt->data);
3010+ free(rpt);
3011+ rpt = next;
3012+ }
3013+
3014+ /* Free the string and the report buffer. The check for NULL
3015+ is necessary here as CFRelease() doesn't handle NULL like
3016+ free() and others do. */
3017+ if (dev->run_loop_mode)
3018+ CFRelease(dev->run_loop_mode);
3019+ if (dev->source)
3020+ CFRelease(dev->source);
3021+ free(dev->input_report_buf);
3022+
3023+ /* Clean up the thread objects */
3024+ pthread_barrier_destroy(&dev->shutdown_barrier);
3025+ pthread_barrier_destroy(&dev->barrier);
3026+ pthread_cond_destroy(&dev->condition);
3027+ pthread_mutex_destroy(&dev->mutex);
3028+
3029+ /* Remove it from the device list. */
3030+ pthread_mutex_lock(&device_list_mutex);
3031+ hid_device *d = device_list;
3032+ if (d == dev) {
3033+ device_list = d->next;
3034+ }
3035+ else {
3036+ while (d) {
3037+ if (d->next == dev) {
3038+ d->next = d->next->next;
3039+ break;
3040+ }
3041+
3042+ d = d->next;
3043+ }
3044+ }
3045+ pthread_mutex_unlock(&device_list_mutex);
3046+
3047+ /* Free the structure itself. */
3048+ free(dev);
3049+}
3050+
3051+static IOHIDManagerRef hid_mgr = 0x0;
3052+
3053+
3054+#if 0
3055+static void register_error(hid_device *device, const char *op)
3056+{
3057+
3058+}
3059+#endif
3060+
3061+
3062+static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key)
3063+{
3064+ CFTypeRef ref;
3065+ int32_t value;
3066+
3067+ ref = IOHIDDeviceGetProperty(device, key);
3068+ if (ref) {
3069+ if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
3070+ CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value);
3071+ return value;
3072+ }
3073+ }
3074+ return 0;
3075+}
3076+
3077+static unsigned short get_vendor_id(IOHIDDeviceRef device)
3078+{
3079+ return get_int_property(device, CFSTR(kIOHIDVendorIDKey));
3080+}
3081+
3082+static unsigned short get_product_id(IOHIDDeviceRef device)
3083+{
3084+ return get_int_property(device, CFSTR(kIOHIDProductIDKey));
3085+}
3086+
3087+
3088+static int32_t get_max_report_length(IOHIDDeviceRef device)
3089+{
3090+ return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey));
3091+}
3092+
3093+static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len)
3094+{
3095+ CFStringRef str = IOHIDDeviceGetProperty(device, prop);
3096+
3097+ buf[0] = 0x0000;
3098+
3099+ if (str) {
3100+ CFRange range;
3101+ range.location = 0;
3102+ range.length = len;
3103+ CFIndex used_buf_len;
3104+ CFStringGetBytes(str,
3105+ range,
3106+ kCFStringEncodingUTF32LE,
3107+ (char)'?',
3108+ FALSE,
3109+ (UInt8*)buf,
3110+ len,
3111+ &used_buf_len);
3112+ buf[len-1] = 0x00000000;
3113+ return used_buf_len;
3114+ }
3115+ else
3116+ return 0;
3117+
3118+}
3119+
3120+static int get_string_property_utf8(IOHIDDeviceRef device, CFStringRef prop, char *buf, size_t len)
3121+{
3122+ CFStringRef str = IOHIDDeviceGetProperty(device, prop);
3123+
3124+ buf[0] = 0x0000;
3125+
3126+ if (str) {
3127+ CFRange range;
3128+ range.location = 0;
3129+ range.length = len;
3130+ CFIndex used_buf_len;
3131+ CFStringGetBytes(str,
3132+ range,
3133+ kCFStringEncodingUTF8,
3134+ (char)'?',
3135+ FALSE,
3136+ (UInt8*)buf,
3137+ len,
3138+ &used_buf_len);
3139+ buf[len-1] = 0x00000000;
3140+ return used_buf_len;
3141+ }
3142+ else
3143+ return 0;
3144+
3145+}
3146+
3147+
3148+static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len)
3149+{
3150+ return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len);
3151+}
3152+
3153+static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
3154+{
3155+ return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len);
3156+}
3157+
3158+static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
3159+{
3160+ return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len);
3161+}
3162+
3163+
3164+/* Implementation of wcsdup() for Mac. */
3165+static wchar_t *dup_wcs(const wchar_t *s)
3166+{
3167+ size_t len = wcslen(s);
3168+ wchar_t *ret = malloc((len+1)*sizeof(wchar_t));
3169+ wcscpy(ret, s);
3170+
3171+ return ret;
3172+}
3173+
3174+
3175+static int make_path(IOHIDDeviceRef device, char *buf, size_t len)
3176+{
3177+ int res;
3178+ unsigned short vid, pid;
3179+ char transport[32];
3180+
3181+ buf[0] = '\0';
3182+
3183+ res = get_string_property_utf8(
3184+ device, CFSTR(kIOHIDTransportKey),
3185+ transport, sizeof(transport));
3186+
3187+ if (!res)
3188+ return -1;
3189+
3190+ vid = get_vendor_id(device);
3191+ pid = get_product_id(device);
3192+
3193+ res = snprintf(buf, len, "%s_%04hx_%04hx_%p",
3194+ transport, vid, pid, device);
3195+
3196+
3197+ buf[len-1] = '\0';
3198+ return res+1;
3199+}
3200+
3201+static int init_hid_manager(void)
3202+{
3203+ IOReturn res;
3204+
3205+ /* Initialize all the HID Manager Objects */
3206+ hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
3207+ IOHIDManagerSetDeviceMatching(hid_mgr, NULL);
3208+ IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
3209+ res = IOHIDManagerOpen(hid_mgr, kIOHIDOptionsTypeNone);
3210+ return (res == kIOReturnSuccess)? 0: -1;
3211+}
3212+
3213+int HID_API_EXPORT hid_init(void)
3214+{
3215+ if (!hid_mgr) {
3216+ if (init_hid_manager() < 0) {
3217+ hid_exit();
3218+ return -1;
3219+ }
3220+ }
3221+ return 0;
3222+}
3223+
3224+int HID_API_EXPORT hid_exit(void)
3225+{
3226+ if (hid_mgr) {
3227+ /* Close the HID manager. */
3228+ IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone);
3229+ CFRelease(hid_mgr);
3230+ hid_mgr = NULL;
3231+ }
3232+
3233+ return 0;
3234+}
3235+
3236+struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
3237+{
3238+ struct hid_device_info *root = NULL; // return object
3239+ struct hid_device_info *cur_dev = NULL;
3240+ CFIndex num_devices;
3241+ int i;
3242+
3243+ setlocale(LC_ALL,"");
3244+
3245+ /* Set up the HID Manager if it hasn't been done */
3246+ hid_init();
3247+
3248+ /* Get a list of the Devices */
3249+ CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
3250+
3251+ /* Convert the list into a C array so we can iterate easily. */
3252+ num_devices = CFSetGetCount(device_set);
3253+ IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
3254+ CFSetGetValues(device_set, (const void **) device_array);
3255+
3256+ /* Iterate over each device, making an entry for it. */
3257+ for (i = 0; i < num_devices; i++) {
3258+ unsigned short dev_vid;
3259+ unsigned short dev_pid;
3260+ #define BUF_LEN 256
3261+ wchar_t buf[BUF_LEN];
3262+ char cbuf[BUF_LEN];
3263+
3264+ IOHIDDeviceRef dev = device_array[i];
3265+
3266+ if (!dev) {
3267+ continue;
3268+ }
3269+ dev_vid = get_vendor_id(dev);
3270+ dev_pid = get_product_id(dev);
3271+
3272+ /* Check the VID/PID against the arguments */
3273+ if ((vendor_id == 0x0 && product_id == 0x0) ||
3274+ (vendor_id == dev_vid && product_id == dev_pid)) {
3275+ struct hid_device_info *tmp;
3276+ size_t len;
3277+
3278+ /* VID/PID match. Create the record. */
3279+ tmp = malloc(sizeof(struct hid_device_info));
3280+ if (cur_dev) {
3281+ cur_dev->next = tmp;
3282+ }
3283+ else {
3284+ root = tmp;
3285+ }
3286+ cur_dev = tmp;
3287+
3288+ // Get the Usage Page and Usage for this device.
3289+ cur_dev->usage_page = get_int_property(dev, CFSTR(kIOHIDPrimaryUsagePageKey));
3290+ cur_dev->usage = get_int_property(dev, CFSTR(kIOHIDPrimaryUsageKey));
3291+
3292+ /* Fill out the record */
3293+ cur_dev->next = NULL;
3294+ len = make_path(dev, cbuf, sizeof(cbuf));
3295+ cur_dev->path = strdup(cbuf);
3296+
3297+ /* Serial Number */
3298+ get_serial_number(dev, buf, BUF_LEN);
3299+ cur_dev->serial_number = dup_wcs(buf);
3300+
3301+ /* Manufacturer and Product strings */
3302+ get_manufacturer_string(dev, buf, BUF_LEN);
3303+ cur_dev->manufacturer_string = dup_wcs(buf);
3304+ get_product_string(dev, buf, BUF_LEN);
3305+ cur_dev->product_string = dup_wcs(buf);
3306+
3307+ /* VID/PID */
3308+ cur_dev->vendor_id = dev_vid;
3309+ cur_dev->product_id = dev_pid;
3310+
3311+ /* Release Number */
3312+ cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey));
3313+
3314+ /* Interface Number (Unsupported on Mac)*/
3315+ cur_dev->interface_number = -1;
3316+ }
3317+ }
3318+
3319+ free(device_array);
3320+ CFRelease(device_set);
3321+
3322+ return root;
3323+}
3324+
3325+void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
3326+{
3327+ /* This function is identical to the Linux version. Platform independent. */
3328+ struct hid_device_info *d = devs;
3329+ while (d) {
3330+ struct hid_device_info *next = d->next;
3331+ free(d->path);
3332+ free(d->serial_number);
3333+ free(d->manufacturer_string);
3334+ free(d->product_string);
3335+ free(d);
3336+ d = next;
3337+ }
3338+}
3339+
3340+hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number)
3341+{
3342+ /* This function is identical to the Linux version. Platform independent. */
3343+ struct hid_device_info *devs, *cur_dev;
3344+ const char *path_to_open = NULL;
3345+ hid_device * handle = NULL;
3346+
3347+ devs = hid_enumerate(vendor_id, product_id);
3348+ cur_dev = devs;
3349+ while (cur_dev) {
3350+ if (cur_dev->vendor_id == vendor_id &&
3351+ cur_dev->product_id == product_id) {
3352+ if (serial_number) {
3353+ if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
3354+ path_to_open = cur_dev->path;
3355+ break;
3356+ }
3357+ }
3358+ else {
3359+ path_to_open = cur_dev->path;
3360+ break;
3361+ }
3362+ }
3363+ cur_dev = cur_dev->next;
3364+ }
3365+
3366+ if (path_to_open) {
3367+ /* Open the device */
3368+ handle = hid_open_path(path_to_open);
3369+ }
3370+
3371+ hid_free_enumeration(devs);
3372+
3373+ return handle;
3374+}
3375+
3376+static void hid_device_removal_callback(void *context, IOReturn result,
3377+ void *sender, IOHIDDeviceRef dev_ref)
3378+{
3379+ /* Stop the Run Loop for this device. */
3380+ pthread_mutex_lock(&device_list_mutex);
3381+ hid_device *d = device_list;
3382+ while (d) {
3383+ if (d->device_handle == dev_ref) {
3384+ d->disconnected = 1;
3385+ CFRunLoopStop(d->run_loop);
3386+ }
3387+
3388+ d = d->next;
3389+ }
3390+ pthread_mutex_unlock(&device_list_mutex);
3391+}
3392+
3393+/* The Run Loop calls this function for each input report received.
3394+ This function puts the data into a linked list to be picked up by
3395+ hid_read(). */
3396+static void hid_report_callback(void *context, IOReturn result, void *sender,
3397+ IOHIDReportType report_type, uint32_t report_id,
3398+ uint8_t *report, CFIndex report_length)
3399+{
3400+ struct input_report *rpt;
3401+ hid_device *dev = context;
3402+
3403+ /* Make a new Input Report object */
3404+ rpt = calloc(1, sizeof(struct input_report));
3405+ rpt->data = calloc(1, report_length);
3406+ memcpy(rpt->data, report, report_length);
3407+ rpt->len = report_length;
3408+ rpt->next = NULL;
3409+
3410+ /* Lock this section */
3411+ pthread_mutex_lock(&dev->mutex);
3412+
3413+ /* Attach the new report object to the end of the list. */
3414+ if (dev->input_reports == NULL) {
3415+ /* The list is empty. Put it at the root. */
3416+ dev->input_reports = rpt;
3417+ }
3418+ else {
3419+ /* Find the end of the list and attach. */
3420+ struct input_report *cur = dev->input_reports;
3421+ int num_queued = 0;
3422+ while (cur->next != NULL) {
3423+ cur = cur->next;
3424+ num_queued++;
3425+ }
3426+ cur->next = rpt;
3427+
3428+ /* Pop one off if we've reached 30 in the queue. This
3429+ way we don't grow forever if the user never reads
3430+ anything from the device. */
3431+ if (num_queued > 30) {
3432+ return_data(dev, NULL, 0);
3433+ }
3434+ }
3435+
3436+ /* Signal a waiting thread that there is data. */
3437+ pthread_cond_signal(&dev->condition);
3438+
3439+ /* Unlock */
3440+ pthread_mutex_unlock(&dev->mutex);
3441+
3442+}
3443+
3444+/* This gets called when the read_thred's run loop gets signaled by
3445+ hid_close(), and serves to stop the read_thread's run loop. */
3446+static void perform_signal_callback(void *context)
3447+{
3448+ hid_device *dev = context;
3449+ CFRunLoopStop(dev->run_loop); //TODO: CFRunLoopGetCurrent()
3450+}
3451+
3452+static void *read_thread(void *param)
3453+{
3454+ hid_device *dev = param;
3455+
3456+ /* Move the device's run loop to this thread. */
3457+ IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode);
3458+
3459+ /* Create the RunLoopSource which is used to signal the
3460+ event loop to stop when hid_close() is called. */
3461+ CFRunLoopSourceContext ctx;
3462+ memset(&ctx, 0, sizeof(ctx));
3463+ ctx.version = 0;
3464+ ctx.info = dev;
3465+ ctx.perform = &perform_signal_callback;
3466+ dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx);
3467+ CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode);
3468+
3469+ /* Store off the Run Loop so it can be stopped from hid_close()
3470+ and on device disconnection. */
3471+ dev->run_loop = CFRunLoopGetCurrent();
3472+
3473+ /* Notify the main thread that the read thread is up and running. */
3474+ pthread_barrier_wait(&dev->barrier);
3475+
3476+ /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input
3477+ reports into the hid_report_callback(). */
3478+ SInt32 code;
3479+ while (!dev->shutdown_thread && !dev->disconnected) {
3480+ code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE);
3481+ /* Return if the device has been disconnected */
3482+ if (code == kCFRunLoopRunFinished) {
3483+ dev->disconnected = 1;
3484+ break;
3485+ }
3486+
3487+
3488+ /* Break if The Run Loop returns Finished or Stopped. */
3489+ if (code != kCFRunLoopRunTimedOut &&
3490+ code != kCFRunLoopRunHandledSource) {
3491+ /* There was some kind of error. Setting
3492+ shutdown seems to make sense, but
3493+ there may be something else more appropriate */
3494+ dev->shutdown_thread = 1;
3495+ break;
3496+ }
3497+ }
3498+
3499+ /* Now that the read thread is stopping, Wake any threads which are
3500+ waiting on data (in hid_read_timeout()). Do this under a mutex to
3501+ make sure that a thread which is about to go to sleep waiting on
3502+ the condition acutally will go to sleep before the condition is
3503+ signaled. */
3504+ pthread_mutex_lock(&dev->mutex);
3505+ pthread_cond_broadcast(&dev->condition);
3506+ pthread_mutex_unlock(&dev->mutex);
3507+
3508+ /* Close the OS handle to the device, but only if it's not
3509+ been unplugged. If it's been unplugged, then calling
3510+ IOHIDDeviceClose() will crash. */
3511+ if (!dev->disconnected) {
3512+ IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeNone);
3513+ }
3514+
3515+ /* Wait here until hid_close() is called and makes it past
3516+ the call to CFRunLoopWakeUp(). This thread still needs to
3517+ be valid when that function is called on the other thread. */
3518+ pthread_barrier_wait(&dev->shutdown_barrier);
3519+
3520+ return NULL;
3521+}
3522+
3523+hid_device * HID_API_EXPORT hid_open_path(const char *path)
3524+{
3525+ int i;
3526+ hid_device *dev = NULL;
3527+ CFIndex num_devices;
3528+
3529+ dev = new_hid_device();
3530+
3531+ /* Set up the HID Manager if it hasn't been done */
3532+ hid_init();
3533+
3534+ CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
3535+
3536+ num_devices = CFSetGetCount(device_set);
3537+ IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
3538+ CFSetGetValues(device_set, (const void **) device_array);
3539+ for (i = 0; i < num_devices; i++) {
3540+ char cbuf[BUF_LEN];
3541+ size_t len;
3542+ IOHIDDeviceRef os_dev = device_array[i];
3543+
3544+ len = make_path(os_dev, cbuf, sizeof(cbuf));
3545+ if (!strcmp(cbuf, path)) {
3546+ // Matched Paths. Open this Device.
3547+ IOReturn ret = IOHIDDeviceOpen(os_dev, kIOHIDOptionsTypeNone);
3548+ if (ret == kIOReturnSuccess) {
3549+ char str[32];
3550+
3551+ free(device_array);
3552+ CFRelease(device_set);
3553+ dev->device_handle = os_dev;
3554+
3555+ /* Create the buffers for receiving data */
3556+ dev->max_input_report_len = (CFIndex) get_max_report_length(os_dev);
3557+ dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t));
3558+
3559+ /* Create the Run Loop Mode for this device.
3560+ printing the reference seems to work. */
3561+ sprintf(str, "HIDAPI_%p", os_dev);
3562+ dev->run_loop_mode =
3563+ CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII);
3564+
3565+ /* Attach the device to a Run Loop */
3566+ IOHIDDeviceRegisterInputReportCallback(
3567+ os_dev, dev->input_report_buf, dev->max_input_report_len,
3568+ &hid_report_callback, dev);
3569+ IOHIDManagerRegisterDeviceRemovalCallback(hid_mgr, hid_device_removal_callback, NULL);
3570+
3571+ /* Start the read thread */
3572+ pthread_create(&dev->thread, NULL, read_thread, dev);
3573+
3574+ /* Wait here for the read thread to be initialized. */
3575+ pthread_barrier_wait(&dev->barrier);
3576+
3577+ return dev;
3578+ }
3579+ else {
3580+ goto return_error;
3581+ }
3582+ }
3583+ }
3584+
3585+return_error:
3586+ free(device_array);
3587+ CFRelease(device_set);
3588+ free_hid_device(dev);
3589+ return NULL;
3590+}
3591+
3592+static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length)
3593+{
3594+ const unsigned char *data_to_send;
3595+ size_t length_to_send;
3596+ IOReturn res;
3597+
3598+ /* Return if the device has been disconnected. */
3599+ if (dev->disconnected)
3600+ return -1;
3601+
3602+ if (data[0] == 0x0) {
3603+ /* Not using numbered Reports.
3604+ Don't send the report number. */
3605+ data_to_send = data+1;
3606+ length_to_send = length-1;
3607+ }
3608+ else {
3609+ /* Using numbered Reports.
3610+ Send the Report Number */
3611+ data_to_send = data;
3612+ length_to_send = length;
3613+ }
3614+
3615+ if (!dev->disconnected) {
3616+ res = IOHIDDeviceSetReport(dev->device_handle,
3617+ type,
3618+ data[0], /* Report ID*/
3619+ data_to_send, length_to_send);
3620+
3621+ if (res == kIOReturnSuccess) {
3622+ return length;
3623+ }
3624+ else
3625+ return -1;
3626+ }
3627+
3628+ return -1;
3629+}
3630+
3631+int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
3632+{
3633+ return set_report(dev, kIOHIDReportTypeOutput, data, length);
3634+}
3635+
3636+/* Helper function, so that this isn't duplicated in hid_read(). */
3637+static int return_data(hid_device *dev, unsigned char *data, size_t length)
3638+{
3639+ /* Copy the data out of the linked list item (rpt) into the
3640+ return buffer (data), and delete the liked list item. */
3641+ struct input_report *rpt = dev->input_reports;
3642+ size_t len = (length < rpt->len)? length: rpt->len;
3643+ memcpy(data, rpt->data, len);
3644+ dev->input_reports = rpt->next;
3645+ free(rpt->data);
3646+ free(rpt);
3647+ return len;
3648+}
3649+
3650+static int cond_wait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex)
3651+{
3652+ while (!dev->input_reports) {
3653+ int res = pthread_cond_wait(cond, mutex);
3654+ if (res != 0)
3655+ return res;
3656+
3657+ /* A res of 0 means we may have been signaled or it may
3658+ be a spurious wakeup. Check to see that there's acutally
3659+ data in the queue before returning, and if not, go back
3660+ to sleep. See the pthread_cond_timedwait() man page for
3661+ details. */
3662+
3663+ if (dev->shutdown_thread || dev->disconnected)
3664+ return -1;
3665+ }
3666+
3667+ return 0;
3668+}
3669+
3670+static int cond_timedwait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
3671+{
3672+ while (!dev->input_reports) {
3673+ int res = pthread_cond_timedwait(cond, mutex, abstime);
3674+ if (res != 0)
3675+ return res;
3676+
3677+ /* A res of 0 means we may have been signaled or it may
3678+ be a spurious wakeup. Check to see that there's acutally
3679+ data in the queue before returning, and if not, go back
3680+ to sleep. See the pthread_cond_timedwait() man page for
3681+ details. */
3682+
3683+ if (dev->shutdown_thread || dev->disconnected)
3684+ return -1;
3685+ }
3686+
3687+ return 0;
3688+
3689+}
3690+
3691+int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
3692+{
3693+ int bytes_read = -1;
3694+
3695+ /* Lock the access to the report list. */
3696+ pthread_mutex_lock(&dev->mutex);
3697+
3698+ /* There's an input report queued up. Return it. */
3699+ if (dev->input_reports) {
3700+ /* Return the first one */
3701+ bytes_read = return_data(dev, data, length);
3702+ goto ret;
3703+ }
3704+
3705+ /* Return if the device has been disconnected. */
3706+ if (dev->disconnected) {
3707+ bytes_read = -1;
3708+ goto ret;
3709+ }
3710+
3711+ if (dev->shutdown_thread) {
3712+ /* This means the device has been closed (or there
3713+ has been an error. An error code of -1 should
3714+ be returned. */
3715+ bytes_read = -1;
3716+ goto ret;
3717+ }
3718+
3719+ /* There is no data. Go to sleep and wait for data. */
3720+
3721+ if (milliseconds == -1) {
3722+ /* Blocking */
3723+ int res;
3724+ res = cond_wait(dev, &dev->condition, &dev->mutex);
3725+ if (res == 0)
3726+ bytes_read = return_data(dev, data, length);
3727+ else {
3728+ /* There was an error, or a device disconnection. */
3729+ bytes_read = -1;
3730+ }
3731+ }
3732+ else if (milliseconds > 0) {
3733+ /* Non-blocking, but called with timeout. */
3734+ int res;
3735+ struct timespec ts;
3736+ struct timeval tv;
3737+ gettimeofday(&tv, NULL);
3738+ TIMEVAL_TO_TIMESPEC(&tv, &ts);
3739+ ts.tv_sec += milliseconds / 1000;
3740+ ts.tv_nsec += (milliseconds % 1000) * 1000000;
3741+ if (ts.tv_nsec >= 1000000000L) {
3742+ ts.tv_sec++;
3743+ ts.tv_nsec -= 1000000000L;
3744+ }
3745+
3746+ res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts);
3747+ if (res == 0)
3748+ bytes_read = return_data(dev, data, length);
3749+ else if (res == ETIMEDOUT)
3750+ bytes_read = 0;
3751+ else
3752+ bytes_read = -1;
3753+ }
3754+ else {
3755+ /* Purely non-blocking */
3756+ bytes_read = 0;
3757+ }
3758+
3759+ret:
3760+ /* Unlock */
3761+ pthread_mutex_unlock(&dev->mutex);
3762+ return bytes_read;
3763+}
3764+
3765+int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
3766+{
3767+ return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
3768+}
3769+
3770+int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
3771+{
3772+ /* All Nonblocking operation is handled by the library. */
3773+ dev->blocking = !nonblock;
3774+
3775+ return 0;
3776+}
3777+
3778+int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
3779+{
3780+ return set_report(dev, kIOHIDReportTypeFeature, data, length);
3781+}
3782+
3783+int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
3784+{
3785+ CFIndex len = length;
3786+ IOReturn res;
3787+
3788+ /* Return if the device has been unplugged. */
3789+ if (dev->disconnected)
3790+ return -1;
3791+
3792+ res = IOHIDDeviceGetReport(dev->device_handle,
3793+ kIOHIDReportTypeFeature,
3794+ data[0], /* Report ID */
3795+ data, &len);
3796+ if (res == kIOReturnSuccess)
3797+ return len;
3798+ else
3799+ return -1;
3800+}
3801+
3802+
3803+void HID_API_EXPORT hid_close(hid_device *dev)
3804+{
3805+ if (!dev)
3806+ return;
3807+
3808+ /* Disconnect the report callback before close. */
3809+ if (!dev->disconnected) {
3810+ IOHIDDeviceRegisterInputReportCallback(
3811+ dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
3812+ NULL, dev);
3813+ IOHIDManagerRegisterDeviceRemovalCallback(hid_mgr, NULL, dev);
3814+ IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode);
3815+ IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
3816+ }
3817+
3818+ /* Cause read_thread() to stop. */
3819+ dev->shutdown_thread = 1;
3820+
3821+ /* Wake up the run thread's event loop so that the thread can exit. */
3822+ CFRunLoopSourceSignal(dev->source);
3823+ CFRunLoopWakeUp(dev->run_loop);
3824+
3825+ /* Notify the read thread that it can shut down now. */
3826+ pthread_barrier_wait(&dev->shutdown_barrier);
3827+
3828+ /* Wait for read_thread() to end. */
3829+ pthread_join(dev->thread, NULL);
3830+
3831+ /* Close the OS handle to the device, but only if it's not
3832+ been unplugged. If it's been unplugged, then calling
3833+ IOHIDDeviceClose() will crash. */
3834+ if (!dev->disconnected) {
3835+ IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeNone);
3836+ }
3837+
3838+ /* Clear out the queue of received reports. */
3839+ pthread_mutex_lock(&dev->mutex);
3840+ while (dev->input_reports) {
3841+ return_data(dev, NULL, 0);
3842+ }
3843+ pthread_mutex_unlock(&dev->mutex);
3844+
3845+ free_hid_device(dev);
3846+}
3847+
3848+int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
3849+{
3850+ return get_manufacturer_string(dev->device_handle, string, maxlen);
3851+}
3852+
3853+int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
3854+{
3855+ return get_product_string(dev->device_handle, string, maxlen);
3856+}
3857+
3858+int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
3859+{
3860+ return get_serial_number(dev->device_handle, string, maxlen);
3861+}
3862+
3863+int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
3864+{
3865+ // TODO:
3866+
3867+ return 0;
3868+}
3869+
3870+
3871+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
3872+{
3873+ // TODO:
3874+
3875+ return NULL;
3876+}
3877+
3878+
3879+
3880+
3881+
3882+
3883+#if 0
3884+static int32_t get_location_id(IOHIDDeviceRef device)
3885+{
3886+ return get_int_property(device, CFSTR(kIOHIDLocationIDKey));
3887+}
3888+
3889+static int32_t get_usage(IOHIDDeviceRef device)
3890+{
3891+ int32_t res;
3892+ res = get_int_property(device, CFSTR(kIOHIDDeviceUsageKey));
3893+ if (!res)
3894+ res = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey));
3895+ return res;
3896+}
3897+
3898+static int32_t get_usage_page(IOHIDDeviceRef device)
3899+{
3900+ int32_t res;
3901+ res = get_int_property(device, CFSTR(kIOHIDDeviceUsagePageKey));
3902+ if (!res)
3903+ res = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey));
3904+ return res;
3905+}
3906+
3907+static int get_transport(IOHIDDeviceRef device, wchar_t *buf, size_t len)
3908+{
3909+ return get_string_property(device, CFSTR(kIOHIDTransportKey), buf, len);
3910+}
3911+
3912+
3913+int main(void)
3914+{
3915+ IOHIDManagerRef mgr;
3916+ int i;
3917+
3918+ mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
3919+ IOHIDManagerSetDeviceMatching(mgr, NULL);
3920+ IOHIDManagerOpen(mgr, kIOHIDOptionsTypeNone);
3921+
3922+ CFSetRef device_set = IOHIDManagerCopyDevices(mgr);
3923+
3924+ CFIndex num_devices = CFSetGetCount(device_set);
3925+ IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
3926+ CFSetGetValues(device_set, (const void **) device_array);
3927+
3928+ setlocale(LC_ALL, "");
3929+
3930+ for (i = 0; i < num_devices; i++) {
3931+ IOHIDDeviceRef dev = device_array[i];
3932+ printf("Device: %p\n", dev);
3933+ printf(" %04hx %04hx\n", get_vendor_id(dev), get_product_id(dev));
3934+
3935+ wchar_t serial[256], buf[256];
3936+ char cbuf[256];
3937+ get_serial_number(dev, serial, 256);
3938+
3939+
3940+ printf(" Serial: %ls\n", serial);
3941+ printf(" Loc: %ld\n", get_location_id(dev));
3942+ get_transport(dev, buf, 256);
3943+ printf(" Trans: %ls\n", buf);
3944+ make_path(dev, cbuf, 256);
3945+ printf(" Path: %s\n", cbuf);
3946+
3947+ }
3948+
3949+ return 0;
3950+}
3951+#endif
3952
3953=== added directory 'mixxx/lib/hidapi-0.7.0/windows'
3954=== added file 'mixxx/lib/hidapi-0.7.0/windows/.gitignore'
3955--- mixxx/lib/hidapi-0.7.0/windows/.gitignore 1970-01-01 00:00:00 +0000
3956+++ mixxx/lib/hidapi-0.7.0/windows/.gitignore 2012-04-07 14:24:23 +0000
3957@@ -0,0 +1,11 @@
3958+Debug
3959+Release
3960+*.exp
3961+*.ilk
3962+*.lib
3963+*.suo
3964+*.vcproj.*
3965+*.ncb
3966+*.suo
3967+*.dll
3968+*.pdb
3969
3970=== added file 'mixxx/lib/hidapi-0.7.0/windows/Makefile'
3971--- mixxx/lib/hidapi-0.7.0/windows/Makefile 1970-01-01 00:00:00 +0000
3972+++ mixxx/lib/hidapi-0.7.0/windows/Makefile 2012-04-07 14:24:23 +0000
3973@@ -0,0 +1,14 @@
3974+
3975+
3976+OS=$(shell uname)
3977+
3978+ifneq (,$(findstring MINGW,$(OS)))
3979+ FILE=Makefile.mingw
3980+endif
3981+
3982+ifeq ($(FILE), )
3983+all:
3984+ $(error Your platform ${OS} is not supported at this time.)
3985+endif
3986+
3987+include $(FILE)
3988
3989=== added file 'mixxx/lib/hidapi-0.7.0/windows/Makefile.mingw'
3990--- mixxx/lib/hidapi-0.7.0/windows/Makefile.mingw 1970-01-01 00:00:00 +0000
3991+++ mixxx/lib/hidapi-0.7.0/windows/Makefile.mingw 2012-04-07 14:24:23 +0000
3992@@ -0,0 +1,32 @@
3993+###########################################
3994+# Simple Makefile for HIDAPI test program
3995+#
3996+# Alan Ott
3997+# Signal 11 Software
3998+# 2010-06-01
3999+###########################################
4000+
4001+all: hidtest
4002+
4003+CC=gcc
4004+CXX=g++
4005+COBJS=hid.o
4006+CPPOBJS=../hidtest/hidtest.o
4007+OBJS=$(COBJS) $(CPPOBJS)
4008+CFLAGS=-I../hidapi -g -c
4009+LIBS= -lsetupapi
4010+
4011+
4012+hidtest: $(OBJS)
4013+ g++ -g $^ $(LIBS) -o hidtest
4014+
4015+$(COBJS): %.o: %.c
4016+ $(CC) $(CFLAGS) $< -o $@
4017+
4018+$(CPPOBJS): %.o: %.cpp
4019+ $(CXX) $(CFLAGS) $< -o $@
4020+
4021+clean:
4022+ rm *.o ../hidtest/*.o hidtest.exe
4023+
4024+.PHONY: clean
4025
4026=== added directory 'mixxx/lib/hidapi-0.7.0/windows/ddk_build'
4027=== added file 'mixxx/lib/hidapi-0.7.0/windows/ddk_build/.gitignore'
4028--- mixxx/lib/hidapi-0.7.0/windows/ddk_build/.gitignore 1970-01-01 00:00:00 +0000
4029+++ mixxx/lib/hidapi-0.7.0/windows/ddk_build/.gitignore 2012-04-07 14:24:23 +0000
4030@@ -0,0 +1,2 @@
4031+*.log
4032+obj*_*_*
4033\ No newline at end of file
4034
4035=== added file 'mixxx/lib/hidapi-0.7.0/windows/ddk_build/hidapi.def'
4036--- mixxx/lib/hidapi-0.7.0/windows/ddk_build/hidapi.def 1970-01-01 00:00:00 +0000
4037+++ mixxx/lib/hidapi-0.7.0/windows/ddk_build/hidapi.def 2012-04-07 14:24:23 +0000
4038@@ -0,0 +1,17 @@
4039+LIBRARY hidapi
4040+EXPORTS
4041+ hid_open @1
4042+ hid_write @2
4043+ hid_read @3
4044+ hid_close @4
4045+ hid_get_product_string @5
4046+ hid_get_manufacturer_string @6
4047+ hid_get_serial_number_string @7
4048+ hid_get_indexed_string @8
4049+ hid_error @9
4050+ hid_set_nonblocking @10
4051+ hid_enumerate @11
4052+ hid_open_path @12
4053+ hid_send_feature_report @13
4054+ hid_get_feature_report @14
4055+
4056\ No newline at end of file
4057
4058=== added file 'mixxx/lib/hidapi-0.7.0/windows/ddk_build/makefile'
4059--- mixxx/lib/hidapi-0.7.0/windows/ddk_build/makefile 1970-01-01 00:00:00 +0000
4060+++ mixxx/lib/hidapi-0.7.0/windows/ddk_build/makefile 2012-04-07 14:24:23 +0000
4061@@ -0,0 +1,49 @@
4062+#############################################################################
4063+#
4064+# Copyright (C) Microsoft Corporation 1995, 1996
4065+# All Rights Reserved.
4066+#
4067+# MAKEFILE for HID directory
4068+#
4069+#############################################################################
4070+
4071+!IFDEF WIN95_BUILD
4072+
4073+ROOT=..\..\..\..
4074+
4075+VERSIONLIST = debug retail
4076+IS_32 = TRUE
4077+IS_SDK = TRUE
4078+IS_PRIVATE = TRUE
4079+IS_SDK = TRUE
4080+IS_DDK = TRUE
4081+WIN32 = TRUE
4082+COMMONMKFILE = hidapi.mk
4083+
4084+!include $(ROOT)\dev\master.mk
4085+
4086+
4087+!ELSE
4088+
4089+#
4090+# DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source
4091+# file to this component. This file merely indirects to the real make file
4092+# that is shared by all the driver components of the Windows NT DDK
4093+#
4094+
4095+!IF DEFINED(_NT_TARGET_VERSION)
4096+! IF $(_NT_TARGET_VERSION)>=0x501
4097+! INCLUDE $(NTMAKEENV)\makefile.def
4098+! ELSE
4099+# Only warn once per directory
4100+! INCLUDE $(NTMAKEENV)\makefile.plt
4101+! IF "$(BUILD_PASS)"=="PASS1"
4102+! message BUILDMSG: Warning : The sample "$(MAKEDIR)" is not valid for the current OS target.
4103+! ENDIF
4104+! ENDIF
4105+!ELSE
4106+! INCLUDE $(NTMAKEENV)\makefile.def
4107+!ENDIF
4108+
4109+!ENDIF
4110+
4111
4112=== added file 'mixxx/lib/hidapi-0.7.0/windows/ddk_build/sources'
4113--- mixxx/lib/hidapi-0.7.0/windows/ddk_build/sources 1970-01-01 00:00:00 +0000
4114+++ mixxx/lib/hidapi-0.7.0/windows/ddk_build/sources 2012-04-07 14:24:23 +0000
4115@@ -0,0 +1,23 @@
4116+TARGETNAME=hidapi
4117+TARGETTYPE=DYNLINK
4118+UMTYPE=console
4119+UMENTRY=main
4120+
4121+MSC_WARNING_LEVEL=/W3 /WX
4122+
4123+TARGETLIBS=$(SDK_LIB_PATH)\hid.lib \
4124+ $(SDK_LIB_PATH)\setupapi.lib \
4125+ $(SDK_LIB_PATH)\kernel32.lib \
4126+ $(SDK_LIB_PATH)\comdlg32.lib
4127+
4128+USE_MSVCRT=1
4129+
4130+INCLUDES= ..\..\hidapi
4131+SOURCES= ..\hid.c \
4132+
4133+
4134+TARGET_DESTINATION=retail
4135+
4136+MUI=0
4137+MUI_COMMENT="HID Interface DLL"
4138+
4139
4140=== added file 'mixxx/lib/hidapi-0.7.0/windows/hid.c'
4141--- mixxx/lib/hidapi-0.7.0/windows/hid.c 1970-01-01 00:00:00 +0000
4142+++ mixxx/lib/hidapi-0.7.0/windows/hid.c 2012-04-07 14:24:23 +0000
4143@@ -0,0 +1,873 @@
4144+/*******************************************************
4145+ HIDAPI - Multi-Platform library for
4146+ communication with HID devices.
4147+
4148+ Alan Ott
4149+ Signal 11 Software
4150+
4151+ 8/22/2009
4152+
4153+ Copyright 2009, All Rights Reserved.
4154+
4155+ At the discretion of the user of this library,
4156+ this software may be licensed under the terms of the
4157+ GNU Public License v3, a BSD-Style license, or the
4158+ original HIDAPI license as outlined in the LICENSE.txt,
4159+ LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
4160+ files located at the root of the source distribution.
4161+ These files may also be found in the public source
4162+ code repository located at:
4163+ http://github.com/signal11/hidapi .
4164+********************************************************/
4165+
4166+#include <windows.h>
4167+
4168+#ifndef _NTDEF_
4169+typedef LONG NTSTATUS;
4170+#endif
4171+
4172+#ifdef __MINGW32__
4173+#include <ntdef.h>
4174+#include <winbase.h>
4175+#endif
4176+
4177+#ifdef __CYGWIN__
4178+#include <ntdef.h>
4179+#define _wcsdup wcsdup
4180+#endif
4181+
4182+//#define HIDAPI_USE_DDK
4183+
4184+#ifdef __cplusplus
4185+extern "C" {
4186+#endif
4187+ #include <setupapi.h>
4188+ #include <winioctl.h>
4189+ #ifdef HIDAPI_USE_DDK
4190+ #include <hidsdi.h>
4191+ #endif
4192+
4193+ // Copied from inc/ddk/hidclass.h, part of the Windows DDK.
4194+ #define HID_OUT_CTL_CODE(id) \
4195+ CTL_CODE(FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
4196+ #define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100)
4197+
4198+#ifdef __cplusplus
4199+} // extern "C"
4200+#endif
4201+
4202+#include <stdio.h>
4203+#include <stdlib.h>
4204+
4205+
4206+#include "hidapi.h"
4207+
4208+#ifdef _MSC_VER
4209+ // Thanks Microsoft, but I know how to use strncpy().
4210+ #pragma warning(disable:4996)
4211+#endif
4212+
4213+#ifdef __cplusplus
4214+extern "C" {
4215+#endif
4216+
4217+#ifndef HIDAPI_USE_DDK
4218+ // Since we're not building with the DDK, and the HID header
4219+ // files aren't part of the SDK, we have to define all this
4220+ // stuff here. In lookup_functions(), the function pointers
4221+ // defined below are set.
4222+ typedef struct _HIDD_ATTRIBUTES{
4223+ ULONG Size;
4224+ USHORT VendorID;
4225+ USHORT ProductID;
4226+ USHORT VersionNumber;
4227+ } HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES;
4228+
4229+ typedef USHORT USAGE;
4230+ typedef struct _HIDP_CAPS {
4231+ USAGE Usage;
4232+ USAGE UsagePage;
4233+ USHORT InputReportByteLength;
4234+ USHORT OutputReportByteLength;
4235+ USHORT FeatureReportByteLength;
4236+ USHORT Reserved[17];
4237+ USHORT fields_not_used_by_hidapi[10];
4238+ } HIDP_CAPS, *PHIDP_CAPS;
4239+ typedef char* HIDP_PREPARSED_DATA;
4240+ #define HIDP_STATUS_SUCCESS 0x0
4241+
4242+ typedef BOOLEAN (__stdcall *HidD_GetAttributes_)(HANDLE device, PHIDD_ATTRIBUTES attrib);
4243+ typedef BOOLEAN (__stdcall *HidD_GetSerialNumberString_)(HANDLE device, PVOID buffer, ULONG buffer_len);
4244+ typedef BOOLEAN (__stdcall *HidD_GetManufacturerString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
4245+ typedef BOOLEAN (__stdcall *HidD_GetProductString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
4246+ typedef BOOLEAN (__stdcall *HidD_SetFeature_)(HANDLE handle, PVOID data, ULONG length);
4247+ typedef BOOLEAN (__stdcall *HidD_GetFeature_)(HANDLE handle, PVOID data, ULONG length);
4248+ typedef BOOLEAN (__stdcall *HidD_GetIndexedString_)(HANDLE handle, ULONG string_index, PVOID buffer, ULONG buffer_len);
4249+ typedef BOOLEAN (__stdcall *HidD_GetPreparsedData_)(HANDLE handle, HIDP_PREPARSED_DATA **preparsed_data);
4250+ typedef BOOLEAN (__stdcall *HidD_FreePreparsedData_)(HIDP_PREPARSED_DATA *preparsed_data);
4251+ typedef BOOLEAN (__stdcall *HidP_GetCaps_)(HIDP_PREPARSED_DATA *preparsed_data, HIDP_CAPS *caps);
4252+
4253+ static HidD_GetAttributes_ HidD_GetAttributes;
4254+ static HidD_GetSerialNumberString_ HidD_GetSerialNumberString;
4255+ static HidD_GetManufacturerString_ HidD_GetManufacturerString;
4256+ static HidD_GetProductString_ HidD_GetProductString;
4257+ static HidD_SetFeature_ HidD_SetFeature;
4258+ static HidD_GetFeature_ HidD_GetFeature;
4259+ static HidD_GetIndexedString_ HidD_GetIndexedString;
4260+ static HidD_GetPreparsedData_ HidD_GetPreparsedData;
4261+ static HidD_FreePreparsedData_ HidD_FreePreparsedData;
4262+ static HidP_GetCaps_ HidP_GetCaps;
4263+
4264+ static HMODULE lib_handle = NULL;
4265+ static BOOLEAN initialized = FALSE;
4266+#endif // HIDAPI_USE_DDK
4267+
4268+struct hid_device_ {
4269+ HANDLE device_handle;
4270+ BOOL blocking;
4271+ size_t input_report_length;
4272+ void *last_error_str;
4273+ DWORD last_error_num;
4274+ BOOL read_pending;
4275+ char *read_buf;
4276+ OVERLAPPED ol;
4277+};
4278+
4279+static hid_device *new_hid_device()
4280+{
4281+ hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
4282+ dev->device_handle = INVALID_HANDLE_VALUE;
4283+ dev->blocking = TRUE;
4284+ dev->input_report_length = 0;
4285+ dev->last_error_str = NULL;
4286+ dev->last_error_num = 0;
4287+ dev->read_pending = FALSE;
4288+ dev->read_buf = NULL;
4289+ memset(&dev->ol, 0, sizeof(dev->ol));
4290+ dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*inital state f=nonsignaled*/, NULL);
4291+
4292+ return dev;
4293+}
4294+
4295+
4296+static void register_error(hid_device *device, const char *op)
4297+{
4298+ WCHAR *ptr, *msg;
4299+
4300+ FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
4301+ FORMAT_MESSAGE_FROM_SYSTEM |
4302+ FORMAT_MESSAGE_IGNORE_INSERTS,
4303+ NULL,
4304+ GetLastError(),
4305+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
4306+ (LPWSTR)&msg, 0/*sz*/,
4307+ NULL);
4308+
4309+ // Get rid of the CR and LF that FormatMessage() sticks at the
4310+ // end of the message. Thanks Microsoft!
4311+ ptr = msg;
4312+ while (*ptr) {
4313+ if (*ptr == '\r') {
4314+ *ptr = 0x0000;
4315+ break;
4316+ }
4317+ ptr++;
4318+ }
4319+
4320+ // Store the message off in the Device entry so that
4321+ // the hid_error() function can pick it up.
4322+ LocalFree(device->last_error_str);
4323+ device->last_error_str = msg;
4324+}
4325+
4326+#ifndef HIDAPI_USE_DDK
4327+static int lookup_functions()
4328+{
4329+ lib_handle = LoadLibraryA("hid.dll");
4330+ if (lib_handle) {
4331+#define RESOLVE(x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) return -1;
4332+ RESOLVE(HidD_GetAttributes);
4333+ RESOLVE(HidD_GetSerialNumberString);
4334+ RESOLVE(HidD_GetManufacturerString);
4335+ RESOLVE(HidD_GetProductString);
4336+ RESOLVE(HidD_SetFeature);
4337+ RESOLVE(HidD_GetFeature);
4338+ RESOLVE(HidD_GetIndexedString);
4339+ RESOLVE(HidD_GetPreparsedData);
4340+ RESOLVE(HidD_FreePreparsedData);
4341+ RESOLVE(HidP_GetCaps);
4342+#undef RESOLVE
4343+ }
4344+ else
4345+ return -1;
4346+
4347+ return 0;
4348+}
4349+#endif
4350+
4351+static HANDLE open_device(const char *path)
4352+{
4353+ HANDLE handle;
4354+
4355+ /* First, try to open with sharing mode turned off. This will make it so
4356+ that a HID device can only be opened once. This is to be consistent
4357+ with the behavior on the other platforms. */
4358+ handle = CreateFileA(path,
4359+ GENERIC_WRITE |GENERIC_READ,
4360+ 0, /*share mode*/
4361+ NULL,
4362+ OPEN_EXISTING,
4363+ FILE_FLAG_OVERLAPPED,//FILE_ATTRIBUTE_NORMAL,
4364+ 0);
4365+
4366+ if (handle == INVALID_HANDLE_VALUE) {
4367+ /* Couldn't open the device. Some devices must be opened
4368+ with sharing enabled (even though they are only opened once),
4369+ so try it here. */
4370+ handle = CreateFileA(path,
4371+ GENERIC_WRITE |GENERIC_READ,
4372+ FILE_SHARE_READ|FILE_SHARE_WRITE, /*share mode*/
4373+ NULL,
4374+ OPEN_EXISTING,
4375+ FILE_FLAG_OVERLAPPED,//FILE_ATTRIBUTE_NORMAL,
4376+ 0);
4377+ }
4378+
4379+ return handle;
4380+}
4381+
4382+int HID_API_EXPORT hid_init(void)
4383+{
4384+#ifndef HIDAPI_USE_DDK
4385+ if (!initialized) {
4386+ if (lookup_functions() < 0) {
4387+ hid_exit();
4388+ return -1;
4389+ }
4390+ initialized = TRUE;
4391+ }
4392+#endif
4393+ return 0;
4394+}
4395+
4396+int HID_API_EXPORT hid_exit(void)
4397+{
4398+#ifndef HIDAPI_USE_DDK
4399+ if (lib_handle)
4400+ FreeLibrary(lib_handle);
4401+ lib_handle = NULL;
4402+ initialized = FALSE;
4403+#endif
4404+ return 0;
4405+}
4406+
4407+struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id)
4408+{
4409+ BOOL res;
4410+ struct hid_device_info *root = NULL; // return object
4411+ struct hid_device_info *cur_dev = NULL;
4412+
4413+ // Windows objects for interacting with the driver.
4414+ GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30} };
4415+ SP_DEVINFO_DATA devinfo_data;
4416+ SP_DEVICE_INTERFACE_DATA device_interface_data;
4417+ SP_DEVICE_INTERFACE_DETAIL_DATA_A *device_interface_detail_data = NULL;
4418+ HDEVINFO device_info_set = INVALID_HANDLE_VALUE;
4419+ int device_index = 0;
4420+
4421+ if (hid_init() < 0)
4422+ return NULL;
4423+
4424+ // Initialize the Windows objects.
4425+ devinfo_data.cbSize = sizeof(SP_DEVINFO_DATA);
4426+ device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
4427+
4428+ // Get information for all the devices belonging to the HID class.
4429+ device_info_set = SetupDiGetClassDevsA(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
4430+
4431+ // Iterate over each device in the HID class, looking for the right one.
4432+
4433+ for (;;) {
4434+ HANDLE write_handle = INVALID_HANDLE_VALUE;
4435+ DWORD required_size = 0;
4436+ HIDD_ATTRIBUTES attrib;
4437+
4438+ res = SetupDiEnumDeviceInterfaces(device_info_set,
4439+ NULL,
4440+ &InterfaceClassGuid,
4441+ device_index,
4442+ &device_interface_data);
4443+
4444+ if (!res) {
4445+ // A return of FALSE from this function means that
4446+ // there are no more devices.
4447+ break;
4448+ }
4449+
4450+ // Call with 0-sized detail size, and let the function
4451+ // tell us how long the detail struct needs to be. The
4452+ // size is put in &required_size.
4453+ res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
4454+ &device_interface_data,
4455+ NULL,
4456+ 0,
4457+ &required_size,
4458+ NULL);
4459+
4460+ // Allocate a long enough structure for device_interface_detail_data.
4461+ device_interface_detail_data = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) malloc(required_size);
4462+ device_interface_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
4463+
4464+ // Get the detailed data for this device. The detail data gives us
4465+ // the device path for this device, which is then passed into
4466+ // CreateFile() to get a handle to the device.
4467+ res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
4468+ &device_interface_data,
4469+ device_interface_detail_data,
4470+ required_size,
4471+ NULL,
4472+ NULL);
4473+
4474+ if (!res) {
4475+ //register_error(dev, "Unable to call SetupDiGetDeviceInterfaceDetail");
4476+ // Continue to the next device.
4477+ goto cont;
4478+ }
4479+
4480+ //wprintf(L"HandleName: %s\n", device_interface_detail_data->DevicePath);
4481+
4482+ // Open a handle to the device
4483+ write_handle = open_device(device_interface_detail_data->DevicePath);
4484+
4485+ // Check validity of write_handle.
4486+ if (write_handle == INVALID_HANDLE_VALUE) {
4487+ // Unable to open the device.
4488+ //register_error(dev, "CreateFile");
4489+ goto cont_close;
4490+ }
4491+
4492+
4493+ // Get the Vendor ID and Product ID for this device.
4494+ attrib.Size = sizeof(HIDD_ATTRIBUTES);
4495+ HidD_GetAttributes(write_handle, &attrib);
4496+ //wprintf(L"Product/Vendor: %x %x\n", attrib.ProductID, attrib.VendorID);
4497+
4498+ // Check the VID/PID to see if we should add this
4499+ // device to the enumeration list.
4500+ if ((vendor_id == 0x0 && product_id == 0x0) ||
4501+ (attrib.VendorID == vendor_id && attrib.ProductID == product_id)) {
4502+
4503+ #define WSTR_LEN 512
4504+ const char *str;
4505+ struct hid_device_info *tmp;
4506+ HIDP_PREPARSED_DATA *pp_data = NULL;
4507+ HIDP_CAPS caps;
4508+ BOOLEAN res;
4509+ NTSTATUS nt_res;
4510+ wchar_t wstr[WSTR_LEN]; // TODO: Determine Size
4511+ size_t len;
4512+
4513+ /* VID/PID match. Create the record. */
4514+ tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
4515+ if (cur_dev) {
4516+ cur_dev->next = tmp;
4517+ }
4518+ else {
4519+ root = tmp;
4520+ }
4521+ cur_dev = tmp;
4522+
4523+ // Get the Usage Page and Usage for this device.
4524+ res = HidD_GetPreparsedData(write_handle, &pp_data);
4525+ if (res) {
4526+ nt_res = HidP_GetCaps(pp_data, &caps);
4527+ if (nt_res == HIDP_STATUS_SUCCESS) {
4528+ cur_dev->usage_page = caps.UsagePage;
4529+ cur_dev->usage = caps.Usage;
4530+ }
4531+
4532+ HidD_FreePreparsedData(pp_data);
4533+ }
4534+
4535+ /* Fill out the record */
4536+ cur_dev->next = NULL;
4537+ str = device_interface_detail_data->DevicePath;
4538+ if (str) {
4539+ len = strlen(str);
4540+ cur_dev->path = (char*) calloc(len+1, sizeof(char));
4541+ strncpy(cur_dev->path, str, len+1);
4542+ cur_dev->path[len] = '\0';
4543+ }
4544+ else
4545+ cur_dev->path = NULL;
4546+
4547+ /* Serial Number */
4548+ res = HidD_GetSerialNumberString(write_handle, wstr, sizeof(wstr));
4549+ wstr[WSTR_LEN-1] = 0x0000;
4550+ if (res) {
4551+ cur_dev->serial_number = _wcsdup(wstr);
4552+ }
4553+
4554+ /* Manufacturer String */
4555+ res = HidD_GetManufacturerString(write_handle, wstr, sizeof(wstr));
4556+ wstr[WSTR_LEN-1] = 0x0000;
4557+ if (res) {
4558+ cur_dev->manufacturer_string = _wcsdup(wstr);
4559+ }
4560+
4561+ /* Product String */
4562+ res = HidD_GetProductString(write_handle, wstr, sizeof(wstr));
4563+ wstr[WSTR_LEN-1] = 0x0000;
4564+ if (res) {
4565+ cur_dev->product_string = _wcsdup(wstr);
4566+ }
4567+
4568+ /* VID/PID */
4569+ cur_dev->vendor_id = attrib.VendorID;
4570+ cur_dev->product_id = attrib.ProductID;
4571+
4572+ /* Release Number */
4573+ cur_dev->release_number = attrib.VersionNumber;
4574+
4575+ /* Interface Number. It can sometimes be parsed out of the path
4576+ on Windows if a device has multiple interfaces. See
4577+ http://msdn.microsoft.com/en-us/windows/hardware/gg487473 or
4578+ search for "Hardware IDs for HID Devices" at MSDN. If it's not
4579+ in the path, it's set to -1. */
4580+ cur_dev->interface_number = -1;
4581+ if (cur_dev->path) {
4582+ char *interface_component = strstr(cur_dev->path, "&mi_");
4583+ if (interface_component) {
4584+ char *hex_str = interface_component + 4;
4585+ char *endptr = NULL;
4586+ cur_dev->interface_number = strtol(hex_str, &endptr, 16);
4587+ if (endptr == hex_str) {
4588+ /* The parsing failed. Set interface_number to -1. */
4589+ cur_dev->interface_number = -1;
4590+ }
4591+ }
4592+ }
4593+ }
4594+
4595+cont_close:
4596+ CloseHandle(write_handle);
4597+cont:
4598+ // We no longer need the detail data. It can be freed
4599+ free(device_interface_detail_data);
4600+
4601+ device_index++;
4602+
4603+ }
4604+
4605+ // Close the device information handle.
4606+ SetupDiDestroyDeviceInfoList(device_info_set);
4607+
4608+ return root;
4609+
4610+}
4611+
4612+void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs)
4613+{
4614+ // TODO: Merge this with the Linux version. This function is platform-independent.
4615+ struct hid_device_info *d = devs;
4616+ while (d) {
4617+ struct hid_device_info *next = d->next;
4618+ free(d->path);
4619+ free(d->serial_number);
4620+ free(d->manufacturer_string);
4621+ free(d->product_string);
4622+ free(d);
4623+ d = next;
4624+ }
4625+}
4626+
4627+
4628+HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number)
4629+{
4630+ // TODO: Merge this functions with the Linux version. This function should be platform independent.
4631+ struct hid_device_info *devs, *cur_dev;
4632+ const char *path_to_open = NULL;
4633+ hid_device *handle = NULL;
4634+
4635+ devs = hid_enumerate(vendor_id, product_id);
4636+ cur_dev = devs;
4637+ while (cur_dev) {
4638+ if (cur_dev->vendor_id == vendor_id &&
4639+ cur_dev->product_id == product_id) {
4640+ if (serial_number) {
4641+ if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
4642+ path_to_open = cur_dev->path;
4643+ break;
4644+ }
4645+ }
4646+ else {
4647+ path_to_open = cur_dev->path;
4648+ break;
4649+ }
4650+ }
4651+ cur_dev = cur_dev->next;
4652+ }
4653+
4654+ if (path_to_open) {
4655+ /* Open the device */
4656+ handle = hid_open_path(path_to_open);
4657+ }
4658+
4659+ hid_free_enumeration(devs);
4660+
4661+ return handle;
4662+}
4663+
4664+HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path)
4665+{
4666+ hid_device *dev;
4667+ HIDP_CAPS caps;
4668+ HIDP_PREPARSED_DATA *pp_data = NULL;
4669+ BOOLEAN res;
4670+ NTSTATUS nt_res;
4671+
4672+ if (hid_init() < 0) {
4673+ return NULL;
4674+ }
4675+
4676+ dev = new_hid_device();
4677+
4678+ // Open a handle to the device
4679+ dev->device_handle = open_device(path);
4680+
4681+ // Check validity of write_handle.
4682+ if (dev->device_handle == INVALID_HANDLE_VALUE) {
4683+ // Unable to open the device.
4684+ register_error(dev, "CreateFile");
4685+ goto err;
4686+ }
4687+
4688+ // Get the Input Report length for the device.
4689+ res = HidD_GetPreparsedData(dev->device_handle, &pp_data);
4690+ if (!res) {
4691+ register_error(dev, "HidD_GetPreparsedData");
4692+ goto err;
4693+ }
4694+ nt_res = HidP_GetCaps(pp_data, &caps);
4695+ if (nt_res != HIDP_STATUS_SUCCESS) {
4696+ register_error(dev, "HidP_GetCaps");
4697+ goto err_pp_data;
4698+ }
4699+ dev->input_report_length = caps.InputReportByteLength;
4700+ HidD_FreePreparsedData(pp_data);
4701+
4702+ dev->read_buf = (char*) malloc(dev->input_report_length);
4703+
4704+ return dev;
4705+
4706+err_pp_data:
4707+ HidD_FreePreparsedData(pp_data);
4708+err:
4709+ CloseHandle(dev->device_handle);
4710+ free(dev);
4711+ return NULL;
4712+}
4713+
4714+int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length)
4715+{
4716+ DWORD bytes_written;
4717+ BOOL res;
4718+
4719+ OVERLAPPED ol;
4720+ memset(&ol, 0, sizeof(ol));
4721+
4722+ res = WriteFile(dev->device_handle, data, length, NULL, &ol);
4723+
4724+ if (!res) {
4725+ if (GetLastError() != ERROR_IO_PENDING) {
4726+ // WriteFile() failed. Return error.
4727+ register_error(dev, "WriteFile");
4728+ return -1;
4729+ }
4730+ }
4731+
4732+ // Wait here until the write is done. This makes
4733+ // hid_write() synchronous.
4734+ res = GetOverlappedResult(dev->device_handle, &ol, &bytes_written, TRUE/*wait*/);
4735+ if (!res) {
4736+ // The Write operation failed.
4737+ register_error(dev, "WriteFile");
4738+ return -1;
4739+ }
4740+
4741+ return bytes_written;
4742+}
4743+
4744+
4745+int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
4746+{
4747+ DWORD bytes_read = 0;
4748+ BOOL res;
4749+
4750+ // Copy the handle for convenience.
4751+ HANDLE ev = dev->ol.hEvent;
4752+
4753+ if (!dev->read_pending) {
4754+ // Start an Overlapped I/O read.
4755+ dev->read_pending = TRUE;
4756+ ResetEvent(ev);
4757+ res = ReadFile(dev->device_handle, dev->read_buf, dev->input_report_length, &bytes_read, &dev->ol);
4758+
4759+ if (!res) {
4760+ if (GetLastError() != ERROR_IO_PENDING) {
4761+ // ReadFile() has failed.
4762+ // Clean up and return error.
4763+ CancelIo(dev->device_handle);
4764+ dev->read_pending = FALSE;
4765+ goto end_of_function;
4766+ }
4767+ }
4768+ }
4769+
4770+ if (milliseconds >= 0) {
4771+ // See if there is any data yet.
4772+ res = WaitForSingleObject(ev, milliseconds);
4773+ if (res != WAIT_OBJECT_0) {
4774+ // There was no data this time. Return zero bytes available,
4775+ // but leave the Overlapped I/O running.
4776+ return 0;
4777+ }
4778+ }
4779+
4780+ // Either WaitForSingleObject() told us that ReadFile has completed, or
4781+ // we are in non-blocking mode. Get the number of bytes read. The actual
4782+ // data has been copied to the data[] array which was passed to ReadFile().
4783+ res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/);
4784+
4785+ // Set pending back to false, even if GetOverlappedResult() returned error.
4786+ dev->read_pending = FALSE;
4787+
4788+ if (res && bytes_read > 0) {
4789+ if (dev->read_buf[0] == 0x0) {
4790+ /* If report numbers aren't being used, but Windows sticks a report
4791+ number (0x0) on the beginning of the report anyway. To make this
4792+ work like the other platforms, and to make it work more like the
4793+ HID spec, we'll skip over this byte. */
4794+ bytes_read--;
4795+ memcpy(data, dev->read_buf+1, length);
4796+ }
4797+ else {
4798+ /* Copy the whole buffer, report number and all. */
4799+ memcpy(data, dev->read_buf, length);
4800+ }
4801+ }
4802+
4803+end_of_function:
4804+ if (!res) {
4805+ register_error(dev, "GetOverlappedResult");
4806+ return -1;
4807+ }
4808+
4809+ return bytes_read;
4810+}
4811+
4812+int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length)
4813+{
4814+ return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
4815+}
4816+
4817+int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock)
4818+{
4819+ dev->blocking = !nonblock;
4820+ return 0; /* Success */
4821+}
4822+
4823+int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
4824+{
4825+ BOOL res = HidD_SetFeature(dev->device_handle, (PVOID)data, length);
4826+ if (!res) {
4827+ register_error(dev, "HidD_SetFeature");
4828+ return -1;
4829+ }
4830+
4831+ return length;
4832+}
4833+
4834+
4835+int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
4836+{
4837+ BOOL res;
4838+#if 0
4839+ res = HidD_GetFeature(dev->device_handle, data, length);
4840+ if (!res) {
4841+ register_error(dev, "HidD_GetFeature");
4842+ return -1;
4843+ }
4844+ return 0; /* HidD_GetFeature() doesn't give us an actual length, unfortunately */
4845+#else
4846+ DWORD bytes_returned;
4847+
4848+ OVERLAPPED ol;
4849+ memset(&ol, 0, sizeof(ol));
4850+
4851+ res = DeviceIoControl(dev->device_handle,
4852+ IOCTL_HID_GET_FEATURE,
4853+ data, length,
4854+ data, length,
4855+ &bytes_returned, &ol);
4856+
4857+ if (!res) {
4858+ if (GetLastError() != ERROR_IO_PENDING) {
4859+ // DeviceIoControl() failed. Return error.
4860+ register_error(dev, "Send Feature Report DeviceIoControl");
4861+ return -1;
4862+ }
4863+ }
4864+
4865+ // Wait here until the write is done. This makes
4866+ // hid_get_feature_report() synchronous.
4867+ res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/);
4868+ if (!res) {
4869+ // The operation failed.
4870+ register_error(dev, "Send Feature Report GetOverLappedResult");
4871+ return -1;
4872+ }
4873+ return bytes_returned;
4874+#endif
4875+}
4876+
4877+void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev)
4878+{
4879+ if (!dev)
4880+ return;
4881+ CancelIo(dev->device_handle);
4882+ CloseHandle(dev->ol.hEvent);
4883+ CloseHandle(dev->device_handle);
4884+ LocalFree(dev->last_error_str);
4885+ free(dev->read_buf);
4886+ free(dev);
4887+}
4888+
4889+int HID_API_EXPORT_CALL HID_API_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
4890+{
4891+ BOOL res;
4892+
4893+ res = HidD_GetManufacturerString(dev->device_handle, string, 2 * maxlen);
4894+ if (!res) {
4895+ register_error(dev, "HidD_GetManufacturerString");
4896+ return -1;
4897+ }
4898+
4899+ return 0;
4900+}
4901+
4902+int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
4903+{
4904+ BOOL res;
4905+
4906+ res = HidD_GetProductString(dev->device_handle, string, 2 * maxlen);
4907+ if (!res) {
4908+ register_error(dev, "HidD_GetProductString");
4909+ return -1;
4910+ }
4911+
4912+ return 0;
4913+}
4914+
4915+int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
4916+{
4917+ BOOL res;
4918+
4919+ res = HidD_GetSerialNumberString(dev->device_handle, string, 2 * maxlen);
4920+ if (!res) {
4921+ register_error(dev, "HidD_GetSerialNumberString");
4922+ return -1;
4923+ }
4924+
4925+ return 0;
4926+}
4927+
4928+int HID_API_EXPORT_CALL HID_API_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
4929+{
4930+ BOOL res;
4931+
4932+ res = HidD_GetIndexedString(dev->device_handle, string_index, string, 2 * maxlen);
4933+ if (!res) {
4934+ register_error(dev, "HidD_GetIndexedString");
4935+ return -1;
4936+ }
4937+
4938+ return 0;
4939+}
4940+
4941+
4942+HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
4943+{
4944+ return (wchar_t*)dev->last_error_str;
4945+}
4946+
4947+
4948+//#define PICPGM
4949+//#define S11
4950+#define P32
4951+#ifdef S11
4952+ unsigned short VendorID = 0xa0a0;
4953+ unsigned short ProductID = 0x0001;
4954+#endif
4955+
4956+#ifdef P32
4957+ unsigned short VendorID = 0x04d8;
4958+ unsigned short ProductID = 0x3f;
4959+#endif
4960+
4961+
4962+#ifdef PICPGM
4963+ unsigned short VendorID = 0x04d8;
4964+ unsigned short ProductID = 0x0033;
4965+#endif
4966+
4967+
4968+#if 0
4969+int __cdecl main(int argc, char* argv[])
4970+{
4971+ int res;
4972+ unsigned char buf[65];
4973+
4974+ UNREFERENCED_PARAMETER(argc);
4975+ UNREFERENCED_PARAMETER(argv);
4976+
4977+ // Set up the command buffer.
4978+ memset(buf,0x00,sizeof(buf));
4979+ buf[0] = 0;
4980+ buf[1] = 0x81;
4981+
4982+
4983+ // Open the device.
4984+ int handle = open(VendorID, ProductID, L"12345");
4985+ if (handle < 0)
4986+ printf("unable to open device\n");
4987+
4988+
4989+ // Toggle LED (cmd 0x80)
4990+ buf[1] = 0x80;
4991+ res = write(handle, buf, 65);
4992+ if (res < 0)
4993+ printf("Unable to write()\n");
4994+
4995+ // Request state (cmd 0x81)
4996+ buf[1] = 0x81;
4997+ write(handle, buf, 65);
4998+ if (res < 0)
4999+ printf("Unable to write() (2)\n");
5000+
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches