diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000..4f22e6081d
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,33 @@
+---
+name: Bug report
+about: Create a report to help us improve
+title: ''
+labels: ''
+assignees: ''
+
+---
+
+**Describe the bug**
+A clear and concise description of what the bug is.
+
+**To Reproduce**
+Steps to reproduce the behavior:
+1. Go to '...'
+2. Click on '....'
+3. Scroll down to '....'
+4. See error
+
+**Expected behavior**
+A clear and concise description of what you expected to happen.
+
+**Screenshots and Logs**
+If applicable, add screenshots to help explain your problem. Also, please add the most
+log file (ds4windows_log.txt) from the Logs folder in your DS4Windows config folder.
+
+**Desktop (please complete the following information):**
+ - Controller Make and Model: Sony DS4 v.2 (CUH-ZCT2U)
+ - OS: [e.g. Windows 10 Pro Build 2004]
+ - DS4Windows Version [e.g. 3.0.3]
+
+**Additional context**
+Add any other context about the problem here.
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000000..0860221811
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,6 @@
+version: 2
+updates:
+ - package-ecosystem: "nuget"
+ directory: "/"
+ schedule:
+ interval: "monthly"
diff --git a/.github/workflows/duplicate.yml b/.github/workflows/duplicate.yml
new file mode 100644
index 0000000000..f170667ca2
--- /dev/null
+++ b/.github/workflows/duplicate.yml
@@ -0,0 +1,24 @@
+name: 'Duplicate Issue'
+
+on:
+ issues:
+ types: [labeled, unlabeled, reopened]
+
+permissions:
+ issues: write
+
+jobs:
+ action:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: dessant/support-requests@v2
+ with:
+ github-token: ${{ github.token }}
+ support-label: 'duplicate'
+ issue-comment: >
+ :wave: @{issue-author}, one or more issues for this topic already exist,
+ please follow those instead of opening another one. Use the search function
+ to find issues related to your troubles. Thank you!
+ close-issue: true
+ lock-issue: true
+ issue-lock-reason: 'off-topic'
\ No newline at end of file
diff --git a/.github/workflows/fix-shipped.yml b/.github/workflows/fix-shipped.yml
new file mode 100644
index 0000000000..85f9262a95
--- /dev/null
+++ b/.github/workflows/fix-shipped.yml
@@ -0,0 +1,23 @@
+name: 'Fix shipped with Release'
+
+on:
+ issues:
+ types: [labeled, unlabeled, reopened]
+
+permissions:
+ issues: write
+
+jobs:
+ action:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: dessant/support-requests@v2
+ with:
+ github-token: ${{ github.token }}
+ support-label: 'fix-shipped'
+ issue-comment: >
+ This issues' topic has been resolved and an update has been published.
+ Please check out the Releases page for a new version.
+ close-issue: true
+ lock-issue: false
+ issue-lock-reason: 'off-topic'
\ No newline at end of file
diff --git a/.github/workflows/out-of-scope.yml b/.github/workflows/out-of-scope.yml
new file mode 100644
index 0000000000..ee0bec8093
--- /dev/null
+++ b/.github/workflows/out-of-scope.yml
@@ -0,0 +1,23 @@
+name: 'Out-of-scope Issue'
+
+on:
+ issues:
+ types: [labeled, unlabeled, reopened]
+
+permissions:
+ issues: write
+
+jobs:
+ action:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: dessant/support-requests@v2
+ with:
+ github-token: ${{ github.token }}
+ support-label: 'out-of-scope'
+ issue-comment: >
+ :wave: @{issue-author}, unfortunately this topic is out of scope
+ of the projects' overall goals and will not be worked on.
+ close-issue: true
+ lock-issue: true
+ issue-lock-reason: 'off-topic'
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 1bc915c5cb..1eb67a32ee 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,34 +1,73 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
+*.userosscache
*.sln.docstates
-# Build results
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+# Build results
[Dd]ebug/
+[Dd]ebugPublic/
[Rr]elease/
+[Rr]eleases/
x64/
-build/
+x86/
+bld/
[Bb]in/
[Oo]bj/
+[Ll]og/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
-# Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
-!packages/*/build/
+# Visual Studio 2017 auto generated files
+Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
+# NUNIT
+*.VisualState.xml
+TestResult.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+**/Properties/launchSettings.json
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
*_i.c
*_p.c
+*_i.h
*.ilk
*.meta
*.obj
+*.iobj
*.pch
*.pdb
+*.ipdb
*.pgc
*.pgd
*.rsp
@@ -43,21 +82,34 @@ build/
*.vssscc
.builds
*.pidb
-*.log
+*.svclog
*.scc
+# Chutzpah Test files
+_Chutzpah*
+
# Visual C++ cache files
ipch/
*.aps
*.ncb
+*.opendb
*.opensdf
*.sdf
*.cachefile
+*.VC.db
+*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
# Guidance Automation Toolkit
*.gpState
@@ -65,6 +117,10 @@ ipch/
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# JustCode is a .NET coding add-in
+.JustCode
# TeamCity is a build add-in
_TeamCity*
@@ -72,9 +128,25 @@ _TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
# NCrunch
-*.ncrunch*
+_NCrunch_*
.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
# Installshield output folder
[Ee]xpress/
@@ -93,64 +165,170 @@ DocProject/Help/html
publish/
# Publish Web Output
-*.Publish.xml
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
-# NuGet Packages Directory
-## TODO: If you have NuGet Package Restore enabled, uncomment the next line
-#packages/
+# NuGet Packages
+*.nupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
-# Windows Azure Build Output
-csx
+# Microsoft Azure Build Output
+csx/
*.build.csdef
-# Windows Store app package directory
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!*.[Cc]ache/
# Others
-sql/
-*.Cache
ClientBin/
-[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
-*.[Pp]ublish.xml
+*.dbproj.schemaview
+*.jfm
*.pfx
*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
# RIA/Silverlight projects
Generated_Code/
-# Backup & report files from converting an old project file to a newer
-# Visual Studio version. Backup files are not needed, because we have git ;-)
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
# SQL Server files
-App_Data/*.mdf
-App_Data/*.ldf
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# JetBrains Rider
+.idea/
+*.sln.iml
+
+# CodeRush
+.cr/
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+# OpenCover UI analysis results
+OpenCover/
-#LightSwitch generated files
-GeneratedArtifacts/
-_Pvt_Extensions/
-ModelManifest.xml
+# Azure Stream Analytics local run output
+ASALocalRun/
-# =========================
-# Windows detritus
-# =========================
+# MSBuild Binary and Structured Log
+*.binlog
-# Windows image file caches
-Thumbs.db
-ehthumbs.db
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
-# Folder config file
-Desktop.ini
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
-# Recycle Bin used on file shares
-$RECYCLE.BIN/
+!DS4Windows/libs/x64/
+!DS4Windows/libs/x86/
-# Mac desktop service store files
-.DS_Store
diff --git a/.vs/config/applicationhost.config b/.vs/config/applicationhost.config
deleted file mode 100644
index c2abfb4801..0000000000
--- a/.vs/config/applicationhost.config
+++ /dev/null
@@ -1,1030 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000000..f288702d2f
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/DS4Windows.sln b/DS4Windows.sln
deleted file mode 100644
index 916f340568..0000000000
--- a/DS4Windows.sln
+++ /dev/null
@@ -1,28 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 14
-VisualStudioVersion = 14.0.25420.1
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DS4Windows", "DS4Windows\DS4Windows.csproj", "{7B9354BF-AF82-4CCB-A83D-4BEB1E9D8C96}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Debug|x64 = Debug|x64
- Release|Any CPU = Release|Any CPU
- Release|x64 = Release|x64
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {7B9354BF-AF82-4CCB-A83D-4BEB1E9D8C96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {7B9354BF-AF82-4CCB-A83D-4BEB1E9D8C96}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {7B9354BF-AF82-4CCB-A83D-4BEB1E9D8C96}.Debug|x64.ActiveCfg = Debug|Any CPU
- {7B9354BF-AF82-4CCB-A83D-4BEB1E9D8C96}.Debug|x64.Build.0 = Debug|Any CPU
- {7B9354BF-AF82-4CCB-A83D-4BEB1E9D8C96}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {7B9354BF-AF82-4CCB-A83D-4BEB1E9D8C96}.Release|Any CPU.Build.0 = Release|Any CPU
- {7B9354BF-AF82-4CCB-A83D-4BEB1E9D8C96}.Release|x64.ActiveCfg = Release|Any CPU
- {7B9354BF-AF82-4CCB-A83D-4BEB1E9D8C96}.Release|x64.Build.0 = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
-EndGlobal
diff --git a/DS4Windows/App.xaml b/DS4Windows/App.xaml
new file mode 100644
index 0000000000..955ad023ea
--- /dev/null
+++ b/DS4Windows/App.xaml
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/DS4Windows/App.xaml.cs b/DS4Windows/App.xaml.cs
new file mode 100644
index 0000000000..3152d460c8
--- /dev/null
+++ b/DS4Windows/App.xaml.cs
@@ -0,0 +1,781 @@
+/*
+DS4Windows
+Copyright (C) 2023 Travis Nickles
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
+*/
+
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Data;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.IO.MemoryMappedFiles;
+using System.Linq;
+using System.Net.Http;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Interop;
+using WPFLocalizeExtension.Engine;
+using NLog;
+using System.Windows.Media;
+using System.Net;
+using Microsoft.Win32.SafeHandles;
+using DS4Windows.DS4Control;
+
+namespace DS4WinWPF
+{
+ ///
+ /// Interaction logic for App.xaml
+ ///
+ [System.Security.SuppressUnmanagedCodeSecurity]
+ public partial class App : Application
+ {
+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
+ private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
+
+ [DllImport("user32.dll", EntryPoint = "FindWindow")]
+ private static extern IntPtr FindWindow(string sClass, string sWindow);
+
+ [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
+ private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct COPYDATASTRUCT
+ {
+ public IntPtr dwData;
+ public int cbData;
+ public IntPtr lpData;
+ }
+
+ private Thread controlThread;
+ public static DS4Windows.ControlService rootHub;
+ public static HttpClient requestClient;
+ private bool skipSave;
+ private bool runShutdown;
+ private bool exitApp;
+ private Thread testThread;
+ private bool exitComThread = false;
+ private const string SingleAppComEventName = "{a52b5b20-d9ee-4f32-8518-307fa14aa0c6}";
+ private EventWaitHandle threadComEvent = null;
+ private Timer collectTimer;
+ private static LoggerHolder logHolder;
+
+ private MemoryMappedFile ipcClassNameMMF = null; // MemoryMappedFile for inter-process communication used to hold className of DS4Form window
+ private MemoryMappedFile ipcResultDataMMF = null; // MemoryMappedFile for inter-process communication used to exchange string result data between cmdline client process and the background running DS4Windows app
+
+ private static Dictionary themeLocs = new
+ Dictionary()
+ {
+ [DS4Windows.AppThemeChoice.Default] = "DS4Forms/Themes/DefaultTheme.xaml",
+ [DS4Windows.AppThemeChoice.Light] = "DS4Forms/Themes/DefaultTheme.xaml",
+ [DS4Windows.AppThemeChoice.Dark] = "DS4Forms/Themes/DarkTheme.xaml",
+ };
+
+ public event EventHandler ThemeChanged;
+
+ private void Application_Startup(object sender, StartupEventArgs e)
+ {
+ runShutdown = true;
+ skipSave = true;
+
+ ArgumentParser parser = new ArgumentParser();
+ parser.Parse(e.Args);
+ CheckOptions(parser);
+
+ if (exitApp)
+ {
+ return;
+ }
+
+ try
+ {
+ Process.GetCurrentProcess().PriorityClass =
+ ProcessPriorityClass.High;
+ }
+ catch { } // Ignore problems raising the priority.
+
+ // Force Normal IO Priority
+ IntPtr ioPrio = new IntPtr(2);
+ DS4Windows.Util.NtSetInformationProcess(Process.GetCurrentProcess().Handle,
+ DS4Windows.Util.PROCESS_INFORMATION_CLASS.ProcessIoPriority, ref ioPrio, 4);
+
+ // Force Normal Page Priority
+ IntPtr pagePrio = new IntPtr(5);
+ DS4Windows.Util.NtSetInformationProcess(Process.GetCurrentProcess().Handle,
+ DS4Windows.Util.PROCESS_INFORMATION_CLASS.ProcessPagePriority, ref pagePrio, 4);
+
+ // another instance is already running if TryOpenExisting returns true.
+ try
+ {
+ if (EventWaitHandleAcl.TryOpenExisting(SingleAppComEventName,
+ System.Security.AccessControl.EventWaitHandleRights.Synchronize |
+ System.Security.AccessControl.EventWaitHandleRights.Modify,
+ out EventWaitHandle tempComEvent))
+ {
+ tempComEvent.Set(); // signal the other instance.
+ tempComEvent.Close();
+
+ runShutdown = false;
+ Current.Shutdown(); // Quit temp instance
+ return;
+ }
+ }
+ catch (System.UnauthorizedAccessException)
+ {
+ // Ignore exception
+ }
+
+ // Allow sleep time durations less than 16 ms
+ DS4Windows.Util.timeBeginPeriod(1);
+
+ // Retrieve info about installed ViGEmBus device if found
+ DS4Windows.Global.RefreshViGEmBusInfo();
+
+ // Create the Event handle
+ threadComEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SingleAppComEventName);
+ CreateTempWorkerThread();
+
+ CreateControlService(parser);
+ RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
+
+ DS4Windows.Global.FindConfigLocation();
+ bool firstRun = DS4Windows.Global.firstRun;
+
+ // Could not find unique profile location; does not exist or multiple places.
+ // Advise user to specify where DS4Windows should save its configuation files
+ // and profiles
+ if (firstRun)
+ {
+ DS4Forms.SaveWhere savewh =
+ new DS4Forms.SaveWhere(DS4Windows.Global.multisavespots);
+ savewh.ShowDialog();
+ }
+
+ // Exit if base configuration could not be generated
+ if (firstRun && !CreateConfDirSkeleton())
+ {
+ MessageBox.Show($"Cannot create config folder structure in {DS4Windows.Global.appdatapath}. Exiting",
+ "DS4Windows", MessageBoxButton.OK, MessageBoxImage.Error);
+ Current.Shutdown(1);
+ return;
+ }
+
+ logHolder = new LoggerHolder(rootHub);
+ DispatcherUnhandledException += App_DispatcherUnhandledException;
+ AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
+ Logger logger = logHolder.Logger;
+ string version = DS4Windows.Global.exeversion;
+ logger.Info($"DS4Windows version {version}");
+ logger.Info($"DS4Windows exe file: {DS4Windows.Global.exeFileName}");
+ logger.Info($"DS4Windows Assembly Architecture: {(Environment.Is64BitProcess ? "x64" : "x86")}");
+ logger.Info($"OS Version: {Environment.OSVersion}");
+ logger.Info($"OS Product Name: {DS4Windows.Util.GetOSProductName()}");
+ logger.Info($"OS Release ID: {DS4Windows.Util.GetOSReleaseId()}");
+ logger.Info($"System Architecture: {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}");
+ logger.Info("Logger created");
+
+ bool readAppConfig = DS4Windows.Global.Load();
+ if (!firstRun && !readAppConfig)
+ {
+ logger.Info($@"Profiles.xml not read at location ${DS4Windows.Global.appdatapath}\Profiles.xml. Using default app settings");
+ }
+
+ // Ask user which devices the mapper should attempt to open when detected.
+ // Currently only support DS4 by default to avoid extra complications from
+ // Steam Input
+ if (firstRun)
+ {
+ DS4Forms.FirstLaunchUtilWindow firstLaunchUtilWin =
+ new DS4Forms.FirstLaunchUtilWindow(DS4Windows.Global.DeviceOptions);
+ firstLaunchUtilWin.ShowDialog();
+ DS4Windows.Global.Save();
+ }
+
+ if (firstRun)
+ {
+ logger.Info("No config found. Creating default config");
+ AttemptSave();
+
+ DS4Windows.Global.SaveAsNewProfile(0, "Default");
+ for (int i = 0; i < DS4Windows.ControlService.MAX_DS4_CONTROLLER_COUNT; i++)
+ {
+ DS4Windows.Global.ProfilePath[i] = DS4Windows.Global.OlderProfilePath[i] = "Default";
+ }
+
+ logger.Info("Default config created");
+ }
+
+ skipSave = false;
+
+ if (!DS4Windows.Global.LoadActions())
+ {
+ DS4Windows.Global.CreateStdActions();
+ }
+
+ // Have app use selected culture
+ SetUICulture(DS4Windows.Global.UseLang);
+ DS4Windows.AppThemeChoice themeChoice = DS4Windows.Global.UseCurrentTheme;
+ ChangeTheme(DS4Windows.Global.UseCurrentTheme, false);
+
+ DS4Windows.Global.LoadLinkedProfiles();
+ DS4Forms.MainWindow window = new DS4Forms.MainWindow(parser);
+ MainWindow = window;
+ window.IsInitialShow = true;
+ window.Show();
+ window.IsInitialShow = false;
+
+ // Set up hooks for IPC command calls
+ HwndSource source = PresentationSource.FromVisual(window) as HwndSource;
+ CreateIPCClassNameMMF(source.Handle);
+
+ window.CheckMinStatus();
+
+ bool runningAsAdmin = DS4Windows.Global.IsAdministrator();
+ rootHub.LogDebug($"Running as {(runningAsAdmin ? "Admin" : "User")}");
+
+ if (DS4Windows.Global.hidHideInstalled)
+ {
+ rootHub.CheckHidHidePresence();
+ }
+
+ rootHub.LoadPermanentSlotsConfig();
+ window.LateChecks(parser);
+ }
+
+ private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
+ {
+ if (!Current.Dispatcher.CheckAccess())
+ {
+ Logger logger = logHolder.Logger;
+ Exception exp = e.ExceptionObject as Exception;
+ logger.Error($"Thread App Crashed with message {exp.Message}");
+ logger.Error(exp.ToString());
+ //LogManager.Flush();
+ //LogManager.Shutdown();
+ if (e.IsTerminating)
+ {
+ Dispatcher.Invoke(() =>
+ {
+ rootHub?.PrepareAbort();
+ CleanShutdown();
+ });
+ }
+ }
+ else
+ {
+ Logger logger = logHolder.Logger;
+ Exception exp = e.ExceptionObject as Exception;
+ if (e.IsTerminating)
+ {
+ logger.Error($"Thread Crashed with message {exp.Message}");
+ logger.Error(exp.ToString());
+
+ rootHub?.PrepareAbort();
+ CleanShutdown();
+ }
+ }
+ }
+
+ private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
+ {
+ //Debug.WriteLine("App Crashed");
+ //Debug.WriteLine(e.Exception.StackTrace);
+ Logger logger = logHolder.Logger;
+ logger.Error($"Thread Crashed with message {e.Exception.Message}");
+ logger.Error(e.Exception.ToString());
+ //LogManager.Flush();
+ //LogManager.Shutdown();
+ }
+
+ private bool CreateConfDirSkeleton()
+ {
+ bool result = true;
+ try
+ {
+ Directory.CreateDirectory(DS4Windows.Global.appdatapath);
+ Directory.CreateDirectory(DS4Windows.Global.appdatapath + @"\Profiles\");
+ Directory.CreateDirectory(DS4Windows.Global.appdatapath + @"\Logs\");
+ //Directory.CreateDirectory(DS4Windows.Global.appdatapath + @"\Macros\");
+ }
+ catch (UnauthorizedAccessException)
+ {
+ result = false;
+ }
+
+
+ return result;
+ }
+
+ private void AttemptSave()
+ {
+ if (!DS4Windows.Global.Save()) //if can't write to file
+ {
+ if (MessageBox.Show("Cannot write at current location\nCopy Settings to appdata?", "DS4Windows",
+ MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
+ {
+ try
+ {
+ Directory.CreateDirectory(DS4Windows.Global.appDataPpath);
+ File.Copy(DS4Windows.Global.exedirpath + "\\Profiles.xml",
+ DS4Windows.Global.appDataPpath + "\\Profiles.xml");
+ File.Copy(DS4Windows.Global.exedirpath + "\\Auto Profiles.xml",
+ DS4Windows.Global.appDataPpath + "\\Auto Profiles.xml");
+ Directory.CreateDirectory(DS4Windows.Global.appDataPpath + "\\Profiles");
+ foreach (string s in Directory.GetFiles(DS4Windows.Global.exedirpath + "\\Profiles"))
+ {
+ File.Copy(s, DS4Windows.Global.appDataPpath + "\\Profiles\\" + Path.GetFileName(s));
+ }
+ }
+ catch { }
+ MessageBox.Show("Copy complete, please relaunch DS4Windows and remove settings from Program Directory",
+ "DS4Windows");
+ }
+ else
+ {
+ MessageBox.Show("DS4Windows cannot edit settings here, This will now close",
+ "DS4Windows");
+ }
+
+ DS4Windows.Global.appdatapath = null;
+ skipSave = true;
+ Current.Shutdown();
+ return;
+ }
+ }
+
+ private void CheckOptions(ArgumentParser parser)
+ {
+ if (parser.HasErrors)
+ {
+ runShutdown = false;
+ exitApp = true;
+ Current.Shutdown(1);
+ }
+ else if (parser.Driverinstall)
+ {
+ // Retrieve info about installed ViGEmBus device if found.
+ // Might not be needed here
+ DS4Windows.Global.RefreshViGEmBusInfo();
+
+ // Load DS4Windows config if it exists
+ DS4Windows.Global.FindConfigLocation();
+ bool readAppConfig = DS4Windows.Global.Load();
+ if (readAppConfig)
+ {
+ // Have app use selected culture
+ SetUICulture(DS4Windows.Global.UseLang);
+ DS4Windows.AppThemeChoice themeChoice = DS4Windows.Global.UseCurrentTheme;
+ ChangeTheme(DS4Windows.Global.UseCurrentTheme, false);
+ }
+
+ CreateBaseThread();
+ DS4Forms.WelcomeDialog dialog = new DS4Forms.WelcomeDialog(true);
+ dialog.ShowDialog();
+ runShutdown = false;
+ exitApp = true;
+ Current.Shutdown();
+ }
+ else if (parser.ReenableDevice)
+ {
+ DS4Windows.DS4Devices.reEnableDevice(parser.DeviceInstanceId);
+ runShutdown = false;
+ exitApp = true;
+ Current.Shutdown();
+ }
+ else if (parser.Runtask)
+ {
+ StartupMethods.LaunchOldTask();
+ runShutdown = false;
+ exitApp = true;
+ Current.Shutdown();
+ }
+ else if (parser.Command)
+ {
+ IntPtr hWndDS4WindowsForm = IntPtr.Zero;
+ hWndDS4WindowsForm = FindWindow(ReadIPCClassNameMMF(), "DS4Windows");
+ if (hWndDS4WindowsForm != IntPtr.Zero)
+ {
+ bool bDoSendMsg = true;
+ bool bWaitResultData = false;
+ bool bOwnsMutex = false;
+ Mutex ipcSingleTaskMutex = null;
+ EventWaitHandle ipcNotifyEvent = null;
+
+ COPYDATASTRUCT cds;
+ cds.lpData = IntPtr.Zero;
+
+ try
+ {
+ if (parser.CommandArgs.ToLower().StartsWith("query."))
+ {
+ // Query.device# (1..4) command returns a string result via memory mapped file. The cmd is sent to the background DS4Windows
+ // process (via WM_COPYDATA wnd msg), then this client process waits for the availability of the result and prints it to console output pipe.
+ // Use mutex obj to make sure that concurrent client calls won't try to write and read the same MMF result file at the same time.
+ ipcSingleTaskMutex = new Mutex(false, "DS4Windows_IPCResultData_SingleTaskMtx");
+ try
+ {
+ bOwnsMutex = ipcSingleTaskMutex.WaitOne(10000);
+ }
+ catch (AbandonedMutexException)
+ {
+ bOwnsMutex = true;
+ }
+
+ if (bOwnsMutex)
+ {
+ // This process owns the inter-process sync mutex obj. Let's proceed with creating the output MMF file and waiting for a result.
+ bWaitResultData = true;
+ CreateIPCResultDataMMF();
+ ipcNotifyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DS4Windows_IPCResultData_ReadyEvent");
+ }
+ else
+ // If the mtx failed then something must be seriously wrong. Cannot do anything in that case because MMF file may be modified by concurrent processes.
+ bDoSendMsg = false;
+ }
+
+ if (bDoSendMsg)
+ {
+ cds.dwData = IntPtr.Zero;
+ cds.cbData = parser.CommandArgs.Length;
+ cds.lpData = Marshal.StringToHGlobalAnsi(parser.CommandArgs);
+ SendMessage(hWndDS4WindowsForm, DS4Forms.MainWindow.WM_COPYDATA, IntPtr.Zero, ref cds);
+
+ if (bWaitResultData)
+ Console.WriteLine(WaitAndReadIPCResultDataMMF(ipcNotifyEvent));
+ }
+ }
+ finally
+ {
+ // Release the result MMF file in the client process before releasing the mtx and letting other client process to proceed with the same MMF file
+ if (ipcResultDataMMF != null) ipcResultDataMMF.Dispose();
+ ipcResultDataMMF = null;
+
+ // If this was "Query.xxx" cmdline client call then release the inter-process mutex and let other concurrent clients to proceed (if there are anyone waiting for the MMF result file)
+ if (bOwnsMutex && ipcSingleTaskMutex != null)
+ ipcSingleTaskMutex.ReleaseMutex();
+
+ if (cds.lpData != IntPtr.Zero)
+ Marshal.FreeHGlobal(cds.lpData);
+ }
+ }
+
+ runShutdown = false;
+ exitApp = true;
+ Current.Shutdown();
+ }
+ }
+
+ private void CreateControlService(ArgumentParser parser)
+ {
+ controlThread = new Thread(() => {
+ rootHub = new DS4Windows.ControlService(parser);
+
+ DS4Windows.Program.rootHub = rootHub;
+ requestClient = new HttpClient();
+ collectTimer = new Timer(GarbageTask, null, 30000, 30000);
+
+ });
+ controlThread.Priority = ThreadPriority.Normal;
+ controlThread.IsBackground = true;
+ controlThread.Start();
+ while (controlThread.IsAlive)
+ Thread.SpinWait(500);
+ }
+
+ private void CreateBaseThread()
+ {
+ controlThread = new Thread(() => {
+ DS4Windows.Program.rootHub = rootHub;
+ requestClient = new HttpClient();
+ collectTimer = new Timer(GarbageTask, null, 30000, 30000);
+ });
+ controlThread.Priority = ThreadPriority.Normal;
+ controlThread.IsBackground = true;
+ controlThread.Start();
+ while (controlThread.IsAlive)
+ Thread.SpinWait(500);
+ }
+
+ private void GarbageTask(object state)
+ {
+ GC.Collect(0, GCCollectionMode.Forced, false);
+ }
+
+ private void CreateTempWorkerThread()
+ {
+ testThread = new Thread(SingleAppComThread_DoWork);
+ testThread.Priority = ThreadPriority.Lowest;
+ testThread.IsBackground = true;
+ testThread.Start();
+ }
+
+ private void SingleAppComThread_DoWork()
+ {
+ while (!exitComThread)
+ {
+ // check for a signal.
+ if (threadComEvent.WaitOne())
+ {
+ threadComEvent.Reset();
+ // The user tried to start another instance. We can't allow that,
+ // so bring the other instance back into view and enable that one.
+ // That form is created in another thread, so we need some thread sync magic.
+ if (!exitComThread)
+ {
+ Dispatcher.BeginInvoke((Action)(() =>
+ {
+ MainWindow.Show();
+ MainWindow.WindowState = WindowState.Normal;
+ }));
+ }
+ }
+ }
+ }
+
+ public void CreateIPCClassNameMMF(IntPtr hWnd)
+ {
+ if (ipcClassNameMMF != null) return; // Already holding a handle to MMF file. No need to re-write the data
+
+ try
+ {
+ StringBuilder wndClassNameStr = new StringBuilder(128);
+ if (GetClassName(hWnd, wndClassNameStr, wndClassNameStr.Capacity) != 0 && wndClassNameStr.Length > 0)
+ {
+ byte[] buffer = ASCIIEncoding.ASCII.GetBytes(wndClassNameStr.ToString());
+
+ ipcClassNameMMF = MemoryMappedFile.CreateNew("DS4Windows_IPCClassName.dat", 128);
+ MemoryMappedViewAccessor ipcClassNameMMA_Now = ipcClassNameMMF.CreateViewAccessor(0, buffer.Length);
+ ipcClassNameMMA_Now.WriteArray(0, buffer, 0, buffer.Length);
+ ipcClassNameMMA_Now?.Dispose();
+ // The MMF file is alive as long this process holds the file handle open
+ }
+ }
+ catch (Exception)
+ {
+ /* Eat all exceptions because errors here are not fatal for DS4Win */
+ }
+ }
+
+ private string ReadIPCClassNameMMF()
+ {
+ MemoryMappedFile mmf = null;
+ MemoryMappedViewAccessor mma = null;
+
+ try
+ {
+ byte[] buffer = new byte[128];
+ mmf = MemoryMappedFile.OpenExisting("DS4Windows_IPCClassName.dat");
+ mma = mmf.CreateViewAccessor(0, 128);
+ mma.ReadArray(0, buffer, 0, buffer.Length);
+ return ASCIIEncoding.ASCII.GetString(buffer);
+ }
+ catch (Exception)
+ {
+ // Eat all exceptions
+ }
+ finally
+ {
+ if (mma != null) mma.Dispose();
+ if (mmf != null) mmf.Dispose();
+ }
+
+ return null;
+ }
+
+ private void CreateIPCResultDataMMF()
+ {
+ // Cmdline client process calls this to create the MMF file used in inter-process-communications. The background DS4Windows process
+ // uses WriteIPCResultDataMMF method to write a command result and the client process reads the result from the same MMF file.
+ if (ipcResultDataMMF != null) return; // Already holding a handle to MMF file. No need to re-write the data
+
+ try
+ {
+ ipcResultDataMMF = MemoryMappedFile.CreateNew("DS4Windows_IPCResultData.dat", 256);
+ // The MMF file is alive as long this process holds the file handle open
+ }
+ catch (Exception)
+ {
+ /* Eat all exceptions because errors here are not fatal for DS4Win */
+ }
+ }
+
+ private string WaitAndReadIPCResultDataMMF(EventWaitHandle ipcNotifyEvent)
+ {
+ if (ipcResultDataMMF != null)
+ {
+ // Wait until the inter-process-communication (IPC) result data is available and read the result
+ try
+ {
+ // Wait max 10 secs and if the result is still not available then timeout and return "empty" result
+ if (ipcNotifyEvent == null || ipcNotifyEvent.WaitOne(10000))
+ {
+ int strNullCharIdx;
+ byte[] buffer = new byte[256];
+ MemoryMappedViewAccessor ipcResultDataMMA = ipcClassNameMMF.CreateViewAccessor(0, buffer.Length);
+ ipcResultDataMMA.ReadArray(0, buffer, 0, buffer.Length);
+ strNullCharIdx = Array.FindIndex(buffer, byteVal => byteVal == 0);
+ return ASCIIEncoding.ASCII.GetString(buffer, 0, (strNullCharIdx <= 1 ? 1 : strNullCharIdx));
+ }
+ }
+ catch (Exception)
+ {
+ /* Eat all exceptions because errors here are not fatal for DS4Win */
+ }
+ }
+
+ return String.Empty;
+ }
+
+ public void WriteIPCResultDataMMF(string dataStr)
+ {
+ // The background DS4Windows process calls this method to write out the result of "-command QueryProfile.device#" command.
+ // The cmdline client process reads the result from the DS4Windows_IPCResultData.dat MMF file and sends the result to console output pipe.
+ MemoryMappedFile mmf = null;
+ MemoryMappedViewAccessor mma = null;
+ EventWaitHandle ipcNotifyEvent = null;
+
+ try
+ {
+ ipcNotifyEvent = EventWaitHandle.OpenExisting("DS4Windows_IPCResultData_ReadyEvent");
+
+ byte[] buffer = ASCIIEncoding.ASCII.GetBytes(dataStr);
+ mmf = MemoryMappedFile.OpenExisting("DS4Windows_IPCResultData.dat");
+ mma = mmf.CreateViewAccessor(0, 256);
+ mma.WriteArray(0, buffer, 0, (buffer.Length >= 256 ? 256 : buffer.Length));
+ }
+ catch (Exception)
+ {
+ // Eat all exceptions
+ }
+ finally
+ {
+ if (mma != null) mma.Dispose();
+ if (mmf != null) mmf.Dispose();
+
+ if (ipcNotifyEvent != null) ipcNotifyEvent.Set();
+ }
+ }
+
+ private void SetUICulture(string culture)
+ {
+ try
+ {
+ //CultureInfo ci = new CultureInfo("ja");
+ CultureInfo ci = CultureInfo.GetCultureInfo(culture);
+ LocalizeDictionary.Instance.SetCurrentThreadCulture = true;
+ LocalizeDictionary.Instance.Culture = ci;
+ // fixes the culture in threads
+ CultureInfo.DefaultThreadCurrentCulture = ci;
+ CultureInfo.DefaultThreadCurrentUICulture = ci;
+ //DS4WinWPF.Properties.Resources.Culture = ci;
+ Thread.CurrentThread.CurrentCulture = ci;
+ Thread.CurrentThread.CurrentUICulture = ci;
+ }
+ catch (CultureNotFoundException) { /* Skip setting culture that we cannot set */ }
+ }
+
+ public void ChangeTheme(DS4Windows.AppThemeChoice themeChoice,
+ bool fireChanged=true)
+ {
+ if (themeChoice == DS4Windows.AppThemeChoice.Default)
+ {
+ Application.Current.Resources.MergedDictionaries.Clear();
+
+ // Attempt to switch theme based on currently selected Windows apps theme mode
+ DS4Windows.AppThemeChoice implicitTheme = DS4Windows.Util.SystemAppsUsingDarkTheme() ?
+ DS4Windows.AppThemeChoice.Dark : DS4Windows.AppThemeChoice.Light;
+ themeLocs.TryGetValue(implicitTheme, out string loc);
+ Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(loc, uriKind: UriKind.Relative) });
+
+ if (fireChanged)
+ {
+ ThemeChanged?.Invoke(this, EventArgs.Empty);
+ }
+ }
+ else if (themeLocs.TryGetValue(themeChoice, out string loc))
+ {
+ Application.Current.Resources.MergedDictionaries.Clear();
+ Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(loc, uriKind: UriKind.Relative) });
+
+ if (fireChanged)
+ {
+ ThemeChanged?.Invoke(this, EventArgs.Empty);
+ }
+ }
+ }
+
+ private void Application_Exit(object sender, ExitEventArgs e)
+ {
+ if (runShutdown)
+ {
+ Logger logger = logHolder.Logger;
+ logger.Info("Request App Shutdown");
+ CleanShutdown();
+ }
+ }
+
+ private void Application_SessionEnding(object sender, SessionEndingCancelEventArgs e)
+ {
+ Logger logger = logHolder.Logger;
+ logger.Info("User Session Ending");
+ CleanShutdown();
+ }
+
+ private void CleanShutdown()
+ {
+ if (runShutdown)
+ {
+ if (rootHub != null)
+ {
+ Task.Run(() =>
+ {
+ if (rootHub.running)
+ {
+ rootHub.Stop(immediateUnplug: true);
+ rootHub.ShutDown();
+ }
+ }).Wait();
+ }
+
+ if (!skipSave)
+ {
+ DS4Windows.Global.Save();
+ }
+
+ // Reset timer
+ DS4Windows.Util.timeEndPeriod(1);
+
+ exitComThread = true;
+ if (threadComEvent != null)
+ {
+ threadComEvent.Set(); // signal the other instance.
+ while (testThread.IsAlive)
+ Thread.SpinWait(500);
+ threadComEvent.Close();
+ }
+
+ if (ipcClassNameMMF != null) ipcClassNameMMF.Dispose();
+
+ LogManager.Flush();
+ LogManager.Shutdown();
+ }
+ }
+ }
+}
diff --git a/DS4Windows/ArgumentParser.cs b/DS4Windows/ArgumentParser.cs
new file mode 100644
index 0000000000..ab1f48729f
--- /dev/null
+++ b/DS4Windows/ArgumentParser.cs
@@ -0,0 +1,130 @@
+/*
+DS4Windows
+Copyright (C) 2023 Travis Nickles
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
+*/
+
+using System.Collections.Generic;
+using DS4Windows.DS4Control;
+
+namespace DS4WinWPF
+{
+ public class ArgumentParser
+ {
+ private bool mini;
+ private bool stop;
+ private bool driverinstall;
+ private bool reenableDevice;
+ private string deviceInstanceId;
+ private bool runtask;
+ private bool command;
+ private string commandArgs;
+ private string virtualkbmHandler = VirtualKBMFactory.DEFAULT_IDENTIFIER;
+
+ private Dictionary errors =
+ new Dictionary();
+
+ public bool Mini { get => mini; }
+ public bool Stop { get => stop; }
+ public bool Driverinstall { get => driverinstall; }
+ public bool ReenableDevice { get => reenableDevice; }
+ public bool Runtask { get => runtask; }
+ public bool Command { get => command; }
+ public string DeviceInstanceId { get => deviceInstanceId; }
+ public string CommandArgs { get => commandArgs; }
+ public string VirtualkbmHandler { get => virtualkbmHandler; }
+ public Dictionary Errors { get => errors; }
+
+ public bool HasErrors => errors.Count > 0;
+
+ public void Parse(string[] args)
+ {
+ errors.Clear();
+ //foreach (string arg in args)
+ for (int i = 0; i < args.Length; i++)
+ {
+ string arg = args[i];
+ switch(arg)
+ {
+ case "driverinstall":
+ case "-driverinstall":
+ driverinstall = true;
+ break;
+
+ case "re-enabledevice":
+ case "-re-enabledevice":
+ reenableDevice = true;
+ if (i + 1 < args.Length)
+ {
+ deviceInstanceId = args[++i];
+ }
+
+ break;
+
+ case "runtask":
+ case "-runtask":
+ runtask = true;
+ break;
+
+ case "-stop":
+ stop = true;
+ break;
+
+ case "-m":
+ mini = true;
+ break;
+
+ case "command":
+ case "-command":
+ command = true;
+ if (i + 1 < args.Length)
+ {
+ i++;
+ string temp = args[i];
+ if (temp.Length > 0 && temp.Length <= 256)
+ {
+ commandArgs = temp;
+ }
+ else
+ {
+ command = false;
+ errors["Command"] = "Command length is invalid";
+ }
+ }
+ else
+ {
+ errors["Command"] = "Command string not given";
+ }
+ break;
+ case "-virtualkbm":
+ if (i + 1 < args.Length)
+ {
+ i++;
+ string temp = args[i];
+ bool valid = VirtualKBMFactory.IsValidHandler(temp);
+ if (valid)
+ {
+ virtualkbmHandler = temp;
+ }
+ }
+
+ break;
+
+ default: break;
+ }
+ }
+ }
+ }
+}
diff --git a/DS4Windows/AutoProfileChecker.cs b/DS4Windows/AutoProfileChecker.cs
new file mode 100644
index 0000000000..59bb4341b6
--- /dev/null
+++ b/DS4Windows/AutoProfileChecker.cs
@@ -0,0 +1,339 @@
+/*
+DS4Windows
+Copyright (C) 2023 Travis Nickles
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
+*/
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+using System.Diagnostics; // StopWatch
+using System.Threading; // Sleep
+using System.Threading.Tasks;
+using DS4Windows;
+
+namespace DS4WinWPF
+{
+ [SuppressUnmanagedCodeSecurity]
+ public class AutoProfileChecker
+ {
+ private AutoProfileHolder profileHolder;
+ private IntPtr prevForegroundWnd = IntPtr.Zero;
+ private uint prevForegroundProcessID;
+ private string prevForegroundProcessName = string.Empty;
+ private string prevForegroundWndTitleName = string.Empty;
+ private StringBuilder autoProfileCheckTextBuilder = new StringBuilder(1000);
+ private int autoProfileDebugLogLevel = 0;
+ private bool turnOffTemp;
+ private AutoProfileEntity tempAutoProfile;
+ private bool running;
+
+ public int AutoProfileDebugLogLevel { get => autoProfileDebugLogLevel; set => autoProfileDebugLogLevel = value; }
+ public bool Running { get => running; set => running = value; }
+
+ public delegate void ChangeServiceHandler(AutoProfileChecker sender, bool state);
+ public event ChangeServiceHandler RequestServiceChange;
+
+ public AutoProfileChecker(AutoProfileHolder holder)
+ {
+ profileHolder = holder;
+ }
+
+ public void Process()
+ {
+ string topProcessName, topWindowTitle;
+ bool turnOffDS4WinApp = false;
+ AutoProfileEntity matchedProfileEntity = null;
+
+ if (GetTopWindowName(out topProcessName, out topWindowTitle))
+ {
+ // Find a profile match based on autoprofile program path and wnd title list.
+ // The same program may set different profiles for each of the controllers, so we need an array of newProfileName[controllerIdx] values.
+ for (int i = 0, pathsLen = profileHolder.AutoProfileColl.Count; i < pathsLen; i++)
+ {
+ AutoProfileEntity tempEntity = profileHolder.AutoProfileColl[i];
+ if (tempEntity.IsMatch(topProcessName, topWindowTitle))
+ {
+ if (autoProfileDebugLogLevel > 0)
+ DS4Windows.AppLogger.LogToGui($"DEBUG: Auto-Profile. Rule#{i + 1} Path={tempEntity.path} Title={tempEntity.title}", false, true);
+
+ // Matching autoprofile rule found
+ turnOffDS4WinApp = tempEntity.Turnoff;
+ matchedProfileEntity = tempEntity;
+ break;
+ }
+ }
+
+ if (matchedProfileEntity != null)
+ {
+ bool forceLoadProfile = false;
+
+ if (!turnOffDS4WinApp && turnOffTemp)
+ {
+ // DS4Win was temporarily turned off by another auto-profile rule. Turn DS4Win on before trying to load a new profile because otherwise the new profile won't do anything.
+ // Force load the profile when DS4Win service afer waking up DS4Win service to make sure that the new profile will be active.
+ turnOffTemp = false;
+ SetAndWaitServiceStatus(true);
+ forceLoadProfile = true;
+ }
+
+ // Program match found. Check if the new profile is different than current profile of the controller. Load the new profile only if it is not already loaded.
+ for (int j = 0; j < ControlService.CURRENT_DS4_CONTROLLER_LIMIT; j++)
+ {
+ string tempname = matchedProfileEntity.ProfileNames[j];
+ if (tempname != string.Empty && tempname != "(none)")
+ {
+ if ((Global.useTempProfile[j] && tempname != Global.tempprofilename[j]) ||
+ (!Global.useTempProfile[j] && tempname != Global.ProfilePath[j]) ||
+ forceLoadProfile)
+ {
+ if (autoProfileDebugLogLevel > 0)
+ DS4Windows.AppLogger.LogToGui($"DEBUG: Auto-Profile. LoadProfile Controller {j + 1}={tempname}", false, true);
+
+ if (Global.autoProfileSwitchNotifyChoice !=
+ AutoProfileDisplayProfileSwitchChoices.None)
+ {
+ DisplayProfileChange(j, tempname);
+ }
+
+ DS4Device device = Program.rootHub.DS4Controllers[j];
+ if (device != null)
+ {
+ // Wait for controller to be in a wait period
+ int tempInd = j;
+ device.HaltReportingRunAction(() =>
+ {
+ Global.LoadTempProfile(tempInd, tempname, true, Program.rootHub); // j is controller index, i is filename
+ // if (LaunchProgram[j] != string.Empty) Process.Start(LaunchProgram[j]);
+ });
+ }
+ else
+ {
+ Global.LoadTempProfile(j, tempname, true, Program.rootHub); // j is controller index, i is filename
+ // if (LaunchProgram[j] != string.Empty) Process.Start(LaunchProgram[j]);
+ }
+ }
+ else
+ {
+ if (autoProfileDebugLogLevel > 0)
+ DS4Windows.AppLogger.LogToGui($"DEBUG: Auto-Profile. LoadProfile Controller {j + 1}={tempname} (already loaded)", false, true);
+ }
+ }
+ }
+
+ if (turnOffDS4WinApp)
+ {
+ turnOffTemp = true;
+ if (App.rootHub.running)
+ {
+ if (autoProfileDebugLogLevel > 0)
+ DS4Windows.AppLogger.LogToGui($"DEBUG: Auto-Profile. Turning DS4Windows temporarily off", false, true);
+
+ SetAndWaitServiceStatus(false);
+ }
+ }
+
+ tempAutoProfile = matchedProfileEntity;
+ }
+ else if (tempAutoProfile != null)
+ {
+ if (turnOffTemp && DS4Windows.Global.AutoProfileRevertDefaultProfile)
+ {
+ turnOffTemp = false;
+ if (!App.rootHub.running)
+ {
+ if (autoProfileDebugLogLevel > 0)
+ DS4Windows.AppLogger.LogToGui($"DEBUG: Auto-Profile. Turning DS4Windows on before reverting to default profile", false, true);
+
+ SetAndWaitServiceStatus(true);
+ }
+ }
+
+ tempAutoProfile = null;
+ for (int j = 0; j < ControlService.CURRENT_DS4_CONTROLLER_LIMIT; j++)
+ {
+ if (Global.useTempProfile[j])
+ {
+ if (DS4Windows.Global.AutoProfileRevertDefaultProfile)
+ {
+ if (autoProfileDebugLogLevel > 0)
+ DS4Windows.AppLogger.LogToGui($"DEBUG: Auto-Profile. Unknown process. Reverting to default profile. Controller {j + 1}={Global.ProfilePath[j]} (default)", false, true);
+
+ if (Global.autoProfileSwitchNotifyChoice !=
+ AutoProfileDisplayProfileSwitchChoices.None)
+ {
+ DisplayProfileChange(j, "default");
+ }
+
+ DS4Device device = Program.rootHub.DS4Controllers[j];
+ if (device != null)
+ {
+ // Wait for controller to be in a wait period
+ int tempInd = j;
+ device.HaltReportingRunAction(() =>
+ {
+ Global.LoadProfile(tempInd, false, Program.rootHub);
+ });
+ }
+ else
+ {
+ Global.LoadProfile(j, false, Program.rootHub);
+ }
+ }
+ else
+ {
+ if (autoProfileDebugLogLevel > 0)
+ DS4Windows.AppLogger.LogToGui($"DEBUG: Auto-Profile. Unknown process. Existing profile left as active. Controller {j + 1}={Global.tempprofilename[j]}", false, true);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private bool GetTopWindowName(out string topProcessName, out string topWndTitleName)
+ {
+ IntPtr hWnd = GetForegroundWindow();
+ if (hWnd == IntPtr.Zero)
+ {
+ // Top window unknown or cannot acquire a handle. Return FALSE and return unknown process and wndTitle values
+ prevForegroundWnd = IntPtr.Zero;
+ prevForegroundProcessID = 0;
+ topProcessName = topWndTitleName = String.Empty;
+ return false;
+ }
+
+ //
+ // If this function was called from "auto-profile watcher timer" then check cached "previous hWnd handle". If the current hWnd is the same
+ // as during the previous check then return cached previous wnd and name values (ie. foreground app and window are assumed to be the same, so no need to re-query names).
+ // This should optimize the auto-profile timer check process and causes less burden to .NET GC collector because StringBuffer is not re-allocated every second.
+ //
+ // Note! hWnd handles may be re-cycled but not during the lifetime of the window. This "cache" optimization still works because when an old window is closed
+ // then foreground window changes to something else and the cached prevForgroundWnd variable is updated to store the new hWnd handle.
+ // It doesn't matter even when the previously cached handle is recycled by WinOS to represent some other window (it is no longer used as a cached value anyway).
+ //
+ if (hWnd == prevForegroundWnd)
+ {
+ // The active window is still the same. Return cached process and wndTitle values and FALSE to indicate caller that no changes since the last call of this method
+ topProcessName = prevForegroundProcessName;
+ topWndTitleName = prevForegroundWndTitleName;
+ return false;
+ }
+
+ prevForegroundWnd = hWnd;
+
+ IntPtr hProcess = IntPtr.Zero;
+ uint lpdwProcessId = 0;
+ GetWindowThreadProcessId(hWnd, out lpdwProcessId);
+
+ if (lpdwProcessId == prevForegroundProcessID)
+ {
+ topProcessName = prevForegroundProcessName;
+ }
+ else
+ {
+ prevForegroundProcessID = lpdwProcessId;
+
+ hProcess = OpenProcess(0x0410, false, lpdwProcessId);
+ if (hProcess != IntPtr.Zero) GetModuleFileNameEx(hProcess, IntPtr.Zero, autoProfileCheckTextBuilder, autoProfileCheckTextBuilder.Capacity);
+ else autoProfileCheckTextBuilder.Clear();
+
+ prevForegroundProcessName = topProcessName = autoProfileCheckTextBuilder.Replace('/', '\\').ToString().ToLower();
+ }
+
+ GetWindowText(hWnd, autoProfileCheckTextBuilder, autoProfileCheckTextBuilder.Capacity);
+ prevForegroundWndTitleName = topWndTitleName = autoProfileCheckTextBuilder.ToString().ToLower();
+
+
+ if (hProcess != IntPtr.Zero) CloseHandle(hProcess);
+
+ if (autoProfileDebugLogLevel > 0)
+ DS4Windows.AppLogger.LogToGui($"DEBUG: Auto-Profile. PID={lpdwProcessId} Path={topProcessName} | WND={hWnd} Title={topWndTitleName}", false, true);
+
+ return true;
+ }
+
+ private void SetAndWaitServiceStatus(bool serviceRunningStatus)
+ {
+ // Start or Stop the service only if it is not already in the requested state
+ if (App.rootHub.running != serviceRunningStatus)
+ {
+ RequestServiceChange?.Invoke(this, serviceRunningStatus);
+
+ // Wait until DS4Win app service is running or stopped (as requested by serviceRunningStatus value) or timeout.
+ // LoadProfile call fails if a new profile is loaded while DS4Win service is still in stopped state (ie the loaded temp profile doesn't do anything).
+ Stopwatch sw = new Stopwatch();
+ sw.Start();
+ while (App.rootHub.running != serviceRunningStatus && sw.Elapsed.TotalSeconds < 10)
+ {
+ Thread.SpinWait(1000);
+ }
+ Thread.SpinWait(1000);
+ }
+ }
+
+ private void DisplayProfileChange(int ind, string profile)
+ {
+ switch (Global.autoProfileSwitchNotifyChoice)
+ {
+ case AutoProfileDisplayProfileSwitchChoices.Log:
+ {
+ string prolog = string.Format(DS4WinWPF.Properties.Resources.UsingAutoTempProfile, (ind + 1).ToString(), profile);
+ DS4Windows.AppLogger.LogToGui(prolog, false);
+ }
+
+ break;
+ case AutoProfileDisplayProfileSwitchChoices.Notification:
+ {
+ string prolog = string.Format(DS4WinWPF.Properties.Resources.UsingAutoTempProfile, (ind + 1).ToString(), profile);
+ DS4Windows.AppLogger.LogToTray(prolog);
+ }
+
+ break;
+ case AutoProfileDisplayProfileSwitchChoices.LogAndNotification:
+ {
+ string prolog = string.Format(DS4WinWPF.Properties.Resources.UsingAutoTempProfile, (ind + 1).ToString(), profile);
+ DS4Windows.AppLogger.LogToGui(prolog, false);
+ DS4Windows.AppLogger.LogToTray(prolog);
+ }
+
+ break;
+ default:
+ break;
+ }
+ }
+
+ [DllImport("user32.dll")]
+ private static extern IntPtr GetForegroundWindow();
+
+ [DllImport("user32.dll")]
+ private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
+
+ [DllImport("kernel32.dll")]
+ private static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
+
+ [DllImport("kernel32.dll")]
+ private static extern bool CloseHandle(IntPtr handle);
+
+ [DllImport("psapi.dll")]
+ private static extern uint GetModuleFileNameEx(IntPtr hWnd, IntPtr hModule, StringBuilder lpFileName, int nSize);
+
+ [DllImport("user32.dll", CharSet = CharSet.Auto)]
+ private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nSize);
+ }
+}
diff --git a/DS4Windows/AutoProfileHolder.cs b/DS4Windows/AutoProfileHolder.cs
new file mode 100644
index 0000000000..ecd7f11759
--- /dev/null
+++ b/DS4Windows/AutoProfileHolder.cs
@@ -0,0 +1,212 @@
+/*
+DS4Windows
+Copyright (C) 2023 Travis Nickles
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
+*/
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Data;
+using System.Xml;
+using System.Xml.Serialization;
+using DS4Windows;
+using DS4WinWPF.DS4Control.DTOXml;
+
+namespace DS4WinWPF
+{
+ public class AutoProfileHolder
+ {
+ private object _colLockobj = new object();
+ private ObservableCollection autoProfileColl;
+ public ObservableCollection AutoProfileColl { get => autoProfileColl; }
+ //public Dictionary AutoProfileDict { get => autoProfileDict; }
+
+ //private Dictionary autoProfileDict;
+
+ public AutoProfileHolder()
+ {
+ autoProfileColl = new ObservableCollection();
+ //autoProfileDict = new Dictionary();
+ Load();
+
+ BindingOperations.EnableCollectionSynchronization(autoProfileColl, _colLockobj);
+ }
+
+ private void Load()
+ {
+ string configFile = Path.Combine(Global.appdatapath, "Auto Profiles.xml");
+ if (!File.Exists(configFile))
+ return;
+
+ XmlSerializer serializer = new XmlSerializer(typeof(AutoProfilesDTO));
+ using StreamReader sr = new StreamReader(configFile);
+ try
+ {
+ AutoProfilesDTO dto = serializer.Deserialize(sr) as AutoProfilesDTO;
+ dto.MapTo(this);
+ }
+ catch (InvalidOperationException) {}
+ catch (XmlException) {}
+ }
+
+ public bool Save(string m_Profile)
+ {
+ bool saved = true;
+
+ string output_path = m_Profile;
+ string testStr = string.Empty;
+ XmlSerializer serializer = new XmlSerializer(typeof(AutoProfilesDTO));
+ using (Utf8StringWriter strWriter = new Utf8StringWriter())
+ {
+ using XmlWriter xmlWriter = XmlWriter.Create(strWriter,
+ new XmlWriterSettings()
+ {
+ Encoding = Encoding.UTF8,
+ Indent = true,
+ });
+
+ // Write header explicitly
+ //xmlWriter.WriteStartDocument();
+ xmlWriter.WriteComment(string.Format(" Auto-Profile Configuration Data. {0} ", DateTime.Now));
+ xmlWriter.WriteWhitespace("\r\n");
+ xmlWriter.WriteWhitespace("\r\n");
+
+ // Write root element and children
+ AutoProfilesDTO dto = new AutoProfilesDTO();
+ dto.MapFrom(this);
+ // Omit xmlns:xsi and xmlns:xsd from output
+ serializer.Serialize(xmlWriter, dto,
+ new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));
+ xmlWriter.Flush();
+ xmlWriter.Close();
+
+ testStr = strWriter.ToString();
+ //Trace.WriteLine("TEST OUTPUT");
+ //Trace.WriteLine(testStr);
+ }
+
+ try
+ {
+ using (StreamWriter sw = new StreamWriter(output_path, false))
+ {
+ sw.Write(testStr);
+ }
+ }
+ catch (UnauthorizedAccessException)
+ {
+ saved = false;
+ }
+
+ return saved;
+ }
+
+ public void Remove(AutoProfileEntity item)
+ {
+ //autoProfileDict.Remove(item.Path);
+ autoProfileColl.Remove(item);
+ }
+ }
+
+ public class AutoProfileEntity
+ {
+ public string path = string.Empty;
+ public string title = string.Empty;
+ private string path_lowercase;
+ private string title_lowercase;
+ private bool turnoff;
+ private string[] profileNames = new string[DS4Windows.Global.MAX_DS4_CONTROLLER_COUNT] { string.Empty, string.Empty,
+ string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
+ public const string NONE_STRING = "(none)";
+
+ public string Path { get => path; set => SetSearchPath(value); }
+ public string Title { get => title; set => SetSearchTitle(value); }
+ public bool Turnoff { get => turnoff; set => turnoff = value; }
+ public string[] ProfileNames { get => profileNames; set => profileNames = value; }
+
+ public AutoProfileEntity(string pathStr, string titleStr)
+ {
+ // Initialize autoprofile search keywords(xxx_tolower).To improve performance the search keyword is pre - calculated in xxx_tolower variables,
+ // so autoprofile timer thread doesn't have to create substrings/replace/tolower string instances every second over and over again.
+ SetSearchPath(pathStr);
+ SetSearchTitle(titleStr);
+ }
+
+ public bool IsMatch(string searchPath, string searchTitle)
+ {
+ bool bPathMatched = true;
+ bool bTitleMwatched = true;
+
+ if (!string.IsNullOrEmpty(path_lowercase))
+ {
+ bPathMatched = (path_lowercase == searchPath
+ || (path[0] == '^' && searchPath.StartsWith(path_lowercase))
+ || (path[path.Length - 1] == '$' && searchPath.EndsWith(path_lowercase))
+ || (path[0] == '*' && searchPath.Contains(path_lowercase))
+ );
+ }
+
+ if (bPathMatched && !string.IsNullOrEmpty(title_lowercase))
+ {
+ bTitleMwatched = (title_lowercase == searchTitle
+ || (title[0] == '^' && searchTitle.StartsWith(title_lowercase))
+ || (title[title.Length - 1] == '$' && searchTitle.EndsWith(title_lowercase))
+ || (title[0] == '*' && searchTitle.Contains(title_lowercase))
+ );
+ }
+
+ // If both path and title defined in autoprofile entry then do AND condition (ie. both path and title should match)
+ return bPathMatched && bTitleMwatched;
+ }
+
+ private void SetSearchPath(string pathStr)
+ {
+ if (!string.IsNullOrEmpty(pathStr))
+ {
+ path = pathStr;
+ path_lowercase = path.ToLower().Replace('/', '\\');
+
+ if (path.Length >= 2)
+ {
+ if (path[0] == '^') path_lowercase = path_lowercase.Substring(1);
+ else if (path[path.Length - 1] == '$') path_lowercase = path_lowercase.Substring(0, path_lowercase.Length - 1);
+ else if (path[0] == '*') path_lowercase = path_lowercase.Substring(1);
+ }
+ }
+ else path = path_lowercase = string.Empty;
+ }
+
+ private void SetSearchTitle(string titleStr)
+ {
+ if (!string.IsNullOrEmpty(titleStr))
+ {
+ title = titleStr;
+ title_lowercase = title.ToLower();
+
+ if (title.Length >= 2)
+ {
+ if (title[0] == '^') title_lowercase = title_lowercase.Substring(1);
+ else if (title[title.Length - 1] == '$') title_lowercase = title_lowercase.Substring(0, title_lowercase.Length - 1);
+ else if (title[0] == '*') title_lowercase = title_lowercase.Substring(1);
+ }
+ }
+ else title = title_lowercase = string.Empty;
+ }
+ }
+}
diff --git a/DS4Windows/BezierCurveEditor/BezierCurve.cs b/DS4Windows/BezierCurveEditor/BezierCurve.cs
new file mode 100644
index 0000000000..efd65c21cb
--- /dev/null
+++ b/DS4Windows/BezierCurveEditor/BezierCurve.cs
@@ -0,0 +1,395 @@
+/* MIT License
+ *
+ * KeySpline - use bezier curve for transition easing function
+ * Copyright (c) 2012 Gaetan Renaudeau (GRE)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+/* KeySpline - use bezier curve for transition easing function is inspired from Firefox's nsSMILKeySpline.cpp */
+
+/*
+* This file contains the original bezier curve code (see comments above) and calculations ported as C# code. The original code was in JavaScript.
+*
+* This file has few customizations and optimizations for the needs of DS4Windows application (see https://github.com/Ryochan7/DS4Windows).
+* MIT License. Permission is hereby granted, free of charge, to any person to do whatever they want with this C# ported version of BezierCurve calculation code
+* as long this part of the code is open sourced and usage is in compliance with the above shown original license, also.
+*
+* Copyright (c) 2019, MIKA-N (https://github.com/mika-n).
+*
+* The original JavaScript version of bezier easing made by GRE (https://github.com/gre/bezier-easing).
+*
+* Usage:
+* BezierCurve.InitBezierCurve = Initialize bezier curve and output lookup table. Must be called at least once before calling GetBezierEasing method (or accessing lookup table directly) to re-map analog axis input.
+* BezierCurve.GetBezierEasing = Return re-mapped output value for an input axis value (or alternatively directly accessing the lookup table BezierCurve.arrayBezierLUT[inputVal] if even tiny CPU cycles matter)
+*
+*/
+using System;
+using System.Globalization;
+
+namespace DS4Windows
+{
+ public class BezierCurve
+ {
+ public enum AxisType { LSRS, L2R2, SA };
+
+ private static int kSplineTableSize = 11;
+ private static double kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
+ private double[] arraySampleValues;
+
+ // These values are established by empiricism with tests (tradeoff: performance VS precision) (comment by GRE)
+ private static int NEWTON_ITERATIONS = 4;
+ private static double NEWTON_MIN_SLOPE = 0.001;
+ private static double SUBDIVISION_PRECISION = 0.0000001;
+ private static int SUBDIVISION_MAX_ITERATIONS = 10;
+
+ private double mX1 = 0, mY1 = 0, mX2 = 0, mY2 = 0; // Bezier curve definition (0, 0, 0, 0 = Linear. 99, 99, 0, 0 = Pre-defined hard-coded EnhancedPrecision curve)
+
+ // Set or Get string representation of the bezier curve definition value (Note! Set doesn't initialize the lookup table. InitBezierCurve needs to be called to actually initalize the calculation)
+ public string AsString
+ {
+ get
+ {
+ //CultureInfo usDataFormatCulture = CultureInfo.CreateSpecificCulture("en-US");
+ return $"{mX1.ToString("G")}, {mY1.ToString("G")}, {mX2.ToString("G")}, {mY2.ToString("G")}";
+ }
+ set
+ {
+ // Set bezier curve defintion from a string value (4 comma separated decimals). If any of the string values are invalid then set curve as linear "zero" curve.
+ // Original assumption was values were in "en-US" data format (ie. period as decimal separator and comma as list separator).
+ // Attempt to not enforce that anymore. Do very basic parsing and rely on double.TryParse to handle confirming values are valid
+ var bezierMatch = System.Text.RegularExpressions.Regex.Match(value,
+ @"(.{3,9}),\s?(.{3,9}),\s?(.{3,9}),\s?(.{3,9})");
+ if (bezierMatch.Success)
+ {
+ //var bezierDef = value.Split(new Char[] { ',' }, 4);
+ //CultureInfo usDataFormatCulture = CultureInfo.CreateSpecificCulture("en-US");
+ if (bezierMatch.Groups.Count < 5 || !double.TryParse(bezierMatch.Groups[1].Value, out mX1) ||
+ !double.TryParse(bezierMatch.Groups[2].Value, out mY1) || !double.TryParse(bezierMatch.Groups[3].Value, out mX2) ||
+ !double.TryParse(bezierMatch.Groups[4].Value, out mY2))
+ mX1 = mY1 = mX2 = mY2 = 0;
+ }
+ }
+ }
+
+ // Custom definition set by DS4Windows options screens. This string is not validated (ie. the value is as user entered it and could be an invalid curve definition). This value is saved in a profile XML file.
+ public string CustomDefinition { get; set; }
+ public override string ToString() { return this.CustomDefinition; }
+
+ public AxisType axisType; // Axis type of curve object (LS/RS/R2/L2/SA)
+ private double axisMaxDouble; // Max range of axis (range of positive values)
+ private double axisCenterPosDouble; // Center pos of axis (LS/RS has 128 as "stick center", other axies has 0 as zero center point)
+
+ // Lookup result table is always either in 0..128 or 0..255 range depending on the DS4 analog axis range. LUT table set as public to let DS4Win reading thread to access it directly (every CPU cycle matters)
+ public byte[] arrayBezierLUT = null;
+
+ public BezierCurve()
+ {
+ CustomDefinition = "";
+ }
+
+ public bool InitBezierCurve(string bezierCurveDefinition, AxisType gamepadAxisType, bool setCustomDefinitionProperty = false)
+ {
+ if (setCustomDefinitionProperty)
+ this.CustomDefinition = bezierCurveDefinition;
+
+ this.AsString = bezierCurveDefinition;
+ return InitBezierCurve(mX1, mY1, mX2, mY2, gamepadAxisType);
+ }
+
+ public bool InitBezierCurve(double x1, double y1, double x2, double y2, AxisType gamepadAxisType)
+ {
+ bool bRetValue = true;
+
+ if (arrayBezierLUT == null)
+ arrayBezierLUT = new byte[256];
+
+ // Axis type and max range per axis
+ axisType = gamepadAxisType;
+ switch (gamepadAxisType)
+ {
+ case AxisType.LSRS:
+ axisMaxDouble = 127; // DS4 LS/RS axis has a "center position" at 128. Left turn has 0..127 positions and right turn 128..255 positions
+ axisCenterPosDouble = 128;
+ break;
+
+ case AxisType.L2R2:
+ axisMaxDouble = 255; // L2R2 analog trigger range 0..255
+ axisCenterPosDouble = 0;
+ break;
+
+ default:
+ axisMaxDouble = 128; // SixAxis x/z/y range 0..128
+ axisCenterPosDouble = 0;
+ break;
+ }
+
+ // If x1 = 99.0 then this is probably just a dummy bezier curve value
+ if (x1 == 99.0)
+ {
+ mX1 = 99.0;
+ mY1 = y1;
+ mX2 = x2;
+ mY2 = y2;
+
+ switch (y1)
+ {
+ case 91.0: return InitEnhancedPrecision_91();
+ case 92.0: return InitQuadric_92();
+ case 93.0: return InitCubic_93();
+ case 94.0: return InitEaseoutQuad_94();
+ case 95.0: return InitEaseoutCubic_95();
+ }
+ }
+
+ if (x1 < 0 || x1 > 1 || x2 < 0 || x2 > 1)
+ {
+ // throw new Exception("INVALID VALUE. BezierCurve X1 and X2 should be in [0, 1] range");
+ AppLogger.LogToGui($"WARNING. Invalid custom bezier curve \"{x1}, {y1}, {x2}, {y2}\" in {gamepadAxisType} axis. x1 and x2 should be in 0..1 range. Using linear curve.", true);
+ mX1 = mY1 = mX2 = mY2 = 0;
+ bRetValue = false;
+ }
+ else
+ {
+ mX1 = x1;
+ mY1 = y1;
+ mX2 = x2;
+ mY2 = y2;
+ }
+
+ // If this is linear definition then init the lookup table with 1-on-1 mapping
+ if (x1 == 0 && y1 == 0 && ((x2 == 0 && y2 == 0) || (x2 == 1 && y2 == 1)))
+ {
+ for (int idx = 0; idx <= 255; idx++)
+ arrayBezierLUT[idx] = (byte)idx;
+
+ return bRetValue;
+ }
+
+ try
+ {
+ arraySampleValues = new double[BezierCurve.kSplineTableSize];
+ for (int idx = 0; idx < BezierCurve.kSplineTableSize; idx++)
+ arraySampleValues[idx] = CalcBezier(idx * BezierCurve.kSampleStepSize, mX1, mX2);
+
+ // Pre-populate lookup result table for GetBezierEasing function (performance optimization)
+ for (byte idx = 0; idx <= (byte)axisMaxDouble; idx++)
+ {
+ arrayBezierLUT[idx + (byte)axisCenterPosDouble] = (byte)(Global.Clamp(0, Math.Round(CalcBezier(getTForX(idx / axisMaxDouble), mY1, mY2) * axisMaxDouble), axisMaxDouble) + axisCenterPosDouble);
+
+ // Invert curve from a right side of the center position (128) to the left tilted stick axis (or from up tilt to down tilt)
+ if (gamepadAxisType == AxisType.LSRS)
+ arrayBezierLUT[127 - idx] = (byte)(255 - arrayBezierLUT[idx + (byte)axisCenterPosDouble]);
+
+ // If the axisMaxDouble is 255 then we need this to break the look (byte is unsigned 0..255, so the FOR loop never reaches 256 idx value. C# would throw an overflow exceptio)
+ if (idx == axisMaxDouble) break;
+ }
+ }
+ finally
+ {
+ arraySampleValues = null;
+ }
+
+ return bRetValue;
+ }
+
+ // Initialize a special "hard-coded" and pre-defined EnhancedPrecision output curve as a lookup result table
+ private bool InitEnhancedPrecision_91()
+ {
+ double abs, output;
+
+ for (byte idx = 0; idx <= axisMaxDouble; idx++)
+ {
+ abs = idx / axisMaxDouble;
+ if (abs <= 0.4)
+ output = 0.55 * abs;
+ else if (abs <= 0.75)
+ output = abs - 0.18;
+ else //if (abs > 0.75)
+ output = (abs * 1.72) - 0.72;
+
+ arrayBezierLUT[idx + (byte)axisCenterPosDouble] = (byte)(output * axisMaxDouble + axisCenterPosDouble);
+
+ // Invert curve from a right side of the center position (128) to the left tilted stick axis (or from up tilt to down tilt)
+ if (this.axisType == AxisType.LSRS)
+ arrayBezierLUT[127 - idx] = (byte)(255 - arrayBezierLUT[idx + (byte)axisCenterPosDouble]);
+
+ // If the axisMaxDouble is 255 then we need this to break the look (byte is unsigned 0..255, so the FOR loop never reaches 256 idx value. C# would throw an overflow exceptio)
+ if (idx == axisMaxDouble) break;
+ }
+ return true;
+ }
+
+ private bool InitQuadric_92()
+ {
+ double temp;
+ for (byte idx = 0; idx <= axisMaxDouble; idx++)
+ {
+ temp = idx / axisMaxDouble;
+ arrayBezierLUT[idx + (byte)axisCenterPosDouble] = (byte)((temp * temp * axisMaxDouble) + axisCenterPosDouble);
+
+ // Invert curve from a right side of the center position (128) to the left tilted stick axis (or from up tilt to down tilt)
+ if (this.axisType == AxisType.LSRS)
+ arrayBezierLUT[127 - idx] = (byte)(255 - arrayBezierLUT[idx + (byte)axisCenterPosDouble]);
+
+ // If the axisMaxDouble is 255 then we need this to break the look (byte is unsigned 0..255, so the FOR loop never reaches 256 idx value. C# would throw an overflow exceptio)
+ if (idx == axisMaxDouble) break;
+ }
+ return true;
+ }
+
+ private bool InitCubic_93()
+ {
+ double temp;
+ for (byte idx = 0; idx <= axisMaxDouble; idx++)
+ {
+ temp = idx / axisMaxDouble;
+ arrayBezierLUT[idx + (byte)axisCenterPosDouble] = (byte)((temp * temp * temp * axisMaxDouble) + axisCenterPosDouble);
+
+ // Invert curve from a right side of the center position (128) to the left tilted stick axis (or from up tilt to down tilt)
+ if (this.axisType == AxisType.LSRS)
+ arrayBezierLUT[127 - idx] = (byte)(255 - arrayBezierLUT[idx + (byte)axisCenterPosDouble]);
+
+ // If the axisMaxDouble is 255 then we need this to break the look (byte is unsigned 0..255, so the FOR loop never reaches 256 idx value. C# would throw an overflow exceptio)
+ if (idx == axisMaxDouble) break;
+ }
+ return true;
+ }
+
+ private bool InitEaseoutQuad_94()
+ {
+ double abs, output;
+ for (byte idx = 0; idx <= axisMaxDouble; idx++)
+ {
+ abs = idx / axisMaxDouble;
+ output = abs * (abs - 2.0);
+ arrayBezierLUT[idx + (byte)axisCenterPosDouble] = (byte)((-1.0 * output * axisMaxDouble) + axisCenterPosDouble);
+
+ // Invert curve from a right side of the center position (128) to the left tilted stick axis (or from up tilt to down tilt)
+ if (this.axisType == AxisType.LSRS)
+ arrayBezierLUT[127 - idx] = (byte)(255 - arrayBezierLUT[idx + (byte)axisCenterPosDouble]);
+
+ // If the axisMaxDouble is 255 then we need this to break the look (byte is unsigned 0..255, so the FOR loop never reaches 256 idx value. C# would throw an overflow exceptio)
+ if (idx == axisMaxDouble) break;
+ }
+ return true;
+ }
+
+ private bool InitEaseoutCubic_95()
+ {
+ double inner, output;
+ for (byte idx = 0; idx <= axisMaxDouble; idx++)
+ {
+ inner = (idx / axisMaxDouble) - 1.0;
+ output = (inner * inner * inner) + 1.0;
+ arrayBezierLUT[idx + (byte)axisCenterPosDouble] = (byte)((1.0 * output * axisMaxDouble) + axisCenterPosDouble);
+
+ // Invert curve from a right side of the center position (128) to the left tilted stick axis (or from up tilt to down tilt)
+ if (this.axisType == AxisType.LSRS)
+ arrayBezierLUT[127 - idx] = (byte)(255 - arrayBezierLUT[idx + (byte)axisCenterPosDouble]);
+
+ // If the axisMaxDouble is 255 then we need this to break the look (byte is unsigned 0..255, so the FOR loop never reaches 256 idx value. C# would throw an overflow exceptio)
+ if (idx == axisMaxDouble) break;
+ }
+ return true;
+ }
+
+ public byte GetBezierEasing(byte inputXValue)
+ {
+ unchecked
+ {
+ return (arrayBezierLUT == null ? inputXValue : arrayBezierLUT[inputXValue]);
+ //return (byte)(Global.Clamp(0, Math.Round(CalcBezier(getTForX(inputXValue / 255), mY1, mY2) * 255), 255));
+ }
+ }
+
+ private double A(double aA1, double aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
+ private double B(double aA1, double aA2) { return 3.0 * aA2 - 6.0 * aA1; }
+ private double C(double aA1) { return 3.0 * aA1; }
+
+ private double CalcBezier(double aT, double aA1, double aA2)
+ {
+ return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
+ }
+
+ private double getTForX(double aX)
+ {
+ double intervalStart = 0.0;
+ int currentSample = 1;
+ int lastSample = kSplineTableSize - 1;
+
+ for (; currentSample != lastSample && arraySampleValues[currentSample] <= aX; ++currentSample)
+ {
+ intervalStart += kSampleStepSize;
+ }
+ --currentSample;
+
+ // Interpolate to provide an initial guess for t
+ double dist = (aX - arraySampleValues[currentSample]) / (arraySampleValues[currentSample + 1] - arraySampleValues[currentSample]);
+ double guessForT = intervalStart + dist * kSampleStepSize;
+
+ double initialSlope = getSlope(guessForT, mX1, mX2);
+ if (initialSlope >= NEWTON_MIN_SLOPE)
+ {
+ return newtonRaphsonIterate(aX, guessForT /*, mX1, mX2*/);
+ }
+ else if (initialSlope == 0.0)
+ {
+ return guessForT;
+ }
+ else
+ {
+ return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize /*, mX1, mX2*/);
+ }
+ }
+
+ // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
+ private double getSlope(double aT, double aA1, double aA2)
+ {
+ return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
+ }
+
+ private double newtonRaphsonIterate(double aX, double aGuessT /*, double mX1, double mX2*/)
+ {
+ for (int i = 0; i < BezierCurve.NEWTON_ITERATIONS; ++i)
+ {
+ double currentSlope = getSlope(aGuessT, mX1, mX2);
+ if (currentSlope == 0.0)
+ {
+ return aGuessT;
+ }
+ double currentX = CalcBezier(aGuessT, mX1, mX2) - aX;
+ aGuessT -= currentX / currentSlope;
+ }
+ return aGuessT;
+ }
+
+ private double binarySubdivide(double aX, double aA, double aB /*, double mX1, double mX2*/)
+ {
+ double currentX, currentT, i = 0;
+ do
+ {
+ currentT = aA + (aB - aA) / 2.0;
+ currentX = CalcBezier(currentT, mX1, mX2) - aX;
+ if (currentX > 0.0)
+ {
+ aB = currentT;
+ }
+ else
+ {
+ aA = currentT;
+ }
+ } while (Math.Abs(currentX) > BezierCurve.SUBDIVISION_PRECISION && ++i < BezierCurve.SUBDIVISION_MAX_ITERATIONS);
+
+ return currentT;
+ }
+
+ }
+}
diff --git a/DS4Windows/BezierCurveEditor/build.js b/DS4Windows/BezierCurveEditor/build.js
new file mode 100644
index 0000000000..278059de0a
--- /dev/null
+++ b/DS4Windows/BezierCurveEditor/build.js
@@ -0,0 +1,10114 @@
+! function e(t, n, r) {
+ function o(i, s) {
+ if (!n[i]) {
+ if (!t[i]) {
+ var u = "function" == typeof require && require;
+ if (!s && u) return u(i, !0);
+ if (a) return a(i, !0);
+ var c = new Error("Cannot find module '" + i + "'");
+ throw c.code = "MODULE_NOT_FOUND", c
+ }
+ var l = n[i] = {
+ exports: {}
+ };
+ t[i][0].call(l.exports, function(e) {
+ var n = t[i][1][e];
+ return o(n ? n : e)
+ }, l, l.exports, e, t, n, r)
+ }
+ return n[i].exports
+ }
+ for (var a = "function" == typeof require && require, i = 0; i < r.length; i++) o(r[i]);
+ return o
+}({
+ 1: [function(e) {
+ "use strict";
+ var t = function(e) {
+ return e && e.__esModule ? e["default"] : e
+ },
+ n = function() {
+ function e(e, t) {
+ for (var n in t) {
+ var r = t[n];
+ r.configurable = !0, r.value && (r.writable = !0)
+ }
+ Object.defineProperties(e, t)
+ }
+ return function(t, n, r) {
+ return n && e(t.prototype, n), r && e(t, r), t
+ }
+ }(),
+ r = function f(e, t, n) {
+ var r = Object.getOwnPropertyDescriptor(e, t);
+ if (void 0 === r) {
+ var o = Object.getPrototypeOf(e);
+ return null === o ? void 0 : f(o, t, n)
+ }
+ if ("value" in r && r.writable) return r.value;
+ var a = r.get;
+ return void 0 === a ? void 0 : a.call(n)
+ },
+ o = function(e, t) {
+ if ("function" != typeof t && null !== t) throw new TypeError("Super expression must either be null or a function, not " + typeof t);
+ e.prototype = Object.create(t && t.prototype, {
+ constructor: {
+ value: e,
+ enumerable: !1,
+ writable: !0,
+ configurable: !0
+ }
+ }), t && (e.__proto__ = t)
+ },
+ a = function(e, t) {
+ if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
+ },
+ i = t(e("react/addons")),
+ s = t(e("..")),
+ u = t(e("../package.json")),
+ c = t(e("raf"));
+ window.Perf = i.addons.Perf;
+ var l = {
+ color: "#0000c6",
+ textDecoration: "none"
+ },
+ p = {
+ display: "inline-block",
+ margin: "5px"
+ },
+ qryVariableValue = function(variableName)
+ {
+ var query = window.location.search.substring(1);
+ var vars = query.split("&");
+ for (var i=0;i o; ++o) {
+ var a = v(r, e, c);
+ if (0 === a) return r;
+ var i = h(r, e, c) - t;
+ r -= i / a
+ }
+ return r
+ }
+
+ function y() {
+ for (var t = 0; i > t; ++t) _[t] = h(t * s, e, c)
+ }
+
+ function g(t, n, r) {
+ var i, s, u = 0;
+ do s = n + (r - n) / 2, i = h(s, e, c) - t, i > 0 ? r = s : n = s; while (Math.abs(i) > o && ++u < a);
+ return s
+ }
+
+ function E(t) {
+ for (var n = 0, o = 1, a = i - 1; o != a && _[o] <= t; ++o) n += s;
+ --o;
+ var u = (t - _[o]) / (_[o + 1] - _[o]),
+ l = n + u * s,
+ p = v(l, e, c);
+ return p >= r ? m(t, l) : 0 === p ? l : g(t, n, n + s)
+ }
+
+ function C() {
+ N = !0, (e != t || c != l) && y()
+ }
+ if (4 !== arguments.length) throw new Error("BezierEasing requires 4 arguments.");
+ for (var b = 0; 4 > b; ++b)
+ if ("number" != typeof arguments[b] || isNaN(arguments[b]) || !isFinite(arguments[b])) throw new Error("BezierEasing arguments should be integers.");
+ if (0 > e || e > 1 || 0 > c || c > 1) throw new Error("BezierEasing x values must be in [0, 1] range.");
+ var _ = u ? new Float32Array(i) : new Array(i),
+ N = !1,
+ O = function(n) {
+ return N || C(), e === t && c === l ? n : 0 === n ? 0 : 1 === n ? 1 : h(E(n), t, l)
+ };
+ O.getControlPoints = function() {
+ return [{
+ x: e,
+ y: t
+ }, {
+ x: c,
+ y: l
+ }]
+ };
+ var R = [e, t, c, l],
+ D = "BezierEasing(" + R + ")";
+ O.toString = function() {
+ return D
+ };
+ var w = "cubic-bezier(" + R + ")";
+ return O.toCSS = function() {
+ return w
+ }, O
+ }
+ var t = this,
+ n = 4,
+ r = .001,
+ o = 1e-7,
+ a = 10,
+ i = 11,
+ s = 1 / (i - 1),
+ u = "Float32Array" in t;
+ return e.css = {
+ ease: e(.25, .1, .25, 1),
+ linear: e(0, 0, 1, 1),
+ "ease-in": e(.42, 0, 1, 1),
+ "ease-out": e(0, 0, .58, 1),
+ "ease-in-out": e(.42, 0, .58, 1)
+ }, e
+ })
+ }, {}],
+ 6: [function(e, t) {
+ "use strict";
+
+ function n(e) {
+ if (null == e) throw new TypeError("Object.assign cannot be called with null or undefined");
+ return Object(e)
+ }
+ t.exports = Object.assign || function(e) {
+ for (var t, r, o = n(e), a = 1; a < arguments.length; a++) {
+ t = arguments[a], r = Object.keys(Object(t));
+ for (var i = 0; i < r.length; i++) o[r[i]] = t[r[i]]
+ }
+ return o
+ }
+ }, {}],
+ 7: [function(e, t) {
+ t.exports = e("./lib/ReactWithAddons")
+ }, {
+ "./lib/ReactWithAddons": 107
+ }],
+ 8: [function(e, t) {
+ "use strict";
+ var n = e("./focusNode"),
+ r = {
+ componentDidMount: function() {
+ this.props.autoFocus && n(this.getDOMNode())
+ }
+ };
+ t.exports = r
+ }, {
+ "./focusNode": 141
+ }],
+ 9: [function(e, t) {
+ "use strict";
+
+ function n() {
+ var e = window.opera;
+ return "object" == typeof e && "function" == typeof e.version && parseInt(e.version(), 10) <= 12
+ }
+
+ function r(e) {
+ return (e.ctrlKey || e.altKey || e.metaKey) && !(e.ctrlKey && e.altKey)
+ }
+
+ function o(e) {
+ switch (e) {
+ case w.topCompositionStart:
+ return M.compositionStart;
+ case w.topCompositionEnd:
+ return M.compositionEnd;
+ case w.topCompositionUpdate:
+ return M.compositionUpdate
+ }
+ }
+
+ function a(e, t) {
+ return e === w.topKeyDown && t.keyCode === C
+ }
+
+ function i(e, t) {
+ switch (e) {
+ case w.topKeyUp:
+ return -1 !== E.indexOf(t.keyCode);
+ case w.topKeyDown:
+ return t.keyCode !== C;
+ case w.topKeyPress:
+ case w.topMouseDown:
+ case w.topBlur:
+ return !0;
+ default:
+ return !1
+ }
+ }
+
+ function s(e) {
+ var t = e.detail;
+ return "object" == typeof t && "data" in t ? t.data : null
+ }
+
+ function u(e, t, n, r) {
+ var u, c;
+ if (b ? u = o(e) : T ? i(e, r) && (u = M.compositionEnd) : a(e, r) && (u = M.compositionStart), !u) return null;
+ O && (T || u !== M.compositionStart ? u === M.compositionEnd && T && (c = T.getData()) : T = v.getPooled(t));
+ var l = m.getPooled(u, n, r);
+ if (c) l.data = c;
+ else {
+ var p = s(r);
+ null !== p && (l.data = p)
+ }
+ return f.accumulateTwoPhaseDispatches(l), l
+ }
+
+ function c(e, t) {
+ switch (e) {
+ case w.topCompositionEnd:
+ return s(t);
+ case w.topKeyPress:
+ var n = t.which;
+ return n !== R ? null : (x = !0, D);
+ case w.topTextInput:
+ var r = t.data;
+ return r === D && x ? null : r;
+ default:
+ return null
+ }
+ }
+
+ function l(e, t) {
+ if (T) {
+ if (e === w.topCompositionEnd || i(e, t)) {
+ var n = T.getData();
+ return v.release(T), T = null, n
+ }
+ return null
+ }
+ switch (e) {
+ case w.topPaste:
+ return null;
+ case w.topKeyPress:
+ return t.which && !r(t) ? String.fromCharCode(t.which) : null;
+ case w.topCompositionEnd:
+ return O ? null : t.data;
+ default:
+ return null
+ }
+ }
+
+ function p(e, t, n, r) {
+ var o;
+ if (o = N ? c(e, r) : l(e, r), !o) return null;
+ var a = y.getPooled(M.beforeInput, n, r);
+ return a.data = o, f.accumulateTwoPhaseDispatches(a), a
+ }
+ var d = e("./EventConstants"),
+ f = e("./EventPropagators"),
+ h = e("./ExecutionEnvironment"),
+ v = e("./FallbackCompositionState"),
+ m = e("./SyntheticCompositionEvent"),
+ y = e("./SyntheticInputEvent"),
+ g = e("./keyOf"),
+ E = [9, 13, 27, 32],
+ C = 229,
+ b = h.canUseDOM && "CompositionEvent" in window,
+ _ = null;
+ h.canUseDOM && "documentMode" in document && (_ = document.documentMode);
+ var N = h.canUseDOM && "TextEvent" in window && !_ && !n(),
+ O = h.canUseDOM && (!b || _ && _ > 8 && 11 >= _),
+ R = 32,
+ D = String.fromCharCode(R),
+ w = d.topLevelTypes,
+ M = {
+ beforeInput: {
+ phasedRegistrationNames: {
+ bubbled: g({
+ onBeforeInput: null
+ }),
+ captured: g({
+ onBeforeInputCapture: null
+ })
+ },
+ dependencies: [w.topCompositionEnd, w.topKeyPress, w.topTextInput, w.topPaste]
+ },
+ compositionEnd: {
+ phasedRegistrationNames: {
+ bubbled: g({
+ onCompositionEnd: null
+ }),
+ captured: g({
+ onCompositionEndCapture: null
+ })
+ },
+ dependencies: [w.topBlur, w.topCompositionEnd, w.topKeyDown, w.topKeyPress, w.topKeyUp, w.topMouseDown]
+ },
+ compositionStart: {
+ phasedRegistrationNames: {
+ bubbled: g({
+ onCompositionStart: null
+ }),
+ captured: g({
+ onCompositionStartCapture: null
+ })
+ },
+ dependencies: [w.topBlur, w.topCompositionStart, w.topKeyDown, w.topKeyPress, w.topKeyUp, w.topMouseDown]
+ },
+ compositionUpdate: {
+ phasedRegistrationNames: {
+ bubbled: g({
+ onCompositionUpdate: null
+ }),
+ captured: g({
+ onCompositionUpdateCapture: null
+ })
+ },
+ dependencies: [w.topBlur, w.topCompositionUpdate, w.topKeyDown, w.topKeyPress, w.topKeyUp, w.topMouseDown]
+ }
+ },
+ x = !1,
+ T = null,
+ P = {
+ eventTypes: M,
+ extractEvents: function(e, t, n, r) {
+ return [u(e, t, n, r), p(e, t, n, r)]
+ }
+ };
+ t.exports = P
+ }, {
+ "./EventConstants": 22,
+ "./EventPropagators": 27,
+ "./ExecutionEnvironment": 28,
+ "./FallbackCompositionState": 29,
+ "./SyntheticCompositionEvent": 113,
+ "./SyntheticInputEvent": 117,
+ "./keyOf": 164
+ }],
+ 10: [function(e, t) {
+ (function(n) {
+ var r = e("./invariant"),
+ o = {
+ addClass: function(e, t) {
+ return "production" !== n.env.NODE_ENV ? r(!/\s/.test(t), 'CSSCore.addClass takes only a single class name. "%s" contains multiple classes.', t) : r(!/\s/.test(t)), t && (e.classList ? e.classList.add(t) : o.hasClass(e, t) || (e.className = e.className + " " + t)), e
+ },
+ removeClass: function(e, t) {
+ return "production" !== n.env.NODE_ENV ? r(!/\s/.test(t), 'CSSCore.removeClass takes only a single class name. "%s" contains multiple classes.', t) : r(!/\s/.test(t)), t && (e.classList ? e.classList.remove(t) : o.hasClass(e, t) && (e.className = e.className.replace(new RegExp("(^|\\s)" + t + "(?:\\s|$)", "g"), "$1").replace(/\s+/g, " ").replace(/^\s*|\s*$/g, ""))), e
+ },
+ conditionClass: function(e, t, n) {
+ return (n ? o.addClass : o.removeClass)(e, t)
+ },
+ hasClass: function(e, t) {
+ return "production" !== n.env.NODE_ENV ? r(!/\s/.test(t), "CSS.hasClass takes only a single class name.") : r(!/\s/.test(t)), e.classList ? !!t && e.classList.contains(t) : (" " + e.className + " ").indexOf(" " + t + " ") > -1
+ }
+ };
+ t.exports = o
+ }).call(this, e("_process"))
+ }, {
+ "./invariant": 157,
+ _process: 2
+ }],
+ 11: [function(e, t) {
+ "use strict";
+
+ function n(e, t) {
+ return e + t.charAt(0).toUpperCase() + t.substring(1)
+ }
+ var r = {
+ boxFlex: !0,
+ boxFlexGroup: !0,
+ columnCount: !0,
+ flex: !0,
+ flexGrow: !0,
+ flexShrink: !0,
+ fontWeight: !0,
+ lineClamp: !0,
+ lineHeight: !0,
+ opacity: !0,
+ order: !0,
+ orphans: !0,
+ widows: !0,
+ zIndex: !0,
+ zoom: !0,
+ fillOpacity: !0,
+ strokeOpacity: !0
+ },
+ o = ["Webkit", "ms", "Moz", "O"];
+ Object.keys(r).forEach(function(e) {
+ o.forEach(function(t) {
+ r[n(t, e)] = r[e]
+ })
+ });
+ var a = {
+ background: {
+ backgroundImage: !0,
+ backgroundPosition: !0,
+ backgroundRepeat: !0,
+ backgroundColor: !0
+ },
+ border: {
+ borderWidth: !0,
+ borderStyle: !0,
+ borderColor: !0
+ },
+ borderBottom: {
+ borderBottomWidth: !0,
+ borderBottomStyle: !0,
+ borderBottomColor: !0
+ },
+ borderLeft: {
+ borderLeftWidth: !0,
+ borderLeftStyle: !0,
+ borderLeftColor: !0
+ },
+ borderRight: {
+ borderRightWidth: !0,
+ borderRightStyle: !0,
+ borderRightColor: !0
+ },
+ borderTop: {
+ borderTopWidth: !0,
+ borderTopStyle: !0,
+ borderTopColor: !0
+ },
+ font: {
+ fontStyle: !0,
+ fontVariant: !0,
+ fontWeight: !0,
+ fontSize: !0,
+ lineHeight: !0,
+ fontFamily: !0
+ }
+ },
+ i = {
+ isUnitlessNumber: r,
+ shorthandPropertyExpansions: a
+ };
+ t.exports = i
+ }, {}],
+ 12: [function(e, t) {
+ (function(n) {
+ "use strict";
+ var r = e("./CSSProperty"),
+ o = e("./ExecutionEnvironment"),
+ a = e("./camelizeStyleName"),
+ i = e("./dangerousStyleValue"),
+ s = e("./hyphenateStyleName"),
+ u = e("./memoizeStringOnly"),
+ c = e("./warning"),
+ l = u(function(e) {
+ return s(e)
+ }),
+ p = "cssFloat";
+ if (o.canUseDOM && void 0 === document.documentElement.style.cssFloat && (p = "styleFloat"), "production" !== n.env.NODE_ENV) var d = /^(?:webkit|moz|o)[A-Z]/,
+ f = /;\s*$/,
+ h = {},
+ v = {},
+ m = function(e) {
+ h.hasOwnProperty(e) && h[e] || (h[e] = !0, "production" !== n.env.NODE_ENV ? c(!1, "Unsupported style property %s. Did you mean %s?", e, a(e)) : null)
+ },
+ y = function(e) {
+ h.hasOwnProperty(e) && h[e] || (h[e] = !0, "production" !== n.env.NODE_ENV ? c(!1, "Unsupported vendor-prefixed style property %s. Did you mean %s?", e, e.charAt(0).toUpperCase() + e.slice(1)) : null)
+ },
+ g = function(e, t) {
+ v.hasOwnProperty(t) && v[t] || (v[t] = !0, "production" !== n.env.NODE_ENV ? c(!1, 'Style property values shouldn\'t contain a semicolon. Try "%s: %s" instead.', e, t.replace(f, "")) : null)
+ },
+ E = function(e, t) {
+ e.indexOf("-") > -1 ? m(e) : d.test(e) ? y(e) : f.test(t) && g(e, t)
+ };
+ var C = {
+ createMarkupForStyles: function(e) {
+ var t = "";
+ for (var r in e)
+ if (e.hasOwnProperty(r)) {
+ var o = e[r];
+ "production" !== n.env.NODE_ENV && E(r, o), null != o && (t += l(r) + ":", t += i(r, o) + ";")
+ } return t || null
+ },
+ setValueForStyles: function(e, t) {
+ var o = e.style;
+ for (var a in t)
+ if (t.hasOwnProperty(a)) {
+ "production" !== n.env.NODE_ENV && E(a, t[a]);
+ var s = i(a, t[a]);
+ if ("float" === a && (a = p), s) o[a] = s;
+ else {
+ var u = r.shorthandPropertyExpansions[a];
+ if (u)
+ for (var c in u) o[c] = "";
+ else o[a] = ""
+ }
+ }
+ }
+ };
+ t.exports = C
+ }).call(this, e("_process"))
+ }, {
+ "./CSSProperty": 11,
+ "./ExecutionEnvironment": 28,
+ "./camelizeStyleName": 128,
+ "./dangerousStyleValue": 135,
+ "./hyphenateStyleName": 155,
+ "./memoizeStringOnly": 166,
+ "./warning": 178,
+ _process: 2
+ }],
+ 13: [function(e, t) {
+ (function(n) {
+ "use strict";
+
+ function r() {
+ this._callbacks = null, this._contexts = null
+ }
+ var o = e("./PooledClass"),
+ a = e("./Object.assign"),
+ i = e("./invariant");
+ a(r.prototype, {
+ enqueue: function(e, t) {
+ this._callbacks = this._callbacks || [], this._contexts = this._contexts || [], this._callbacks.push(e), this._contexts.push(t)
+ },
+ notifyAll: function() {
+ var e = this._callbacks,
+ t = this._contexts;
+ if (e) {
+ "production" !== n.env.NODE_ENV ? i(e.length === t.length, "Mismatched list of contexts in callback queue") : i(e.length === t.length), this._callbacks = null, this._contexts = null;
+ for (var r = 0, o = e.length; o > r; r++) e[r].call(t[r]);
+ e.length = 0, t.length = 0
+ }
+ },
+ reset: function() {
+ this._callbacks = null, this._contexts = null
+ },
+ destructor: function() {
+ this.reset()
+ }
+ }), o.addPoolingTo(r), t.exports = r
+ }).call(this, e("_process"))
+ }, {
+ "./Object.assign": 35,
+ "./PooledClass": 36,
+ "./invariant": 157,
+ _process: 2
+ }],
+ 14: [function(e, t) {
+ "use strict";
+
+ function n(e) {
+ return "SELECT" === e.nodeName || "INPUT" === e.nodeName && "file" === e.type
+ }
+
+ function r(e) {
+ var t = _.getPooled(w.change, x, e);
+ E.accumulateTwoPhaseDispatches(t), b.batchedUpdates(o, t)
+ }
+
+ function o(e) {
+ g.enqueueEvents(e), g.processEventQueue()
+ }
+
+ function a(e, t) {
+ M = e, x = t, M.attachEvent("onchange", r)
+ }
+
+ function i() {
+ M && (M.detachEvent("onchange", r), M = null, x = null)
+ }
+
+ function s(e, t, n) {
+ return e === D.topChange ? n : void 0
+ }
+
+ function u(e, t, n) {
+ e === D.topFocus ? (i(), a(t, n)) : e === D.topBlur && i()
+ }
+
+ function c(e, t) {
+ M = e, x = t, T = e.value, P = Object.getOwnPropertyDescriptor(e.constructor.prototype, "value"), Object.defineProperty(M, "value", k), M.attachEvent("onpropertychange", p)
+ }
+
+ function l() {
+ M && (delete M.value, M.detachEvent("onpropertychange", p), M = null, x = null, T = null, P = null)
+ }
+
+ function p(e) {
+ if ("value" === e.propertyName) {
+ var t = e.srcElement.value;
+ t !== T && (T = t, r(e))
+ }
+ }
+
+ function d(e, t, n) {
+ return e === D.topInput ? n : void 0
+ }
+
+ function f(e, t, n) {
+ e === D.topFocus ? (l(), c(t, n)) : e === D.topBlur && l()
+ }
+
+ function h(e) {
+ return e !== D.topSelectionChange && e !== D.topKeyUp && e !== D.topKeyDown || !M || M.value === T ? void 0 : (T = M.value, x)
+ }
+
+ function v(e) {
+ return "INPUT" === e.nodeName && ("checkbox" === e.type || "radio" === e.type)
+ }
+
+ function m(e, t, n) {
+ return e === D.topClick ? n : void 0
+ }
+ var y = e("./EventConstants"),
+ g = e("./EventPluginHub"),
+ E = e("./EventPropagators"),
+ C = e("./ExecutionEnvironment"),
+ b = e("./ReactUpdates"),
+ _ = e("./SyntheticEvent"),
+ N = e("./isEventSupported"),
+ O = e("./isTextInputElement"),
+ R = e("./keyOf"),
+ D = y.topLevelTypes,
+ w = {
+ change: {
+ phasedRegistrationNames: {
+ bubbled: R({
+ onChange: null
+ }),
+ captured: R({
+ onChangeCapture: null
+ })
+ },
+ dependencies: [D.topBlur, D.topChange, D.topClick, D.topFocus, D.topInput, D.topKeyDown, D.topKeyUp, D.topSelectionChange]
+ }
+ },
+ M = null,
+ x = null,
+ T = null,
+ P = null,
+ I = !1;
+ C.canUseDOM && (I = N("change") && (!("documentMode" in document) || document.documentMode > 8));
+ var S = !1;
+ C.canUseDOM && (S = N("input") && (!("documentMode" in document) || document.documentMode > 9));
+ var k = {
+ get: function() {
+ return P.get.call(this)
+ },
+ set: function(e) {
+ T = "" + e, P.set.call(this, e)
+ }
+ },
+ A = {
+ eventTypes: w,
+ extractEvents: function(e, t, r, o) {
+ var a, i;
+ if (n(t) ? I ? a = s : i = u : O(t) ? S ? a = d : (a = h, i = f) : v(t) && (a = m), a) {
+ var c = a(e, t, r);
+ if (c) {
+ var l = _.getPooled(w.change, c, o);
+ return E.accumulateTwoPhaseDispatches(l), l
+ }
+ }
+ i && i(e, t, r)
+ }
+ };
+ t.exports = A
+ }, {
+ "./EventConstants": 22,
+ "./EventPluginHub": 24,
+ "./EventPropagators": 27,
+ "./ExecutionEnvironment": 28,
+ "./ReactUpdates": 106,
+ "./SyntheticEvent": 115,
+ "./isEventSupported": 158,
+ "./isTextInputElement": 160,
+ "./keyOf": 164
+ }],
+ 15: [function(e, t) {
+ "use strict";
+ var n = 0,
+ r = {
+ createReactRootIndex: function() {
+ return n++
+ }
+ };
+ t.exports = r
+ }, {}],
+ 16: [function(e, t) {
+ (function(n) {
+ "use strict";
+
+ function r(e, t, n) {
+ e.insertBefore(t, e.childNodes[n] || null)
+ }
+ var o = e("./Danger"),
+ a = e("./ReactMultiChildUpdateTypes"),
+ i = e("./setTextContent"),
+ s = e("./invariant"),
+ u = {
+ dangerouslyReplaceNodeWithMarkup: o.dangerouslyReplaceNodeWithMarkup,
+ updateTextContent: i,
+ processUpdates: function(e, t) {
+ for (var u, c = null, l = null, p = 0; p < e.length; p++)
+ if (u = e[p], u.type === a.MOVE_EXISTING || u.type === a.REMOVE_NODE) {
+ var d = u.fromIndex,
+ f = u.parentNode.childNodes[d],
+ h = u.parentID;
+ "production" !== n.env.NODE_ENV ? s(f, "processUpdates(): Unable to find child %s of element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a when using tables, nesting tags like