Compare commits

...

160 commits
v4.3 ... master

Author SHA1 Message Date
Dmitry Isaenko
6d243a2be1 Close #171. BlytheScythe contribution 2025-01-26 23:05:24 +03:00
Dmitry Isaenko
ff31494f50 Switch to Woodpecker CI 2024-11-21 01:42:57 +03:00
Dmitry Isaenko
e3c22390a9 Correct text 2024-10-31 00:45:51 +03:00
Dmitry Isaenko
0ca162be1e increment version 2024-10-06 16:32:38 +03:00
Dmitry Isaenko
6cac53df7c remove no longer valid info 2024-10-06 16:10:06 +03:00
Dmitry Isaenko
17134e235c
Merge pull request #168 from DDinghoya/patch-8
Update locale_ko_KR.properties
2024-09-28 18:50:34 +03:00
DDinghoya
2ef3ccd442
Update locale_ko_KR.properties 2024-09-28 23:46:44 +09:00
Dmitry Isaenko
fd8bad836c
Merge pull request #166 from exiori/master
update Simplified Chinese
2024-09-28 17:33:11 +03:00
exiori
0b3ac95130
Sync locale.properties and Update 2024-09-02 10:35:55 +08:00
exiori
0429b4dc45
Update locale_zh_CN.properties 2024-09-02 10:22:08 +08:00
exiori
7bf48c6e51
Update locale_zh_CN.properties 2024-09-02 10:18:11 +08:00
Dmitry Isaenko
d382181700 Update architecture. Change mediator, add simple observer to track active 'transfers' 2024-05-27 19:15:04 +03:00
Dmitry Isaenko
5ee9f6aacd
Merge pull request #160 from secretjupiter/patch-1
Added mandatory info to README.md for Apple Silicon users
2024-02-07 13:07:53 +03:00
Dmitry Isaenko
7f9b3a7598
Merge pull request #161 from Erimsaholut/master
Turkish Lang file
2024-02-07 13:07:24 +03:00
01ut
cd9e3ddf30
Turkish Lang file
I just upload the .properties file
2024-02-03 16:05:11 +03:00
Kevin | Secret Jupiter
d1ac1f5403
Added mandatory info to README.md for Apple Silicon users
Added mandatory info for Apple Silicon users
2024-01-28 22:00:45 +01:00
Dmitry Isaenko
e9b0fa309e Merge remote-tracking branch 'origin/master' 2023-12-26 14:39:31 +03:00
Dmitry Isaenko
c0bf247666 Bundle drivers to windows installer #156 2023-12-26 14:39:05 +03:00
Dmitry Isaenko
66758ffdb9
Merge pull request #154 from justindhillon/broken-links
Fix Broken Links
2023-11-15 18:01:36 +03:00
Justin Dhillon
b32986682e revert maven.apache.org link 2023-11-11 12:49:17 -08:00
Justin Dhillon
2935d4ef55 revert broken link 2023-11-11 12:48:21 -08:00
Justin Dhillon
353b058388 revert Swarsele 2023-11-08 09:13:44 -08:00
Justin Dhillon
5b3ea13b08 revert Stephane Meden (JackFromNice) 2023-11-08 09:12:22 -08:00
Justin Dhillon
1251d39a6b revert Adubbz/Tinfoil 2023-11-08 09:11:36 -08:00
Justin Dhillon
57e7f72531
Merge branch 'developersu:master' into broken-links 2023-11-08 09:08:38 -08:00
Dmitry Isaenko
88ca0815ed Properly disable integration tests 2023-11-08 15:08:24 +03:00
Dmitry Isaenko
66e7338fa5 Save few integration tests 2023-11-08 14:35:15 +03:00
Dmitry Isaenko
fa236cb1ad Correct Goldleaf supported versions list 2023-11-08 14:34:00 +03:00
Justin Dhillon
5b120204ef fixed broken link 2023-11-07 10:10:24 -08:00
Justin Dhillon
94ad332bf7 fixed broken link to maven.apache.org/POM/4.0.0 2023-11-07 10:05:17 -08:00
Justin Dhillon
b89bfa806d fixed broken link to github user developersu 2023-11-07 09:59:17 -08:00
Justin Dhillon
abf7621f28 github account does not exist anymore, so I replaced the link with instagram 2023-11-07 09:57:50 -08:00
Justin Dhillon
c5688f79df replaced missing github repo link with link to creator 2023-11-07 09:56:31 -08:00
Justin Dhillon
25910ac94c fixed broken website link 2023-11-07 09:55:05 -08:00
Justin Dhillon
474f90a427 replaced 404 github link to twitter profile 2023-11-07 09:52:55 -08:00
Dmitry Isaenko
8348c9f2ab Correct 'Font settings' window size. 2023-10-30 00:09:27 +03:00
Dmitry Isaenko
47045b2aeb correct version 2023-10-29 06:29:33 +03:00
Dmitry Isaenko
67351642ae Merge remote-tracking branch 'origin/master' 2023-10-29 06:16:10 +03:00
Dmitry Isaenko
3909371774 Add fonts selector for #153 2023-10-29 06:15:43 +03:00
Dmitry Isaenko
1e4593afb6
Merge pull request #145 from DDinghoya/patch-7
Update locale_ko_KR.properties
2023-06-02 15:54:55 +03:00
DDinghoya
d3faa384ae
Update locale_ko_KR.properties 2023-05-30 23:32:29 +09:00
Dmitry Isaenko
9d4cac26e5
Merge pull request #144 from requinDr/patch-1
Update locale_fr_FR.properties
2023-05-17 16:32:32 +03:00
requinDr
ad211cd562
\N -> \n 2023-05-17 00:16:11 +02:00
requinDr
4bdc5ffb63
Update locale_fr_FR.properties
Add missings translations and missing accents to French (note that a few translations are still missing)
2023-05-17 00:14:00 +02:00
Dmitry Isaenko
7db7af0cf8
Merge pull request #140 from exiori/patch-1
Update locale_zh_CN.properties
2023-04-15 14:24:13 +03:00
exiori
6052d385d9
Update locale_zh_CN.properties 2023-04-15 17:00:46 +08:00
exiori
f6b875af0b
Update locale_zh_CN.properties
Update Dialog Tips
2023-04-05 10:58:17 +08:00
Dmitry Isaenko
01a25f071a Make CI output a bit more verbose 2023-03-17 04:27:09 +03:00
Dmitry Isaenko
c1651e874b Correct AppPreferences class. Fix #139 2023-03-17 04:00:48 +03:00
Dmitry Isaenko
94845c1411 readme update 2023-03-09 04:12:28 +03:00
Dmitry Isaenko
7cf3970aa7 Fix CI 2023-02-10 21:23:22 +03:00
Dmitry Isaenko
5b69435e89 Setup builds for M1 2023-02-10 21:09:26 +03:00
Dmitry Isaenko
b463a63180 Fix 'class file version' mismatch. Aligned to Java11 2023-02-10 03:15:58 +03:00
Dmitry Isaenko
cbb9fd60b9 Correct CSS 2023-02-09 18:16:10 +03:00
Dmitry Isaenko
5f0278fc7b Fix pom.xml 2023-02-09 17:22:22 +03:00
Dmitry Isaenko
3981d0d8ca Merge remote-tracking branch 'origin/master' 2023-02-09 15:26:32 +03:00
Dmitry Isaenko
29f29b7d31 Minor fixes 2023-02-09 15:25:13 +03:00
Dmitry Isaenko
38f495ebc1 Correct pom.xml 2023-02-08 17:43:38 +03:00
Dmitry Isaenko
4d7c6f6ef1 Merge remote-tracking branch 'origin/master' 2023-02-08 02:31:05 +03:00
Dmitry Isaenko
7f01805cd5 Fix CI+3: Append timestamps to installer artifact 2023-02-08 02:21:55 +03:00
Dmitry Isaenko
f82275e82d Fix CI+2 2023-02-08 01:58:27 +03:00
Dmitry Isaenko
2356bfe0e9 Fix CI+1 2023-02-08 01:50:27 +03:00
Dmitry Isaenko
fc02a8af6b Fix CI 2023-02-08 01:32:45 +03:00
Dmitry Isaenko
c408f70b79 Switch to Java 11. Add win installer 2023-02-08 01:15:30 +03:00
Dmitry Isaenko
c39a5f4c5b Correct Java 8 related things 2023-02-07 00:05:13 +03:00
Dmitry Isaenko
ffa9c6903f https for secure! 2023-02-06 16:21:11 +03:00
Dmitry Isaenko
c34531a92f Fix dependencies resolution 2023-02-06 16:16:03 +03:00
Dmitry Isaenko
83695511d3 Hide 'extended network settings' instead of setting it disabled 2023-02-06 02:00:05 +03:00
Dmitry Isaenko
c84f70ec10 "Installs Split NSP/XCI/NSZ/XCZ over Lan or USB", not only NSP. Also breaking every locale 2023-02-04 17:05:57 +03:00
Dmitry Isaenko
6c51b8e1b6 Corrections at front and back end 2023-02-04 15:25:34 +03:00
Dmitry Isaenko
f8b60af41b FS drafts 2023-02-01 12:44:45 +03:00
Dmitry Isaenko
4ccf833aa5 Fix issue where version was not showing in CLI mode; clear locale_en_US since it's just placeholder 2022-12-26 07:59:56 +03:00
Dmitry Isaenko
a60d929dcd Update readme 2022-12-23 21:53:34 +03:00
Dmitry Isaenko
338bb699d1 Another one build-system-related fix 2022-12-23 07:47:10 +03:00
Dmitry Isaenko
115625e3a3 Correct drone config to archive Launch4j artifact 2022-12-23 07:22:24 +03:00
Dmitry Isaenko
55df39923f Correct readme, update few icons, add freedesktop entry and svg icon. Could be useful for packagers. 2022-12-23 07:08:22 +03:00
Dmitry Isaenko
8b23b8967b Correct locales logic to get some kind of ISO 639-3 support, update pom, make ja_ryu appear (unfortunately as 'Japanese' language and not as 'Central Okinawan') 2022-10-11 17:04:55 +03:00
Dmitry Isaenko
9aa4551ef0
Merge pull request #130 from kuragehimekurara1/master
Added Japanese translation and Ryukyuan language translation
2022-10-11 15:17:12 +03:00
kuragehime
610d04c9bd
Update locale_ja_ryu.properties 2022-10-08 03:24:08 +09:00
kuragehime
9b02750dd3
Update locale_ja_ryu.properties 2022-10-08 03:10:04 +09:00
kuragehime
89dd6fdbe0
Update locale_ja_JP.properties 2022-10-08 02:53:51 +09:00
kuragehime
b75421bc9e
Update locale_ja_ryu.properties 2022-10-08 01:35:32 +09:00
kuragehime
cc09128373
Update locale_ja_JP.properties 2022-10-08 01:02:16 +09:00
kuragehime
6244fd974a
Update locale_ja_JP.properties 2022-10-07 01:35:21 +09:00
kuragehime
2edea43d63
Create locale_ja_ryu.properties 2022-10-06 17:13:01 +09:00
kuragehime
c9dbb37c14
Create locale_ja_JP.properties 2022-10-06 17:06:49 +09:00
Dmitry Isaenko
51a3b1e7a1 Update pom 2022-09-25 00:28:58 +03:00
Dmitry Isaenko
182c5293b5 Add Swedish translation kindly prepared by @yeager 2022-08-22 20:26:10 +03:00
Dmitry Isaenko
38af160ae7 small readme adjustments 2022-08-13 17:07:17 +03:00
Dmitry Isaenko
edc27d6db0
Merge pull request #126 from DDinghoya/patch-6
Update locale_ko_KR.properties
2022-08-05 22:06:08 +03:00
DDinghoya
d08993be17
Update locale_ko_KR.properties 2022-08-05 22:36:58 +09:00
Dmitry Isaenko
bc2cf44a97 Update build hacks 2022-08-02 21:46:36 +03:00
Dmitry Isaenko
eefaa70f95 fix yaml 2022-07-26 20:16:01 +03:00
Dmitry Isaenko
5ed2167e9d Add Goldleaf v0.10 support. Remove jenkins malware, add Drone, update readme, increment version. Shifting code to the safer place. Update dependencies.
Fix #94: Just doing as @Fatih120 said
Fix #124: Implement updated Spanish translation by @Uzi-Oni
2022-07-26 18:25:26 +03:00
Dmitry Isaenko
0b8092077a Remove paypal and liberapay out of the 'donations' section. I don't know if I can tell names of the people who decided to support this project by donations, but anyway: Dear ap*** R** and Ku**** A********, I highly appreciate your participation and want to assure you that all funding this project received will go to one of the local charity funds. Thank you both! 2022-03-15 03:01:51 +03:00
Dmitry Isaenko
5f03939b91 Update README.md 2022-03-01 16:06:55 +03:00
Dmitry Isaenko
503edcd127
Merge pull request #110 from DDinghoya/patch-5
Update locale_ko_KR.properties
2021-11-15 17:41:23 +03:00
DDinghoya
ac3c0a3698
Update locale_ko_KR.properties 2021-11-13 10:11:32 +09:00
Dmitry Isaenko
0fab994a45
Merge pull request #106 from exiori/master
Create locale_zh_CN.properties
2021-09-23 05:14:30 +03:00
exiori
5b67821d3b
Create locale_zh_CN.properties
Update  a line
2021-09-22 10:03:30 +08:00
Dmitry Isaenko
8547eb0e4e Polish README.md 2021-09-21 01:42:13 +03:00
Dmitry Isaenko
a6f95f32bb
Merge pull request #105 from qazrfv1234/qazrfv1234-patch-1
Update locale_zh_TW.properties
2021-09-21 01:16:34 +03:00
qazrfv1234
eb72fd17b6
Update locale_zh_TW.properties 2021-09-16 21:46:44 +08:00
Dmitry Isaenko
f0714ef961 And I forgot to update screenshot. Here. 2021-09-16 01:00:05 +03:00
Dmitry Isaenko
9301f4da8e update README 2021-09-16 00:54:42 +03:00
Dmitry Isaenko
2ee0362980 Move to OpenJFX 17 2021-09-16 00:51:02 +03:00
Dmitry Isaenko
ff77c117ad Add libusb4java.dylib that @agungrbudiman gave me. 2021-09-05 02:57:08 +03:00
Dmitry Isaenko
325b7fa32a
Merge pull request #104 from exiori/master
update chinsee translation
2021-08-28 15:16:35 +03:00
exiori
3fde307ea1
Update chinese translation 2021-08-28 11:27:45 +08:00
exiori
c5e8dc67ad
Update chinese translation 2021-08-28 11:24:50 +08:00
exiori
66f4c22417
Update Chinese(Traditional)by FFT9 2021-08-28 11:18:08 +08:00
exiori
b5a6972671
Update Chinese (Simplified) by FFT9 2021-08-28 09:25:10 +08:00
exiori
7d8b32dc7c
Add and Update simChinese list by FFT9 2021-08-28 09:22:02 +08:00
Dmitry Isaenko
8af1aa485e Fix #102 2021-08-27 18:35:53 +03:00
Dmitry Isaenko
747a745bbd Update screenshots, small UI corrections. 2021-08-26 16:16:04 +03:00
Dmitry Isaenko
3f2e986aed Validated using newest GoldLeaf v0.9 and works fine. Updated text, application preferences record, fxml, readme. 2021-08-25 07:03:17 +03:00
Dmitry Isaenko
825af65ff2
Merge pull request #101 from unbranched/patch-2
Italian translation update
2021-08-25 03:30:28 +03:00
unbranched
892e919d18
Italian translation update 2021-08-21 11:03:05 +00:00
Dmitry Isaenko
b02bc7ed2d Using idea from #90: Replace 'Tinfoil' by 'Awoo' everywhere on the front end. Also touched translation files (hope didn't broke it, but could be)
Add 'Fusee Geelee' and 'RCM' labels used on 'RCM' tab to 'properties' files in case someone wants to translate it.. I don't think if someone should but there is an option.
(note: CLI arguments remains the same while only description updated)
2021-08-10 17:00:33 +03:00
Dmitry Isaenko
86c867ab2c
Merge pull request #98 from calini/master
Add Romanian translation
2021-08-09 22:53:06 +03:00
Dmitry Isaenko
2a3bdd949f Solve - #44: move to JFX 16 2021-08-09 22:50:44 +03:00
Dmitry Isaenko
1176ad9e83 Solve - #87. Break LogPrinterGui 2021-08-09 22:47:52 +03:00
Calin Ilie
ba1ba20d43
Convert Romanian translation to Java entities 2021-07-28 23:00:24 +01:00
Calin Ilie
62de68ba89
Add Romanian translation 2021-07-28 22:51:14 +01:00
Dmitry Isaenko
79c519b1f3 Hotfix for 'open recent tab' feature: if non-functional tab selected then 'Games' (default) tab would be opened. 2021-01-11 00:44:37 +03:00
Dmitry Isaenko
4d92e536ae Always open tab which had been opened before application was closed last time. 2021-01-11 00:30:46 +03:00
Dmitry Isaenko
d231a39e0c Merge remote-tracking branch 'origin/master' 2020-12-14 22:10:44 +03:00
Dmitry Isaenko
d759bf01de Update settings screenshot 2020-12-14 22:10:17 +03:00
Dmitry Isaenko
3f04ce97f9
Merge pull request #86 from DDinghoya/patch-4
Update locale_ko_KR.properties
2020-12-13 21:35:32 +03:00
DDinghoya
48cdd4f830
Update locale_ko_KR.properties 2020-12-13 20:12:28 +09:00
Dmitry Isaenko
f5b0c1549f Remove empty lines in Arabic translation 2020-12-10 01:29:16 +03:00
Dmitry Isaenko
da623518d1 UI fixes and enhancements 2020-12-10 00:32:25 +03:00
Dmitry Isaenko
d8ea426fa4 Update scan-folder-to-add-files function: set pop-up window with indicator showing how many files did we scan and how many files would be added.
Minor color corrections on light theme for whoever use it
Fix TF progress-bar (can't recall when I broke it..)
2020-12-10 00:07:44 +03:00
Dmitry Isaenko
619a2b157e Remove select-folders button, add settings option
Hide 'Select split-files' button when 'Search-for-roms' option enabled in options
Add settings option for this
Update l10n
Update icons, correct css.
2020-11-29 17:19:57 +03:00
Dmitry Isaenko
0a8440ef34 Minor corrections to wolfposd's implementation 2020-11-29 02:18:35 +03:00
Dmitry Isaenko
dcabf76522
Merge pull request #82 from wolfposd/master
allows adding files and folders via filechooser and drag and drop #51
2020-11-29 00:12:11 +03:00
Wolf Posdorfer
112a0f80e0 tooltips for a great user experience =) 2020-11-24 20:05:18 +01:00
Wolf Posdorfer
2936d65a31 looking through the whole hdd takes time, peform on background, update list on ui-thread 2020-11-24 19:54:06 +01:00
Wolf Posdorfer
b2202cf483 Reverting FileChooser and adding DirChooser
- old filechooser
- directory chooser can choose any directory and recursively adds all *.xyz files
- add button template
2020-11-24 19:12:19 +01:00
Dmitry Isaenko
128d305ea4
Merge pull request #84 from DDinghoya/patch-3
Update locale_ko_KR.properties
2020-11-24 16:51:25 +03:00
DDinghoya
9af20a98cc
Update locale_ko_KR.properties 2020-11-24 17:53:29 +09:00
Dmitry Isaenko
7a94c48559 Add Arabic by @eslamabdel (#83) 2020-11-22 23:12:07 +03:00
Wolf Posdorfer
503aa8cbe2 allows adding files and folders via filechooser and drag and drop
need to switch to JFileChooser, as javafx filechooser doesnt allow files+folders selection
selection folders (filechooser/dragndrop) now recursively walks the directory and adds every file.xyz it finds
2020-11-21 17:32:11 +01:00
Dmitry Isaenko
9a42e42c30 Version increment 2020-11-06 23:25:25 +03:00
Dmitry Isaenko
953dcb50cb Rally fix #81 2020-11-06 22:29:09 +03:00
Dmitry Isaenko
5e5a774e34 Fix #81 2020-11-06 22:26:35 +03:00
Dmitry Isaenko
fbd5ec970b Small NXDT-code refactoring 2020-10-29 16:54:41 +03:00
Dmitry Isaenko
050982f8ea Update Jenkinsfile 2020-10-28 19:10:08 +03:00
Dmitry Isaenko
0cb945a7f4 Cosmetic updates of GL code and working prototype of NXDT 2020-10-28 15:59:45 +03:00
Dmitry Isaenko
6e21c514a8 Update test, rename FrontTab to GamesTab 2020-10-27 21:33:56 +03:00
Dmitry Isaenko
eb07ab1df8 Update NXDT-related part 2020-10-27 20:53:52 +03:00
Dmitry Isaenko
98822de559 Fix POM, update package name a bit, update NXDT-related part 2020-10-27 18:15:52 +03:00
Dmitry Isaenko
8771d551a4 Fix split-files validation. Add JUnit5 dependency on testing stage. 2020-10-27 00:22:26 +03:00
Dmitry Isaenko
4cb3cbb491 Resolve #79 2020-10-26 14:12:14 +03:00
Dmitry Isaenko
50e2b739a8
Merge pull request #76 from andercard0/patch-1
Update Brazilian Portuguese Translation
2020-10-25 03:26:37 +03:00
Anderson_Cardoso
bd624d649a
Update Brazilian Portuguese Translation
- Quick Fix typo; 
- Cleared out some terms in English to proper Portuguese.
2020-10-10 11:12:39 -03:00
Dmitry Isaenko
f7b8e4d265 Add a notice for Mac users in README.md 2020-10-06 15:49:30 +03:00
Dmitry Isaenko
85a54cabc2 Refactor 'network-stopper' related code 2020-10-06 02:19:08 +03:00
Dmitry Isaenko
45696881e2 Add NS-USBloader network-stopper feature (front-end implementation) 2020-09-29 02:54:18 +03:00
Dmitry Isaenko
22b18710a5 Fix "Don't serve requests" option, update version number, fix typo 2020-09-25 02:56:09 +03:00
166 changed files with 11729 additions and 2397 deletions

101
.drone.yml Normal file
View file

@ -0,0 +1,101 @@
kind: pipeline
type: docker
name: default
steps:
- name: test
image: maven:3-openjdk-17
commands:
- mvn -B -DskipTests clean package
- mvn test -B
volumes:
- name: m2
path: /root/.m2
- name: archive-standard-artifact
image: alpine:latest
commands:
- mkdir -p /builds/ns-usbloader
- echo target/ns-usbloader-*jar
- cp target/ns-usbloader-*jar /builds/ns-usbloader/
volumes:
- name: builds
path: /builds
- name: make-win-installer
image: wheatstalk/makensis:3
commands:
- cp target/NS-USBloader.exe misc/windows/NSIS/
- misc/windows/update_version.sh
- cd misc/windows/NSIS
- makensis -V4 ./installer.nsi
- echo Installer-*.exe
- cp Installer-*.exe /builds/ns-usbloader/
- rm ./NS-USBloader.exe
- rm ./Installer-*.exe
- cd ../../../
volumes:
- name: builds
path: /builds
- name: jdk
path: /drone/src/misc/windows/NSIS/jdk
- name: drivers
path: /drone/src/misc/windows/NSIS/Drivers_set.exe
- name: emerge-legacy-artifact
image: maven:3-openjdk-17
commands:
- . ./.make_legacy
- mvn -B -DskipTests clean package
- echo target/ns-usbloader-*jar
- cp target/ns-usbloader-*jar /builds/ns-usbloader/
volumes:
- name: m2
path: /root/.m2
- name: builds
path: /builds
- name: make-legacy-win-installer
image: wheatstalk/makensis:3
commands:
- cp target/NS-USBloader.exe misc/windows/NSIS/
- misc/windows/update_version.sh legacy
- cd misc/windows/NSIS
- makensis -V4 ./installer.nsi
- echo Installer-*.exe
- cp Installer-*.exe /builds/ns-usbloader/
- cd ../../../
volumes:
- name: builds
path: /builds
- name: jdk
path: /drone/src/misc/windows/NSIS/jdk
- name: drivers
path: /drone/src/misc/windows/NSIS/Drivers_set.exe
- name: emerge-mac-m1-artifact
image: maven:3-openjdk-17
commands:
- . ./.make_m1
- mvn -B -DskipTests clean package
- echo target/ns-usbloader-*jar
- cp target/ns-usbloader-*jar /builds/ns-usbloader/
volumes:
- name: m2
path: /root/.m2
- name: builds
path: /builds
volumes:
- name: m2
host:
path: /home/docker/drone/files/m2
- name: builds
host:
path: /home/www/builds
- name: jdk
host:
path: /home/docker/drone/files/assembly/openjdk-19.0.2
- name: drivers
host:
path: /home/docker/drone/files/assembly/Drivers_set.exe

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
offsets.txt
environment.txt

3
.make_legacy Normal file
View file

@ -0,0 +1,3 @@
sed -z -i -e 's/<groupId>org.usb4java<\/groupId>\n\s*<artifactId>usb4java<\/artifactId>\s*<version>1.3.0<\/version>/<groupId>org.usb4java<\/groupId>\n<artifactId>usb4java<\/artifactId>\n<version>1.2.0<\/version>/g' pom.xml
sed -z -i -e 's/<finalName>${project.artifactId}-${project.version}-${maven.build.timestamp}<\/finalName>/<finalName>${project.artifactId}-${project.version}-legacy-${maven.build.timestamp}<\/finalName>/g' pom.xml
sed -z -i -e 's/<jar>target\/${project.artifactId}-${project.version}-${maven.build.timestamp}.jar<\/jar>/<jar>target\/${project.artifactId}-${project.version}-legacy-${maven.build.timestamp}.jar<\/jar>/g' pom.xml

5
.make_m1 Normal file
View file

@ -0,0 +1,5 @@
sed -z -i -e 's/<groupId>org.usb4java<\/groupId>\n<artifactId>usb4java<\/artifactId>\n<version>1.2.0<\/version>/<groupId>org.usb4java<\/groupId>\n<artifactId>usb4java<\/artifactId>\n<version>1.3.0<\/version>/g' pom.xml
sed -z -i -e 's/<classifier>mac<\/classifier>/<classifier>mac-aarch64<\/classifier>/g' pom.xml
sed -z -i -e 's/<finalName>${project.artifactId}-${project.version}-legacy-${maven.build.timestamp}<\/finalName>/<finalName>${project.artifactId}-${project.version}-m1-${maven.build.timestamp}<\/finalName>/g' pom.xml
sed -i -e '/<groupId>com.akathist.maven.plugins.launch4j/,/<\/executions>/d' pom.xml
sed -z -i -e 's/<plugin>\n\s*<\/plugin>//g' pom.xml

View file

@ -0,0 +1,82 @@
steps:
- name: test-standard
when:
event: [tag, push]
image: maven:3-openjdk-17
commands:
- mvn -B -DskipTests clean package
- mvn test -B
- echo target/ns-usbloader-*jar
- mkdir artifacts
- cp target/ns-usbloader-*jar artifacts
volumes:
- /home/docker/woodpecker/files/m2:/root/.m2
- name: make-windows-installer
when:
event: [tag, push]
image: wheatstalk/makensis:3
commands:
- cp target/NS-USBloader.exe misc/windows/NSIS/
- misc/windows/update_version.sh
- cd misc/windows/NSIS
- makensis -V4 ./installer.nsi
- echo Installer-*.exe
- cp Installer-*.exe "../../../artifacts"
- rm ./NS-USBloader.exe
- rm ./Installer-*.exe
- cd ../../../
volumes:
- /home/docker/woodpecker/files/assembly/openjdk-19.0.2:/assembly/jdk
- /home/docker/woodpecker/files/assembly/Drivers_set.exe:/assembly/Drivers_set.exe
- name: emerge-legacy-artifact
when:
event: [tag, push]
image: maven:3-openjdk-17
commands:
- . ./.make_legacy
- mvn -B -DskipTests clean package
- echo target/ns-usbloader-*jar
- cp target/ns-usbloader-*jar artifacts
volumes:
- /home/docker/woodpecker/files/m2:/root/.m2
- name: make-legacy-windows-installer
when:
event: [tag, push]
image: wheatstalk/makensis:3
commands:
- cp target/NS-USBloader.exe misc/windows/NSIS/
- misc/windows/update_version.sh legacy
- cd misc/windows/NSIS
- makensis -V4 ./installer.nsi
- echo Installer-*.exe
- cp Installer-*.exe "../../../artifacts"
- cd ../../../
volumes:
- /home/docker/woodpecker/files/assembly/openjdk-19.0.2:/assembly/jdk
- /home/docker/woodpecker/files/assembly/Drivers_set.exe:/assembly/Drivers_set.exe
- name: emerge-mac-m1-artifact
when:
event: [tag, push]
image: maven:3-openjdk-17
commands:
- . ./.make_m1
- mvn -B -DskipTests clean package
- echo target/ns-usbloader-*jar
- cp target/ns-usbloader-*jar artifacts
volumes:
- /home/docker/woodpecker/files/m2:/root/.m2
- name: save-artifacts
when:
event: [tag, push]
image: alpine:latest
commands:
- export ARTIFACTS_DIR="$(date -d @$CI_PIPELINE_CREATED +'%Y-%m-%d %H:%m %Z')"
- mkdir -p /builds/ns-usbloader/
- mv artifacts "/builds/ns-usbloader/$ARTIFACTS_DIR"
volumes:
- /home/www/builds:/builds

21
Jenkinsfile vendored
View file

@ -1,21 +0,0 @@
pipeline {
agent {
docker {
image 'maven:3-jdk-11'
args '-v /home/docker/jenkins/files/m2:/root/.m2'
}
}
stages {
stage('Build') {
steps {
sh 'mvn -B -DskipTests clean package'
}
}
}
post {
always {
archiveArtifacts artifacts: 'target/*.jar, target/*.exe', onlyIfSuccessful: true
}
}
}

143
README.md
View file

@ -1,25 +1,30 @@
# NS-USBloader
<h1 align="center"><img src="screenshots/ApplicationLogo.svg" alt="NS-USBloader" width="450px"/></h1>
![License](https://img.shields.io/badge/License-GPLv3-blue.svg) ![Releases](https://img.shields.io/github/downloads/developersu/ns-usbloader/total.svg) ![LatestVer](https://img.shields.io/github/release/developersu/ns-usbloader.svg)
[Support author](#support-this-app)
![License](https://img.shields.io/badge/License-GPLv3-blue.svg) ![Releases](https://img.shields.io/github/downloads/developersu/ns-usbloader/total.svg) ![LatestVer](https://img.shields.io/github/release/developersu/ns-usbloader.svg) [![status-badge](https://ci.redrise.ru/api/badges/12/status.svg)](https://ci.redrise.ru/repos/12)
NS-USBloader is:
* A PC-side installer for **[Adubbz/TinFoil (v0.2.1)](https://github.com/Adubbz/Tinfoil/)**, **[Huntereb/Awoo-Installer](https://github.com/Huntereb/Awoo-Installer)** (USB and Network supported) and **[XorTroll/GoldLeaf](https://github.com/XorTroll/Goldleaf)** (USB) NSP installer.
Replacement for default **usb_install_pc.py**, **remote_install_pc.py**, **GoldTree**/**Quark**.
* This application also could be used as RCM payload on Windows, MacOS and Linux (supported arch: x86, x86_64 and Raspberry Pi).
* And of course it's a tool for split files!
* And also for merging split-files into one :)
* A PC-side installer for **[Huntereb/Awoo-Installer](https://github.com/Huntereb/Awoo-Installer)** / other compatible installers (USB and Network supported) and **[XorTroll/Goldleaf](https://github.com/XorTroll/Goldleaf)** (USB) NSP installer.
Alternative to default **usb_install_pc.py**, **remote_install_pc.py**, **GoldTree**/**Quark**.
* RCM payload tool that works on Windows, macOS (Intel and Apple Silicon) and Linux (x86, amd64 and Raspberry Pi ARM).
* It's a tool for creating split files!
* Also you can use it for merging split-files into one :)
[Click here for Android version ;)](https://github.com/developersu/ns-usbloader-mobile)
With GUI and cookies. Works on Windows, macOS and Linux.
### Let's stay in touch:
#### [→ Independent source code storage](https://git.redrise.ru/desu/ns-usbloader)
#### [→ Mirror, issues tracker, place to send PRs](https://github.com/developersu/ns-usbloader)
#### [→ Nightly builds](https://redrise.ru/builds/ns-usbloader/)
Sometimes I add new posts about this project [on my home page](https://developersu.blogspot.com/search/label/NS-USBloader).
[Support/Donate](#support-this-app)
![Application screenshot](screenshots/1.png)
<img src="screenshots/2.png" alt="screenshot" width="250"/> <img src="screenshots/3.png" alt="screenshot" width="250"/>
<img src="screenshots/4.png" alt="screenshot" width="250"/> <img src="screenshots/5.png" alt="screenshot" width="250"/>
Sometimes I add new posts about this project [on my blog page](https://developersu.blogspot.com/search/label/NS-USBloader).
<img src="screenshots/1.png" alt="screenshot" width="250"/> <img src="screenshots/2.png" alt="screenshot" width="250"/>
<img src="screenshots/3.png" alt="screenshot" width="250"/> <img src="screenshots/4.png" alt="screenshot" width="250"/>
<img src="screenshots/5.png" alt="screenshot" width="250"/>
#### License
@ -36,39 +41,52 @@ Sometimes I add new posts about this project [on my home page](https://developer
* [Pablo Curiel (DarkMatterCore)](https://github.com/DarkMatterCore)
* [wolfposd](https://github.com/wolfposd)
* [agungrbudiman](https://github.com/agungrbudiman)
* Perfect algorithms and great examples taken from mrdude project [mrdude2478/IPS_Patch_Creator](https://github.com/mrdude2478/IPS_Patch_Creator/)
* French by [Stephane Meden (JackFromNice)](https://github.com/JackFromNice)
* Italian by [unbranched](https://github.com/unbranched)
* Korean by [DDinghoya](https://github.com/DDinghoya)
* Portuguese by [almircanella](https://github.com/almircanella)
* Spanish by [/u/cokimaya007](https://www.reddit.com/u/cokimaya007), Kuziel Alejandro
* Chinese (Simplified) by [Huang YunKun (htynkn)](https://github.com/htynkn), [exiori](https://github.com/exiori)
* Spanish by [/u/cokimaya007](https://www.reddit.com/u/cokimaya007), [Kuziel Alejandro](https://github.com/Uzi-Oni)
* Chinese (Simplified) by [Huang YunKun (htynkn)](https://github.com/htynkn), [FFT9 (XXgame Group)](http://xxgame.net/)
* Chinese (Traditional) by [qazrfv1234](https://github.com/qazrfv1234), [FFT9 (XXgame Group)](http://xxgame.net/)
* German by [Swarsele](https://github.com/Swarsele)
* Vietnamese by [Hai Phan Nguyen (pnghai)](https://github.com/pnghai)
* Czech by [Spenaat](https://github.com/spenaat)
* Chinese (Traditional) by [qazrfv1234](https://github.com/qazrfv1234)
* Arabic by [eslamabdel](https://github.com/eslamabdel)
* Romanian by [Călin Ilie](https://github.com/calini)
* Swedish by [Daniel Nylander](https://github.com/yeager)
* Japanese by [kuragehime](https://github.com/kuragehimekurara1)
* Ryukyuan languages by [kuragehime](https://github.com/kuragehimekurara1)
* Turkish language by [Erimsaholut](https://github.com/Erimsaholut)
* Serbian (Latin) translation [BlytheScythe](https://github.com/BlytheScythe)
* Angelo Elias Dalzotto makes packages in AUR
* Phoenix[Msc] provides his shiny Mac M1 for debug
### System requirements
JRE/JDK 8u60 or higher
- JDK 11 for macOS and Linux
- libusb, if you have a Mac with Apple Silicon (install via `brew install libusb`)
### Supported GoldLeaf versions
| GoldLeaf version | NS-USBloader version |
| ---------------- | -------------------- |
### Supported Goldleaf versions
| Goldleaf version | NS-USBloader version |
|------------------|----------------------|
| v0.5 | v0.4 - v0.5.2, v0.8+ |
| v0.6 | none |
| v0.6.1 | v0.6 |
| v0.7 - 0.7.3 | v0.7+ |
| v0.8 | v1.0+ |
| v0.8 - 0.9 | v1.0+ |
| v0.10 | v6.0+ |
where '+' means 'any next NS-USBloader version'.
### Awoo Installer support
### Awoo Installer and compatible applications support
Awoo Installer uses the same command-set (or 'protocol') to TinFoil. So just select 'TinFoil' in case you're going to use Awoo.
Awoo Installer uses the same command-set (or 'protocol') to [Adubbz/Tinfoil](https://github.com/Adubbz/Tinfoil/).
Also, please go to 'Settings' tab of NS-USBloader after first installation and check 'Allow XCI / NSZ / XCZ files selection for TinFoil' option. This installer can install not only NSPs but a way more formats!
A lot of other forks/apps uses the same command-set. To stop speculating about the name it's now called 'Awoo'. It WAS called 'TinFoil' before. Not any more.
### Usage
##### Linux:
@ -80,17 +98,17 @@ Also, please go to 'Settings' tab of NS-USBloader after first installation and c
3. Optional: add user to 'udev' rules to use NS not-from-root-account
```
root # vim /etc/udev/rules.d/99-NS.rules
SUBSYSTEM=="usb", ATTRS{idVendor}=="057e", ATTRS{idProduct}=="3000", GROUP="plugdev"
SUBSYSTEM=="usb", ATTRS{idVendor}=="057e", ATTRS{idProduct}=="3000", MODE="0666"
root # udevadm control --reload-rules && udevadm trigger
```
4. For RCM part
```
root # vim /etc/udev/rules.d/99-NS-RCM.rules
SUBSYSTEM=="usb", ATTRS{idVendor}=="0955", ATTRS{idProduct}=="7321", GROUP="plugdev"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0955", ATTRS{idProduct}=="7321", MODE="0666"
root # udevadm control --reload-rules && udevadm trigger
```
Please note: you may have to change 'plugdev' group from example above to the different one. It's depends on you linux distro.
5. For HiDPI use scaling like `java -Dglass.gtk.uiScale=150% -jar application.jar`
##### Raspberry Pi
@ -106,19 +124,25 @@ Double-click on downloaded .jar file. Follow instructions. Or see 'Linux' sectio
Set 'Security & Privacy' settings if needed.
*Please note: JDK 19 is recommended for using on macOS. There are issues already reported from users on Mac with JDK 14.*
##### macOS on Apple Silicon (ARM)
Download application with `-m1.jar` postfix.
Manually install libusb with Homebrew by running `brew install libusb` in your Terminal.
##### Windows:
* [Download and install Java JRE](http://java.com/download/) (8u60 or higher)
* Get this application (JAR file) and double-click on on it (alternatively open 'cmd', go to place where jar located and execute via `java -jar thisAppName.jar`)
* Once application opens click on 'Gear' icon.
* Click 'Download and install drivers'
* Install drivers
#### And how to use it?
The first thing you should do it install TinFoil ([Adubbz](https://github.com/Adubbz/Tinfoil/)), GoldLeaf ([XorTroll](https://github.com/XorTroll/Goldleaf)) or Awoo ([Huntereb](https://github.com/Huntereb/Awoo-Installer)) on your NS.
The first thing you should do it install Awoo ([Huntereb](https://github.com/Huntereb/Awoo-Installer)) or Goldleaf ([XorTroll](https://github.com/XorTroll/Goldleaf)) on your NS.
Take a look on app, find where is the option to install from USB and/or Network. Maybe [this article (about TinFoil)](https://developersu.blogspot.com/2019/02/ns-usbloader-en.html) will be helpful.
Take a look on app, find where is the option to install from USB and/or Network. Maybe (very old) [this article (about TinFoil)](https://developersu.blogspot.com/2019/02/ns-usbloader-en.html) will be helpful.
#### In details
@ -126,19 +150,19 @@ There are three tabs. First one is main.
##### 'Gamepad' tab.
At the top of you selecting from drop-down application and protocol that you're going to use. For GoldLeaf only USB is available. Lamp icon stands for switching themes (light or dark).
At the top of you selecting from drop-down application and protocol that you're going to use. For Goldleaf only USB is available. Lamp icon stands for switching themes (light or dark).
Then you may drag-n-drop files (split-files aka folders) to application or use 'Select NSP files' button. Multiple selection for files available. Click it again and select files from another folder it you want, it will be added into the table.
Table.
There you can select checkbox for files that will be send to application (TF/GL). ~~Since GoldLeaf allow you only one file transmission per time, only one file is available for selection.~~
There you can select checkbox for files that will be sent to application (AW/GL). ~~Since Goldleaf v0.5 allow you only one file transmission per time, only one file is available for selection.~~
Also you can use space to select/un-select files and 'delete' button for deleting. By right-mouse-click you can see context menu where you can delete one OR all items from the table.
Also, you can use space to select/un-select files and 'delete' button for deleting. By right-mouse-click you can see context menu where you can delete one OR all items from the table.
For GoldLeaf v0.6.1 and NS-USBloader v0.6 (and higher) you will have to use 'Explore content' -> 'Remote PC (via USB)' You will see two drives HOME:/ and VIRT:/. First drive is pointing to your home directory. Second one is reflection of what you've added to table (first application tab). Also VIRT:/ drive have limited functionality in comparison to HOME:/. E.g. you can't write files to this drive since it's not a drive. But don't worry, it won't make any impact on GoldLeaf or your NS if you try.
For Goldleaf v0.6.1 and NS-USBloader v0.6 (and higher) you will have to use 'Explore content' -> 'Remote PC (via USB)' You will see two drives HOME:/ and VIRT:/. First drive is pointing to your home directory. Second one is reflection of what you've added to table (first application tab). Also VIRT:/ drive have limited functionality in comparison to HOME:/. E.g. you can't write files to this drive since it's not a drive. But don't worry, it won't make any impact on Goldleaf or your NS if you try.
Also, for GoldLeaf write files (from NS to PC): You have to 'Stop execution' properly before accessing files transferred from GL. Usually you have to wait 5sec or less. It will guarantee that your files properly written to PC.
Also, for Goldleaf write files (from NS to PC): You have to 'Stop execution' properly before accessing files transferred from GL. Usually you have to wait 5sec or less. It will guarantee that your files properly written to PC.
##### 'RCM' tab
@ -146,15 +170,15 @@ On this tab you can select payloader like Hekate or LockPick_RCM and send it to
##### 'Folder with arrows and zeroes' tab
On this tab you can split and merge files. Select 'Split' or 'Merge' and split (or merge).
On this tab you can split and merge files. Select 'Split' or 'Merge' and split (or merge). BTW Drag-n-drop supported.
##### 'Gears' tab.
Here you can configure settings for network file transmission. Usually you shouldn't change anything. But it you're cool hacker, go ahead! The most interesting option here is 'Don't serve requests'. Architecture of the TinFoil's NET part is working interesting way. When you select in TF network NSP transfer, application will wait at port 2000 for the information about where should it take files from. Like '192.168.1.5:6060/my file.nsp'. Usually NS-USBloader serves requests by implementing simplified HTTP server and bringing it up and so on. But if this option selected, you can define path to remote location of the files. For example if you set in settings '192.168.4.2:80/ROMS/NS/' and add in table file 'my file.nsp' then NS-USBloader will simply tell TinFoil "Hey, go take files from '192.168.4.2:80/ROMS/NS/my%20file.nsp' ". Of course you have to bring '192.168.4.2' host up and make file accessible from such address (just go install nginx). As I said, this feature is interesting, but I guess won't be popular.
Here you can configure settings for network file transmission. Usually you shouldn't change anything. But it you're cool hacker, go ahead! The most interesting option here is 'Don't serve requests'. Architecture of the Awoo's NET part is working interesting way. When you select in Awoo network NSP transfer, application will wait at port 2000 for the information about where should it take files from. Like '192.168.1.5:6060/my file.nsp'. Usually NS-USBloader serves requests by implementing simplified HTTP server and bringing it up and so on. But if this option selected, you can define path to remote location of the files. For example if you set in settings '192.168.4.2:80/ROMS/NS/' and add in table file 'my file.nsp' then NS-USBloader will simply tell Awoo "Hey, go take files from '192.168.4.2:80/ROMS/NS/my%20file.nsp' ". Of course you have to bring '192.168.4.2' host up and make file accessible from such address (just go install nginx). As I said, this feature is interesting, but I guess won't be popular.
Also here you can:
* Set 'Auto-check for updates' for checking for updates when application starts, or click button to verify if new version released immediately.
* Set 'Show only *.nsp in GoldLeaf' to filter all files displayed at HOME:/ drive. So only NSP files will appear.
* Set 'Show only *.nsp in Goldleaf' to filter all files displayed at HOME:/ drive. So only NSP files will appear.
##### 'Dialog with three dots' tab.
@ -167,13 +191,13 @@ To get help run ``$ java -jar ns-usbloader-4.0.jar --help``
```
-c,--clean Remove/reset settings and exit
-g,--goldleaf <...> Install via GoldLeaf mode. Check '-g help' for information.
-g,--Goldleaf <...> Install via Goldleaf mode. Check '-g help' for information.
-h,--help Show this help
-m,--merge <...> Merge files. Check '-m help' for information.
-n,--tfn <...> Install via Tinfoil/Awoo Network mode. Check '-n help' for information.
-n,--tfn <...> Install via Awoo Network mode. Check '-n help' for information.
-r,--rcm <[PATH/]payload.bin> Send payload
-s,--split <...> Split files. Check '-s help' for information.
-t,--tinfoil <FILE...> Install via Tinfoil/Awoo USB mode.
-t,--tinfoil <FILE...> Install via Awoo USB mode.
-v,--version Show application version
```
@ -198,7 +222,7 @@ Send RCM payload:
$ java -jar ns-usbloader-4.0.jar -r C:\Users\Superhero\hekate.bin
Send files to Awoo Installer via Net-install:
$ java -jar ns-usbloader-4.0.jar -n nsip=192.168.0.1 ./file.nsz ./file.nsp ~/*.xci
Send files to GoldLeaf v0.8:
Send files to Goldleaf v0.8:
$ java -jar ns-usbloader-4.0.jar -g ver=v0.8 ./*
Split files:
$ java -jar ns-usbloader-4.0.jar -s /tmp/ ~/*.nsp
@ -209,34 +233,31 @@ $ java -jar ns-usbloader-4.0.jar -m /tmp/ ~/*.nsp
### Other notes
'Status' = 'Uploaded' that appears in the table does not mean that file has been installed. It means that it has been sent to NS without any issues! That's what this app about.
Handling successful/failed installation is a purpose of the other side application: TinFoil or GoldLeaf. And they don't provide any feedback interfaces so I can't detect success/failure.
Handling successful/failed installation is a purpose of the other side application: Awoo/Awoo-like or Goldleaf. And they don't provide any feedback interfaces so I can't detect success/failure.
usb4java since NS-USBloader-v0.2.3 switched to 1.2.0 instead of 1.3.0. This should not impact anyone except users of macOS High Sierra (and Sierra, and El Capitan) where previous versions of NS-USBloader didn't work. Now builds with usb4java-1.2.0 marked as '-legacy' and builds with usb4java-1.3.0 doesn't have postfixes.
#### What is this '-legacy' jar?!
**JAR with NO postfixes** recommended for Windows users, Linux users and macOS users who're using Mojave or later versions.
**JAR with '-legacy' postfix** is for macOS users who're still using OS X releases before (!) Mojave.
(It also works for Linux and for Windows, but sometimes it doesn't work for Windows and I don't know why).
We have this situation because of weird behaviour inside usb4java library used in this application for USB interactions. In '-legacy' it's v1.2.0 and in 'normal' it's v1.3.0
### Translators!
If you want to see this app translated to your language, go grab [this file](https://github.com/developersu/ns-usbloader/blob/master/src/main/resources/locale.properties) and translate it.
Upload somewhere (create PR, use pastebin/google drive/whatever else). [Create new issue](https://github.com/developersu/ns-usbloader/issues) and post a link. I'll grab it and add.
If you're familiar with pull request, go ahead and create it! No worries it you are not. Just upload somewhere (like pastebin/google drive/whatever else). [Create new issue](https://github.com/developersu/ns-usbloader/issues) and post a link. I'll grab it and add.
To convert files of any locale to readable format (and vise-versa) you can use this site [https://itpro.cz/juniconv/](https://itpro.cz/juniconv/)
#### TODO (maybe):
- [x] [Android support](https://github.com/developersu/ns-usbloader-mobile)
## Support this app
If you like this app, just give a star.
If you like this app, just give a star (@ GitHub).
If you want to make a donation*, please see below:
This is non-commercial project.
<a href="https://liberapay.com/developersu/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg"></a>
<a href="https://paypal.me/developersu" title="PayPal"><img src="https://www.paypalobjects.com/webstatic/mktg/Logo/pp-logo-100px.png" border="0" alt="PayPal Logo" /></a>
[Yandex.Money](https://money.yandex.ru/to/410014301951665)
* Please note: this is non-commercial application.
Thanks
Thanks!
Appreciate assistance and support of both [Vitaliy](https://github.com/SebastianUA) and [Konstantin](https://github.com/konstantin-kelemen). Without you all this magic would not have happened.

View file

@ -0,0 +1,9 @@
#!/usr/bin/env xdg-open
[Desktop Entry]
Type=Application
Name=NS-USBloader
Exec=ns-usbloader
Comment=NS multi tool
Terminal=false
Icon=ns-usbloader.svg
Categories=Game;

View file

@ -0,0 +1,118 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="45mm"
height="45mm"
viewBox="0 0 45.000001 45"
version="1.1"
id="svg8"
inkscape:version="1.2.1 (9c6d41e410, 2022-07-14)"
sodipodi:docname="ns-usbloader.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="5.6568543"
inkscape:cx="206.82873"
inkscape:cy="90.421279"
inkscape:document-units="mm"
inkscape:current-layer="svg8"
showgrid="false"
units="mm"
inkscape:window-width="3754"
inkscape:window-height="2127"
inkscape:window-x="1166"
inkscape:window-y="0"
inkscape:window-maximized="1"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:document-rotation="0"
inkscape:showpageshadow="0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1">
<inkscape:grid
type="xygrid"
id="grid829"
originx="-40.993993"
originy="-37.999754" />
</sodipodi:namedview>
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<g
id="g851"
inkscape:label="mainGRP"
transform="translate(-40.993968,-26.999903)">
<path
id="path847"
transform="scale(0.26458333)"
d="m 188.97656,102.04688 c -18.97637,0 -34.01562,18.70089 -34.01562,30.23632 -0.0219,42.2441 -0.0386,69.16374 0,109.60742 0,11.85827 15.03925,30.23633 34.01562,30.23633 h 48.94141 V 102.04688 Z"
style="fill:#00c8fc;fill-opacity:1;stroke-width:1"
inkscape:connector-curvature="0"
inkscape:label="con" />
<path
id="rect823"
d="m 64.973294,26.999903 v 45 h 21.02 v -45 z"
style="fill:#ec0000;fill-opacity:1;stroke-width:0.116442"
inkscape:connector-curvature="0"
inkscape:label="big" />
</g>
<path
id="path862"
style="fill:#ffffff;fill-opacity:1;stroke-width:0.392613"
d="m 11.547015,28.4105 a 2.1593723,2.1593723 0 0 0 -2.2000565,2.117691 2.1593723,2.1593723 0 0 0 2.1176905,2.200059 2.1593723,2.1593723 0 0 0 2.200555,-2.1167 2.1593723,2.1593723 0 0 0 -2.1167,-2.20105 l -0.04267,2.158874 z m 3.840427,-3.937182 a 2.1593723,2.1593723 0 0 0 -2.199561,2.117693 2.1593723,2.1593723 0 0 0 2.117195,2.200057 2.1593723,2.1593723 0 0 0 2.200555,-2.117195 2.1593723,2.1593723 0 0 0 -2.1167,-2.200555 l -0.04217,2.158876 z m -7.6809635,0 a 2.1593722,2.1593722 0 0 0 -2.200057,2.117693 2.1593722,2.1593722 0 0 0 2.117691,2.200057 2.1593722,2.1593722 0 0 0 2.200554,-2.117195 2.1593722,2.1593722 0 0 0 -2.117195,-2.200555 l -0.04218,2.158876 z m 3.8405365,-3.938173 a 2.1593723,2.1593723 0 0 0 -2.2000565,2.117691 2.1593723,2.1593723 0 0 0 2.1176905,2.200059 2.1593723,2.1593723 0 0 0 2.200555,-2.1167 2.1593723,2.1593723 0 0 0 -2.1167,-2.20105 l -0.04267,2.158874 z"
inkscape:label="small_c"
inkscape:connector-curvature="0" />
<g
inkscape:label="slogan"
id="layer1"
transform="translate(-40.993968,-213.9999)"
inkscape:groupmode="layer">
<g
aria-label="everywhere"
transform="matrix(0.26458333,0,0,0.26458333,-24.077084,181.70833)"
style="font-style:normal;font-variant:normal;font-weight:300;font-stretch:normal;font-size:35.0667px;line-height:1.25;font-family:Raleway;-inkscape-font-specification:'Raleway, Light';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none"
id="flowRoot1022"
inkscape:label="flowRoot1022"
inkscape:groupmode="layer" />
</g>
<path
id="path853"
style="fill:#ffffff;fill-opacity:1;stroke-width:0.272727"
d="m 11.506852,6.300096 a 4.5000001,4.5000001 0 0 1 4.49918,4.500616 4.5000001,4.5000001 0 0 1 -4.500411,4.499384 4.5000001,4.5000001 0 0 1 -4.4995895,-4.500205 4.5000001,4.5000001 0 0 1 4.5000005,-4.499795"
inkscape:label="big_c"
inkscape:connector-curvature="0" />
<path
id="path1334"
d="m 35.091899,7.050931 -1.966235,3.404775 h 1.402615 v 17.402765 l -3.579993,-3.388515 c -0.231149,-0.288377 -0.393301,-0.665687 -0.402284,-1.053816 0,-1.570143 -3.97e-4,-2.502567 -9.76e-4,-2.845788 0.662828,-0.232646 1.141253,-0.857572 1.141253,-1.600489 0,-0.939842 -0.76265,-1.702559 -1.702831,-1.702559 -0.940589,0 -1.702967,0.76265 -1.702967,1.702559 0,0.742917 0.478154,1.367843 1.140438,1.600489 l -4.76e-4,2.812447 c 0,0.762241 0.418205,1.560957 0.90847,2.069322 -0.01456,-0.01388 -0.03007,-0.02831 2.83e-4,8.15e-4 0.01211,0.01075 3.797875,3.595101 3.797875,3.595101 0.230809,0.287762 0.39194,0.664868 0.401196,1.052727 v 1.968677 c -1.30057,0.260954 -2.28042,1.409421 -2.28042,2.787065 0,1.570687 1.273194,2.843881 2.843405,2.843881 1.570686,0 2.843946,-1.273194 2.843946,-2.843881 0,-1.377917 -0.980663,-2.526381 -2.282303,-2.787335 v -1.934186 c 0,-0.005 2.59e-4,-0.0099 0,-0.01498 v -4.278078 c 0.0098,-0.38711 0.171203,-0.763741 0.402285,-1.051231 0,0 3.785488,-3.583532 3.797733,-3.594625 0.03043,-0.02872 0.01454,-0.01444 2.59e-4,-2.58e-4 0.490197,-0.508364 0.908134,-1.307418 0.908134,-2.069798 l -3.97e-4,-2.710376 h 1.141588 v -3.405646 h -3.405338 v 3.405663 h 1.140097 c 0,0 -0.0012,0.713861 -0.0012,2.743583 -0.0089,0.388196 -0.170862,0.765917 -0.402012,1.054155 l -3.580815,3.389238 V 10.455706 h 1.404858 z"
inkscape:connector-curvature="0"
style="fill:#ffffff;stroke-width:0.0680452"
inkscape:label="usb_logo" />
<path
style="fill:#000000;fill-opacity:1;stroke-width:0.264583"
d="m 21.967046,0 c -0.0065,-1.9994448e-6 -0.01188,0.0054 -0.01188,0.01188 v 44.976581 c 0,0.0065 0.0054,0.01188 0.01188,0.01188 h 2.000395 c 0.0065,0 0.01188,-0.0054 0.01188,-0.01188 V 0.011885 c 0,-0.0065 -0.0054,-0.011879999445 -0.01188,-0.011879999445 z"
id="rect1136"
inkscape:connector-curvature="0"
sodipodi:nodetypes="csssssssc" />
</svg>

After

Width:  |  Height:  |  Size: 6.5 KiB

View file

@ -0,0 +1,8 @@
#### How to prepare JRE from JDK to bundle it with application
1. Run `java --list-modules`
2. Update resulting list s/@.*\n/\,/g
3. Run `jlink --no-header-files --no-man-pages --compress=2 --add-modules !!!_PASTE_RESULT_HERE_!!! --output jre`
4. JRE created at folder 'jre
jlink --no-header-files --no-man-pages --compress=2 --add-modules $($(java --list-modules) -join "," -replace "@[0-9].*") --output jre-11'

View file

@ -0,0 +1,160 @@
;Include Modern UI
!include "MUI.nsh"
Unicode true
;Name and file
!define APPNAME "NS-USBloader"
!define COMPANYNAME "Dmitry Isaenko"
!define VERSIONMAJOR 0
!define VERSIONMINOR 0
!define VERSIONBUILD 0
Name "NS-USBloader"
OutFile "Installer.exe"
;Default installation folder
InstallDir "$PROGRAMFILES\${APPNAME}"
;Get installation folder from registry if available
InstallDirRegKey HKCU "Software\${APPNAME}" ""
;Request application privileges for Windows Vista
RequestExecutionLevel admin
!define MUI_ICON installer_logo.ico
!define MUI_UNICON uninstaller_logo.ico
; !define MUI_FINISHPAGE_NOAUTOCLOSE
!define MUI_WELCOMEFINISHPAGE_BITMAP "leftbar.bmp"
!define MUI_UNWELCOMEFINISHPAGE_BITMAP "leftbar_uninstall.bmp"
!define MUI_FINISHPAGE_LINK "NS-USBloader at GitHub"
!define MUI_FINISHPAGE_LINK_LOCATION https://github.com/developersu/NS-USBloader/
!define MUI_FINISHPAGE_RUN "$INSTDIR\NS-USBloader.exe"
!define MUI_FINISHPAGE_SHOWREADME
!define MUI_FINISHPAGE_SHOWREADME_TEXT $(l10n_CreateShortcut)
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateDesktopShortCut
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
;--------------------------------
;Interface Settings
!define MUI_ABORTWARNING
;--------------------------------
;Language Selection Dialog Settings
;Remember the installer language
!define MUI_LANGDLL_REGISTRY_ROOT "HKCU"
!define MUI_LANGDLL_REGISTRY_KEY "Software\${APPNAME}"
!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language"
;--------------------------------
;Pages
;!define MUI_HEADERIMAGE
;!define MUI_HEADERIMAGE_RIGHTi
;!define MUI_HEADERIMAGE_BITMAP "install_header.bmp"
;!define MUI_HEADERIMAGE_UNBITMAP "install_header.bmp"
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_LICENSE "license.txt"
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_UNPAGE_FINISH
;--------------------------------
;Languages
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Russian"
!insertmacro MUI_LANGUAGE "SpanishInternational"
!insertmacro MUI_LANGUAGE "SimpChinese"
!insertmacro MUI_LANGUAGE "TradChinese"
!insertmacro MUI_LANGUAGE "Japanese"
!insertmacro MUI_LANGUAGE "Korean"
!insertmacro MUI_LANGUAGE "Italian"
!insertmacro MUI_LANGUAGE "PortugueseBR"
!insertmacro MUI_LANGUAGE "Vietnamese"
!insertmacro MUI_LANGUAGE "Arabic"
!insertmacro MUI_LANGUAGE "Czech"
!insertmacro MUI_LANGUAGE "Romanian"
!insertmacro MUI_LANGUAGE "French"
!insertmacro MUI_LANGUAGE "Swedish"
;Language strings
LangString l10n_CreateShortcut ${LANG_ENGLISH} "Create Desktop Shortcut"
LangString l10n_CreateShortcut ${LANG_RUSSIAN} "Создать ярлык на Рабочем столе"
;--------------------------------
Section "NS-USBloader" Install
SetOutPath "$INSTDIR"
file /r \assembly\jdk
file \assembly\Drivers_set.exe
file NS-USBloader.exe
file logo.ico
; Registry information for add/remove programs
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APPNAME}" "DisplayName" "${APPNAME}"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APPNAME}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APPNAME}" "DisplayIcon" "$\"$INSTDIR\logo.ico$\""
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APPNAME}" "Publisher" "$\"${COMPANYNAME}$\""
; Start Menu
CreateDirectory "$SMPROGRAMS\${APPNAME}"
CreateShortCut "$SMPROGRAMS\${APPNAME}\${APPNAME}.lnk" "$INSTDIR\NS-USBloader.exe" "" "$INSTDIR\logo.ico"
CreateShortCut "$SMPROGRAMS\${APPNAME}\Uninstall.lnk" "$INSTDIR\Uninstall.exe"
;Store installation folder
WriteRegStr HKCU "Software\${APPNAME}" "" $INSTDIR
;Create uninstaller
WriteUninstaller "$INSTDIR\Uninstall.exe"
SectionEnd
;--------------------------------
;Installer Functions
Function .onInit
; set mandatory installation rule to section
SectionSetFlags ${Install} 17
FunctionEnd
Function un.onInit
!insertmacro MUI_UNGETLANGUAGE
FunctionEnd
Function CreateDesktopShortCut
CreateShortcut "$DESKTOP\NS-USBloader.lnk" "$INSTDIR\NS-USBloader.exe"
FunctionEnd
;--------------------------------
;Uninstaller Section
Section "Uninstall"
; Start Menu
Delete "$SMPROGRAMS\${APPNAME}\${APPNAME}.lnk"
Delete "$SMPROGRAMS\${APPNAME}\Uninstall.lnk"
Delete "$DESKTOP\NS-USBloader.lnk"
rmDir "$SMPROGRAMS\${APPNAME}"
;Delete installed files
RMDir /r "$INSTDIR\jdk\*"
Delete "$INSTDIR\Drivers_set.exe"
Delete "$INSTDIR\NS-USBloader.exe"
Delete "$INSTDIR\logo.ico"
Delete "$SMPROGRAMS\Uninstall.exe"
RMDir "$INSTDIR"
DeleteRegKey /ifempty HKCU "Software\${APPNAME}"
; Cleanup records stored for uninstaller from the registry
DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APPNAME}"
SectionEnd
;--------------------------------
;Uninstaller Functions

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

File diff suppressed because it is too large Load diff

BIN
misc/windows/NSIS/logo.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

13
misc/windows/update_version.sh Executable file
View file

@ -0,0 +1,13 @@
#!/bin/bash
TIMESTAMP=`date +%Y%m%d.%H%M%S`
VERSIONMAJOR=`grep '<version>' pom.xml | head -1 | sed -e 's/^.*<version>//g' -e 's/\..*$//g'`
VERSIONMINOR=`grep '<version>' pom.xml | head -1 | sed -E 's/^.*<version>[0-9]+?\.//g' | sed -E -e 's/(\..*|-SNAPSHOT|)<\/version>.*$//g'`
sed -z -i -e "s/!define\ VERSIONMAJOR\ [0-9]/!define\ VERSIONMAJOR $VERSIONMAJOR\ /" misc/windows/NSIS/installer.nsi
sed -z -i -e "s/!define\ VERSIONMINOR\ [0-9]/!define\ VERSIONMINOR $VERSIONMINOR\ /" misc/windows/NSIS/installer.nsi
if [ $# -eq 0 ]
then
sed -z -i -e "s/OutFile\ \"Installer.exe\"/OutFile\ \"Installer-$VERSIONMAJOR.$VERSIONMINOR-$TIMESTAMP.exe\"\ /" misc/windows/NSIS/installer.nsi
else
sed -z -i -e "s/OutFile\ \"Installer-$VERSIONMAJOR.$VERSIONMINOR-[0-9]*\.[0-9]*.exe\"/OutFile\ \"Installer-legacy-$VERSIONMAJOR.$VERSIONMINOR-$TIMESTAMP.exe\"\ /" misc/windows/NSIS/installer.nsi
fi

187
pom.xml
View file

@ -8,12 +8,10 @@
<name>NS-USBloader</name>
<artifactId>ns-usbloader</artifactId>
<version>4.3-SNAPSHOT</version>
<version>7.3</version> <!-- linked via script to NSIS system. Should have format of 2 blocks of numbers -->
<url>https://github.com/developersu/ns-usbloader/</url>
<description>
NSP USB loader for TinFoil (USB and Network) and GoldLeaf
</description>
<url>https://redrise.ru</url>
<description>NS multi-tool</description>
<inceptionYear>2019</inceptionYear>
<organization>
<name>Dmitry Isaenko</name>
@ -40,106 +38,96 @@
</developer>
</developers>
<repositories>
<repository>
<id>redrise</id>
<name>redrise.ru repository</name>
<url>https://repo.redrise.ru/releases</url>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.build.timestamp.format>yyyyMMdd.HHmmss</maven.build.timestamp.format>
<javafx.version>19.0.2.1</javafx.version>
<maven.compiler.release>11</maven.compiler.release>
</properties>
<issueManagement>
<system>GitHub</system>
<url>https://github.com/developer_su/${project.artifactId}/issues</url>
<url>https://github.com/developersu/${project.artifactId}/issues</url>
</issueManagement>
<!-- openJFX Linux -->
<dependencies>
<!-- https://mvnrepository.com/artifact/commons-cli/commons-cli -->
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
<version>1.5.0</version>
<scope>compile</scope>
</dependency>
<!-- openJFX Linux -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11</version>
<artifactId>javafx-graphics</artifactId>
<version>${javafx.version}</version>
<classifier>linux</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>11</version>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
<classifier>linux</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>11</version>
<classifier>linux</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>11</version>
<version>${javafx.version}</version>
<classifier>linux</classifier>
<scope>compile</scope>
</dependency>
<!-- openJFX Windows -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11</version>
<artifactId>javafx-graphics</artifactId>
<version>${javafx.version}</version>
<classifier>win</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>11</version>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
<classifier>win</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>11</version>
<classifier>win</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>11</version>
<version>${javafx.version}</version>
<classifier>win</classifier>
<scope>compile</scope>
</dependency>
<!-- openJFX MAC -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11</version>
<artifactId>javafx-graphics</artifactId>
<version>${javafx.version}</version>
<classifier>mac</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>11</version>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
<classifier>mac</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>11</version>
<classifier>mac</classifier>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>11</version>
<version>${javafx.version}</version>
<classifier>mac</classifier>
<scope>compile</scope>
</dependency>
@ -150,22 +138,88 @@
<version>1.3.0</version> <!-- Must be 1.2.0 for macOS lower than Mojave -->
<scope>compile</scope>
</dependency>
<!-- Junit5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.9.0</version>
<scope>test</scope>
</dependency>
<!-- redrise repository -->
<dependency>
<groupId>ru.redrise</groupId>
<artifactId>libKonogonka</artifactId>
<version>0.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}-${project.version}-${maven.build.timestamp}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources-filtered</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!--OpenJFX for Java9+
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.8</version>
<configuration>
<mainClass>nsusbloader.NSLMain</mainClass>
</configuration>
</plugin>
-->
<!-- Junit5 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<version>3.10.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<release>11</release>
</configuration>
</plugin>
<!-- Don't generate default JAR without dependencies -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<version>3.1.2</version>
<!--
<configuration>
<manifestEntries>
<Automatic-Module-Name>nsusbloader</Automatic-Module-Name>
</manifestEntries>
</configuration>
-->
<executions>
<execution>
<id>default-jar</id>
@ -187,6 +241,7 @@
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
<executions>
<execution>
@ -198,14 +253,13 @@
</execution>
</executions>
</plugin>
<!-- Launch4j
<plugin>
<groupId>com.akathist.maven.plugins.launch4j</groupId>
<version>1.7.25</version>
<version>2.2.0</version>
<artifactId>launch4j-maven-plugin</artifactId>
<executions>
<execution>
<id>l4j-NS-USBloader</id>
<id>l4j-ns-usbloader</id>
<phase>package</phase>
<goals>
<goal>launch4j</goal>
@ -213,34 +267,37 @@
<configuration>
<headerType>gui</headerType>
<icon>appicon.ico</icon>
<outfile>target/NS-USBloader-${project.version}.exe</outfile>
<jar>target/ns-usbloader-${project.version}-jar-with-dependencies.jar</jar>
<errTitle>NS-USBloader</errTitle>
<classPath>
<mainClass>nsusbloader.Main</mainClass>
<addDependencies>false</addDependencies>
<preCp>anything</preCp>
</classPath>
<outfile>target/${project.name}.exe</outfile>
<jar>target/${project.artifactId}-${project.version}-${maven.build.timestamp}.jar</jar>
<!-- <downloadUrl>https://download.oracle.com/java/17/archive/jdk-17.0.1_windows-x64_bin.msi</downloadUrl> -->
<errTitle>Launching error</errTitle>
<!-- <dontWrapJar>true</dontWrapJar> -->
<jre>
<minVersion>1.8</minVersion>
<path>%PWD%/jdk</path>
<minVersion>11.0.0</minVersion>
</jre>
<versionInfo>
<fileVersion>1.0.0.0</fileVersion>
<fileVersion>${project.version}.0.0</fileVersion>
<txtFileVersion>${project.version}</txtFileVersion>
<fileDescription>TinFoil and GoldLeaf installer for your NS</fileDescription>
<copyright>GNU General Public License v3, 2019 ${project.organization.name}. Russia/LPR.</copyright>
<productVersion>1.0.0.0</productVersion>
<fileDescription>NS multi-tool</fileDescription>
<copyright>GNU General Public License v3, ${project.inceptionYear} ${project.organization.name}, Russia.</copyright>
<productVersion>${project.version}.0.0</productVersion>
<txtProductVersion>${project.version}</txtProductVersion>
<companyName>${project.organization.name}</companyName>
<productName>${project.name}</productName>
<internalName>${project.name}</internalName>
<originalFilename>${project.name}.exe</originalFilename>
</versionInfo>
<messages>
<startupErr>Startup error</startupErr>
<jreNotFoundErr>JDK not found</jreNotFoundErr>
<jreVersionErr>JDK Version mismatch</jreVersionErr>
<launcherErr>Launcher Error</launcherErr>
</messages>
</configuration>
</execution>
</executions>
</plugin>
-->
</plugins>
</build>
</project>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 54 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 43 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 67 KiB

Before After
Before After

View file

@ -1,19 +1,19 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="132.50603mm"
height="58.000351mm"
viewBox="0 0 132.50603 58.000351"
height="45.000351mm"
viewBox="0 0 132.50603 45.000351"
version="1.1"
id="svg8"
inkscape:version="1.0 (4035a4fb49, 2020-05-01)"
sodipodi:docname="Application Logo.svg">
inkscape:version="1.2.1 (9c6d41e410, 2022-07-14)"
sodipodi:docname="Application Logo.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<defs
id="defs2" />
<sodipodi:namedview
@ -23,28 +23,31 @@
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.4142136"
inkscape:cx="383.67648"
inkscape:cy="100.29922"
inkscape:zoom="4.0000001"
inkscape:cx="233.49999"
inkscape:cy="127.875"
inkscape:document-units="mm"
inkscape:current-layer="svg8"
inkscape:current-layer="flowRoot1022"
showgrid="false"
units="mm"
inkscape:window-width="1860"
inkscape:window-height="1058"
inkscape:window-x="1980"
inkscape:window-width="3754"
inkscape:window-height="2127"
inkscape:window-x="1166"
inkscape:window-y="0"
inkscape:window-maximized="1"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
inkscape:document-rotation="0">
inkscape:document-rotation="0"
inkscape:showpageshadow="0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1">
<inkscape:grid
type="xygrid"
id="grid829"
originx="-40.993969"
originy="-37.999746" />
originx="-40.99399"
originy="-37.999752" />
</sodipodi:namedview>
<metadata
id="metadata5">
@ -54,7 +57,6 @@
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
@ -114,145 +116,65 @@
inkscape:connector-curvature="0"
style="fill:#ffffff;stroke-width:0.0680452"
inkscape:label="usb_logo" />
<text
xml:space="preserve"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:1.43163px;line-height:1.25;font-family:Play;-inkscape-font-specification:'Play, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.357908"
x="47.959785"
y="17.188828"
id="text982"
<g
aria-label="NS-USBloader"
transform="scale(0.97866107,1.0218042)"
inkscape:label="ns-usbloader"><tspan
sodipodi:role="line"
id="tspan980"
x="47.959785"
y="17.188828"
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:13.3619px;font-family:Play;-inkscape-font-specification:'Play, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;stroke-width:0.357908">NS-USBloader</tspan></text>
id="text982"
style="font-size:1.43163px;line-height:1.25;font-family:Play;-inkscape-font-specification:'Play, Normal';letter-spacing:0px;word-spacing:0px;fill:#ffffff;stroke-width:0.357908"
inkscape:label="ns-usbloader">
<path
d="M 56.49804,17.188828 H 54.934697 L 50.217947,9.9065918 V 17.188828 H 49.082185 V 8.5169542 h 1.563342 l 4.716751,7.1619788 V 8.5169542 h 1.135762 z"
style="font-size:13.3619px"
id="path880" />
<path
d="m 64.488451,14.249209 v 0.62801 q 0,1.389637 -0.788353,1.924113 -0.788352,0.521115 -2.458589,0.521115 -1.068952,0 -2.645656,-0.213791 v -1.082314 q 1.576704,0.334048 2.725827,0.334048 0.921971,0 1.403,-0.200429 0.49439,-0.21379 0.49439,-0.8418 v -1.122399 q 0,-0.547838 -0.320686,-0.77499 -0.307323,-0.240515 -1.122399,-0.240515 H 60.76048 q -1.309466,0 -1.83058,-0.521114 -0.507752,-0.534476 -0.507752,-1.563342 v -0.694819 q 0,-1.0288662 0.721542,-1.5232565 0.734905,-0.4943903 2.685742,-0.4943903 0.935333,0 2.231438,0.1469809 v 0.9754187 q -1.483171,-0.2271523 -2.324971,-0.2271523 -1.242657,0 -1.656876,0.2538761 -0.400857,0.2405142 -0.400857,0.8284374 v 0.988781 q 0,0.454305 0.320686,0.668095 0.320686,0.200429 1.135762,0.200429 h 1.042228 q 1.349552,0 1.83058,0.49439 0.481029,0.481028 0.481029,1.536618 z"
style="font-size:13.3619px"
id="path882" />
<path
d="m 69.472442,13.848352 h -3.714608 v -0.962056 h 3.714608 z"
style="font-size:13.3619px"
id="path884" />
<path
d="m 77.903799,8.5169542 v 6.4537978 q 0,2.351695 -3.393923,2.351695 -0.681456,0 -1.215932,-0.09353 -0.534476,-0.08017 -1.055591,-0.307323 -0.521114,-0.240515 -0.815076,-0.734905 -0.293961,-0.49439 -0.293961,-1.215933 V 8.5169542 h 1.242656 V 14.95739 q 0,0.855162 0.574562,1.175847 0.574562,0.320686 1.590066,0.320686 1.015505,0 1.563343,-0.320686 0.561199,-0.320685 0.561199,-1.175847 V 8.5169542 Z"
style="font-size:13.3619px"
id="path886" />
<path
d="m 85.907587,14.249209 v 0.62801 q 0,1.389637 -0.788352,1.924113 -0.788353,0.521115 -2.45859,0.521115 -1.068952,0 -2.645656,-0.213791 v -1.082314 q 1.576704,0.334048 2.725827,0.334048 0.921971,0 1.403,-0.200429 0.49439,-0.21379 0.49439,-0.8418 v -1.122399 q 0,-0.547838 -0.320686,-0.77499 -0.307323,-0.240515 -1.122399,-0.240515 h -1.015505 q -1.309466,0 -1.83058,-0.521114 -0.507752,-0.534476 -0.507752,-1.563342 v -0.694819 q 0,-1.0288662 0.721542,-1.5232565 0.734905,-0.4943903 2.685742,-0.4943903 0.935333,0 2.231438,0.1469809 v 0.9754187 q -1.483171,-0.2271523 -2.324971,-0.2271523 -1.242657,0 -1.656875,0.2538761 -0.400857,0.2405142 -0.400857,0.8284374 v 0.988781 q 0,0.454305 0.320685,0.668095 0.320686,0.200429 1.135762,0.200429 h 1.042228 q 1.349552,0 1.83058,0.49439 0.481029,0.481028 0.481029,1.536618 z"
style="font-size:13.3619px"
id="path888" />
<path
d="m 94.031625,14.008695 v 1.456447 q 0,0.948695 -0.721543,1.33619 -0.721542,0.387496 -2.351694,0.387496 H 87.764894 V 8.5169542 h 3.099961 q 1.122399,0 1.750409,0.2271523 0.641371,0.2271523 0.828437,0.5611998 0.200429,0.3340475 0.200429,0.8551617 v 1.162485 q 0,0.534476 -0.307324,0.815076 -0.293962,0.2806 -0.881885,0.414219 v 0.05345 q 0.694819,0.120257 1.135761,0.481028 0.440943,0.360771 0.440943,0.921971 z m -1.603428,-2.725827 v -1.015505 q 0,-0.4943902 -0.360771,-0.6948187 -0.360772,-0.2004285 -1.202571,-0.2004285 h -1.803857 v 2.9396182 h 1.843942 q 0.828438,0 1.175848,-0.240514 0.347409,-0.253876 0.347409,-0.788352 z m 0.307324,4.128827 v -1.309466 q 0,-0.34741 -0.146981,-0.547838 -0.133619,-0.213791 -0.440943,-0.293962 -0.293962,-0.09353 -0.534476,-0.106895 -0.227152,-0.02672 -0.654733,-0.02672 h -1.89739 v 3.16677 h 1.89739 q 0.975419,0 1.376276,-0.200428 0.400857,-0.200429 0.400857,-0.681457 z"
style="font-size:13.3619px"
id="path890" />
<path
d="M 97.07815,17.188828 H 95.875579 V 7.8354973 h 1.202571 z"
style="font-size:13.3619px"
id="path892" />
<path
d="m 104.8815,12.899658 v 2.244799 q 0,0.601285 -0.14698,1.015504 -0.14698,0.414219 -0.37413,0.641371 -0.22715,0.227153 -0.65474,0.34741 -0.41421,0.120257 -0.80171,0.146981 -0.37413,0.02672 -1.00214,0.02672 -0.80172,0 -1.25602,-0.05345 -0.44094,-0.05345 -0.895248,-0.253876 -0.440942,-0.213791 -0.641371,-0.668095 -0.187067,-0.454305 -0.187067,-1.202571 v -2.244799 q 0,-0.641372 0.146981,-1.082314 0.160343,-0.440943 0.374134,-0.681457 0.227152,-0.240515 0.654731,-0.360772 0.42758,-0.133619 0.78835,-0.160342 0.37414,-0.02672 1.01551,-0.02672 0.64137,0 1.00214,0.02672 0.37413,0.02672 0.80171,0.160342 0.42759,0.120257 0.64138,0.360772 0.22715,0.240514 0.37413,0.681457 0.16034,0.440942 0.16034,1.082314 z m -1.22929,2.418503 v -2.618932 q 0,-0.895247 -0.36077,-1.109038 -0.36078,-0.21379 -1.38964,-0.21379 -1.02887,0 -1.38964,0.21379 -0.36077,0.213791 -0.36077,1.109038 v 2.618932 q 0,0.427581 0.0935,0.681457 0.0935,0.253876 0.34741,0.374134 0.25388,0.106895 0.52112,0.133619 0.26723,0.02672 0.78835,0.02672 0.52111,0 0.78835,-0.02672 0.26724,-0.02672 0.52111,-0.133619 0.25388,-0.120258 0.34741,-0.374134 0.0935,-0.253876 0.0935,-0.681457 z"
style="font-size:13.3619px"
id="path894" />
<path
d="m 111.85643,17.188828 h -1.16249 V 16.57418 q -0.14698,0.748267 -1.95084,0.748267 -1.33619,0 -1.8573,-0.400857 -0.50775,-0.414219 -0.50775,-1.656876 0,-1.082314 0.48103,-1.483171 0.48103,-0.414219 1.8573,-0.414219 h 1.93748 v -1.028866 q 0,-0.534476 -0.33405,-0.721543 -0.32069,-0.187067 -1.2293,-0.187067 -0.98878,0 -2.21807,0.160343 v -0.881885 q 1.32283,-0.120257 2.39178,-0.120257 1.63015,0 2.11118,0.400857 0.48103,0.387495 0.48103,1.630152 z m -1.20257,-1.309467 V 14.11559 h -1.85731 q -0.82844,0 -1.04223,0.213791 -0.20042,0.21379 -0.20042,0.975419 0,0.681456 0.21379,0.962056 0.22715,0.267238 0.93533,0.267238 h 0.24051 q 0.34741,0 0.57456,-0.01336 0.24052,-0.01336 0.53448,-0.06681 0.29396,-0.06681 0.44094,-0.200429 0.16035,-0.14698 0.16035,-0.374134 z"
style="font-size:13.3619px"
id="path896" />
<path
d="m 119.59297,17.188828 h -1.17585 v -0.761629 q 0,0.34741 -0.58792,0.62801 -0.57456,0.267238 -1.5767,0.267238 -1.403,0 -1.97757,-0.440943 -0.57456,-0.440943 -0.57456,-1.61679 v -2.846085 q 0,-0.975419 0.60129,-1.402999 0.60128,-0.427581 2.01765,-0.427581 0.76162,0 1.40299,0.200428 0.65474,0.200429 0.6681,0.62801 h 0.0267 q -0.0267,-1.095676 -0.0267,-1.6435142 V 7.8354973 h 1.20257 z m -1.20257,-1.696962 v -3.193494 q 0,-0.868524 -1.77713,-0.868524 -1.06895,0 -1.403,0.160343 -0.32069,0.160343 -0.32069,0.708181 v 3.193494 q 0,0.547838 0.36077,0.77499 0.37414,0.227153 1.25602,0.227153 0.98878,0 1.42973,-0.227153 0.4543,-0.227152 0.4543,-0.77499 z"
style="font-size:13.3619px"
id="path898" />
<path
d="m 126.88855,14.222486 h -4.34261 v 0.975418 q 0,0.681457 0.48103,0.975419 0.48102,0.2806 1.42972,0.2806 0.92197,0 2.17799,-0.320686 v 0.921972 q -1.20257,0.267238 -2.33833,0.267238 -2.96635,0 -2.96635,-1.977562 v -2.552123 q 0,-1.189209 0.68146,-1.696961 0.68146,-0.507752 2.17799,-0.507752 1.403,0 2.04437,0.49439 0.65473,0.481028 0.65473,1.710323 z m -1.20257,-0.788352 v -1.015505 q 0,-0.587924 -0.36077,-0.801714 -0.36077,-0.227152 -1.20257,-0.227152 -0.80171,0 -1.18921,0.21379 -0.38749,0.213791 -0.38749,0.815076 v 1.015505 z"
style="font-size:13.3619px"
id="path900" />
<path
d="m 132.20659,11.616915 h -0.6681 q -0.82844,0 -1.22929,0.21379 -0.3875,0.213791 -0.3875,0.801715 v 4.556408 h -1.20257 v -6.46716 h 1.13576 v 1.05559 q 0,-0.467667 0.57456,-0.828438 0.58793,-0.360771 1.18921,-0.360771 h 0.58793 z"
style="font-size:13.3619px"
id="path902" />
</g>
<path
style="fill:#000000;fill-opacity:1;stroke-width:0.264583"
d="m 21.967046,0 c -0.0065,-1.9994448e-6 -0.01188,0.0054 -0.01188,0.01188 v 44.976581 c 0,0.0065 0.0054,0.01188 0.01188,0.01188 h 2.000395 c 0.0065,0 0.01188,-0.0054 0.01188,-0.01188 V 0.011885 c 0,-0.0065 -0.0054,-0.011879999445 -0.01188,-0.011879999445 z"
id="rect1136"
inkscape:connector-curvature="0"
sodipodi:nodetypes="csssssssc" />
<g
inkscape:label="CREATIVE_COMMONS_SHIELD"
transform="matrix(0.1713381,0,0,0.17131892,77.526533,36.479842)"
id="g287"
inkscape:export-filename="/mnt/hgfs/Bov/Documents/Work/2007/cc/identity/srr buttons/big/by-sa.png"
inkscape:export-xdpi="300.23013"
inkscape:export-ydpi="300.23013">
<path
id="path3817_2_"
nodetypes="ccccccc"
d="m 182.23532,75.39014 114.06396,0.20312 c 1.59375,0 3.01758,-0.23682 3.01758,3.18018 l -0.13965,37.56689 H 179.3569 V 78.63379 c 0,-1.68457 0.16309,-3.24365 2.87842,-3.24365 z"
style="fill:#aab2ab" />
<g
id="g5908_2_"
transform="matrix(0.872921,0,0,0.872921,50.12536,143.2144)">
<path
id="path5906_2_"
cx="296.35416"
ry="22.939548"
cy="264.3577"
type="arc"
rx="22.939548"
d="m 187.20944,-55.6792 c 0.006,8.68024 -7.02786,15.72095 -15.7081,15.72708 -8.68021,0.005 -15.72205,-7.02786 -15.72708,-15.70804 0,-0.0067 0,-0.01233 0,-0.01904 -0.005,-8.68134 7.02783,-15.72205 15.70807,-15.72711 8.68134,-0.0056 15.72208,7.02789 15.72711,15.70807 0,0.0056 0,0.01233 0,0.01904 z"
style="fill:#ffffff" />
<g
id="g5706_2_"
transform="translate(-289.6157,99.0653)">
<path
id="path5708_2_"
d="m 473.88455,-167.54724 c 3.48541,3.48596 5.22839,7.75391 5.22839,12.80273 0,5.04938 -1.7128,9.27148 -5.13834,12.66736 -3.63531,3.5766 -7.93179,5.36432 -12.88947,5.36432 -4.89777,0 -9.11987,-1.77261 -12.6651,-5.31955 -3.54584,-3.54581 -5.31845,-7.78299 -5.31845,-12.71213 0,-4.92859 1.77261,-9.19598 5.31845,-12.80273 3.4552,-3.48651 7.67725,-5.22894 12.6651,-5.22894 5.04829,0 9.31401,1.74243 12.79942,5.22894 z m -23.11798,2.34485 c -2.94675,2.97638 -4.41956,6.46289 -4.41956,10.46234 0,3.99835 1.45828,7.4552 4.37424,10.37067 2.91653,2.9165 6.38849,4.37476 10.41705,4.37476 4.02853,0 7.53018,-1.47281 10.50656,-4.41901 2.8259,-2.73584 4.23941,-6.17706 4.23941,-10.32642 0,-4.11804 -1.43646,-7.61292 -4.30768,-10.48474 -2.87064,-2.87067 -6.34988,-4.30652 -10.43829,-4.30652 -4.08837,0 -7.54638,1.44318 -10.37173,4.32892 z m 7.75449,8.70312 c -0.45032,-0.98163 -1.12433,-1.47223 -2.02325,-1.47223 -1.58914,0 -2.38342,1.06952 -2.38342,3.2085 0,2.13959 0.79428,3.20911 2.38342,3.20911 1.04938,0 1.79895,-0.5213 2.24866,-1.56512 l 2.20276,1.17303 c -1.04993,1.86548 -2.62506,2.79901 -4.72549,2.79901 -1.6199,0 -2.91763,-0.4967 -3.89206,-1.48956 -0.97607,-0.99341 -1.46274,-2.36273 -1.46274,-4.10797 0,-1.71558 0.50229,-3.07709 1.50748,-4.08563 1.00519,-1.00793 2.25705,-1.51251 3.75781,-1.51251 2.22012,0 3.80984,0.87488 4.77081,2.62286 z m 10.36334,0 c -0.45087,-0.98163 -1.11148,-1.47223 -1.98239,-1.47223 -1.62106,0 -2.43213,1.06952 -2.43213,3.2085 0,2.13959 0.81107,3.20911 2.43213,3.20911 1.05103,0 1.78717,-0.5213 2.20724,-1.56512 l 2.25201,1.17303 c -1.04825,1.86548 -2.62119,2.79901 -4.71768,2.79901 -1.61771,0 -2.91263,-0.4967 -3.88647,-1.48956 -0.97217,-0.99341 -1.45938,-2.36273 -1.45938,-4.10797 0,-1.71558 0.49448,-3.07709 1.48288,-4.08563 0.98782,-1.00793 2.24527,-1.51251 3.77347,-1.51251 2.21619,0 3.80368,0.87488 4.76132,2.62286 z" />
</g>
</g>
<path
d="M 297.29639,74.91064 H 181.06688 c -1.24658,0 -2.26074,1.01465 -2.26074,2.26123 v 39.49561 c 0,0.28174 0.22852,0.51074 0.51025,0.51074 h 119.73 c 0.28174,0 0.51074,-0.229 0.51074,-0.51074 v -39.4956 c 0,-1.24659 -1.01416,-2.26124 -2.26074,-2.26124 z m -116.22951,1.02149 h 116.22951 c 0.68359,0 1.23926,0.55615 1.23926,1.23975 0,0 0,15.91943 0,27.41846 H 215.4619 c -3.04492,5.50537 -8.91113,9.24365 -15.64355,9.24365 -6.73535,0 -12.6001,-3.73486 -15.64355,-9.24365 h -4.34814 c 0,-11.49902 0,-27.41846 0,-27.41846 -2e-5,-0.6836 0.55663,-1.23975 1.24022,-1.23975 z"
id="path294" />
<g
enable-background="new "
id="g296">
<path
d="m 265.60986,112.8833 c 0.0801,0.15576 0.1875,0.28174 0.32129,0.37842 0.13379,0.0962 0.29004,0.16797 0.46973,0.21436 0.18066,0.0469 0.36719,0.0703 0.55957,0.0703 0.12988,0 0.26953,-0.0107 0.41895,-0.0327 0.14844,-0.0215 0.28809,-0.064 0.41895,-0.12598 0.12988,-0.062 0.23926,-0.14795 0.3252,-0.25684 0.0879,-0.10889 0.13086,-0.24707 0.13086,-0.41553 0,-0.18018 -0.0576,-0.32617 -0.17285,-0.43848 -0.11426,-0.1123 -0.26562,-0.20508 -0.45215,-0.28027 -0.18555,-0.0742 -0.39746,-0.13965 -0.63281,-0.1958 -0.23633,-0.0562 -0.47559,-0.11816 -0.71777,-0.18701 -0.24902,-0.062 -0.49121,-0.13818 -0.72754,-0.22852 -0.23535,-0.0898 -0.44727,-0.20703 -0.63379,-0.3501 -0.18652,-0.14307 -0.33691,-0.32178 -0.45215,-0.53662 -0.11426,-0.21484 -0.17188,-0.47461 -0.17188,-0.7793 0,-0.34277 0.0732,-0.63965 0.21875,-0.8916 0.14648,-0.25195 0.33789,-0.46191 0.57422,-0.63037 0.23535,-0.16797 0.50293,-0.29248 0.80176,-0.37354 0.29785,-0.0806 0.59668,-0.12109 0.89453,-0.12109 0.34863,0 0.68262,0.0391 1.00293,0.11719 0.31934,0.0776 0.60449,0.2041 0.85254,0.37842 0.24902,0.17432 0.44629,0.39697 0.59277,0.66797 0.14551,0.271 0.21875,0.59961 0.21875,0.98535 h -1.42188 c -0.0127,-0.19922 -0.0547,-0.36426 -0.125,-0.49463 -0.0713,-0.13086 -0.16602,-0.2334 -0.2832,-0.30859 -0.11816,-0.0742 -0.25293,-0.12744 -0.4043,-0.1582 -0.15234,-0.0312 -0.31738,-0.0469 -0.49707,-0.0469 -0.11719,0 -0.23535,0.0127 -0.35254,0.0371 -0.11816,0.0254 -0.22461,0.0688 -0.32031,0.13086 -0.0967,0.0625 -0.17578,0.14014 -0.2373,0.2334 -0.0615,0.0937 -0.0928,0.21191 -0.0928,0.35498 0,0.13086 0.0244,0.23682 0.0742,0.31738 0.0498,0.0811 0.14844,0.15576 0.29395,0.22412 0.14551,0.0684 0.34766,0.13721 0.60547,0.20557 0.25781,0.0684 0.59473,0.15576 1.01172,0.26123 0.12402,0.0249 0.2959,0.0703 0.5166,0.13574 0.2207,0.0654 0.43945,0.16943 0.65723,0.3125 0.21777,0.14355 0.40527,0.33496 0.56445,0.57422 0.1582,0.23975 0.2373,0.54639 0.2373,0.91992 0,0.30518 -0.0596,0.58838 -0.17773,0.84961 -0.11816,0.26172 -0.29395,0.4873 -0.52734,0.67676 -0.2334,0.19043 -0.52246,0.33789 -0.86719,0.44385 -0.3457,0.10596 -0.74609,0.15869 -1.19922,0.15869 -0.36719,0 -0.72363,-0.0454 -1.06934,-0.13574 -0.34473,-0.0903 -0.65039,-0.23242 -0.91504,-0.42578 -0.26367,-0.19336 -0.47363,-0.43994 -0.62988,-0.73877 -0.15527,-0.29932 -0.22949,-0.65381 -0.22363,-1.06494 h 1.42188 c -3e-5,0.22412 0.04,0.41406 0.12106,0.56933 z"
id="path298"
style="fill:#ffffff" />
<path
d="m 273.8667,107.8667 2.49316,6.66406 h -1.52246 l -0.50391,-1.48438 h -2.49316 l -0.52246,1.48438 h -1.47461 l 2.52051,-6.66406 z m 0.084,4.08594 -0.83984,-2.44336 h -0.0186 l -0.86914,2.44336 z"
id="path300"
style="fill:#ffffff" />
</g>
<g
enable-background="new "
id="g302">
<path
d="m 239.17821,107.8667 c 0.31738,0 0.60742,0.0283 0.86914,0.084 0.26172,0.0561 0.48633,0.14795 0.67383,0.27539 0.18652,0.12744 0.33203,0.29688 0.43457,0.5083 0.10254,0.21142 0.1543,0.47266 0.1543,0.78369 0,0.33594 -0.0762,0.61523 -0.22949,0.83936 -0.15234,0.22412 -0.37891,0.40723 -0.67773,0.55029 0.41211,0.11816 0.71973,0.3252 0.92285,0.62109 0.20312,0.29589 0.30469,0.65234 0.30469,1.06934 0,0.33594 -0.0654,0.62695 -0.19629,0.87305 -0.13086,0.24561 -0.30762,0.44629 -0.52832,0.60205 -0.22168,0.15576 -0.47461,0.271 -0.75781,0.34521 -0.28418,0.0752 -0.5752,0.1123 -0.875,0.1123 h -3.23633 v -6.66406 h 3.14159 z m -0.1875,2.69531 c 0.26172,0 0.47656,-0.062 0.64551,-0.18604 0.16797,-0.12451 0.25195,-0.32568 0.25195,-0.60498 0,-0.15527 -0.0283,-0.28271 -0.084,-0.38184 -0.0566,-0.0996 -0.13086,-0.17676 -0.22461,-0.23291 -0.0937,-0.0557 -0.20117,-0.0947 -0.32227,-0.11621 -0.12207,-0.022 -0.24805,-0.0327 -0.37891,-0.0327 h -1.37305 v 1.55469 z m 0.0859,2.82813 c 0.14355,0 0.28027,-0.0137 0.41113,-0.042 0.13086,-0.0278 0.24707,-0.0747 0.34668,-0.13965 0.0996,-0.0654 0.17871,-0.1543 0.23828,-0.26611 0.0596,-0.11181 0.0889,-0.25488 0.0889,-0.4292 0,-0.3418 -0.0967,-0.58594 -0.29004,-0.73193 -0.19336,-0.14599 -0.44922,-0.21924 -0.7666,-0.21924 h -1.59961 v 1.82812 z"
id="path304"
style="fill:#ffffff" />
<path
d="m 241.88914,107.8667 h 1.64355 l 1.56055,2.63184 1.55078,-2.63184 h 1.63379 l -2.47363,4.10645 v 2.55762 h -1.46875 v -2.59473 z"
id="path306"
style="fill:#ffffff" />
</g>
<g
id="g6316_1_"
transform="matrix(0.624995,0,0,0.624995,391.2294,176.9332)">
<path
id="path6318_1_"
cx="475.97119"
ry="29.209877"
cy="252.08646"
type="arc"
rx="29.209877"
d="m -175.0083,-139.1153 c 0.006,9.4118 -7.61725,17.04779 -17.02982,17.05481 -9.41101,0.007 -17.047,-7.61725 -17.05481,-17.02979 0,-0.008 0,-0.0172 0,-0.025 -0.006,-9.41254 7.6188,-17.047 17.02982,-17.05481 9.41257,-0.007 17.04855,7.61804 17.05481,17.02985 0,0.009 0,0.0164 0,0.025 z"
style="fill:#ffffff" />
<g
id="g6320_1_"
transform="translate(-23.9521,-89.72962)">
<path
id="path6322_1_"
d="m -168.2204,-68.05536 c -5.17194,0 -9.54852,1.80469 -13.13135,5.41333 -3.67661,3.73444 -5.51413,8.1532 -5.51413,13.25635 0,5.10315 1.83752,9.49152 5.51413,13.1626 3.67502,3.67194 8.05316,5.50787 13.13135,5.50787 5.14066,0 9.59537,-1.85156 13.36728,-5.55475 3.55005,-3.51562 5.3266,-7.88831 5.3266,-13.11572 0,-5.22662 -1.8078,-9.64697 -5.42191,-13.25635 -3.61407,-3.60864 -8.03756,-5.41333 -13.27197,-5.41333 z m 0.0469,3.36017 c 4.23752,0 7.836,1.49298 10.79697,4.48053 2.98907,2.9563 4.48441,6.56567 4.48441,10.82898 0,4.29382 -1.46252,7.85712 -4.39224,10.68915 -3.08438,3.04926 -6.71411,4.57349 -10.88913,4.57349 -4.17505,0 -7.7735,-1.5094 -10.79541,-4.52661 -3.02188,-3.01953 -4.53284,-6.59692 -4.53284,-10.73602 0,-4.13831 1.52658,-7.74847 4.57971,-10.82898 2.92815,-2.98756 6.51098,-4.48054 10.74853,-4.48054 z" />
<path
id="path6324_1_"
d="m -176.49548,-52.02087 c 0.74377,-4.69769 4.05161,-7.20862 8.1954,-7.20862 5.96097,0 9.59225,4.32501 9.59225,10.09229 0,5.62738 -3.86411,9.99927 -9.686,9.99927 -4.00473,0 -7.58914,-2.46484 -8.24228,-7.30084 h 4.70319 c 0.14062,2.51099 1.77032,3.39459 4.09845,3.39459 2.65317,0 4.37817,-2.4649 4.37817,-6.23291 0,-3.95233 -1.49063,-6.04535 -4.28598,-6.04535 -2.04846,0 -3.8172,0.74457 -4.19064,3.30157 l 1.36874,-0.007 -3.70316,3.7016 -3.7016,-3.7016 z" />
</g>
</g>
<g
id="g313">
<circle
cx="242.56226"
cy="90.224609"
r="10.8064"
id="circle315"
style="fill:#ffffff" />
<g
id="g317">
<path
d="m 245.68994,87.09766 c 0,-0.4165 -0.33789,-0.75342 -0.75391,-0.75342 h -4.77246 c -0.41602,0 -0.75391,0.33691 -0.75391,0.75342 v 4.77295 h 1.33105 v 5.65234 h 3.61719 v -5.65234 h 1.33203 v -4.77295 z"
id="path319" />
<circle
cx="242.5498"
cy="84.083008"
r="1.63232"
id="circle321" />
</g>
<path
clip-rule="evenodd"
d="m 242.53467,78.31836 c -3.23145,0 -5.96826,1.12744 -8.20752,3.38379 -2.29785,2.33301 -3.44629,5.09521 -3.44629,8.28418 0,3.18897 1.14844,5.93213 3.44629,8.22705 2.29785,2.29443 5.03418,3.44189 8.20752,3.44189 3.21289,0 5.99805,-1.15674 8.35352,-3.47168 2.2207,-2.19678 3.33008,-4.92969 3.33008,-8.19727 0,-3.26758 -1.12891,-6.02881 -3.3877,-8.28418 -2.25879,-2.25634 -5.02442,-3.38378 -8.2959,-3.38378 z m 0.0293,2.09961 c 2.64844,0 4.89746,0.93359 6.74707,2.80078 1.87012,1.84717 2.80469,4.10352 2.80469,6.76758 0,2.68359 -0.91504,4.91113 -2.74609,6.68066 -1.92773,1.90576 -4.19629,2.8584 -6.80566,2.8584 -2.60937,0 -4.8584,-0.94287 -6.74658,-2.82959 -1.88965,-1.88623 -2.8335,-4.12256 -2.8335,-6.70947 0,-2.58643 0.9541,-4.84229 2.8623,-6.76758 1.83057,-1.86719 4.07031,-2.80078 6.71777,-2.80078 z"
id="path323"
style="fill-rule:evenodd" />
</g>
</g>
<text
inkscape:label="HeyMomLookAtMe"
inkscape:transform-center-y="-0.1984375"
inkscape:transform-center-x="-0.33072917"
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:2.82222px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="108.57767"
y="48.318489"
id="text921"><tspan
sodipodi:role="line"
x="108.57767"
y="48.318489"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:2.82222px;font-family:'Nunito Sans';-inkscape-font-specification:'Nunito Sans Bold';stroke-width:0.264583"
id="tspan923">Dmitry Isaenko</tspan></text>
</svg>

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Before After
Before After

View file

@ -18,6 +18,8 @@
*/
package nsusbloader;
import javafx.scene.text.Font;
import java.util.Locale;
import java.util.prefs.Preferences;
@ -27,41 +29,47 @@ public class AppPreferences {
private final Preferences preferences;
private final Locale locale;
public static final String[] goldleafSupportedVersions = {"v0.5", "v0.7.x", "v0.8"};
public static final String[] GOLDLEAF_SUPPORTED_VERSIONS = {"v0.5", "v0.7.x", "v0.8-0.9", "v0.10+"};
private static final Font DEFAULT_FONT = Font.getDefault();
private AppPreferences(){
this.preferences = Preferences.userRoot().node("NS-USBloader");
String localeCode = preferences.get("locale", Locale.getDefault().toString());
this.locale = new Locale(localeCode.substring(0, 2), localeCode.substring(3, 5));
if (localeCode.length() < 5)
this.locale = new Locale("en", "EN");
else
this.locale = new Locale(localeCode.substring(0, 2), localeCode.substring(3));
}
public String getTheme(){
String theme = preferences.get("THEME", "/res/app_dark.css"); // Don't let user to change settings manually
String theme = preferences.get("THEME", "/res/app_dark.css"); // Don't let user change settings manually
if (!theme.matches("(^/res/app_dark.css$)|(^/res/app_light.css$)"))
theme = "/res/app_dark.css";
return theme;
}
public String getProtocol(){
String protocol = preferences.get("PROTOCOL", "TinFoil"); // Don't let user to change settings manually
if (!protocol.matches("(^TinFoil$)|(^GoldLeaf$)"))
protocol = "TinFoil";
return protocol;
public int getProtocol(){
int protocolIndex = preferences.getInt("protocol_index", 0); // Don't let user change settings manually
if (protocolIndex < 0 || protocolIndex > 1)
protocolIndex = 0;
return protocolIndex;
}
public void setProtocol(int protocolIndex){ preferences.putInt("protocol_index", protocolIndex); }
public String getNetUsb(){
String netUsb = preferences.get("NETUSB", "USB"); // Don't let user to change settings manually
String netUsb = preferences.get("NETUSB", "USB"); // Don't let user change settings manually
if (!netUsb.matches("(^USB$)|(^NET$)"))
netUsb = "USB";
return netUsb;
}
public void setTheme(String theme){ preferences.put("THEME", theme); }
public void setProtocol(String protocol){ preferences.put("PROTOCOL", protocol); }
public void setNetUsb(String netUsb){ preferences.put("NETUSB", netUsb); }
public void setNsIp(String ip){preferences.put("NSIP", ip);}
public String getNsIp(){return preferences.get("NSIP", "192.168.1.42");}
public String getRecent(){ return preferences.get("RECENT", System.getProperty("user.home")); }
public String getRecent(){ return FilesHelper.getRealFolder(preferences.get("RECENT", System.getProperty("user.home"))); }
public void setRecent(String path){ preferences.put("RECENT", path); }
//------------ SETTINGS ------------------//
@ -102,18 +110,19 @@ public class AppPreferences {
public boolean getAutoCheckUpdates(){return preferences.getBoolean("AUTOCHECK4UPDATES", false); }
public void setAutoCheckUpdates(boolean prop){preferences.putBoolean("AUTOCHECK4UPDATES", prop); }
public boolean getDirectoriesChooserForRoms(){return preferences.getBoolean("dirchooser4roms", false); }
public void setDirectoriesChooserForRoms(boolean prop){preferences.putBoolean("dirchooser4roms", prop); }
public boolean getTfXCI(){return preferences.getBoolean("TF_XCI", true);}
public void setTfXCI(boolean prop){ preferences.putBoolean("TF_XCI", prop); }
public boolean getNspFileFilterGL(){return preferences.getBoolean("GL_NSP_FILTER", false); }
public void setNspFileFilterGL(boolean prop){preferences.putBoolean("GL_NSP_FILTER", prop);}
public String getGlVersion(){
int recentGlVersionIndex = goldleafSupportedVersions.length - 1;
String recentGlVersion = goldleafSupportedVersions[recentGlVersionIndex];
return preferences.get("gl_version", recentGlVersion);
public int getGlVersion(){
return preferences.getInt("gl_ver", GOLDLEAF_SUPPORTED_VERSIONS.length - 1);
}
public void setGlVersion(String version){ preferences.put("gl_version", version);}
public void setGlVersion(int version){ preferences.putInt("gl_ver", version);}
public double getSceneWidth(){ return preferences.getDouble("WIND_WIDTH", 850.0); }
public void setSceneWidth(double value){ preferences.putDouble("WIND_WIDTH", value); }
@ -124,12 +133,39 @@ public class AppPreferences {
public int getSplitMergeType(){ return preferences.getInt("SM_TYPE", 0); }
public void setSplitMergeType(int value){ preferences.putInt("SM_TYPE", value); }
public String getSplitMergeRecent(){ return preferences.get("SM_RECENT", System.getProperty("user.home")); }
public String getSplitMergeRecent(){ return FilesHelper.getRealFolder(preferences.get("SM_RECENT", System.getProperty("user.home"))); }
public void setSplitMergeRecent(String value){ preferences.put("SM_RECENT", value); }
// RCM //
public String getRecentRcm(int num){ return preferences.get(String.format("RCM_%02d", num), ""); }
public void setRecentRcm(int num, String value){ preferences.put(String.format("RCM_%02d", num), value); }
// NXDT //
public String getNXDTSaveToLocation(){ return preferences.get("nxdt_saveto", System.getProperty("user.home")); }
public String getNXDTSaveToLocation(){ return FilesHelper.getRealFolder(preferences.get("nxdt_saveto", System.getProperty("user.home"))); }
public void setNXDTSaveToLocation(String value){ preferences.put("nxdt_saveto", value); }
public String getLastOpenedTab(){ return preferences.get("recent_tab", ""); }
public void setLastOpenedTab(String tabId){ preferences.put("recent_tab", tabId); }
// Patches
public String getKeysLocation(){ return preferences.get("keys", ""); }
public void setKeysLocation(String path){ preferences.put("keys", path); }
public String getPatchesSaveToLocation(){ return FilesHelper.getRealFolder(preferences.get("patches_saveto", System.getProperty("user.home"))); }
public void setPatchesSaveToLocation(String value){ preferences.put("patches_saveto", value); }
public boolean getPatchesTabInvisible(){return preferences.getBoolean("patches_tab_visible", true); }
public void setPatchesTabInvisible(boolean value){preferences.putBoolean("patches_tab_visible", value);}
public String getPatchPattern(String type, int moduleNumber, int offsetId){ return preferences.get(String.format("%s_%02x_%02x", type, moduleNumber, offsetId), ""); }
public void setPatchPattern(String fullTypeSpecifier, String offset){ preferences.put(fullTypeSpecifier, offset); }
public String getFontFamily(){ return preferences.get("font_family", DEFAULT_FONT.getFamily()); }
public double getFontSize(){ return preferences.getDouble("font_size", DEFAULT_FONT.getSize()); }
public String getFontStyle(){
final String fontFamily = preferences.get("font_family", DEFAULT_FONT.getFamily());
final double fontSize = preferences.getDouble("font_size", DEFAULT_FONT.getSize());
return String.format("-fx-font-family: \"%s\"; -fx-font-size: %.0f;", fontFamily, fontSize);
}
public void setFontStyle(String fontFamily, double size){
preferences.put("font_family", fontFamily);
preferences.putDouble("font_size", size);
}
}

View file

@ -1,72 +0,0 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.COM.USB;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EFileStatus;
import nsusbloader.NSLDataTypes.EMsgType;
import org.usb4java.DeviceHandle;
import java.io.File;
import java.util.*;
public abstract class TransferModule {
EFileStatus status = EFileStatus.UNKNOWN;
LinkedHashMap<String, File> nspMap;
ILogPrinter logPrinter;
DeviceHandle handlerNS;
CancellableRunnable task;
TransferModule(DeviceHandle handler, LinkedHashMap<String, File> nspMap, CancellableRunnable task, ILogPrinter printer){
this.handlerNS = handler;
this.nspMap = nspMap;
this.task = task;
this.logPrinter = printer;
// Validate split files to be sure that there is no crap
//logPrinter.print("TransferModule: Validating split files ...", EMsgType.INFO); // NOTE: Used for debug
Iterator<Map.Entry<String, File>> iterator = nspMap.entrySet().iterator();
while (iterator.hasNext()){
File f = iterator.next().getValue();
if (f.isDirectory()){
File[] subFiles = f.listFiles((file, name) -> name.matches("[0-9]{2}"));
if (subFiles == null || subFiles.length == 0) {
logPrinter.print("TransferModule: Removing empty folder: " + f.getName(), EMsgType.WARNING);
iterator.remove();
}
else {
Arrays.sort(subFiles, Comparator.comparingInt(file -> Integer.parseInt(file.getName())));
for (int i = subFiles.length - 2; i > 0 ; i--){
if (subFiles[i].length() < subFiles[i-1].length()) {
logPrinter.print("TransferModule: Removing strange split file: "+f.getName()+
"\n (Chunk sizes of the split file are not the same, but has to be.)", EMsgType.WARNING);
iterator.remove();
} // what
} // a
} // nice
} // stairway
} // here =)
//logPrinter.print("TransferModule: Validation complete.", EMsgType.INFO); // NOTE: Used for debug
}
public EFileStatus getStatus(){ return status; }
}

View file

@ -0,0 +1,102 @@
/*
Copyright 2019-2021 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
public class BlockListViewController implements Initializable {
@FXML
private ListView<File> splitMergeListView;
private ObservableList<File> filesList;
private ResourceBundle resourceBundle;
private static class FileListCell extends ListCell<File>{
@Override
public void updateItem(File file, boolean isEmpty){
super.updateItem(file, isEmpty);
if (file == null || isEmpty){
setText(null);
return;
}
String fileName = file.getName();
setText(fileName);
}
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
setFilesListView();
filesList = splitMergeListView.getItems();
}
private void setFilesListView(){
splitMergeListView.setCellFactory(fileListView -> {
ListCell<File> item = new FileListCell();
setContextMenuToItem(item);
return item;
});
}
private <T> void setContextMenuToItem(ListCell<T> item){
ContextMenu contextMenu = new ContextMenu();
MenuItem deleteMenuItem = new MenuItem(resourceBundle.getString("tab1_table_contextMenu_Btn_BtnDelete"));
deleteMenuItem.setOnAction(actionEvent -> {
filesList.remove(item.getItem());
splitMergeListView.refresh();
});
MenuItem deleteAllMenuItem = new MenuItem(resourceBundle.getString("tab1_table_contextMenu_Btn_DeleteAll"));
deleteAllMenuItem.setOnAction(actionEvent -> {
filesList.clear();
splitMergeListView.refresh();
});
contextMenu.getItems().addAll(deleteMenuItem, deleteAllMenuItem);
item.setContextMenu(contextMenu);
}
public void add(File file){
if (filesList.contains(file))
return;
filesList.add(file);
}
public void addAll(List<File> files){
for (File file : files) {
add(file);
}
}
public ObservableList<File> getItems(){ return filesList; }
public void clear(){
filesList.clear();
splitMergeListView.refresh();
}
}

View file

@ -0,0 +1,119 @@
/*
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import nsusbloader.AppPreferences;
import nsusbloader.MediatorControl;
import java.io.File;
import java.util.List;
import java.util.ResourceBundle;
public class FilesDropHandle {
public FilesDropHandle(List<File> files,
String filesRegex,
String foldersRegex,
NSTableViewController tableController){
FilesDropHandleTask filesDropHandleTask = new FilesDropHandleTask(files, filesRegex, foldersRegex);
ResourceBundle resourceBundle = MediatorControl.INSTANCE.getResourceBundle();
Button cancelButton = new Button(resourceBundle.getString("btn_Cancel"));
ProgressIndicator progressIndicator = new ProgressIndicator();
progressIndicator.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS);
Label statusLabel = new Label();
statusLabel.setWrapText(true);
statusLabel.setTextAlignment(TextAlignment.CENTER);
statusLabel.textProperty().bind(filesDropHandleTask.messageProperty());
Pane fillerPane1 = new Pane();
Pane fillerPane2 = new Pane();
VBox parentVBox = new VBox();
parentVBox.setAlignment(Pos.TOP_CENTER);
parentVBox.setFillWidth(true);
parentVBox.setSpacing(5.0);
parentVBox.setPadding(new Insets(5.0));
parentVBox.setFillWidth(true);
parentVBox.getChildren().addAll(
statusLabel,
fillerPane1,
progressIndicator,
fillerPane2,
cancelButton
);
VBox.setVgrow(fillerPane1, Priority.ALWAYS);
VBox.setVgrow(fillerPane2, Priority.ALWAYS);
Stage stage = new Stage();
stage.setTitle(resourceBundle.getString("windowTitleAddingFiles"));
stage.getIcons().addAll(
new Image("/res/info_ico32x32.png"),
new Image("/res/info_ico48x48.png"),
new Image("/res/info_ico64x64.png"),
new Image("/res/info_ico128x128.png")
);
stage.setMinWidth(300);
stage.setMinHeight(175);
stage.setAlwaysOnTop(true);
Scene mainScene = new Scene(parentVBox, 310, 185);
mainScene.getStylesheets().add(AppPreferences.getInstance().getTheme());
parentVBox.setStyle(AppPreferences.getInstance().getFontStyle());
stage.setOnHidden(windowEvent -> filesDropHandleTask.cancel(true ) );
stage.setScene(mainScene);
stage.show();
stage.toFront();
filesDropHandleTask.setOnSucceeded(event -> {
cancelButton.setText(resourceBundle.getString("btn_Close"));
List<File> allFiles = filesDropHandleTask.getValue();
if (! allFiles.isEmpty()) {
tableController.setFiles(allFiles);
}
stage.close();
});
new Thread(filesDropHandleTask).start();
cancelButton.setOnAction(actionEvent -> {
filesDropHandleTask.cancel(true);
stage.close();
});
}
}

View file

@ -0,0 +1,96 @@
/*
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import javafx.concurrent.Task;
import nsusbloader.MediatorControl;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FilesDropHandleTask extends Task<List<File>> {
private final String filesRegex;
private final String foldersRegex;
private final List<File> filesDropped;
private final List<File> allFiles;
private final String messageTemplate;
private long filesScanned = 0;
private long filesAdded = 0;
FilesDropHandleTask(List<File> files,
String filesRegex,
String foldersRegex) {
this.filesDropped = files;
this.filesRegex = filesRegex;
this.foldersRegex = foldersRegex;
this.allFiles = new ArrayList<>();
this.messageTemplate = MediatorControl.INSTANCE.getResourceBundle().getString("windowBodyFilesScanned");
}
@Override
protected List<File> call() {
if (filesDropped == null || filesDropped.isEmpty())
return allFiles;
for (File file : filesDropped){
if (isCancelled())
return new ArrayList<>();
collectFiles(file);
updateMessage(String.format(messageTemplate, filesScanned++, filesAdded));
}
return allFiles;
}
private void collectFiles(File startFolder) {
if (startFolder == null)
return;
final String startFolderNameInLowercase = startFolder.getName().toLowerCase();
if (startFolder.isFile()) {
if (startFolderNameInLowercase.matches(filesRegex)) {
allFiles.add(startFolder);
filesAdded++;
}
return;
}
if (startFolderNameInLowercase.matches(foldersRegex)) {
allFiles.add(startFolder);
filesAdded++;
return;
}
File[] files = startFolder.listFiles();
if (files == null)
return;
for (File file : files) {
if (isCancelled())
return;
collectFiles(file);
updateMessage(String.format(messageTemplate, filesScanned++, filesAdded));
}
}
}

View file

@ -0,0 +1,56 @@
/*
Copyright 2019-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import nsusbloader.AppPreferences;
import java.util.ResourceBundle;
public class FontSettings {
public FontSettings(ResourceBundle resourceBundle) throws Exception{
Stage stage = new Stage();
stage.setMinWidth(650);
stage.setMinHeight(450);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/FontSettings.fxml"));
fxmlLoader.setResources(resourceBundle);
stage.setTitle(resourceBundle.getString("tab2_Btn_ApplicationFont"));
stage.getIcons().addAll(
new Image("/res/app_icon32x32.png"),
new Image("/res/app_icon48x48.png"),
new Image("/res/app_icon64x64.png"),
new Image("/res/app_icon128x128.png"));
Parent parent = fxmlLoader.load();
Scene fontScene = new Scene(parent, 660, 525);
fontScene.getStylesheets().add(AppPreferences.getInstance().getTheme());
parent.setStyle(AppPreferences.getInstance().getFontStyle());
stage.setAlwaysOnTop(true);
stage.setScene(fontScene);
stage.show();
}
}

View file

@ -0,0 +1,155 @@
/*
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import nsusbloader.AppPreferences;
import nsusbloader.MediatorControl;
import java.net.URL;
import java.util.ResourceBundle;
public class FontSettingsController implements Initializable {
private final AppPreferences preferences = AppPreferences.getInstance();
@FXML
private Button applyBtn, cancelBtn, resetBtn;
@FXML
private ListView<String> fontsLv;
@FXML
private Spinner<Double> fontSizeSpinner;
@FXML
private Text exampleText;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
applyBtn.setDefaultButton(true);
applyBtn.getStyleClass().add("buttonUp");
applyBtn.setOnAction(e -> applyChanges());
cancelBtn.setCancelButton(true);
cancelBtn.setOnAction(e -> closeWindow());
resetBtn.setOnAction(e -> reset());
fontsLv.setCellFactory(item -> getCellFactory());
fontsLv.setItems(getFonts());
fontsLv.getSelectionModel().select(preferences.getFontFamily());
fontsLv.getSelectionModel().selectedIndexProperty().addListener(
(observableValue, oldValueNumber, newValueNumber) -> setExampleTextFont());
fontsLv.setFixedCellSize(40.0);
fontSizeSpinner.setEditable(false);
fontSizeSpinner.setValueFactory(getValueFactory());
exampleText.setText(resourceBundle.getString("fontPreviewText"));
fontSizeSpinner.getValueFactory().setValue(preferences.getFontSize());
}
private ListCell<String> getCellFactory(){
return new ListCell<>(){
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null)
return;
Font font = Font.font(item);
Text itemText = new Text(item);
itemText.setFont(font);
setGraphic(itemText);
}
};
}
private ObservableList<String> getFonts(){
ObservableList<String> fonts = FXCollections.observableArrayList();
fonts.addAll(Font.getFamilies());
return fonts;
}
private SpinnerValueFactory<Double> getValueFactory(){
return new SpinnerValueFactory<>() {
@Override
public void decrement(int i) {
double value = getValue() - i;
if (value < 4)
return;
setValue(value);
setExampleTextFont(value);
}
@Override
public void increment(int i) {
double value = getValue() + i;
if (value > 100)
return;
setValue(value);
setExampleTextFont(value);
}
};
}
private void setExampleTextFont(){
setExampleTextFont(fontsLv.getSelectionModel().getSelectedItem(), fontSizeSpinner.getValue());
}
private void setExampleTextFont(double size){
setExampleTextFont(fontsLv.getSelectionModel().getSelectedItem(), size);
}
private void setExampleTextFont(String font, double size){
exampleText.setFont(Font.font(font, size));
}
private void reset(){
final Font defaultFont = Font.getDefault();
exampleText.setFont(defaultFont);
fontsLv.getSelectionModel().select(defaultFont.getFamily());
fontSizeSpinner.getValueFactory().setValue(defaultFont.getSize());
}
private void applyChanges(){
final String fontFamily = fontsLv.getSelectionModel().getSelectedItem();
final double fontSize = fontSizeSpinner.getValue().intValue();
preferences.setFontStyle(fontFamily, fontSize);
MediatorControl.INSTANCE.getLogArea().getScene().getRoot().setStyle(
String.format("-fx-font-family: \"%s\"; -fx-font-size: %.0f;", fontFamily, fontSize));
closeWindow();
}
private void closeWindow(){
((Stage) cancelBtn.getScene().getWindow()).close();
}
}

View file

@ -1,407 +0,0 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.DragEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import nsusbloader.AppPreferences;
import nsusbloader.COM.NET.NETCommunications;
import nsusbloader.COM.USB.UsbCommunications;
import nsusbloader.MediatorControl;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.ServiceWindow;
import java.io.File;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
public class FrontController implements Initializable {
@FXML
private AnchorPane usbNetPane;
@FXML
private ChoiceBox<String> choiceProtocol, choiceNetUsb;
@FXML
private Label nsIpLbl;
@FXML
private TextField nsIpTextField;
@FXML
private Button switchThemeBtn;
@FXML
public NSTableViewController tableFilesListController; // Accessible from Mediator (for drag-n-drop support)
@FXML
private Button selectNspBtn, selectSplitNspBtn, uploadStopBtn;
private String previouslyOpenedPath;
private Region btnUpStopImage;
private ResourceBundle resourceBundle;
private CancellableRunnable usbNetCommunications;
private Thread workThread;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
ObservableList<String> choiceProtocolList = FXCollections.observableArrayList("TinFoil", "GoldLeaf");
choiceProtocol.setItems(choiceProtocolList);
choiceProtocol.getSelectionModel().select(AppPreferences.getInstance().getProtocol());
choiceProtocol.setOnAction(e-> {
tableFilesListController.setNewProtocol(getSelectedProtocol());
if (getSelectedProtocol().equals("GoldLeaf")) {
choiceNetUsb.setDisable(true);
choiceNetUsb.getSelectionModel().select("USB");
nsIpLbl.setVisible(false);
nsIpTextField.setVisible(false);
}
else {
choiceNetUsb.setDisable(false);
if (getSelectedNetUsb().equals("NET")) {
nsIpLbl.setVisible(true);
nsIpTextField.setVisible(true);
}
}
// Really bad disable-enable upload button function
disableUploadStopBtn(tableFilesListController.isFilesForUploadListEmpty());
}); // Add listener to notify tableView controller
tableFilesListController.setNewProtocol(getSelectedProtocol()); // Notify tableView controller
ObservableList<String> choiceNetUsbList = FXCollections.observableArrayList("USB", "NET");
choiceNetUsb.setItems(choiceNetUsbList);
choiceNetUsb.getSelectionModel().select(AppPreferences.getInstance().getNetUsb());
if (getSelectedProtocol().equals("GoldLeaf")) {
choiceNetUsb.setDisable(true);
choiceNetUsb.getSelectionModel().select("USB");
}
choiceNetUsb.setOnAction(e->{
if (getSelectedNetUsb().equals("NET")){
nsIpLbl.setVisible(true);
nsIpTextField.setVisible(true);
}
else{
nsIpLbl.setVisible(false);
nsIpTextField.setVisible(false);
}
});
// Set and configure NS IP field behavior
nsIpTextField.setText(AppPreferences.getInstance().getNsIp());
if (getSelectedProtocol().equals("TinFoil") && getSelectedNetUsb().equals("NET")){
nsIpLbl.setVisible(true);
nsIpTextField.setVisible(true);
}
nsIpTextField.setTextFormatter(new TextFormatter<>(change -> {
if (change.getControlNewText().contains(" ") | change.getControlNewText().contains("\t"))
return null;
else
return change;
}));
// Set and configure switch theme button
Region btnSwitchImage = new Region();
btnSwitchImage.getStyleClass().add("regionLamp");
switchThemeBtn.setGraphic(btnSwitchImage);
this.switchThemeBtn.setOnAction(e->switchTheme());
uploadStopBtn.setDisable(getSelectedProtocol().equals("TinFoil"));
selectNspBtn.setOnAction(e-> selectFilesBtnAction());
selectSplitNspBtn.setOnAction(e-> selectSplitBtnAction());
selectSplitNspBtn.getStyleClass().add("buttonSelect");
uploadStopBtn.setOnAction(e-> uploadBtnAction());
selectNspBtn.getStyleClass().add("buttonSelect");
this.btnUpStopImage = new Region();
btnUpStopImage.getStyleClass().add("regionUpload");
uploadStopBtn.getStyleClass().add("buttonUp");
uploadStopBtn.setGraphic(btnUpStopImage);
this.previouslyOpenedPath = AppPreferences.getInstance().getRecent();
}
/**
* Changes UI theme on the go
* */
private void switchTheme(){
final String darkTheme = "/res/app_dark.css";
final String lightTheme = "/res/app_light.css";
final ObservableList<String> styleSheets = switchThemeBtn.getScene().getStylesheets();
if (styleSheets.get(0).equals(darkTheme)) {
styleSheets.remove(darkTheme);
styleSheets.add(lightTheme);
}
else {
styleSheets.remove(lightTheme);
styleSheets.add(darkTheme);
}
AppPreferences.getInstance().setTheme(styleSheets.get(0));
}
/**
* Get selected protocol (GL/TF)
* */
String getSelectedProtocol(){
return choiceProtocol.getSelectionModel().getSelectedItem();
}
/**
* Get selected protocol (USB/NET)
* */
String getSelectedNetUsb(){
return choiceNetUsb.getSelectionModel().getSelectedItem();
}
/**
* Get NS IP address
* */
String getNsIp(){
return nsIpTextField.getText();
}
/**
* Functionality for selecting NSP button.
* */
private void selectFilesBtnAction(){
List<File> filesList;
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(resourceBundle.getString("btn_OpenFile"));
File validator = new File(previouslyOpenedPath);
if (validator.exists() && validator.isDirectory())
fileChooser.setInitialDirectory(validator);
else
fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
if (getSelectedProtocol().equals("TinFoil") && MediatorControl.getInstance().getContoller().getSettingsCtrlr().getTinfoilSettings().isXciNszXczSupport())
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("NSP/XCI/NSZ/XCZ", "*.nsp", "*.xci", "*.nsz", "*.xcz"));
else if (getSelectedProtocol().equals("GoldLeaf") && (! MediatorControl.getInstance().getContoller().getSettingsCtrlr().getGoldleafSettings().getNSPFileFilterForGL()))
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Any file", "*.*"),
new FileChooser.ExtensionFilter("NSP ROM", "*.nsp")
);
else
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("NSP ROM", "*.nsp"));
filesList = fileChooser.showOpenMultipleDialog(usbNetPane.getScene().getWindow());
if (filesList != null && !filesList.isEmpty()) {
tableFilesListController.setFiles(filesList);
uploadStopBtn.setDisable(false);
previouslyOpenedPath = filesList.get(0).getParent();
}
}
/**
* Functionality for selecting Split NSP button.
* */
private void selectSplitBtnAction(){
File splitFile;
DirectoryChooser dirChooser = new DirectoryChooser();
dirChooser.setTitle(resourceBundle.getString("btn_OpenFile"));
File validator = new File(previouslyOpenedPath);
if (validator.exists() && validator.isDirectory())
dirChooser.setInitialDirectory(validator);
else
dirChooser.setInitialDirectory(new File(System.getProperty("user.home")));
splitFile = dirChooser.showDialog(usbNetPane.getScene().getWindow());
if (splitFile != null && splitFile.getName().toLowerCase().endsWith(".nsp")) {
tableFilesListController.setFile(splitFile);
uploadStopBtn.setDisable(false); // Is it useful?
previouslyOpenedPath = splitFile.getParent();
}
}
/**
* It's button listener when no transmission executes
* */
private void uploadBtnAction(){
if (workThread != null && workThread.isAlive())
return;
// Collect files
List<File> nspToUpload;
TextArea logArea = MediatorControl.getInstance().getContoller().logArea;
if (getSelectedProtocol().equals("TinFoil") && tableFilesListController.getFilesForUpload() == null) {
logArea.setText(resourceBundle.getString("tab3_Txt_NoFolderOrFileSelected"));
return;
}
if ((nspToUpload = tableFilesListController.getFilesForUpload()) != null){
logArea.setText(resourceBundle.getString("tab3_Txt_FilesToUploadTitle")+"\n");
nspToUpload.forEach(item -> logArea.appendText(" "+item.getAbsolutePath()+"\n"));
}
else {
logArea.clear();
nspToUpload = new LinkedList<>();
}
SettingsController settings = MediatorControl.getInstance().getContoller().getSettingsCtrlr();
// If USB selected
if (getSelectedProtocol().equals("GoldLeaf") ){
final SettingsBlockGoldleafController goldleafSettings = settings.getGoldleafSettings();
usbNetCommunications = new UsbCommunications(nspToUpload, "GoldLeaf" + goldleafSettings.getGlVer(), goldleafSettings.getNSPFileFilterForGL());
}
else if (( getSelectedProtocol().equals("TinFoil") && getSelectedNetUsb().equals("USB") )){
usbNetCommunications = new UsbCommunications(nspToUpload, "TinFoil", false);
}
else { // NET INSTALL OVER TINFOIL
final String ipValidationPattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
final SettingsBlockTinfoilController tinfoilSettings = settings.getTinfoilSettings();
if (tinfoilSettings.isValidateNSHostName() && ! getNsIp().matches(ipValidationPattern)) {
if (!ServiceWindow.getConfirmationWindow(resourceBundle.getString("windowTitleBadIp"), resourceBundle.getString("windowBodyBadIp")))
return;
}
String nsIP = getNsIp();
if (! tinfoilSettings.isExpertModeSelected())
usbNetCommunications = new NETCommunications(nspToUpload, nsIP, false, "", "", "");
else {
usbNetCommunications = new NETCommunications(
nspToUpload,
nsIP,
tinfoilSettings.isNoRequestsServe(),
tinfoilSettings.isAutoDetectIp()?"":tinfoilSettings.getHostIp(),
tinfoilSettings.isRandomlySelectPort()?"":tinfoilSettings.getHostPort(),
tinfoilSettings.isNoRequestsServe()?tinfoilSettings.getHostExtra():""
);
}
}
workThread = new Thread(usbNetCommunications);
workThread.setDaemon(true);
workThread.start();
}
/**
* It's button listener when transmission in progress
* */
private void stopBtnAction(){
if (workThread != null && workThread.isAlive()){
usbNetCommunications.cancel();
if (usbNetCommunications instanceof NETCommunications){
try{
((NETCommunications) usbNetCommunications).getServerSocket().close();
((NETCommunications) usbNetCommunications).getClientSocket().close();
}
catch (Exception ignore){ }
}
}
}
/**
* Drag-n-drop support (dragOver consumer)
* */
@FXML
private void handleDragOver(DragEvent event){
if (event.getDragboard().hasFiles() && ! MediatorControl.getInstance().getTransferActive())
event.acceptTransferModes(TransferMode.ANY);
event.consume();
}
/**
* Drag-n-drop support (drop consumer)
* */
@FXML
private void handleDrop(DragEvent event){
List<File> filesDropped = event.getDragboard().getFiles();
SettingsController settingsController = MediatorControl.getInstance().getContoller().getSettingsCtrlr();
SettingsBlockTinfoilController tinfoilSettings = settingsController.getTinfoilSettings();
SettingsBlockGoldleafController goldleafController = settingsController.getGoldleafSettings();
if (getSelectedProtocol().equals("TinFoil") && tinfoilSettings.isXciNszXczSupport())
filesDropped.removeIf(file -> ! file.getName().toLowerCase().matches("(.*\\.nsp$)|(.*\\.xci$)|(.*\\.nsz$)|(.*\\.xcz$)"));
else if (getSelectedProtocol().equals("GoldLeaf") && (! goldleafController.getNSPFileFilterForGL()))
filesDropped.removeIf(file -> (file.isDirectory() && ! file.getName().toLowerCase().matches(".*\\.nsp$")));
else
filesDropped.removeIf(file -> ! file.getName().toLowerCase().matches(".*\\.nsp$"));
if ( ! filesDropped.isEmpty() )
tableFilesListController.setFiles(filesDropped);
event.setDropCompleted(true);
event.consume();
}
/**
* This thing modify UI for reusing 'Upload to NS' button and make functionality set for "Stop transmission"
* Called from mediator
* TODO: remove shitcoding practices
* */
public void notifyThreadStarted(boolean isActive, EModule type){
if (! type.equals(EModule.USB_NET_TRANSFERS)){
usbNetPane.setDisable(isActive);
return;
}
if (isActive) {
selectNspBtn.setDisable(true);
selectSplitNspBtn.setDisable(true);
btnUpStopImage.getStyleClass().clear();
btnUpStopImage.getStyleClass().add("regionStop");
uploadStopBtn.setOnAction(e-> stopBtnAction());
uploadStopBtn.setText(resourceBundle.getString("btn_Stop"));
uploadStopBtn.getStyleClass().remove("buttonUp");
uploadStopBtn.getStyleClass().add("buttonStop");
return;
}
selectNspBtn.setDisable(false);
selectSplitNspBtn.setDisable(false);
btnUpStopImage.getStyleClass().clear();
btnUpStopImage.getStyleClass().add("regionUpload");
uploadStopBtn.setOnAction(e-> uploadBtnAction());
uploadStopBtn.setText(resourceBundle.getString("btn_Upload"));
uploadStopBtn.getStyleClass().remove("buttonStop");
uploadStopBtn.getStyleClass().add("buttonUp");
}
/**
* Crunch. This function called from NSTableViewController
* */
public void disableUploadStopBtn(boolean disable){
if (getSelectedProtocol().equals("TinFoil"))
uploadStopBtn.setDisable(disable);
else
uploadStopBtn.setDisable(false);
}
/**
* Get 'Recent' path
*/
public String getRecentPath(){
return previouslyOpenedPath;
}
public void updatePreferencesOnExit(){
AppPreferences preferences = AppPreferences.getInstance();
preferences.setProtocol(getSelectedProtocol());
preferences.setRecent(getRecentPath());
preferences.setNetUsb(getSelectedNetUsb());
preferences.setNsIp(getNsIp());
}
}

View file

@ -0,0 +1,559 @@
/*
Copyright 2019-2024 Dmitry Isaenko, wolfposd
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.DragEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import nsusbloader.AppPreferences;
import nsusbloader.NSLDataTypes.EFileStatus;
import nsusbloader.com.net.NETCommunications;
import nsusbloader.com.usb.UsbCommunications;
import nsusbloader.FilesHelper;
import nsusbloader.MediatorControl;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.ServiceWindow;
import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class GamesController implements Initializable, ISubscriber {
private static final String REGEX_ONLY_NSP = ".*\\.nsp$";
private static final String REGEX_ALLFILES_TINFOIL = ".*\\.(nsp$|xci$|nsz$|xcz$)";
private static final String REGEX_ALLFILES = ".*";
private static final MediatorControl mediator = MediatorControl.INSTANCE;
@FXML
private AnchorPane usbNetPane;
@FXML
private ChoiceBox<String> choiceProtocol, choiceNetUsb;
@FXML
private Label nsIpLbl;
@FXML
private TextField nsIpTextField;
@FXML
private Button switchThemeBtn;
@FXML
private NSTableViewController tableFilesListController;
@FXML
private Button selectNspBtn, selectSplitBtn, uploadStopBtn;
private String previouslyOpenedPath;
private Region btnUpStopImage, btnSelectImage;
private ResourceBundle resourceBundle;
private CancellableRunnable usbNetCommunications;
private Thread workThread;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
AppPreferences preferences = AppPreferences.getInstance();
ObservableList<String> choiceProtocolList = FXCollections.observableArrayList("Awoo", "GoldLeaf");
choiceProtocol.setItems(choiceProtocolList);
choiceProtocol.getSelectionModel().select(preferences.getProtocol());
choiceProtocol.setOnAction(e-> {
tableFilesListController.setNewProtocol(getSelectedProtocolByName());
if (isGoldLeaf()) {
choiceNetUsb.setDisable(true);
choiceNetUsb.getSelectionModel().select("USB");
nsIpLbl.setVisible(false);
nsIpTextField.setVisible(false);
}
else {
choiceNetUsb.setDisable(false);
if (getSelectedNetUsb().equals("NET")) {
nsIpLbl.setVisible(true);
nsIpTextField.setVisible(true);
}
}
// Really bad disable-enable upload button function
disableUploadStopBtn(tableFilesListController.isFilesForUploadListEmpty());
}); // Add listener to notify tableView controller
tableFilesListController.setNewProtocol(getSelectedProtocolByName()); // Notify tableView controller
tableFilesListController.setGamesController(this);
ObservableList<String> choiceNetUsbList = FXCollections.observableArrayList("USB", "NET");
choiceNetUsb.setItems(choiceNetUsbList);
choiceNetUsb.getSelectionModel().select(preferences.getNetUsb());
if (isGoldLeaf()) {
choiceNetUsb.setDisable(true);
choiceNetUsb.getSelectionModel().select("USB");
}
choiceNetUsb.setOnAction(e->{
if (getSelectedNetUsb().equals("NET")){
nsIpLbl.setVisible(true);
nsIpTextField.setVisible(true);
}
else{
nsIpLbl.setVisible(false);
nsIpTextField.setVisible(false);
}
});
// Set and configure NS IP field behavior
nsIpTextField.setText(preferences.getNsIp());
if (isTinfoil() && getSelectedNetUsb().equals("NET")){
nsIpLbl.setVisible(true);
nsIpTextField.setVisible(true);
}
nsIpTextField.setTextFormatter(new TextFormatter<>(change -> {
if (change.getControlNewText().contains(" ") | change.getControlNewText().contains("\t"))
return null;
else
return change;
}));
// Set and configure switch theme button
Region btnSwitchImage = new Region();
btnSwitchImage.getStyleClass().add("regionLamp");
switchThemeBtn.setGraphic(btnSwitchImage);
this.switchThemeBtn.setOnAction(e->switchTheme());
selectNspBtn.getStyleClass().add("buttonSelect");
this.btnSelectImage = new Region();
setFilesSelectorButtonBehaviour(preferences.getDirectoriesChooserForRoms());
selectSplitBtn.setOnAction(e-> selectSplitBtnAction());
selectSplitBtn.getStyleClass().add("buttonSelect");
uploadStopBtn.setOnAction(e-> uploadBtnAction());
uploadStopBtn.setDisable(isTinfoil());
this.btnUpStopImage = new Region();
btnUpStopImage.getStyleClass().add("regionUpload");
uploadStopBtn.getStyleClass().add("buttonUp");
uploadStopBtn.setGraphic(btnUpStopImage);
this.previouslyOpenedPath = preferences.getRecent();
}
/**
* Changes UI theme on the go
* */
private void switchTheme(){
final String darkTheme = "/res/app_dark.css";
final String lightTheme = "/res/app_light.css";
final ObservableList<String> styleSheets = switchThemeBtn.getScene().getStylesheets();
if (styleSheets.get(0).equals(darkTheme)) {
styleSheets.remove(darkTheme);
styleSheets.add(lightTheme);
}
else {
styleSheets.remove(lightTheme);
styleSheets.add(darkTheme);
}
AppPreferences.getInstance().setTheme(styleSheets.get(0));
}
/**
* Get selected protocol index (GL/Awoo)
* */
private int getSelectedProtocolByIndex(){
return choiceProtocol.getSelectionModel().getSelectedIndex();
}
private String getSelectedProtocolByName(){
return choiceProtocol.getSelectionModel().getSelectedItem();
}
/**
* Get selected protocol (USB/NET)
* */
private String getSelectedNetUsb(){
return choiceNetUsb.getSelectionModel().getSelectedItem();
}
/**
* Get NS IP address
* */
private String getNsIp(){
return nsIpTextField.getText();
}
private boolean isGoldLeaf() {
return getSelectedProtocolByName().equals("GoldLeaf");
}
private boolean isTinfoil() {
return getSelectedProtocolByName().equals("Awoo");
}
private boolean isAllFiletypesAllowedForGL() {
return ! mediator.getSettingsController().getGoldleafSettings().getNSPFileFilterForGL();
}
private boolean isXciNszXczSupport() {
return mediator.getSettingsController().getTinfoilSettings().isXciNszXczSupport();
}
/**
* regex for selected program and selected file filter </br>
* tinfoil + xcinszxcz </br>
* tinfoil + nsponly </br>
* goldleaf </br>
* etc...
*/
private String getRegexForFiles() {
if (isTinfoil() && isXciNszXczSupport())
return REGEX_ALLFILES_TINFOIL;
else if (isGoldLeaf() && isAllFiletypesAllowedForGL())
return REGEX_ALLFILES;
else
return REGEX_ONLY_NSP;
}
private String getRegexForFolders() {
final String regexForFiles = getRegexForFiles();
if (regexForFiles.equals(REGEX_ALLFILES))
return REGEX_ALLFILES_TINFOIL;
else
return regexForFiles;
}
/**
* Functionality for selecting NSP button.
*/
private void selectFilesBtnAction() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(resourceBundle.getString("btn_OpenFile"));
fileChooser.setInitialDirectory(new File(FilesHelper.getRealFolder(previouslyOpenedPath)));
if (isTinfoil() && isXciNszXczSupport()) {
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("NSP/XCI/NSZ/XCZ", "*.nsp", "*.xci", "*.nsz", "*.xcz"));
}
else if (isGoldLeaf() && isAllFiletypesAllowedForGL()) {
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Any file", "*.*"),
new FileChooser.ExtensionFilter("NSP ROM", "*.nsp"));
}
else {
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("NSP ROM", "*.nsp"));
}
List<File> filesList = fileChooser.showOpenMultipleDialog(usbNetPane.getScene().getWindow());
if (filesList != null && !filesList.isEmpty()) {
tableFilesListController.setFiles(filesList);
uploadStopBtn.setDisable(false);
previouslyOpenedPath = filesList.get(0).getParent();
}
}
/**
* Functionality for selecting folders button.
* will scan all folders recursively for nsp-files
*/
private void selectFoldersBtnAction() {
DirectoryChooser chooser = new DirectoryChooser();
chooser.setTitle(resourceBundle.getString("btn_OpenFolders"));
chooser.setInitialDirectory(new File(FilesHelper.getRealFolder(previouslyOpenedPath)));
File startFolder = chooser.showDialog(usbNetPane.getScene().getWindow());
performInBackgroundAndUpdate(() -> {
final List<File> allFiles = new ArrayList<>();
collectFiles(allFiles, startFolder, getRegexForFiles(), getRegexForFolders());
return allFiles;
}, (files) -> {
if (!files.isEmpty()) {
tableFilesListController.setFiles(files);
uploadStopBtn.setDisable(false);
previouslyOpenedPath = startFolder.getParent();
}
});
}
/**
* used to recursively walk all directories, every file will be added to the storage list
* @param storage used to hold files
* @param startFolder where to start
* @param filesRegex for filenames
*/
// TODO: Too sophisticated. Should be moved to simple class to keep things simpler
private void collectFiles(List<File> storage,
File startFolder,
final String filesRegex,
final String foldersRegex)
{
if (startFolder == null)
return;
final String startFolderNameInLowercase = startFolder.getName().toLowerCase();
if (startFolder.isFile()) {
if (startFolderNameInLowercase.matches(filesRegex)) {
storage.add(startFolder);
}
return;
}
if (startFolderNameInLowercase.matches(foldersRegex)) {
storage.add(startFolder);
return;
}
File[] files = startFolder.listFiles();
if (files == null)
return;
for (File file : files)
collectFiles(storage, file, filesRegex, foldersRegex);
}
/**
* Functionality for selecting Split-file button.
* */
private void selectSplitBtnAction(){
File splitFile;
DirectoryChooser dirChooser = new DirectoryChooser();
dirChooser.setTitle(resourceBundle.getString("btn_OpenFile"));
String saveToLocation = FilesHelper.getRealFolder(previouslyOpenedPath);
dirChooser.setInitialDirectory(new File(saveToLocation));
splitFile = dirChooser.showDialog(usbNetPane.getScene().getWindow());
if (splitFile == null)
return;
int fileNameLen = splitFile.getName().length();
String fileExtension = splitFile.getName().toLowerCase().substring(fileNameLen-4, fileNameLen);
if (fileExtension.equals(".nsp")){
tableFilesListController.setFile(splitFile);
uploadStopBtn.setDisable(false); // Is it useful?
previouslyOpenedPath = splitFile.getParent();
}
if (isTinfoil() && isXciNszXczSupport()){
switch(fileExtension){
case ".xci":
case ".nsz":
case ".xcz":
tableFilesListController.setFile(splitFile);
uploadStopBtn.setDisable(false); // Is it useful?
previouslyOpenedPath = splitFile.getParent();
}
}
}
/**
* It's button listener when no transmission executes
* */
private void uploadBtnAction(){
if (workThread != null && workThread.isAlive())
return;
if (isTinfoil() && tableFilesListController.getFilesForUpload() == null) {
ServiceWindow.getInfoNotification("(o_o\")", resourceBundle.getString("tab3_Txt_NoFolderOrFileSelected"));
return;
}
// Collect files
List<File> nspToUpload = tableFilesListController.getFilesForUpload();
if (nspToUpload == null)
nspToUpload = new ArrayList<>();
//todo: add to make it visible
/*
else {
TextArea logArea = mediator.getLogArea();
logArea.setText(resourceBundle.getString("tab3_Txt_FilesToUploadTitle")+"\n");
nspToUpload.forEach(item -> logArea.appendText(" "+item.getAbsolutePath()+"\n"));
}
*/
SettingsController settings = mediator.getSettingsController();
// If USB selected
if (isGoldLeaf()){
final SettingsBlockGoldleafController goldleafSettings = settings.getGoldleafSettings();
usbNetCommunications = new UsbCommunications(nspToUpload, "GoldLeaf" + goldleafSettings.getGlVer(), goldleafSettings.getNSPFileFilterForGL());
}
else {
if (getSelectedNetUsb().equals("USB")){
usbNetCommunications = new UsbCommunications(nspToUpload, "TinFoil", false);
}
else { // NET INSTALL OVER TINFOIL
final String ipValidationPattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
final SettingsBlockTinfoilController tinfoilSettings = settings.getTinfoilSettings();
if (tinfoilSettings.isValidateNSHostName() && ! getNsIp().matches(ipValidationPattern)) {
if (!ServiceWindow.getConfirmationWindow(resourceBundle.getString("windowTitleBadIp"), resourceBundle.getString("windowBodyBadIp")))
return;
}
String nsIP = getNsIp();
if (! tinfoilSettings.isExpertModeSelected())
usbNetCommunications = new NETCommunications(nspToUpload, nsIP, false, "", "", "");
else {
usbNetCommunications = new NETCommunications(
nspToUpload,
nsIP,
tinfoilSettings.isNoRequestsServe(),
tinfoilSettings.isAutoDetectIp()?"":tinfoilSettings.getHostIp(),
tinfoilSettings.isRandomlySelectPort()?"":tinfoilSettings.getHostPort(),
tinfoilSettings.isNoRequestsServe()?tinfoilSettings.getHostExtra():""
);
}
}
}
workThread = new Thread(usbNetCommunications);
workThread.setDaemon(true);
workThread.start();
}
/**
* It's button listener when transmission in progress
* */
private void stopBtnAction(){
if (workThread == null || ! workThread.isAlive())
return;
usbNetCommunications.cancel();
if (usbNetCommunications instanceof NETCommunications){
try{
((NETCommunications) usbNetCommunications).getServerSocket().close();
((NETCommunications) usbNetCommunications).getClientSocket().close();
}
catch (Exception ignore){ }
}
}
/**
* Drag-n-drop support (dragOver consumer)
* */
@FXML
private void handleDragOver(DragEvent event){
if (event.getDragboard().hasFiles() && ! mediator.getTransferActive())
event.acceptTransferModes(TransferMode.ANY);
event.consume();
}
/**
* Drag-n-drop support (drop consumer)
* */
@FXML
private void handleDrop(DragEvent event) {
List<File> files = event.getDragboard().getFiles();
new FilesDropHandle(files, getRegexForFiles(), getRegexForFolders(), tableFilesListController);
event.setDropCompleted(true);
event.consume();
}
/**
* This function called from NSTableViewController
* */
void disableUploadStopBtn(boolean disable){
if (isTinfoil())
uploadStopBtn.setDisable(disable);
else
uploadStopBtn.setDisable(false);
}
/**
* Utility function to perform a task in the background and pass the results to a task on the javafx-ui-thread
* @param background performed in background
* @param update performed with results on ui-thread
*/
private <T> void performInBackgroundAndUpdate(Supplier<T> background, Consumer<T> update) {
new Thread(() -> {
final T result = background.get();
Platform.runLater(() -> update.accept(result));
}).start();
}
void setFilesSelectorButtonBehaviour(boolean isDirectoryChooser){
btnSelectImage.getStyleClass().clear();
if (isDirectoryChooser){
selectNspBtn.setOnAction(e -> selectFoldersBtnAction());
btnSelectImage.getStyleClass().add("regionScanFolders");
selectSplitBtn.setVisible(false);
}
else {
selectNspBtn.setOnAction(e -> selectFilesBtnAction());
btnSelectImage.getStyleClass().add("regionSelectFiles");
selectSplitBtn.setVisible(true);
}
selectNspBtn.setGraphic(btnSelectImage);
}
/**
* Get 'Recent' path
*/
private String getRecentPath(){
return previouslyOpenedPath;
}
public void updatePreferencesOnExit(){
AppPreferences preferences = AppPreferences.getInstance();
preferences.setProtocol(getSelectedProtocolByIndex());
preferences.setRecent(getRecentPath());
preferences.setNetUsb(getSelectedNetUsb());
preferences.setNsIp(getNsIp());
}
/**
* This thing modifies UI for reusing 'Upload to NS' button and make functionality set for "Stop transmission"
* */
@Override
public void notify(EModule type, boolean isActive, Payload payload) {
if (! type.equals(EModule.USB_NET_TRANSFERS)){
usbNetPane.setDisable(isActive);
return;
}
selectNspBtn.setDisable(isActive);
selectSplitBtn.setDisable(isActive);
btnUpStopImage.getStyleClass().clear();
if (isActive) {
btnUpStopImage.getStyleClass().add("regionStop");
uploadStopBtn.setOnAction(e-> stopBtnAction());
uploadStopBtn.setText(resourceBundle.getString("btn_Stop"));
uploadStopBtn.getStyleClass().remove("buttonUp");
uploadStopBtn.getStyleClass().add("buttonStop");
return;
}
btnUpStopImage.getStyleClass().add("regionUpload");
uploadStopBtn.setOnAction(e-> uploadBtnAction());
uploadStopBtn.setText(resourceBundle.getString("btn_Upload"));
uploadStopBtn.getStyleClass().remove("buttonStop");
uploadStopBtn.getStyleClass().add("buttonUp");
Map<String, EFileStatus> statusMap = payload.getStatusMap();
if (! statusMap.isEmpty()) {
for (String key : statusMap.keySet())
tableFilesListController.setFileStatus(key, statusMap.get(key));
}
}
}

View file

@ -0,0 +1,25 @@
/*
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import nsusbloader.NSLDataTypes.EModule;
public interface ISubscriber {
void notify(EModule type, boolean status, Payload payload);
}

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
@ -18,7 +18,6 @@
*/
package nsusbloader.Controllers;
import javafx.application.HostServices;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
@ -35,13 +34,18 @@ public class NSLMainController implements Initializable {
private ResourceBundle resourceBundle;
@FXML
public TextArea logArea; // Accessible from Mediator
private TextArea logArea;
@FXML
public ProgressBar progressBar; // Accessible from Mediator
private ProgressBar progressBar;
@FXML
public FrontController FrontTabController; // Accessible from Mediator | todo: incapsulate
private TabPane mainTabPane;
@FXML
private Tab GamesTabHolder, RCMTabHolder, SMTabHolder, PatchesTabHolder;
@FXML
private GamesController GamesTabController;
@FXML
private SettingsController SettingsTabController;
@FXML
@ -50,6 +54,8 @@ public class NSLMainController implements Initializable {
private RcmController RcmTabController;
@FXML
private NxdtController NXDTabController;
@FXML
private PatchesController PatchesTabController;
@Override
public void initialize(URL url, ResourceBundle rb) {
@ -61,67 +67,88 @@ public class NSLMainController implements Initializable {
logArea.appendText(rb.getString("tab3_Txt_GreetingsMessage2")+"\n");
MediatorControl.getInstance().setController(this);
AppPreferences preferences = AppPreferences.getInstance();
if (AppPreferences.getInstance().getAutoCheckUpdates()){
if (preferences.getAutoCheckUpdates())
checkForUpdates();
if (preferences.getPatchesTabInvisible())
mainTabPane.getTabs().remove(3);
openLastOpenedTab();
TransfersPublisher transfersPublisher = new TransfersPublisher(
GamesTabController,
SplitMergeTabController,
RcmTabController,
NXDTabController,
PatchesTabController);
MediatorControl.INSTANCE.configure(
resourceBundle,
SettingsTabController,
logArea,
progressBar,
GamesTabController,
transfersPublisher);
}
private void checkForUpdates(){
Task<List<String>> updTask = new UpdatesChecker();
updTask.setOnSucceeded(event->{
List<String> result = updTask.getValue();
if (result != null){
if (!result.get(0).isEmpty()) {
SettingsTabController.getGenericSettings().setNewVersionLink(result.get(0));
ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionAval"), resourceBundle.getString("windowTitleNewVersionAval") + ": " + result.get(0) + "\n\n" + result.get(1));
ServiceWindow.getInfoNotification(
resourceBundle.getString("windowTitleNewVersionAval"),
resourceBundle.getString("windowTitleNewVersionAval") + ": " + result.get(0) + "\n\n" + result.get(1));
}
}
else
ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionUnknown"), resourceBundle.getString("windowBodyNewVersionUnknown"));
ServiceWindow.getInfoNotification(
resourceBundle.getString("windowTitleNewVersionUnknown"),
resourceBundle.getString("windowBodyNewVersionUnknown"));
});
Thread updates = new Thread(updTask);
updates.setDaemon(true);
updates.start();
}
}
/**
* Get resources
* TODO: Find better solution; used in UsbCommunications() -> GL -> SelectFile command
* @return ResourceBundle
*/
public ResourceBundle getResourceBundle() {
return resourceBundle;
}
/**
* Provide hostServices to Settings tab
* */
public void setHostServices(HostServices hs ){ SettingsTabController.getGenericSettings().registerHostServices(hs);}
/**
* Get 'Settings' controller
* Used by FrontController
* */
public SettingsController getSettingsCtrlr(){
return SettingsTabController;
}
public FrontController getFrontCtrlr(){
return FrontTabController;
}
public SplitMergeController getSmCtrlr(){
return SplitMergeTabController;
}
public RcmController getRcmCtrlr(){ return RcmTabController; }
public NxdtController getNXDTabController(){ return NXDTabController; }
/**
* Save preferences before exit
* */
public void exit(){
FrontTabController.updatePreferencesOnExit();
GamesTabController.updatePreferencesOnExit();
SettingsTabController.updatePreferencesOnExit();
SplitMergeTabController.updatePreferencesOnExit(); // NOTE: This shit above should be re-written to similar pattern
RcmTabController.updatePreferencesOnExit();
NXDTabController.updatePreferencesOnExit();
PatchesTabController.updatePreferencesOnExit();
saveLastOpenedTab();
}
private void openLastOpenedTab(){
String tabId = AppPreferences.getInstance().getLastOpenedTab();
switch (tabId){
case "GamesTabHolder":
mainTabPane.getSelectionModel().select(GamesTabHolder);
break;
case "RCMTabHolder":
mainTabPane.getSelectionModel().select(RCMTabHolder);
break;
case "SMTabHolder":
mainTabPane.getSelectionModel().select(SMTabHolder);
break;
case "PatchesTabHolder":
mainTabPane.getSelectionModel().select(PatchesTabHolder);
break;
}
}
private void saveLastOpenedTab(){
String tabId = mainTabPane.getSelectionModel().getSelectedItem().getId();
if (tabId == null || tabId.isEmpty())
tabId = "";
AppPreferences.getInstance().setLastOpenedTab(tabId);
}
}

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko, wolfposd
Copyright 2019-2024 Dmitry Isaenko, wolfposd
This file is part of NS-USBloader.
@ -24,12 +24,10 @@ import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.*;
import javafx.scene.paint.Paint;
import nsusbloader.MediatorControl;
import nsusbloader.NSLDataTypes.EFileStatus;
@ -40,12 +38,12 @@ import java.util.List;
import java.util.ResourceBundle;
public class NSTableViewController implements Initializable {
private static final DataFormat SERIALIZED_MIME_TYPE = new DataFormat("application/x-java-serialized-object");
@FXML
private TableView<NSLRowModel> table;
private ObservableList<NSLRowModel> rowsObsLst;
private GamesController gamesController;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
rowsObsLst = FXCollections.observableArrayList();
@ -56,10 +54,10 @@ public class NSTableViewController implements Initializable {
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table.setOnKeyPressed(keyEvent -> {
if (!rowsObsLst.isEmpty()) {
if (keyEvent.getCode() == KeyCode.DELETE && !MediatorControl.getInstance().getTransferActive()) {
if (keyEvent.getCode() == KeyCode.DELETE && !MediatorControl.INSTANCE.getTransferActive()) {
rowsObsLst.removeAll(table.getSelectionModel().getSelectedItems());
if (rowsObsLst.isEmpty())
MediatorControl.getInstance().getContoller().getFrontCtrlr().disableUploadStopBtn(true); // TODO: change to something better
gamesController.disableUploadStopBtn(true);
table.refresh();
} else if (keyEvent.getCode() == KeyCode.SPACE) {
for (NSLRowModel item : table.getSelectionModel().getSelectedItems()) {
@ -177,13 +175,13 @@ public class NSTableViewController implements Initializable {
deleteMenuItem.setOnAction(actionEvent -> {
rowsObsLst.remove(row.getItem());
if (rowsObsLst.isEmpty())
MediatorControl.getInstance().getContoller().getFrontCtrlr().disableUploadStopBtn(true); // TODO: change to something better
gamesController.disableUploadStopBtn(true);
table.refresh();
});
MenuItem deleteAllMenuItem = new MenuItem(resourceBundle.getString("tab1_table_contextMenu_Btn_DeleteAll"));
deleteAllMenuItem.setOnAction(actionEvent -> {
rowsObsLst.clear();
MediatorControl.getInstance().getContoller().getFrontCtrlr().disableUploadStopBtn(true); // TODO: change to something better
gamesController.disableUploadStopBtn(true);
table.refresh();
});
contextMenu.getItems().addAll(deleteMenuItem, deleteAllMenuItem);
@ -193,7 +191,7 @@ public class NSTableViewController implements Initializable {
Bindings.when(
Bindings.isNotNull(
row.itemProperty()))
.then(MediatorControl.getInstance().getTransferActive()?null:contextMenu)
.then(MediatorControl.INSTANCE.getTransferActive()?null:contextMenu)
.otherwise((ContextMenu) null)
);
// Just.. don't ask..
@ -214,6 +212,11 @@ public class NSTableViewController implements Initializable {
table.getColumns().add(fileSizeColumn);
table.getColumns().add(uploadColumn);
}
public void setGamesController(GamesController gamesController) {
this.gamesController = gamesController;
}
/**
* Add single file when user selected it (Split file usually)
* */
@ -228,14 +231,14 @@ public class NSTableViewController implements Initializable {
}
else {
rowsObsLst.add(new NSLRowModel(file, true));
MediatorControl.getInstance().getContoller().getFrontCtrlr().disableUploadStopBtn(false); // TODO: change to something better
gamesController.disableUploadStopBtn(false);
}
table.refresh();
}
/**
* Add files when user selected them
* */
public void setFiles(List<File> newFiles){
public synchronized void setFiles(List<File> newFiles){
if (!rowsObsLst.isEmpty()){
List<String> filesAlreayInList = new ArrayList<>();
for (NSLRowModel model : rowsObsLst)
@ -248,7 +251,7 @@ public class NSTableViewController implements Initializable {
else {
for (File file: newFiles)
rowsObsLst.add(new NSLRowModel(file, true));
MediatorControl.getInstance().getContoller().getFrontCtrlr().disableUploadStopBtn(false); // TODO: change to something better
gamesController.disableUploadStopBtn(false);
}
//rowsObsLst.get(0).setMarkForUpload(true);
table.refresh();

View file

@ -25,7 +25,6 @@ import javafx.scene.control.Label;
import javafx.scene.layout.Region;
import javafx.stage.DirectoryChooser;
import nsusbloader.AppPreferences;
import nsusbloader.MediatorControl;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.Utilities.nxdumptool.NxdtTask;
@ -34,7 +33,7 @@ import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
public class NxdtController implements Initializable {
public class NxdtController implements Initializable, ISubscriber {
@FXML
private Label saveToLocationLbl, statusLbl;
@ -52,11 +51,8 @@ public class NxdtController implements Initializable {
public void initialize(URL url, ResourceBundle resourceBundle) {
this.rb = resourceBundle;
File saveToValidator = new File(AppPreferences.getInstance().getNXDTSaveToLocation());
if (saveToValidator.exists())
saveToLocationLbl.setText(saveToValidator.getAbsolutePath());
else
saveToLocationLbl.setText(System.getProperty("user.home"));
String saveToLocation = AppPreferences.getInstance().getNXDTSaveToLocation();
saveToLocationLbl.setText(saveToLocation);
btnDumpStopImage = new Region();
btnDumpStopImage.getStyleClass().add("regionDump");
@ -81,7 +77,6 @@ public class NxdtController implements Initializable {
* */
private void startDumpProcess(){
if ((workThread == null || ! workThread.isAlive())){
MediatorControl.getInstance().getContoller().logArea.clear();
nxdtTask = new NxdtTask(saveToLocationLbl.getText());
workThread = new Thread(nxdtTask);
@ -99,12 +94,22 @@ public class NxdtController implements Initializable {
}
}
public void notifyThreadStarted(boolean isActive, EModule type){
/**
* Save application settings on exit
* */
public void updatePreferencesOnExit(){
AppPreferences.getInstance().setNXDTSaveToLocation(saveToLocationLbl.getText());
}
@Override
public void notify(EModule type, boolean isActive, Payload payload) {
if (! type.equals(EModule.NXDT)){
injectPldBtn.setDisable(isActive);
return;
}
statusLbl.setText(payload.getMessage());
if (isActive) {
btnDumpStopImage.getStyleClass().clear();
btnDumpStopImage.getStyleClass().add("regionStop");
@ -123,16 +128,4 @@ public class NxdtController implements Initializable {
injectPldBtn.getStyleClass().remove("buttonStop");
injectPldBtn.getStyleClass().add("buttonUp");
}
public void setOneLineStatus(boolean status){
if (status)
statusLbl.setText(rb.getString("done_txt"));
else
statusLbl.setText(rb.getString("failure_txt"));
}
/**
* Save application settings on exit
* */
public void updatePreferencesOnExit(){
AppPreferences.getInstance().setNXDTSaveToLocation(saveToLocationLbl.getText());
}
}

View file

@ -0,0 +1,343 @@
/*
Copyright 2018-2024 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.input.DragEvent;
import javafx.scene.input.TransferMode;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import nsusbloader.AppPreferences;
import nsusbloader.FilesHelper;
import nsusbloader.MediatorControl;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.ServiceWindow;
import nsusbloader.Utilities.patches.es.EsPatchMaker;
import nsusbloader.Utilities.patches.fs.FsPatchMaker;
import nsusbloader.Utilities.patches.loader.LoaderPatchMaker;
// TODO: CLI SUPPORT
public class PatchesController implements Initializable, ISubscriber {
@FXML
private VBox patchesToolPane;
@FXML
private Button makeEsBtn, makeFsBtn, makeLoaderBtn;
@FXML
private Label shortNameFirmwareLbl, locationFirmwareLbl, saveToLbl, shortNameKeysLbl, locationKeysLbl, statusLbl,
locationAtmosphereLbl, shortNameAtmoLbl;
private Thread workThread;
private String previouslyOpenedPath;
private ResourceBundle resourceBundle;
private Region convertRegionEs;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
this.previouslyOpenedPath = System.getProperty("user.home");
String myRegexp;
if (File.separator.equals("/"))
myRegexp = "^.+/";
else
myRegexp = "^.+\\\\";
locationFirmwareLbl.textProperty().addListener((observableValue, currentText, updatedText) ->
shortNameFirmwareLbl.setText(updatedText.replaceAll(myRegexp, "")));
locationKeysLbl.textProperty().addListener((observableValue, currentText, updatedText) ->
shortNameKeysLbl.setText(updatedText.replaceAll(myRegexp, "")));
locationAtmosphereLbl.textProperty().addListener((observableValue, currentText, updatedText) ->
shortNameAtmoLbl.setText(updatedText.replaceAll(myRegexp, "")));
convertRegionEs = createCakeRegion();
makeEsBtn.setGraphic(convertRegionEs);
makeFsBtn.setGraphic(createCakeRegion());
makeLoaderBtn.setGraphic(createCakeRegion());
AppPreferences preferences = AppPreferences.getInstance();
String keysLocation = preferences.getKeysLocation();
File keysFile = new File(keysLocation);
if (keysFile.exists() && keysFile.isFile()) {
locationKeysLbl.setText(keysLocation);
}
saveToLbl.setText(preferences.getPatchesSaveToLocation());
makeEsBtn.disableProperty().bind(Bindings.or(
Bindings.isEmpty(locationFirmwareLbl.textProperty()),
Bindings.isEmpty(locationKeysLbl.textProperty())));
makeEsBtn.setOnAction(actionEvent -> makeEs());
makeFsBtn.disableProperty().bind(Bindings.or(
Bindings.isEmpty(locationFirmwareLbl.textProperty()),
Bindings.isEmpty(locationKeysLbl.textProperty())));
makeFsBtn.setOnAction(actionEvent -> makeFs());
makeLoaderBtn.disableProperty().bind(Bindings.isEmpty(locationAtmosphereLbl.textProperty()));
makeLoaderBtn.setOnAction(actionEvent -> makeLoader());
}
private Region createCakeRegion(){
Region cakeRegion = new Region();
cakeRegion.getStyleClass().add("regionCake");
return cakeRegion;
}
/**
* Drag-n-drop support (dragOver consumer)
* */
@FXML
private void handleDragOver(DragEvent event){
if (event.getDragboard().hasFiles())
event.acceptTransferModes(TransferMode.ANY);
event.consume();
}
/**
* Drag-n-drop support (drop consumer)
* */
@FXML
private void handleDrop(DragEvent event){
List<File> filesDropped = event.getDragboard().getFiles();
for (File file : filesDropped){
if (file.isDirectory()) {
if (file.getName().toLowerCase().contains("atmosphe"))
locationAtmosphereLbl.setText(file.getAbsolutePath());
else
locationFirmwareLbl.setText(file.getAbsolutePath());
continue;
}
String fileName = file.getName().toLowerCase();
if ((fileName.endsWith(".dat")) ||
(fileName.endsWith(".keys") &&
! fileName.equals("dev.keys") &&
! fileName.equals("title.keys")))
locationKeysLbl.setText(file.getAbsolutePath());
else if (fileName.equals("offsets.txt"))
setOffsets(file);
}
event.setDropCompleted(true);
event.consume();
}
private void setOffsets(File fileWithOffsets){
AppPreferences preferences = AppPreferences.getInstance();
int count = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(fileWithOffsets))) {
String fileLine;
String[] lineValues;
while ((fileLine = reader.readLine()) != null) {
if (fileLine.startsWith("#"))
continue;
lineValues = fileLine.trim().split("\\s+?=\\s+?", 2);
if (lineValues.length == 2) {
String[] pointer = lineValues[0].split("_", 3);
if (! pointer[0].equals("ES") && ! pointer[0].equals("FS"))
continue;
if (! pointer[1].matches("^([0-9A-Fa-f]{2})$"))
continue;
if (! pointer[2].matches("^([0-9A-Fa-f]{2})$"))
continue;
if (! lineValues[1].matches("^(([0-9A-Fa-f]{2})|\\.)+?$"))
continue;
preferences.setPatchPattern(lineValues[0], lineValues[1]);
System.out.println(pointer[0]+"_"+pointer[1]+"_"+pointer[2]+" = "+lineValues[1]);
count++;
statusLbl.setText("OK "+count);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
@FXML
private void selectFirmware(){
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle(resourceBundle.getString("tabPatches_Lbl_Firmware"));
directoryChooser.setInitialDirectory(new File(FilesHelper.getRealFolder(previouslyOpenedPath)));
File firmware = directoryChooser.showDialog(patchesToolPane.getScene().getWindow());
if (firmware == null)
return;
locationFirmwareLbl.setText(firmware.getAbsolutePath());
previouslyOpenedPath = firmware.getParent();
}
@FXML
private void selectAtmosphereFolder(){
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle(resourceBundle.getString("tabPatches_Lbl_Atmo"));
directoryChooser.setInitialDirectory(new File(FilesHelper.getRealFolder(previouslyOpenedPath)));
File firmware = directoryChooser.showDialog(patchesToolPane.getScene().getWindow());
if (firmware == null)
return;
locationAtmosphereLbl.setText(firmware.getAbsolutePath());
previouslyOpenedPath = firmware.getParent();
}
@FXML
private void selectSaveTo(){
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle(resourceBundle.getString("tabSplMrg_Btn_SelectFolder"));
directoryChooser.setInitialDirectory(new File(FilesHelper.getRealFolder(previouslyOpenedPath)));
File saveToDir = directoryChooser.showDialog(patchesToolPane.getScene().getWindow());
if (saveToDir == null)
return;
saveToLbl.setText(saveToDir.getAbsolutePath());
}
@FXML
private void selectProdKeys(){
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(resourceBundle.getString("tabPatches_Lbl_Keys"));
fileChooser.setInitialDirectory(new File(FilesHelper.getRealFolder(previouslyOpenedPath)));
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("keys", "*.dat", "*.keys"));
File keys = fileChooser.showOpenDialog(patchesToolPane.getScene().getWindow());
if (keys == null || ! keys.exists())
return;
locationKeysLbl.setText(keys.getAbsolutePath());
previouslyOpenedPath = keys.getParent();
}
private void makeEs(){
if (locationFirmwareLbl.getText().isEmpty() || locationKeysLbl.getText().isEmpty()){
ServiceWindow.getErrorNotification(resourceBundle.getString("windowTitleError"),
resourceBundle.getString("tabPatches_ServiceWindowMessageEsFs"));
return;
}
if (workThread != null && workThread.isAlive())
return;
if (MediatorControl.INSTANCE.getTransferActive()) {
ServiceWindow.getErrorNotification(resourceBundle.getString("windowTitleError"),
resourceBundle.getString("windowBodyPleaseStopOtherProcessFirst"));
return;
}
EsPatchMaker esPatchMaker = new EsPatchMaker(locationFirmwareLbl.getText(), locationKeysLbl.getText(),
saveToLbl.getText());
workThread = new Thread(esPatchMaker);
workThread.setDaemon(true);
workThread.start();
}
private void makeFs(){
if (locationFirmwareLbl.getText().isEmpty() || locationKeysLbl.getText().isEmpty()){
ServiceWindow.getErrorNotification(resourceBundle.getString("windowTitleError"),
resourceBundle.getString("tabPatches_ServiceWindowMessageEsFs"));
return;
}
if (workThread != null && workThread.isAlive())
return;
if (MediatorControl.INSTANCE.getTransferActive()) {
ServiceWindow.getErrorNotification(resourceBundle.getString("windowTitleError"),
resourceBundle.getString("windowBodyPleaseStopOtherProcessFirst"));
return;
}
FsPatchMaker fsPatchMaker = new FsPatchMaker(locationFirmwareLbl.getText(), locationKeysLbl.getText(),
saveToLbl.getText());
workThread = new Thread(fsPatchMaker);
workThread.setDaemon(true);
workThread.start();
}
private void makeLoader(){
if (locationAtmosphereLbl.getText().isEmpty()){
ServiceWindow.getErrorNotification(resourceBundle.getString("windowTitleError"),
resourceBundle.getString("tabPatches_ServiceWindowMessageLoader"));
return;
}
if (workThread != null && workThread.isAlive())
return;
if (MediatorControl.INSTANCE.getTransferActive()) {
ServiceWindow.getErrorNotification(resourceBundle.getString("windowTitleError"),
resourceBundle.getString("windowBodyPleaseStopOtherProcessFirst"));
return;
}
LoaderPatchMaker loaderPatchMaker = new LoaderPatchMaker(locationAtmosphereLbl.getText(), saveToLbl.getText());
workThread = new Thread(loaderPatchMaker);
workThread.setDaemon(true);
workThread.start();
}
private void interruptProcessOfPatchMaking(){
if (workThread == null || ! workThread.isAlive())
return;
workThread.interrupt();
}
@Override
public void notify(EModule type, boolean isActive, Payload payload) {
if (! type.equals(EModule.PATCHES)) {
patchesToolPane.setDisable(isActive);
return;
}
statusLbl.setText(payload.getMessage());
convertRegionEs.getStyleClass().clear();
makeFsBtn.setVisible(! isActive);
makeLoaderBtn.setVisible(! isActive);
if (isActive) {
convertRegionEs.getStyleClass().add("regionStop");
makeEsBtn.setOnAction(e-> interruptProcessOfPatchMaking());
makeEsBtn.setText(resourceBundle.getString("btn_Stop"));
makeEsBtn.getStyleClass().remove("buttonUp");
makeEsBtn.getStyleClass().add("buttonStop");
return;
}
convertRegionEs.getStyleClass().add("regionCake");
makeEsBtn.setOnAction(actionEvent -> makeEs());
makeEsBtn.setText(resourceBundle.getString("tabPatches_Btn_MakeEs"));
makeEsBtn.getStyleClass().remove("buttonStop");
makeEsBtn.getStyleClass().add("buttonUp");
}
void updatePreferencesOnExit(){
AppPreferences.getInstance().setPatchesSaveToLocation(saveToLbl.getText());
if (locationKeysLbl.getText().isEmpty())
return;
AppPreferences.getInstance().setKeysLocation(locationKeysLbl.getText());
}
}

View file

@ -0,0 +1,48 @@
/*
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Controllers;
import nsusbloader.NSLDataTypes.EFileStatus;
import java.util.Collections;
import java.util.Map;
public class Payload {
private final String message;
private final Map<String, EFileStatus> statusMap;
public Payload(){
this("");
}
public Payload(String message){
this(message, Collections.emptyMap());
}
public Payload(String message, Map<String, EFileStatus> statusMap){
this.message = message;
this.statusMap = statusMap;
}
public String getMessage() {
return message;
}
public Map<String, EFileStatus> getStatusMap() {
return statusMap;
}
}

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
@ -41,7 +41,7 @@ import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
public class RcmController implements Initializable {
public class RcmController implements Initializable, ISubscriber {
@FXML
private ToggleGroup rcmToggleGrp;
@ -68,12 +68,14 @@ public class RcmController implements Initializable {
@FXML
private Label statusLbl;
private AppPreferences preferences;
private ResourceBundle rb;
private String myRegexp;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
this.rb = resourceBundle;
final AppPreferences preferences = AppPreferences.getInstance();
this.preferences = AppPreferences.getInstance();
rcmToggleGrp.selectToggle(pldrRadio1);
pldrRadio1.setOnAction(e -> statusLbl.setText(""));
@ -193,8 +195,7 @@ public class RcmController implements Initializable {
}
private void smash(){
statusLbl.setText("");
if (MediatorControl.getInstance().getTransferActive()) {
if (MediatorControl.INSTANCE.getTransferActive()) {
ServiceWindow.getErrorNotification(rb.getString("windowTitleError"),
rb.getString("windowBodyPleaseStopOtherProcessFirst"));
return;
@ -273,31 +274,28 @@ public class RcmController implements Initializable {
private void bntResetPayloader(ActionEvent event){
final Node btn = (Node)event.getSource();
statusLbl.setText("");
switch (btn.getId()){
case "resPldBtn1":
payloadFNameLbl1.setText("");
payloadFPathLbl1.setText("");
statusLbl.setText("");
break;
case "resPldBtn2":
payloadFNameLbl2.setText("");
payloadFPathLbl2.setText("");
statusLbl.setText("");
break;
case "resPldBtn3":
payloadFNameLbl3.setText("");
payloadFPathLbl3.setText("");
statusLbl.setText("");
break;
case "resPldBtn4":
payloadFNameLbl4.setText("");
payloadFPathLbl4.setText("");
statusLbl.setText("");
break;
case "resPldBtn5":
payloadFNameLbl5.setText("");
payloadFPathLbl5.setText("");
statusLbl.setText("");
}
}
@ -324,27 +322,20 @@ public class RcmController implements Initializable {
}
}
public void setOneLineStatus(boolean statusSuccess){
if (statusSuccess)
statusLbl.setText(rb.getString("done_txt"));
else
statusLbl.setText(rb.getString("failure_txt"));
}
public void notifyThreadStarted(boolean isStart, EModule type){
rcmToolPane.setDisable(isStart);
if (type.equals(EModule.RCM) && isStart){
MediatorControl.getInstance().getContoller().logArea.clear();
}
@Override
public void notify(EModule type, boolean isActive, Payload payload) {
rcmToolPane.setDisable(isActive);
if (type.equals(EModule.RCM))
statusLbl.setText(payload.getMessage());
}
/**
* Save application settings on exit
* */
public void updatePreferencesOnExit(){
AppPreferences.getInstance().setRecentRcm(1, payloadFPathLbl1.getText());
AppPreferences.getInstance().setRecentRcm(2, payloadFPathLbl2.getText());
AppPreferences.getInstance().setRecentRcm(3, payloadFPathLbl3.getText());
AppPreferences.getInstance().setRecentRcm(4, payloadFPathLbl4.getText());
AppPreferences.getInstance().setRecentRcm(5, payloadFPathLbl5.getText());
preferences.setRecentRcm(1, payloadFPathLbl1.getText());
preferences.setRecentRcm(2, payloadFPathLbl2.getText());
preferences.setRecentRcm(3, payloadFPathLbl3.getText());
preferences.setRecentRcm(4, payloadFPathLbl4.getText());
preferences.setRecentRcm(5, payloadFPathLbl5.getText());
}
}

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
@ -28,6 +28,7 @@ import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Hyperlink;
import javafx.scene.layout.Region;
import nsusbloader.AppPreferences;
import nsusbloader.MediatorControl;
import nsusbloader.ModelControllers.UpdatesChecker;
import nsusbloader.ServiceWindow;
import nsusbloader.UI.LocaleHolder;
@ -42,17 +43,19 @@ import java.util.ResourceBundle;
public class SettingsBlockGenericController implements Initializable {
@FXML
private ChoiceBox<LocaleHolder> languagesChB;
@FXML
private Button fontSelectBtn;
@FXML
private Button submitLanguageBtn,
driversInstallBtn,
checkForUpdBtn;
@FXML
private CheckBox autoCheckForUpdatesCB;
private CheckBox autoCheckForUpdatesCB,
direcroriesChooserForRomsCB;
@FXML
private Hyperlink newVersionHyperlink;
private ResourceBundle resourceBundle;
private HostServices hostServices;
@Override
@ -61,6 +64,10 @@ public class SettingsBlockGenericController implements Initializable {
final AppPreferences preferences = AppPreferences.getInstance();
autoCheckForUpdatesCB.setSelected(preferences.getAutoCheckUpdates());
direcroriesChooserForRomsCB.setSelected(preferences.getDirectoriesChooserForRoms());
direcroriesChooserForRomsCB.setOnAction(actionEvent ->
MediatorControl.INSTANCE.getGamesController().setFilesSelectorButtonBehaviour(direcroriesChooserForRomsCB.isSelected())
);
Region btnSwitchImage = new Region();
btnSwitchImage.getStyleClass().add("regionUpdatesCheck");
@ -72,9 +79,18 @@ public class SettingsBlockGenericController implements Initializable {
languagesChB.setItems(settingsLanguagesSetup.getLanguages());
languagesChB.getSelectionModel().select(settingsLanguagesSetup.getRecentLanguage());
hostServices = MediatorControl.INSTANCE.getHostServices();
newVersionHyperlink.setOnAction(e-> hostServices.showDocument(newVersionHyperlink.getText()));
checkForUpdBtn.setOnAction(e->checkForUpdatesAction());
submitLanguageBtn.setOnAction(e->languageButtonAction());
fontSelectBtn.setOnAction(e -> openFontSettings());
}
private void openFontSettings() {
try {
new FontSettings(resourceBundle);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private void setDriversInstallFeature(){
@ -124,9 +140,13 @@ public class SettingsBlockGenericController implements Initializable {
ResourceBundle.getBundle("locale", newLocale).getString("windowBodyRestartToApplyLang"));
}
private boolean getAutoCheckForUpdates(){ return autoCheckForUpdatesCB.isSelected(); }
private boolean getAutoCheckForUpdates(){
return autoCheckForUpdatesCB.isSelected();
}
protected void registerHostServices(HostServices hostServices){ this.hostServices = hostServices;}
public boolean isDirectoriesChooserForRoms(){
return direcroriesChooserForRomsCB.isSelected();
}
void setNewVersionLink(String newVer){
newVersionHyperlink.setVisible(true);
@ -135,5 +155,6 @@ public class SettingsBlockGenericController implements Initializable {
void updatePreferencesOnExit() {
AppPreferences.getInstance().setAutoCheckUpdates(getAutoCheckForUpdates());
AppPreferences.getInstance().setDirectoriesChooserForRoms(isDirectoriesChooserForRoms());
}
}

View file

@ -38,7 +38,7 @@ public class SettingsBlockGoldleafController implements Initializable {
final AppPreferences preferences = AppPreferences.getInstance();
nspFilesFilterForGLCB.setSelected(preferences.getNspFileFilterGL());
glVersionChoiceBox.getItems().addAll(AppPreferences.goldleafSupportedVersions);
glVersionChoiceBox.getItems().addAll(AppPreferences.GOLDLEAF_SUPPORTED_VERSIONS);
glVersionChoiceBox.getSelectionModel().select(preferences.getGlVersion());
}
@ -53,6 +53,6 @@ public class SettingsBlockGoldleafController implements Initializable {
final AppPreferences preferences = AppPreferences.getInstance();
preferences.setNspFileFilterGL(getNSPFileFilterForGL());
preferences.setGlVersion(getGlVer());
preferences.setGlVersion(glVersionChoiceBox.getSelectionModel().getSelectedIndex());
}
}

View file

@ -55,7 +55,7 @@ public class SettingsBlockTinfoilController implements Initializable {
final AppPreferences preferences = AppPreferences.getInstance();
networkExpertSettingsVBox.disableProperty().bind(networkExpertModeCB.selectedProperty().not());
networkExpertSettingsVBox.visibleProperty().bind(networkExpertModeCB.selectedProperty());
pcIpTF.disableProperty().bind(autoDetectIpCB.selectedProperty());
pcPortTF.disableProperty().bind(randomlySelectPortCB.selectedProperty());

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
@ -18,9 +18,9 @@
*/
package nsusbloader.Controllers;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.input.DragEvent;
import javafx.scene.input.TransferMode;
@ -29,18 +29,18 @@ import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import nsusbloader.AppPreferences;
import nsusbloader.FilesHelper;
import nsusbloader.MediatorControl;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.ServiceWindow;
import nsusbloader.Utilities.splitmerge.MergeTask;
import nsusbloader.Utilities.splitmerge.SplitTask;
import nsusbloader.Utilities.splitmerge.SplitMergeTaskExecutor;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
public class SplitMergeController implements Initializable {
public class SplitMergeController implements Initializable, ISubscriber {
@FXML
private ToggleGroup splitMergeTogGrp;
@FXML
@ -53,40 +53,39 @@ public class SplitMergeController implements Initializable {
changeSaveToBtn,
convertBtn;
@FXML
private Label fileFolderLabelLbl,
fileFolderActualPathLbl,
saveToPathLbl,
private Label saveToPathLbl,
statusLbl;
@FXML
private BlockListViewController BlockListViewController;
private ResourceBundle resourceBundle;
private Region convertRegion;
private Thread smThread;
private CancellableRunnable smTask;
private Runnable smTask;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
convertRegion = new Region();
convertBtn.setGraphic(convertRegion);
convertBtn.disableProperty().bind(Bindings.isEmpty(BlockListViewController.getItems()));
splitRad.setOnAction((actionEvent -> {
statusLbl.setText("");
convertRegion.getStyleClass().clear();
convertRegion.getStyleClass().add("regionSplitToOne");
fileFolderLabelLbl.setText(resourceBundle.getString("tabSplMrg_Txt_File"));
selectFileFolderBtn.setText(resourceBundle.getString("tabSplMrg_Btn_SelectFile"));
fileFolderActualPathLbl.setText("");
convertBtn.setDisable(true);
BlockListViewController.clear();
}));
mergeRad.setOnAction((actionEvent -> {
statusLbl.setText("");
convertRegion.getStyleClass().clear();
convertRegion.getStyleClass().add("regionOneToSplit");
fileFolderLabelLbl.setText(resourceBundle.getString("tabSplMrg_Txt_Folder"));
selectFileFolderBtn.setText(resourceBundle.getString("tabSplMrg_Btn_SelectFolder"));
fileFolderActualPathLbl.setText("");
convertBtn.setDisable(true);
BlockListViewController.clear();
}));
if (AppPreferences.getInstance().getSplitMergeType() == 0)
@ -94,45 +93,45 @@ public class SplitMergeController implements Initializable {
else
mergeRad.fire();
saveToPathLbl.setText(AppPreferences.getInstance().getSplitMergeRecent());
String previouslyUsedSaveToPath = AppPreferences.getInstance().getSplitMergeRecent();
saveToPathLbl.setText(FilesHelper.getRealFolder(previouslyUsedSaveToPath));
changeSaveToBtn.setOnAction((actionEvent -> {
DirectoryChooser dc = new DirectoryChooser();
dc.setTitle(resourceBundle.getString("tabSplMrg_Btn_SelectFolder"));
dc.setInitialDirectory(new File(saveToPathLbl.getText()));
File saveToDir = dc.showDialog(changeSaveToBtn.getScene().getWindow());
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle(resourceBundle.getString("tabSplMrg_Btn_SelectFolder"));
String saveToLocation = FilesHelper.getRealFolder(saveToPathLbl.getText());
directoryChooser.setInitialDirectory(new File(saveToLocation));
File saveToDir = directoryChooser.showDialog(changeSaveToBtn.getScene().getWindow());
if (saveToDir != null)
saveToPathLbl.setText(saveToDir.getAbsolutePath());
}));
selectFileFolderBtn.setOnAction(actionEvent -> {
statusLbl.setText("");
List<File> alreadyAddedFiles = BlockListViewController.getItems();
if (splitRad.isSelected()) {
FileChooser fc = new FileChooser();
fc.setTitle(resourceBundle.getString("tabSplMrg_Btn_SelectFile"));
if (! fileFolderActualPathLbl.getText().isEmpty()){
File temporaryFile = new File(fileFolderActualPathLbl.getText()).getParentFile();
if (temporaryFile != null && temporaryFile.exists())
fc.setInitialDirectory(temporaryFile);
else
fc.setInitialDirectory(new File(System.getProperty("user.home")));
if (! alreadyAddedFiles.isEmpty()){
String recentLocation = FilesHelper.getRealFolder(alreadyAddedFiles.get(0).getParentFile().getAbsolutePath());
fc.setInitialDirectory(new File(recentLocation));
}
else
fc.setInitialDirectory(new File(System.getProperty("user.home")));
File fileFile = fc.showOpenDialog(changeSaveToBtn.getScene().getWindow());
if (fileFile == null)
List<File> files = fc.showOpenMultipleDialog(changeSaveToBtn.getScene().getWindow());
if (files == null || files.isEmpty())
return;
fileFolderActualPathLbl.setText(fileFile.getAbsolutePath());
this.BlockListViewController.addAll(files);
}
else{
DirectoryChooser dc = new DirectoryChooser();
dc.setTitle(resourceBundle.getString("tabSplMrg_Btn_SelectFolder"));
if (! fileFolderActualPathLbl.getText().isEmpty()){
File temporaryFile = new File(fileFolderActualPathLbl.getText());
if (temporaryFile.exists())
dc.setInitialDirectory(temporaryFile);
else
dc.setInitialDirectory(new File(System.getProperty("user.home")));
if (! alreadyAddedFiles.isEmpty()){
String recentLocation = FilesHelper.getRealFolder(alreadyAddedFiles.get(0).getParentFile().getAbsolutePath());
dc.setInitialDirectory(new File(recentLocation));
}
else
dc.setInitialDirectory(new File(System.getProperty("user.home")));
@ -140,21 +139,94 @@ public class SplitMergeController implements Initializable {
File folderFile = dc.showDialog(changeSaveToBtn.getScene().getWindow());
if (folderFile == null)
return;
fileFolderActualPathLbl.setText(folderFile.getAbsolutePath());
this.BlockListViewController.add(folderFile);
}
convertBtn.setDisable(false);
});
convertBtn.setOnAction(actionEvent -> setConvertBtnAction());
}
public void notifySmThreadStarted(boolean isStart, EModule type){ // todo: refactor: remove everything, place to separate container and just disable.
if (! type.equals(EModule.SPLIT_MERGE_TOOL)){
smToolPane.setDisable(isStart);
/**
* It's button listener when convert-process in progress
* */
private void stopBtnAction(){
if (smThread != null && smThread.isAlive()) {
smThread.interrupt();
}
}
/**
* It's button listener when convert-process NOT in progress
* */
private void setConvertBtnAction(){
if (MediatorControl.INSTANCE.getTransferActive()) {
ServiceWindow.getErrorNotification(
resourceBundle.getString("windowTitleError"),
resourceBundle.getString("windowBodyPleaseFinishTransfersFirst")
);
return;
}
if (isStart){
MediatorControl.getInstance().getContoller().logArea.clear();
if (splitRad.isSelected())
smTask = new SplitMergeTaskExecutor(true, BlockListViewController.getItems(), saveToPathLbl.getText());
else
smTask = new SplitMergeTaskExecutor(false, BlockListViewController.getItems(), saveToPathLbl.getText());
smThread = new Thread(smTask);
smThread.setDaemon(true);
smThread.start();
}
/**
* Drag-n-drop support (dragOver consumer)
* */
@FXML
private void handleDragOver(DragEvent event){
if (event.getDragboard().hasFiles() && ! MediatorControl.INSTANCE.getTransferActive())
event.acceptTransferModes(TransferMode.ANY);
event.consume();
}
/**
* Drag-n-drop support (drop consumer)
* */
@FXML
private void handleDrop(DragEvent event) {
List<File> files = event.getDragboard().getFiles();
File firstFile = files.get(0);
if (firstFile.isDirectory())
mergeRad.fire();
else
splitRad.fire();
this.BlockListViewController.addAll(files);
event.setDropCompleted(true);
event.consume();
}
/**
* Save application settings on exit
* */
public void updatePreferencesOnExit(){
if (splitRad.isSelected())
AppPreferences.getInstance().setSplitMergeType(0);
else
AppPreferences.getInstance().setSplitMergeType(1);
AppPreferences.getInstance().setSplitMergeRecent(saveToPathLbl.getText());
}
@Override
public void notify(EModule type, boolean isActive, Payload payload) {
// todo: refactor: remove everything, place to separate container and just disable.
if (! type.equals(EModule.SPLIT_MERGE_TOOL)){
smToolPane.setDisable(isActive);
return;
}
statusLbl.setText(payload.getMessage());
if (isActive){
splitRad.setDisable(true);
mergeRad.setDisable(true);
selectFileFolderBtn.setDisable(true);
@ -183,78 +255,4 @@ public class SplitMergeController implements Initializable {
else
convertRegion.getStyleClass().add("regionOneToSplit");
}
/**
* It's button listener when convert-process in progress
* */
private void stopBtnAction(){
if (smThread != null && smThread.isAlive()) {
smTask.cancel();
}
}
/**
* It's button listener when convert-process NOT in progress
* */
private void setConvertBtnAction(){
statusLbl.setText("");
if (MediatorControl.getInstance().getTransferActive()) {
ServiceWindow.getErrorNotification(
resourceBundle.getString("windowTitleError"),
resourceBundle.getString("windowBodyPleaseFinishTransfersFirst")
);
return;
}
if (splitRad.isSelected())
smTask = new SplitTask(fileFolderActualPathLbl.getText(), saveToPathLbl.getText());
else
smTask = new MergeTask(fileFolderActualPathLbl.getText(), saveToPathLbl.getText());
smThread = new Thread(smTask);
smThread.setDaemon(true);
smThread.start();
}
/**
* Drag-n-drop support (dragOver consumer)
* */
@FXML
private void handleDragOver(DragEvent event){
if (event.getDragboard().hasFiles() && ! MediatorControl.getInstance().getTransferActive())
event.acceptTransferModes(TransferMode.ANY);
event.consume();
}
/**
* Drag-n-drop support (drop consumer)
* */
@FXML
private void handleDrop(DragEvent event) {
Node sourceNode = (Node) event.getSource();
File fileDrpd = event.getDragboard().getFiles().get(0);
if (fileDrpd.isDirectory())
mergeRad.fire();
else
splitRad.fire();
fileFolderActualPathLbl.setText(fileDrpd.getAbsolutePath());
convertBtn.setDisable(false);
event.setDropCompleted(true);
event.consume();
}
public void setOneLineStatus(boolean status){
if (status)
statusLbl.setText(resourceBundle.getString("done_txt"));
else
statusLbl.setText(resourceBundle.getString("failure_txt"));
}
/**
* Save application settings on exit
* */
public void updatePreferencesOnExit(){
if (splitRad.isSelected())
AppPreferences.getInstance().setSplitMergeType(0);
else
AppPreferences.getInstance().setSplitMergeType(1);
AppPreferences.getInstance().setSplitMergeRecent(saveToPathLbl.getText());
}
}

View file

@ -0,0 +1,37 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FilesHelper {
public static String getRealFolder(String location){
try{
Path locationAsPath = Paths.get(location);
if (Files.notExists(locationAsPath) || Files.isRegularFile(locationAsPath))
return System.getProperty("user.home");
return location;
}
catch (Exception ignored){
return System.getProperty("user.home");
}
}
}

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
@ -18,33 +18,57 @@
*/
package nsusbloader;
import nsusbloader.Controllers.NSLMainController;
import javafx.application.HostServices;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextArea;
import nsusbloader.Controllers.*;
import nsusbloader.NSLDataTypes.EModule;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.ResourceBundle;
public class MediatorControl {
private AtomicBoolean isTransferActive = new AtomicBoolean(false); // Overcoded just for sure
private NSLMainController mainCtrler;
public static final MediatorControl INSTANCE = new MediatorControl();
public static MediatorControl getInstance(){
return MediatorControlHold.INSTANCE;
private ResourceBundle resourceBundle;
private TransfersPublisher transfersPublisher;
private HostServices hostServices;
private GamesController gamesController;
private SettingsController settingsController;
private TextArea logArea;
private ProgressBar progressBar;
private MediatorControl(){}
public void configure(ResourceBundle resourceBundle,
SettingsController settingsController,
TextArea logArea,
ProgressBar progressBar,
GamesController gamesController,
TransfersPublisher transfersPublisher) {
this.resourceBundle = resourceBundle;
this.settingsController = settingsController;
this.gamesController = gamesController;
this.logArea = logArea;
this.progressBar = progressBar;
this.transfersPublisher = transfersPublisher;
}
public void setHostServices(HostServices hostServices) {
this.hostServices = hostServices;
}
private static class MediatorControlHold {
private static final MediatorControl INSTANCE = new MediatorControl();
}
public void setController(NSLMainController controller){
this.mainCtrler = controller;
}
public NSLMainController getContoller(){ return this.mainCtrler; }
public HostServices getHostServices() { return hostServices; }
public ResourceBundle getResourceBundle(){ return resourceBundle; }
public SettingsController getSettingsController() { return settingsController; }
public GamesController getGamesController() { return gamesController; }
public TextArea getLogArea() { return logArea; }
public ProgressBar getProgressBar() { return progressBar; }
public synchronized void setBgThreadActive(boolean isActive, EModule appModuleType) {
isTransferActive.set(isActive);
mainCtrler.getFrontCtrlr().notifyThreadStarted(isActive, appModuleType);
mainCtrler.getSmCtrlr().notifySmThreadStarted(isActive, appModuleType);
mainCtrler.getRcmCtrlr().notifyThreadStarted(isActive, appModuleType);
mainCtrler.getNXDTabController().notifyThreadStarted(isActive, appModuleType);
public synchronized void setTransferActive(EModule appModuleType, boolean isActive, Payload payload) {
transfersPublisher.setTransferActive(appModuleType, isActive, payload);
}
public synchronized boolean getTransferActive() {
return transfersPublisher.getTransferActive();
}
public synchronized boolean getTransferActive() { return this.isTransferActive.get(); }
}

View file

@ -26,8 +26,8 @@ import java.io.File;
import java.util.HashMap;
public interface ILogPrinter {
void print(String message, EMsgType type);
void updateProgress(Double value);
void print(String message, EMsgType type) throws InterruptedException;
void updateProgress(Double value) throws InterruptedException;
void update(HashMap<String, File> nspMap, EFileStatus status);
void update(File file, EFileStatus status);
void updateOneLinerStatus(boolean status);

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
@ -32,23 +32,28 @@ public class LogPrinterGui implements ILogPrinter {
private final MessagesConsumer msgConsumer;
private final BlockingQueue<String> msgQueue;
private final BlockingQueue<Double> progressQueue;
private final HashMap<String, EFileStatus> statusMap; // BlockingQueue for literally one object. TODO: read more books ; replace to hashMap
private final HashMap<String, EFileStatus> statusMap;
private final AtomicBoolean oneLinerStatus;
/* TODO: Rewrite 'print()' implementation everywhere */
LogPrinterGui(EModule whoIsAsking){
this.msgQueue = new LinkedBlockingQueue<>();
this.progressQueue = new LinkedBlockingQueue<>();
this.statusMap = new HashMap<>();
this.oneLinerStatus = new AtomicBoolean();
this.msgConsumer = new MessagesConsumer(whoIsAsking, this.msgQueue, this.progressQueue, this.statusMap, this.oneLinerStatus);
this.msgConsumer = new MessagesConsumer(whoIsAsking,
this.msgQueue,
this.progressQueue,
this.statusMap,
this.oneLinerStatus);
this.msgConsumer.start();
}
/**
* This is what will print to textArea of the application.
* */
@Override
public void print(String message, EMsgType type){
try {
public void print(String message, EMsgType type) throws InterruptedException{
switch (type){
case PASS:
msgQueue.put("[ PASS ] "+message+"\n");
@ -66,20 +71,13 @@ public class LogPrinterGui implements ILogPrinter {
msgQueue.put(message);
}
}
catch (InterruptedException ie){
ie.printStackTrace();
}
}
/**
* Update progress for progress bar
* */
@Override
public void updateProgress(Double value) {
try {
public void updateProgress(Double value) throws InterruptedException {
progressQueue.put(value);
}
catch (InterruptedException ignored){} // TODO: Do something with this
}
/**
* When we're done - update status
* */

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
@ -22,28 +22,29 @@ import javafx.animation.AnimationTimer;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;
import nsusbloader.Controllers.NSTableViewController;
import nsusbloader.Controllers.Payload;
import nsusbloader.MediatorControl;
import nsusbloader.NSLDataTypes.EFileStatus;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.NSLDataTypes.EMsgType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
public class MessagesConsumer extends AnimationTimer {
private final BlockingQueue<String> msgQueue;
private final TextArea logsArea;
private static final MediatorControl mediator = MediatorControl.INSTANCE;
private static final TextArea logsArea = mediator.getLogArea();
private static final ProgressBar progressBar = mediator.getProgressBar();;
private static final ResourceBundle resourceBundle = mediator.getResourceBundle();
private final BlockingQueue<String> msgQueue;
private final BlockingQueue<Double> progressQueue;
private final ProgressBar progressBar;
private final HashMap<String, EFileStatus> statusMap;
private final NSTableViewController tableViewController;
private final EModule appModuleType;
private AtomicBoolean oneLinerStatus;
private final AtomicBoolean oneLinerStatus;
private boolean isInterrupted;
@ -54,34 +55,28 @@ public class MessagesConsumer extends AnimationTimer {
AtomicBoolean oneLinerStatus){
this.appModuleType = appModuleType;
this.isInterrupted = false;
this.msgQueue = msgQueue;
this.logsArea = MediatorControl.getInstance().getContoller().logArea;
this.progressQueue = progressQueue;
this.progressBar = MediatorControl.getInstance().getContoller().progressBar;
this.statusMap = statusMap;
this.tableViewController = MediatorControl.getInstance().getContoller().FrontTabController.tableFilesListController;
this.oneLinerStatus = oneLinerStatus;
progressBar.setProgress(0.0);
progressBar.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS);
MediatorControl.getInstance().setBgThreadActive(true, appModuleType);
logsArea.clear();
mediator.setTransferActive(appModuleType, true, new Payload());
}
@Override
public void handle(long l){
ArrayList<String> messages = new ArrayList<>();
int msgRecieved = msgQueue.drainTo(messages);
if (msgRecieved > 0)
int msgReceived = msgQueue.drainTo(messages);
if (msgReceived > 0)
messages.forEach(logsArea::appendText);
ArrayList<Double> progress = new ArrayList<>();
int progressRecieved = progressQueue.drainTo(progress);
if (progressRecieved > 0) {
int progressReceived = progressQueue.drainTo(progress);
if (progressReceived > 0) {
progress.forEach(prg -> {
if (prg != 1.0)
progressBar.setProgress(prg);
@ -90,30 +85,20 @@ public class MessagesConsumer extends AnimationTimer {
});
}
if (isInterrupted) { // It's safe 'cuz it's could't be interrupted while HashMap populating
MediatorControl.getInstance().setBgThreadActive(false, appModuleType);
if (isInterrupted) // safe, could not be interrupted while HashMap populating
updateElementsAndStop();
}
private void updateElementsAndStop(){
Payload payload = new Payload(
resourceBundle.getString(oneLinerStatus.get() ? "done_txt" : "failure_txt"),
statusMap);
mediator.setTransferActive(appModuleType, false, payload);
progressBar.setProgress(0.0);
if (statusMap.size() > 0){
for (String key : statusMap.keySet())
tableViewController.setFileStatus(key, statusMap.get(key));
}
switch (appModuleType){
case RCM:
MediatorControl.getInstance().getContoller().getRcmCtrlr().setOneLineStatus(oneLinerStatus.get());
break;
case NXDT:
MediatorControl.getInstance().getContoller().getNXDTabController().setOneLineStatus(oneLinerStatus.get());
break;
case SPLIT_MERGE_TOOL:
MediatorControl.getInstance().getContoller().getSmCtrlr().setOneLineStatus(oneLinerStatus.get());
break;
}
this.stop();
}
}
public void interrupt(){
this.isInterrupted = true;

View file

@ -22,5 +22,6 @@ public enum EModule {
USB_NET_TRANSFERS,
SPLIT_MERGE_TOOL,
RCM,
NXDT
NXDT,
PATCHES
}

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
@ -28,11 +28,12 @@ import nsusbloader.Controllers.NSLMainController;
import nsusbloader.cli.CommandLineInterface;
import java.util.Locale;
import java.util.Objects;
import java.util.ResourceBundle;
public class NSLMain extends Application {
public static final String appVersion = "v4.3";
public static String appVersion;
public static boolean isCli;
@Override
@ -46,10 +47,10 @@ public class NSLMain extends Application {
Parent root = loader.load();
primaryStage.getIcons().addAll(
new Image(getClass().getResourceAsStream("/res/app_icon32x32.png")),
new Image(getClass().getResourceAsStream("/res/app_icon48x48.png")),
new Image(getClass().getResourceAsStream("/res/app_icon64x64.png")),
new Image(getClass().getResourceAsStream("/res/app_icon128x128.png"))
new Image(Objects.requireNonNull(getClass().getResourceAsStream("/res/app_icon32x32.png"))),
new Image(Objects.requireNonNull(getClass().getResourceAsStream("/res/app_icon48x48.png"))),
new Image(Objects.requireNonNull(getClass().getResourceAsStream("/res/app_icon64x64.png"))),
new Image(Objects.requireNonNull(getClass().getResourceAsStream("/res/app_icon128x128.png")))
);
primaryStage.setTitle("NS-USBloader "+appVersion);
@ -61,18 +62,21 @@ public class NSLMain extends Application {
);
mainScene.getStylesheets().add(AppPreferences.getInstance().getTheme());
root.setStyle(AppPreferences.getInstance().getFontStyle());
primaryStage.setScene(mainScene);
primaryStage.show();
primaryStage.setOnCloseRequest(e->{
if (MediatorControl.getInstance().getTransferActive())
if(! ServiceWindow.getConfirmationWindow(rb.getString("windowTitleConfirmExit"), rb.getString("windowBodyConfirmExit")))
if (MediatorControl.INSTANCE.getTransferActive())
if(! ServiceWindow.getConfirmationWindow(rb.getString("windowTitleConfirmExit"),
rb.getString("windowBodyConfirmExit")))
e.consume();
});
NSLMainController controller = loader.getController();
controller.setHostServices(getHostServices());
MediatorControl.INSTANCE.setHostServices(getHostServices());
primaryStage.setOnHidden(e-> {
AppPreferences.getInstance().setSceneHeight(mainScene.getHeight());
AppPreferences.getInstance().setSceneWidth(mainScene.getWidth());
@ -81,6 +85,7 @@ public class NSLMain extends Application {
}
public static void main(String[] args) {
NSLMain.appVersion = ResourceBundle.getBundle("app").getString("_version");
if (args.length == 0) {
launch(args);
}

View file

@ -1,71 +0,0 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader;
import java.nio.charset.StandardCharsets;
/**
* Debug tool like hexdump <3
*/
public class RainbowHexDump {
private static final String ANSI_RESET = "\u001B[0m";
private static final String ANSI_BLACK = "\u001B[30m";
private static final String ANSI_RED = "\u001B[31m";
private static final String ANSI_GREEN = "\u001B[32m";
private static final String ANSI_YELLOW = "\u001B[33m";
private static final String ANSI_BLUE = "\u001B[34m";
private static final String ANSI_PURPLE = "\u001B[35m";
private static final String ANSI_CYAN = "\u001B[36m";
private static final String ANSI_WHITE = "\u001B[37m";
public static void hexDumpUTF8(byte[] byteArray){
System.out.print(ANSI_BLUE);
for (int i=0; i < byteArray.length; i++)
System.out.print(String.format("%02d-", i%100));
System.out.println(">"+ANSI_RED+byteArray.length+ANSI_RESET);
for (byte b: byteArray)
System.out.print(String.format("%02x ", b));
System.out.println();
System.out.print("\t\t\t"
+ new String(byteArray, StandardCharsets.UTF_8)
+ "\n");
}
public static void hexDumpUTF8ForWin(byte[] byteArray){
for (int i=0; i < byteArray.length; i++)
System.out.print(String.format("%02d-", i%100));
System.out.println(">"+byteArray.length);
for (byte b: byteArray)
System.out.print(String.format("%02x ", b));
System.out.println();
System.out.print(new String(byteArray, StandardCharsets.UTF_8)
+ "\n");
}
public static void hexDumpUTF16LE(byte[] byteArray){
System.out.print(ANSI_BLUE);
for (int i=0; i < byteArray.length; i++)
System.out.print(String.format("%02d-", i%100));
System.out.println(">"+ANSI_RED+byteArray.length+ANSI_RESET);
for (byte b: byteArray)
System.out.print(String.format("%02x ", b));
System.out.print(new String(byteArray, StandardCharsets.UTF_16LE)
+ "\n");
}
}

View file

@ -44,7 +44,6 @@ public class ServiceWindow {
alertBox.getDialogPane().setMinWidth(Region.USE_PREF_SIZE);
alertBox.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alertBox.setResizable(true); // Java bug workaround for JDR11/OpenJFX. TODO: nothing. really.
alertBox.getDialogPane().getStylesheets().add(AppPreferences.getInstance().getTheme());
Stage dialogStage = (Stage) alertBox.getDialogPane().getScene().getWindow();
dialogStage.setAlwaysOnTop(true);
@ -54,6 +53,9 @@ public class ServiceWindow {
new Image("/res/warn_ico64x64.png"),
new Image("/res/warn_ico128x128.png")
);
alertBox.getDialogPane().getStylesheets().add(AppPreferences.getInstance().getTheme());
dialogStage.getScene().getRoot().setStyle(AppPreferences.getInstance().getFontStyle());
alertBox.show();
dialogStage.toFront();
}
@ -68,7 +70,6 @@ public class ServiceWindow {
alertBox.getDialogPane().setMinWidth(Region.USE_PREF_SIZE);
alertBox.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alertBox.setResizable(true); // Java bug workaround for JDR11/OpenJFX. TODO: nothing. really.
alertBox.getDialogPane().getStylesheets().add(AppPreferences.getInstance().getTheme());
Stage dialogStage = (Stage) alertBox.getDialogPane().getScene().getWindow();
dialogStage.setAlwaysOnTop(true);
@ -78,6 +79,10 @@ public class ServiceWindow {
new Image("/res/ask_ico64x64.png"),
new Image("/res/ask_ico128x128.png")
);
alertBox.getDialogPane().getStylesheets().add(AppPreferences.getInstance().getTheme());
dialogStage.getScene().getRoot().setStyle(AppPreferences.getInstance().getFontStyle());
dialogStage.toFront();
Optional<ButtonType> result = alertBox.showAndWait();

View file

@ -0,0 +1,47 @@
/*
Copyright 2019-2024 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader;
import nsusbloader.Controllers.ISubscriber;
import nsusbloader.Controllers.Payload;
import nsusbloader.NSLDataTypes.EModule;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class TransfersPublisher {
private final AtomicBoolean isTransferActive = new AtomicBoolean(false);
private final List<ISubscriber> subscribers = new ArrayList<>();
public TransfersPublisher(ISubscriber... subscriber){
subscribers.addAll(Arrays.asList(subscriber));
}
public void setTransferActive(EModule appModuleType, boolean isActive, Payload payload) {
isTransferActive.set(isActive);
subscribers.forEach(s->s.notify(appModuleType, isActive, payload));
}
public boolean getTransferActive() {
return isTransferActive.get();
}
}

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2022 Dmitry Isaenko
This file is part of NS-USBloader.
@ -26,16 +26,14 @@ public class LocaleHolder {
private final String localeCode;
private final String languageName;
public LocaleHolder(Locale locale){
this.locale = locale;
this.localeCode = locale.toString();
this.languageName = locale.getDisplayLanguage(locale) + " (" + locale + ")";
}
public LocaleHolder(String localeFileName) {
String country = localeFileName.substring(7, 9);
String language = localeFileName.substring(10, 12);
this.locale = new Locale(country, language);
String language = localeFileName.substring(7, 9);
String country;
if (localeFileName.length() > 23) // ISO 639-3 not supported by Java
country = localeFileName.substring(10, localeFileName.indexOf('.'));
else // ISO 639-1
country = localeFileName.substring(10, 12);
this.locale = new Locale(language, country);
this.localeCode = locale.toString();
this.languageName = locale.getDisplayLanguage(locale) + " (" + locale + ")";
}
@ -47,7 +45,7 @@ public class LocaleHolder {
public String getLocaleCode(){
return localeCode;
};
}
public Locale getLocale() {
return locale;

View file

@ -24,8 +24,8 @@
*/
package nsusbloader.Utilities;
import nsusbloader.COM.USB.UsbConnect;
import nsusbloader.COM.USB.UsbErrorCodes;
import nsusbloader.com.usb.UsbConnect;
import nsusbloader.com.usb.UsbErrorCodes;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.ModelControllers.Log;
import nsusbloader.NSLDataTypes.EModule;
@ -39,14 +39,12 @@ import java.util.Arrays;
public class Rcm implements Runnable{
private boolean status = false;
private enum ECurrentOS {
win, lin, mac, unsupported
}
private ILogPrinter logPrinter;
private String filePath;
private final ILogPrinter logPrinter;
private final String filePath;
private DeviceHandle handler;
@ -74,8 +72,8 @@ public class Rcm implements Runnable{
@Override
public void run() {
logPrinter.print("Selected: "+filePath, EMsgType.INFO);
logPrinter.print("=============== RCM ===============", EMsgType.INFO);
print("Selected: "+filePath, EMsgType.INFO);
print("=============== RCM ===============", EMsgType.INFO);
ECurrentOS ecurrentOS;
String realOsName = System.getProperty("os.name").toLowerCase().replace(" ", "");
@ -87,11 +85,11 @@ public class Rcm implements Runnable{
ecurrentOS = ECurrentOS.lin;
else
ecurrentOS = ECurrentOS.unsupported;
logPrinter.print("Found your OS: "+System.getProperty("os.name"), EMsgType.PASS);
print("Found your OS: "+System.getProperty("os.name"), EMsgType.PASS);
if (! ecurrentOS.equals(ECurrentOS.mac)){
if (! RcmSmash.isSupported()){
logPrinter.print("Unfortunately your platform '"+System.getProperty("os.name")+
print("Unfortunately your platform '"+System.getProperty("os.name")+
"' of '"+System.getProperty("os.arch")+"' is not supported :("+
"\n But you could file a bug with request."+
"\n\n Nothing has been sent to NS. Execution stopped.", EMsgType.FAIL);
@ -126,14 +124,14 @@ public class Rcm implements Runnable{
// Send payload
for (int i=0; i < fullPayload.length / 4096 ; i++){
if (writeUsb(Arrays.copyOfRange(fullPayload, i*4096, (i+1)*4096))){
logPrinter.print("Failed to sent payload ["+i+"]"+
print("Failed to sent payload ["+i+"]"+
"\n\n Execution stopped.", EMsgType.FAIL);
usbConnect.close();
logPrinter.close();
return;
}
}
logPrinter.print("Information sent to NS.", EMsgType.PASS);
print("Information sent to NS.", EMsgType.PASS);
if (ecurrentOS.equals(ECurrentOS.mac)){
if (smashMacOS()){
@ -151,7 +149,7 @@ public class Rcm implements Runnable{
retval = RcmSmash.smashWindows();
else {
// ( ?_?)
logPrinter.print("Failed to smash the stack since your OS is not supported. Please report this issue."+
print("Failed to smash the stack since your OS is not supported. Please report this issue."+
"\n\n Execution stopped and failed. And it's strange.", EMsgType.FAIL);
usbConnect.close();
logPrinter.close();
@ -159,18 +157,27 @@ public class Rcm implements Runnable{
}
if (retval != 0){
logPrinter.print("Failed to smash the stack ("+retval+")"+
print("Failed to smash the stack ("+retval+")"+
"\n\n Execution stopped and failed.", EMsgType.FAIL);
usbConnect.close();
logPrinter.close();
return;
}
}
logPrinter.print(".:: Payload complete ::.", EMsgType.PASS);
print(".:: Payload complete ::.", EMsgType.PASS);
usbConnect.close();
logPrinter.updateOneLinerStatus(true);
logPrinter.close();
}
private void print(String message, EMsgType type){
try {
logPrinter.print(message, type);
}
catch (InterruptedException intr){
intr.printStackTrace();
}
}
/**
* Prepare the 'big' or full-size byte-buffer that is actually is a payload that we're about to use.
* @return false for issues
@ -181,7 +188,7 @@ public class Rcm implements Runnable{
// 126296 b <- biggest size per CTCaer; 16384 selected randomly as minimum threshold. It's probably wrong.
if (pldrFile.length() > 126296 || pldrFile.length() < 16384) {
logPrinter.print("File size of this payload looks wired. It's "+pldrFile.length()+" bytes."+
print("File size of this payload looks wired. It's "+pldrFile.length()+" bytes."+
"\n 1. Double-check that you're using the right payload." +
"\n 2. Please report this issue in case you're sure that you're doing everything right." +
"\n\n Nothing has been sent to NS. Execution stopped.", EMsgType.FAIL);
@ -196,7 +203,7 @@ public class Rcm implements Runnable{
totalSize += 4096;
// Double-check
if (totalSize > 0x30298){
logPrinter.print("File size of the payload is too big. Comparing to maximum size, it's greater to "+(totalSize - 0x30298)+" bytes!"+
print("File size of the payload is too big. Comparing to maximum size, it's greater to "+(totalSize - 0x30298)+" bytes!"+
"\n 1. Double-check that you're using the right payload." +
"\n 2. Please report this issue in case you're sure that you're doing everything right." +
"\n\n Nothing has been sent to NS. Execution stopped.", EMsgType.FAIL); // Occurs: never. I'm too lazy to check.
@ -211,7 +218,7 @@ public class Rcm implements Runnable{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pldrFile));
int readSize;
if ((readSize = bis.read(dataPldFile)) != pldFileSize){
logPrinter.print("Failed to retrieve data from payload file." +
print("Failed to retrieve data from payload file." +
"\n Got only "+readSize+" bytes while "+pldFileSize+" expected." +
"\n\n Nothing has been sent to NS. Execution stopped.", EMsgType.FAIL);
bis.close();
@ -220,7 +227,7 @@ public class Rcm implements Runnable{
bis.close();
}
catch (Exception e){
logPrinter.print("Failed to retrieve data from payload file: " +e.getMessage()+
print("Failed to retrieve data from payload file: " +e.getMessage()+
"\n\n Nothing has been sent to NS. Execution stopped.", EMsgType.FAIL);
return true;
}
@ -243,7 +250,7 @@ public class Rcm implements Runnable{
IntBuffer readBufTransferred = IntBuffer.allocate(1);
int result = LibUsb.bulkTransfer(handler, (byte) 0x81, readBuffer, readBufTransferred, 1000);
if (result != LibUsb.SUCCESS) {
logPrinter.print("Unable to get device ID" +
print("Unable to get device ID" +
"\n\n Nothing has been sent to NS. Execution stopped.", EMsgType.FAIL);
return true;
}
@ -253,7 +260,7 @@ public class Rcm implements Runnable{
StringBuilder idStrBld = new StringBuilder("Found device with ID: ");
for (byte b: receivedBytes)
idStrBld.append(String.format("%02x ", b));
logPrinter.print(idStrBld.toString(), EMsgType.PASS);
print(idStrBld.toString(), EMsgType.PASS);
return false;
}
/**
@ -271,13 +278,13 @@ public class Rcm implements Runnable{
if (writeBufTransferred.get() == 4096)
return false;
logPrinter.print("RCM Data transfer issue [write]" +
print("RCM Data transfer issue [write]" +
"\n Requested: " + message.length +
"\n Transferred: " + writeBufTransferred.get()+
"\n\n Execution stopped.", EMsgType.FAIL);
return true;
}
logPrinter.print("RCM Data transfer issue [write]" +
print("RCM Data transfer issue [write]" +
"\n Returned: " + UsbErrorCodes.getErrCode(result) +
"\n\n Execution stopped.", EMsgType.FAIL);
return true;

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2023 Dmitry Isaenko
This file is part of NS-USBloader.
@ -25,8 +25,8 @@ import java.net.URL;
public class DownloadDriversTask extends Task<String> {
public static final long DRIVERS_FILE_SIZE = 3857375;
private static final String driverFileLocationURL = "https://github.com/developersu/NS-Drivers/releases/download/v1.0/Drivers_set.exe";
private static final long driversFileSize = 3857375;
private static File driversInstallerFile;
@ -38,7 +38,7 @@ public class DownloadDriversTask extends Task<String> {
}
private boolean isDriversDownloaded(){
return driversInstallerFile != null && driversInstallerFile.length() == driversFileSize;
return driversInstallerFile != null && driversInstallerFile.length() == DRIVERS_FILE_SIZE;
}
private boolean downloadDrivers(){
@ -64,7 +64,7 @@ public class DownloadDriversTask extends Task<String> {
while ((bytesRead = bis.read(dataBuffer, 0, 1024)) != -1) {
fos.write(dataBuffer, 0, bytesRead);
totalRead += bytesRead;
updateProgress(totalRead, driversFileSize);
updateProgress(totalRead, DRIVERS_FILE_SIZE);
if (this.isCancelled()) {
bis.close();
fos.close();

View file

@ -1,5 +1,5 @@
/*
Copyright 2019-2020 Dmitry Isaenko
Copyright 2019-2023 Dmitry Isaenko
This file is part of NS-USBloader.
@ -32,19 +32,32 @@ import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import nsusbloader.AppPreferences;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.util.ResourceBundle;
public class DriversInstall {
private static volatile boolean isRunning;
private final ResourceBundle resourceBundle;
private Label runInstallerStatusLabel;
public DriversInstall(ResourceBundle rb){
this.resourceBundle = rb;
if (isDriversDistributesWithExecutable())
runInstaller("Drivers_set.exe");
else
runDownloadProcess();
}
private boolean isDriversDistributesWithExecutable(){
final File drivers = new File("Drivers_set.exe");
return drivers.length() == DownloadDriversTask.DRIVERS_FILE_SIZE;
}
private void runDownloadProcess(){
if (DriversInstall.isRunning)
return;
@ -52,11 +65,11 @@ public class DriversInstall {
DownloadDriversTask downloadTask = new DownloadDriversTask();
Button cancelButton = new Button(rb.getString("btn_Cancel"));
Button cancelButton = new Button(resourceBundle.getString("btn_Cancel"));
HBox hBoxInformation = new HBox();
hBoxInformation.setAlignment(Pos.TOP_LEFT);
hBoxInformation.getChildren().add(new Label(rb.getString("windowBodyDownloadDrivers")));
hBoxInformation.getChildren().add(new Label(resourceBundle.getString("windowBodyDownloadDrivers")));
ProgressBar progressBar = new ProgressBar();
progressBar.setPrefWidth(Double.MAX_VALUE);
@ -93,7 +106,7 @@ public class DriversInstall {
Stage stage = new Stage();
stage.setTitle(rb.getString("windowTitleDownloadDrivers"));
stage.setTitle(resourceBundle.getString("windowTitleDownloadDrivers"));
stage.getIcons().addAll(
new Image("/res/dwnload_ico32x32.png"), //TODO: REDRAW
new Image("/res/dwnload_ico48x48.png"),
@ -106,6 +119,7 @@ public class DriversInstall {
Scene mainScene = new Scene(parentVBox, 405, 155);
mainScene.getStylesheets().add(AppPreferences.getInstance().getTheme());
parentVBox.setStyle(AppPreferences.getInstance().getFontStyle());
stage.setOnHidden(windowEvent -> {
downloadTask.cancel(true );
@ -117,7 +131,7 @@ public class DriversInstall {
stage.toFront();
downloadTask.setOnSucceeded(event -> {
cancelButton.setText(rb.getString("btn_Close"));
cancelButton.setText(resourceBundle.getString("btn_Close"));
String returnedValue = downloadTask.getValue();
@ -143,7 +157,7 @@ public class DriversInstall {
return true;
}
catch (Exception e){
runInstallerStatusLabel.setText("Error: "+e.toString());
runInstallerStatusLabel.setText("Error: "+e);
e.printStackTrace();
return false;
}

View file

@ -0,0 +1,28 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.nxdumptool;
class NxdtHostIOException extends Exception {
NxdtHostIOException(){
super();
}
NxdtHostIOException(String message){
super(message);
}
}

View file

@ -0,0 +1,28 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.nxdumptool;
class NxdtMalformedException extends Exception {
NxdtMalformedException(){
super();
}
NxdtMalformedException(String message){
super(message);
}
}

View file

@ -0,0 +1,67 @@
/*
Copyright 2019-2020 Dmitry Isaenko, DarkMatterCore
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.nxdumptool;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class NxdtNspFile {
private final String name;
private final int headerSize;
private final long fullSize;
private long nspRemainingSize;
private final File file;
NxdtNspFile(String name, int headerSize, long fullSize, File file) throws Exception{
this.name = name;
this.headerSize = headerSize;
this.fullSize = fullSize;
this.file = file;
this.nspRemainingSize = fullSize - headerSize;
removeIfExists();
createHeaderFiller();
}
private void removeIfExists() throws Exception{
if (! file.exists())
return;
if (file.delete())
return;
throw new Exception("Unable to delete leftovers of the NSP file: "+name);
}
private void createHeaderFiller() throws Exception {
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")){
raf.setLength(headerSize);
}
catch (IOException e){
throw new Exception("Unable to reserve space for NSP file's header: "+e.getMessage());
}
}
public String getName() { return name; }
public int getHeaderSize() { return headerSize; }
public long getFullSize() { return fullSize; }
public File getFile() { return file; }
public long getNspRemainingSize() { return nspRemainingSize; }
public void setNspRemainingSize(long nspRemainingSize) { this.nspRemainingSize = nspRemainingSize; }
}

View file

@ -18,7 +18,7 @@
*/
package nsusbloader.Utilities.nxdumptool;
import nsusbloader.COM.USB.UsbConnect;
import nsusbloader.com.usb.UsbConnect;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.ModelControllers.Log;
@ -38,8 +38,8 @@ public class NxdtTask extends CancellableRunnable {
@Override
public void run() {
logPrinter.print("Save to location: "+ saveToLocation, EMsgType.INFO);
logPrinter.print("=============== nxdumptool ===============", EMsgType.INFO);
print("Save to location: "+ saveToLocation, EMsgType.INFO);
print("=============== nxdumptool ===============", EMsgType.INFO);
UsbConnect usbConnect = UsbConnect.connectHomebrewMode(logPrinter);
@ -54,13 +54,22 @@ public class NxdtTask extends CancellableRunnable {
new NxdtUsbAbi1(handler, logPrinter, saveToLocation, this);
}
catch (Exception e){
logPrinter.print(e.getMessage(), EMsgType.FAIL);
print(e.getMessage(), EMsgType.FAIL);
}
logPrinter.print(".:: Complete ::.", EMsgType.PASS);
print(".:: Complete ::.", EMsgType.PASS);
usbConnect.close();
logPrinter.updateOneLinerStatus(true);
logPrinter.close();
}
private void print(String message, EMsgType type){
try {
logPrinter.print(message, type);
}
catch (InterruptedException ie){
ie.printStackTrace();
}
}
}

View file

@ -18,9 +18,9 @@
*/
package nsusbloader.Utilities.nxdumptool;
import nsusbloader.COM.USB.UsbErrorCodes;
import nsusbloader.COM.USB.common.DeviceInformation;
import nsusbloader.COM.USB.common.NsUsbEndpointDescriptor;
import nsusbloader.com.usb.UsbErrorCodes;
import nsusbloader.com.usb.common.DeviceInformation;
import nsusbloader.com.usb.common.NsUsbEndpointDescriptor;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EMsgType;
import org.usb4java.DeviceHandle;
@ -31,6 +31,9 @@ import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
class NxdtUsbAbi1 {
@ -42,7 +45,7 @@ class NxdtUsbAbi1 {
private final boolean isWindows;
private boolean isWindows10;
private static final int NXDT_MAX_DIRECTIVE_SIZE = 0x1000;
private static final int NXDT_MAX_DIRECTIVE_SIZE = 0x800000;//0x1000;
private static final int NXDT_FILE_CHUNK_SIZE = 0x800000;
private static final int NXDT_FILE_PROPERTIES_MAX_NAME_LENGTH = 0x300;
@ -51,6 +54,7 @@ class NxdtUsbAbi1 {
private static final int CMD_HANDSHAKE = 0;
private static final int CMD_SEND_FILE_PROPERTIES = 1;
private static final int CMD_SEND_NSP_HEADER = 2;
private static final int CMD_ENDSESSION = 3;
// Standard set of possible replies
@ -79,17 +83,16 @@ class NxdtUsbAbi1 {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00 };
private short endpointMaxPacketSize;
private static final int NXDT_USB_TIMEOUT = 5000;
private NxdtNspFile nspFile;
public NxdtUsbAbi1(DeviceHandle handler,
ILogPrinter logPrinter,
String saveToPath,
NxdtTask parent
)throws Exception{
this.handlerNS = handler;
//this.endpointMaxPacketSize = wMaxPacketSize;
this.logPrinter = logPrinter;
this.parent = parent;
this.isWindows = System.getProperty("os.name").toLowerCase().contains("windows");
@ -110,10 +113,13 @@ class NxdtUsbAbi1 {
private void resolveEndpointMaxPacketSize() throws Exception{
DeviceInformation deviceInformation = DeviceInformation.build(handlerNS);
NsUsbEndpointDescriptor endpointInDescriptor = deviceInformation.getSimplifiedDefaultEndpointDescriptorIn();
this.endpointMaxPacketSize = endpointInDescriptor.getwMaxPacketSize();
short endpointMaxPacketSize = endpointInDescriptor.getwMaxPacketSize();
USBSTATUS_SUCCESS[8] = (byte)(endpointMaxPacketSize & 0xFF);
USBSTATUS_SUCCESS[9] = (byte)((endpointMaxPacketSize >> 8) & 0xFF);
}
private void readLoop(){
private void readLoop() throws InterruptedException{
logPrinter.print("Awaiting for handshake", EMsgType.INFO);
try {
byte[] directive;
@ -134,6 +140,9 @@ class NxdtUsbAbi1 {
case CMD_SEND_FILE_PROPERTIES:
handleSendFileProperties(directive);
break;
case CMD_SEND_NSP_HEADER:
handleSendNspHeader(directive);
break;
case CMD_ENDSESSION:
logPrinter.print("Session successfully ended.", EMsgType.PASS);
return;
@ -187,70 +196,91 @@ class NxdtUsbAbi1 {
writeUsb(USBSTATUS_UNSUPPORTED_ABI);
throw new Exception("ABI v"+versionABI+" is not supported in current version.");
}
replyToHandshake();
}
private void replyToHandshake() throws Exception{
// Send status response + endpoint max packet size
ByteBuffer buffer = ByteBuffer.allocate(USBSTATUS_SUCCESS.length + 2).order(ByteOrder.LITTLE_ENDIAN);
buffer.put(USBSTATUS_SUCCESS);
buffer.putShort(endpointMaxPacketSize);
byte[] response = buffer.array();
writeUsb(response);
writeUsb(USBSTATUS_SUCCESS);
}
private void handleSendFileProperties(byte[] message) throws Exception{
final long fileSize = getLElong(message, 0x10);
try {
final long fullSize = getLElong(message, 0x10);
final int fileNameLen = getLEint(message, 0x18);
final int headerSize = getLEint(message, 0x1C);
checkFileNameLen(fileNameLen); // In case of negative value we should better handle it before String constructor throws error
String filename = new String(message, 0x20, fileNameLen, StandardCharsets.UTF_8);
String absoluteFilePath = getAbsoluteFilePath(filename);
File fileToDump = new File(absoluteFilePath);
if (fileNameLen <= 0 || fileNameLen > NXDT_FILE_PROPERTIES_MAX_NAME_LENGTH){
writeUsb(USBSTATUS_MALFORMED_REQUEST);
logPrinter.print("Invalid filename length!", EMsgType.FAIL);
checkSizes(fullSize, headerSize);
createPath(absoluteFilePath);
checkFileSystem(fileToDump, fullSize);
if (headerSize > 0){ // if NSP
logPrinter.print("Receiving NSP file: '"+filename+"' ("+formatByteSize(fullSize)+")", EMsgType.PASS);
createNewNsp(filename, headerSize, fullSize, fileToDump);
return;
}
// TODO: Note, in case of a big amount of small files performace decreses dramatically. It's better to handle this only in case of 1-big-file-transfer
logPrinter.print("Receiving: '"+filename+"' ("+fileSize+" b)", EMsgType.INFO);
// If RomFs related
if (isRomFs(filename)) {
if (isWindows)
filename = saveToPath + filename.replaceAll("/", "\\\\");
else
filename = saveToPath + filename;
createPath(filename);
}
else {
//logPrinter.print("Receiving: '"+filename+"' ("+fileSize+" b)", EMsgType.INFO); // TODO: see above
filename = saveToPath + filename;
// TODO: Note, in case of a big amount of small files performance decreases dramatically. It's better to handle this only in case of 1-big-file-transfer
logPrinter.print("Receiving: '"+filename+"' ("+fullSize+" b)", EMsgType.INFO);
}
File fileToDump = new File(filename);
writeUsb(USBSTATUS_SUCCESS);
if (fullSize == 0)
return;
if (isNspTransfer())
dumpNspFile(fullSize);
else
dumpFile(fileToDump, fullSize);
writeUsb(USBSTATUS_SUCCESS);
}
catch (NxdtMalformedException malformed){
logPrinter.print(malformed.getMessage(), EMsgType.FAIL);
writeUsb(USBSTATUS_MALFORMED_REQUEST);
}
catch (NxdtHostIOException ioException){
logPrinter.print(ioException.getMessage(), EMsgType.FAIL);
writeUsb(USBSTATUS_HOSTIOERROR);
}
}
private void checkFileNameLen(int fileNameLen) throws NxdtMalformedException{
if (fileNameLen <= 0 || fileNameLen > NXDT_FILE_PROPERTIES_MAX_NAME_LENGTH){
throw new NxdtMalformedException("Invalid filename length!");
}
}
private void checkSizes(long fileSize, int headerSize) throws Exception{
if (headerSize >= fileSize){
resetNsp();
throw new NxdtMalformedException(String.format("File size (%d) should not be less or equal to header size (%d)!", fileSize, headerSize));
}
if (fileSize < 0){ // It's possible to have files of zero-length, so only less is the problem
resetNsp();
throw new NxdtMalformedException("File size should not be less then zero!");
}
}
private void checkFileSystem(File fileToDump, long fileSize) throws Exception{
// Check if enough space
if (fileToDump.getParentFile().getFreeSpace() <= fileSize){
writeUsb(USBSTATUS_HOSTIOERROR);
logPrinter.print("Not enough space on selected volume. Need: "+fileSize+
" while available: "+fileToDump.getParentFile().getFreeSpace(), EMsgType.FAIL);
return;
throw new NxdtHostIOException("Not enough space on selected volume. Need: "+fileSize+
" while available: "+fileToDump.getParentFile().getFreeSpace());
}
// Check if FS is NOT read-only
if (! (fileToDump.canWrite() || fileToDump.createNewFile()) ){
writeUsb(USBSTATUS_HOSTIOERROR);
logPrinter.print("Unable to write into selected volume: "+fileToDump.getAbsolutePath(), EMsgType.FAIL);
return;
throw new NxdtHostIOException("Unable to write into selected volume: "+fileToDump.getAbsolutePath());
}
}
private void createNewNsp(String filename, int headerSize, long fileSize, File fileToDump) throws NxdtHostIOException{
try {
nspFile = new NxdtNspFile(filename, headerSize, fileSize, fileToDump);
writeUsb(USBSTATUS_SUCCESS);
}
catch (Exception e){
e.printStackTrace();
throw new NxdtHostIOException("Unable to create new file for: "+filename+" :"+e.getMessage());
}
writeUsb(USBSTATUS_SUCCESS);
if (fileSize == 0)
return;
dumpFile(fileToDump, fileSize);
writeUsb(USBSTATUS_SUCCESS);
}
private int getLEint(byte[] bytes, int fromOffset){
return ByteBuffer.wrap(bytes, fromOffset, 0x4).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
@ -258,23 +288,27 @@ class NxdtUsbAbi1 {
private long getLElong(byte[] bytes, int fromOffset){
return ByteBuffer.wrap(bytes, fromOffset, 0x8).order(ByteOrder.LITTLE_ENDIAN).getLong();
}
private boolean isNspTransfer(){
return nspFile != null;
}
private String getAbsoluteFilePath(String filename) {
if (isRomFs(filename) && isWindows) // Since RomFS entry starts from '/' it should be replaced to '\'.
return saveToPath + filename.replaceAll("/", "\\\\");
return saveToPath + filename;
}
private boolean isRomFs(String filename){
return filename.startsWith("/");
}
private void createPath(String path) throws Exception{
File resultingFile = new File(path);
File folderForTheFile = resultingFile.getParentFile();
if (folderForTheFile.exists())
return;
if (folderForTheFile.mkdirs())
return;
writeUsb(USBSTATUS_HOSTIOERROR);
throw new Exception("Unable to create dir(s) for file in "+folderForTheFile);
try {
Path folderForTheFile = Paths.get(path).getParent();
Files.createDirectories(folderForTheFile);
}
catch (Exception e){
throw new NxdtHostIOException("Unable to create dir(s) for file '"+path+"':"+e.getMessage());
}
}
// @see https://bugs.openjdk.java.net/browse/JDK-8146538
@ -295,7 +329,6 @@ class NxdtUsbAbi1 {
fd.sync();
bufferSize = readBuffer.length;
received += bufferSize;
logPrinter.updateProgress((double)received / (double)size);
}
int lastChunkSize = (int)(size - received) + 1;
@ -303,15 +336,81 @@ class NxdtUsbAbi1 {
bos.write(readBuffer);
if (isWindows10)
fd.sync();
} finally {
}
finally {
logPrinter.updateProgress(1.0);
}
}
/* Handle Zero-length terminator
private boolean isAligned(long size){
return ((size & (endpointMaxPacketSize - 1)) == 0);
private void dumpNspFile(long size) throws Exception{
FileOutputStream fos = new FileOutputStream(nspFile.getFile(), true);
long nspSize = nspFile.getFullSize();
try (BufferedOutputStream bos = new BufferedOutputStream(fos)) {
long nspRemainingSize = nspFile.getNspRemainingSize();
FileDescriptor fd = fos.getFD();
byte[] readBuffer;
long received = 0;
int bufferSize;
while (received+NXDT_FILE_CHUNK_SIZE < size) {
//readBuffer = readUsbFile();
readBuffer = readUsbFileDebug(NXDT_FILE_CHUNK_SIZE);
bos.write(readBuffer);
if (isWindows10)
fd.sync();
bufferSize = readBuffer.length;
received += bufferSize;
nspRemainingSize -= bufferSize;
logPrinter.updateProgress((double)(nspSize - nspRemainingSize) / (double)nspSize);
}
int lastChunkSize = (int)(size - received) + 1;
readBuffer = readUsbFileDebug(lastChunkSize);
bos.write(readBuffer);
if (isWindows10)
fd.sync();
nspRemainingSize -= (lastChunkSize - 1);
nspFile.setNspRemainingSize(nspRemainingSize);
}
}
private void handleSendNspHeader(byte[] message) throws Exception{
final int headerSize = getLEint(message, 0x8);
NxdtNspFile nsp = nspFile;
resetNsp();
logPrinter.updateProgress(1.0);
if (nsp == null) {
writeUsb(USBSTATUS_MALFORMED_REQUEST);
logPrinter.print("Received NSP send header request outside of known NSPs!", EMsgType.FAIL);
return;
}
if (nsp.getNspRemainingSize() > 0) {
writeUsb(USBSTATUS_MALFORMED_REQUEST);
logPrinter.print("Received NSP send header request without receiving all NSP file entry data!", EMsgType.FAIL);
return;
}
if (headerSize != nsp.getHeaderSize()) {
writeUsb(USBSTATUS_MALFORMED_REQUEST);
logPrinter.print("Received NSP header size mismatch! "+headerSize+" != "+ nsp.getHeaderSize(), EMsgType.FAIL);
return;
}
try (RandomAccessFile raf = new RandomAccessFile(nsp.getFile(), "rw")) {
byte[] headerData = Arrays.copyOfRange(message, 0x10, headerSize + 0x10);
raf.seek(0);
raf.write(headerData);
}
logPrinter.print("NSP file: '"+nsp.getName()+"' successfully received!", EMsgType.PASS);
writeUsb(USBSTATUS_SUCCESS);
}
private void resetNsp(){
this.nspFile = null;
}
*/
/** Sending any byte array to USB device **/
private void writeUsb(byte[] message) throws Exception{
@ -413,4 +512,13 @@ class NxdtUsbAbi1 {
"\n Returned: " + UsbErrorCodes.getErrCode(result) +
"\n (execution stopped)");
}
private String formatByteSize(double length) {
final String[] unitNames = { "bytes", "KiB", "MiB", "GiB", "TiB"};
int i;
for (i = 0; length > 1024 && i < unitNames.length - 1; i++) {
length = length / 1024;
}
return String.format("%,.2f %s", length, unitNames[i]);
}
}

View file

@ -0,0 +1,45 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches;
/**
* Searches instructions (via known patterns) that follows 'specific instruction' we want to patch.
* Returns offset of the pattern. Not offset of the 'specific instruction'.
* */
public abstract class AHeuristic {
protected boolean isLDR(int expression){ return (expression >> 22 & 0x2FF) == 0x2e5; }// LDR ! Sounds like LDP, don't mess up
protected boolean isLDP(int expression){ return (expression >> 22 & 0x1F9) == 0xA1; }// LDP !
protected boolean isCBNZ(int expression){ return (expression >> 24 & 0x7f) == 0x35; }
protected boolean isMOV(int expression){ return (expression >> 23 & 0xff) == 0xA5; }
protected boolean isTBZ(int expression){ return (expression >> 24 & 0x7f) == 0x36; }
protected boolean isLDRB_LDURB(int expression){ return (expression >> 21 & 0x7f7) == 0x1c2; }
protected boolean isMOV_REG(int expression){ return (expression & 0x7FE0FFE0) == 0x2A0003E0; }
protected boolean isB(int expression) { return (expression >> 26 & 0x3f) == 0x5; }
protected boolean isBL(int expression){ return (expression >> 26 & 0x3f) == 0x25; }
protected boolean isADD(int expression){ return (expression >> 23 & 0xff) == 0x22; }
public abstract boolean isFound();
public abstract boolean wantLessEntropy();
public abstract int getOffset() throws Exception;
public abstract String getDetails();
/**
* Should be used if wantLessEntropy() == true
* @return isFound();
* */
public abstract boolean setOffsetsNearby(int offsetNearby);
}

View file

@ -0,0 +1,591 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches;
import libKonogonka.Converter;
import nsusbloader.NSLMain;
public class BinToAsmPrinter {
static {
boolean notWindows = ! System.getProperty("os.name").toLowerCase().contains("windows");
if(notWindows && NSLMain.isCli){
ANSI_RESET = "\u001B[0m";
ANSI_GREEN = "\u001B[32m";
ANSI_BLUE = "\u001B[34m";
ANSI_YELLOW = "\u001B[33m";
ANSI_PURPLE = "\u001B[35m";
ANSI_CYAN = "\u001B[36m";
ANSI_RED = "\u001B[31m";
}
else {
ANSI_RESET = ANSI_RED = ANSI_GREEN = ANSI_BLUE = ANSI_YELLOW = ANSI_PURPLE = ANSI_CYAN = "";
}
}
private static final String ANSI_RESET;
private static final String ANSI_RED;
private static final String ANSI_GREEN;
private static final String ANSI_BLUE;
private static final String ANSI_YELLOW;
private static final String ANSI_PURPLE;
private static final String ANSI_CYAN;
public static String print(int instructionExpression, int offset){
if (instructionExpression == 0xd503201f)
return printNOP(instructionExpression);
if ((instructionExpression & 0x7FE0FFE0) == 0x2A0003E0) {
return printMOVRegister(instructionExpression);
}
switch ((instructionExpression >> 23 & 0b011111111)){
case 0xA5:
return printMOV(instructionExpression);
case 0x62:
if (((instructionExpression & 0x1f) == 0x1f)){
return printCMN(instructionExpression);
}
}
switch (instructionExpression >> 24 & 0xff) {
case 0x34:
case 0xb4:
return printCBZ(instructionExpression, offset);
case 0xb5:
case 0x35:
return printCBNZ(instructionExpression, offset);
case 0x36:
case 0xb6:
return printTBZ(instructionExpression, offset);
case 0x54:
return printBConditional(instructionExpression, offset);
}
switch ((instructionExpression >> 26 & 0b111111)) {
case 0x5:
return printB(instructionExpression, offset);
case 0x25:
return printBL(instructionExpression, offset);
}
return printUnknown(instructionExpression);
}
public static String printSimplified(int instructionExpression, int offset){
if (instructionExpression == 0xd503201f)
return printNOPSimplified(instructionExpression, offset);
if ((instructionExpression & 0x7FE0FFE0) == 0x2A0003E0) {
return printMOVRegisterSimplified(instructionExpression, offset);
}
switch (instructionExpression >> 22 & 0b1011111111) {
case 0x2e5:
return printLRDImmUnsignSimplified(instructionExpression, offset);
case 0xe5:
return printLRDBImmUnsignSimplified(instructionExpression, offset);
}
if ((instructionExpression >> 21 & 0x7FF) == 0x1C2)
return printImTooLazy("LDURB", instructionExpression, offset);
// same to (afterJumpExpression >> 23 & 0x1F9) != 0xA1
switch (instructionExpression >> 22 & 0x1FF){
case 0xA3: // 0b10100011
case 0xA7: // 0b10100111
case 0xA5: // 0b10100101
return printImTooLazy("LDP", instructionExpression, offset);
}
switch ((instructionExpression >> 23 & 0x1ff)){
case 0xA5:
return printMOVSimplified(instructionExpression, offset);
case 0x22:
return printImTooLazy("ADD", instructionExpression, offset);
case 0x62:
if (((instructionExpression & 0x1f) == 0x1f)){
return printCMNSimplified(instructionExpression, offset);
}
case 0xA2:
return printSUBSimplified(instructionExpression, offset);
case 0xE2:
case 0x1e2:
return printCMPSimplified(instructionExpression, offset);
case 0x24:
case 0x124:
return printANDSimplified(instructionExpression, offset);
}
switch (instructionExpression >> 24 & 0xff) {
case 0x34:
case 0xb4:
return printCBZSimplified(instructionExpression, offset);
case 0xb5:
case 0x35:
return printCBNZSimplified(instructionExpression, offset);
case 0x36:
case 0xb6:
return printTBZSimplified(instructionExpression, offset);
case 0x54:
return printBConditionalSimplified(instructionExpression, offset);
case 0xeb:
case 0x6b:
if ((instructionExpression & 0x1f) == 0b11111)
return printCMPShiftedRegisterSimplified(instructionExpression, offset);
}
switch (instructionExpression >> 26 & 0b111111) {
case 0x5:
return printBSimplified(instructionExpression, offset);
case 0x25:
return printBLSimplified(instructionExpression, offset);
}
if ((instructionExpression >> 10 & 0x3FFFFF) == 0x3597c0 && ((instructionExpression & 0x1F) == 0))
return printRetSimplified(instructionExpression, offset);
return printUnknownSimplified(instructionExpression, offset);
}
private static String printCBZ(int instructionExpression, int offset){
int conditionalJumpLocation = ((instructionExpression >> 5 & 0x7FFFF) * 4 + offset) & 0xfffff;
return String.format(ANSI_YELLOW + "sf == 0 ? <Wt> else <Xt>\n" +
"CBZ <?t>, <label> |.....CBZ signature......|\n" +
ANSI_CYAN + " sf 0 1 1 0 1 0 0 |imm19..........................................................||Rd.............|" + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n\n"+
ANSI_YELLOW + "CBZ " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (Real: " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
(instructionExpression >> 31 == 0) ? "w" : "x", (instructionExpression & 0b11111),
conditionalJumpLocation, (conditionalJumpLocation + 0x100));
}
private static String printCBNZ(int instructionExpression, int offset){
int conditionalJumpLocation = ((instructionExpression >> 5 & 0x7FFFF) * 4 + offset) & 0xfffff;
return String.format(ANSI_YELLOW + "sf == 0 ? <Wt> else <Xt>\n" +
"CBNZ <?t>, <label> |.....CBZ signature......|\n" +
ANSI_CYAN + " sf 0 1 1 0 1 0 |imm19..........................................................||Rd.............|" + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n\n"+
ANSI_YELLOW + "CBNZ " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (Real: " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
(instructionExpression >> 31 == 0) ? "w" : "x", (instructionExpression & 0b11111),
conditionalJumpLocation, (conditionalJumpLocation + 0x100));
}
private static String printCMN(int instructionExpression){
int Rn = instructionExpression >> 5 & 0x1F;
int imm = instructionExpression >> 10 & 0xFFF;
return String.format(ANSI_YELLOW + "sf == 0 ? <Wt> else <Xt>\n" +
"CMN <?n>, <label> |.....CMN signature...........| |..CMN signature.|\n" +
ANSI_CYAN+" sf 0 1 1 0 0 0 1 0 |imm12......................................||Rn.............| 1 1 1 1 1" + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n\n" +
ANSI_YELLOW + "CMN " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + "\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
(instructionExpression >> 31 == 0) ? "w" : "x", Rn, imm);
}
private static String printB(int instructionExpression, int offset){
int conditionalJumpLocationPatch = ((instructionExpression & 0x3ffffff) * 4 + offset) & 0xfffff;
return String.format(ANSI_YELLOW+"B <label> |....B signature...|\n" +
" "+ANSI_CYAN+" 0 0 0 1 0 1 |imm26...................................................................................|" + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n" +
ANSI_YELLOW + "%s " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (Real: " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
((instructionExpression >> 26 & 0b111111) == 5)?"B":"Some weird stuff",
conditionalJumpLocationPatch, (conditionalJumpLocationPatch + 0x100));
}
private static String printBL(int instructionExpression, int offset){
int conditionalJumpLocationPatch = ((instructionExpression & 0x3ffffff) * 4 + offset) & 0xfffff;
return String.format(ANSI_YELLOW+"BL <label> |...BL signature...|\n" +
" "+ANSI_CYAN+" 1 0 0 1 0 1 |imm26...................................................................................|" + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n" +
ANSI_YELLOW + "%s " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (Real: " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
((instructionExpression >> 26 & 0b111111) == 25)?"BL":"Some weird stuff",
conditionalJumpLocationPatch, (conditionalJumpLocationPatch + 0x100));
}
private static String printMOV(int instructionExpression){
int imm16 = instructionExpression >> 5 & 0xFFFF;
int sfHw = (instructionExpression >> 22 & 1);
return String.format(ANSI_YELLOW + "sf == 0 && hw == 0x ? <Wt> else <Xt>\n" +
"MOV <?t>, <label> |.....MOV signature...........|\n" +
ANSI_CYAN +" sf 1 0 1 0 0 1 0 1 |hw...|imm16.................................................||Rd.............|" + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n" +
ANSI_YELLOW + "MOV " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + "\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
(sfHw == 0) ? "w" : "x", (instructionExpression & 0b11111), imm16);
}
private static String printMOVRegister(int instructionExpression){
String sfHw = (instructionExpression >> 31 & 1) == 0 ? "W" : "X";
int Rm = instructionExpression >> 16 & 0xF;
int Rd = instructionExpression & 0xF;
return String.format(ANSI_YELLOW + "sf == 0 && hw == 0x ? <Wt> else <Xt>\n" +
"MOV (register) <?d>, <?m> |.....MOV (register) signature.......|\n" +
ANSI_CYAN +" sf 0 1 0 1 0 1 0 0 0 0 |Rm..............| 0 0 0 0 0 0 1 1 1 1 1 |Rd.............|" + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n" +
ANSI_YELLOW + "MOV(reg) " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "%s%d" + ANSI_RESET + "\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
sfHw, Rm, sfHw, Rd);
}
private static String printNOP(int instructionExpression){
return String.format(
ANSI_YELLOW+"NOP |.....NOP signature..........................................................................................|\n" +
ANSI_CYAN +" 1 1 0 1 0 1 0 1 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 1 1 1 1 1 " + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n"+
"Instruction (BE) : %s | %s\n" +
ANSI_YELLOW + "%s" + ANSI_RESET + "\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
(instructionExpression == 0xd503201f)?"NOP":"Some weird stuff");
}
private static String printTBZ(int instructionExpression, int offset){
int xwSelector = (instructionExpression >> 31 & 1);
int imm = instructionExpression >> 18 & 0b11111;
int Rt = instructionExpression & 0b11111;
int label = (offset + (instructionExpression >> 5 & 0x3fff) * 4) & 0xfffff;
return String.format(ANSI_YELLOW + "sf == 0 && hw == 0x ? <Wt> else <Xt>\n" +
"TBZ <?t>,#<imm>, <label> |.....TBZ signature.......|\n" +
ANSI_CYAN+" b5 0 1 1 0 1 1 0 |b40.............|imm14.........................................||Rt.............|" + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n" +
ANSI_YELLOW + "TBZ " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ", " + ANSI_PURPLE + "%x" + ANSI_RESET + "\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
(xwSelector == 0) ? "w" : "x", Rt, imm, label);
}
private static String printBConditional(int instructionExpression, int offset){
int conditionalJumpLocation = ((instructionExpression >> 4 & 0b1111111111111111111) * 4 + offset) & 0xfffff;
return String.format(
ANSI_YELLOW+"B.%s <label> |...B.cond signature.......|\n" +
ANSI_CYAN+" 0 1 0 1 0 1 0 0 |imm19..........................................................| 0 |.condit...|" + ANSI_RESET + "\n" +
ANSI_GREEN +" 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n" +
ANSI_YELLOW + "B.%s " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (Real: " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
getBConditionalMarker(instructionExpression & 0xf),
intAsBinString(instructionExpression), intAsHexString(instructionExpression),
getBConditionalMarker(instructionExpression & 0xf),
conditionalJumpLocation, (conditionalJumpLocation + 0x100));
}
private static String printUnknown(int instructionExpression){
return String.format(ANSI_RED + " 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 " + ANSI_RESET + "\n" +
"Instruction (BE) : %s | %s\n",
intAsBinString(instructionExpression), intAsHexString(instructionExpression));
}
private static String getBConditionalMarker(int cond){
switch (cond){
case 0b0000: return "EQ";
case 0b0001: return "NE";
case 0b0010: return "CS";
case 0b0011: return "CC";
case 0b0100: return "MI";
case 0b0101: return "PL";
case 0b0110: return "VS";
case 0b0111: return "VC";
case 0b1000: return "HI";
case 0b1001: return "LS";
case 0b1010: return "GE";
case 0b1011: return "LT";
case 0b1100: return "GT";
case 0b1101: return "LE";
case 0b1110: return "AL";
default: return "??";
}
/*
"__________________CheatSheet_____________________________________\n"+
"0000 | EQ | Z set | equal\n"+
"0001 | NE | Z clear | not equal\n"+
"0010 | CS | C set | unsigned higher or same\n"+
"0011 | CC | C clear | unsigned lower\n"+
"0100 | MI | N set | negative\n"+
"0101 | PL | N clear | positive or zero\n"+
"0110 | VS | V set | overflow\n"+
"0111 | VC | V clear | no overflow\n"+
"1000 | HI | C set & V clear | unsigned higher\n"+
"1001 | LS | C clear or Z set | unsigned lower or same\n"+
"1010 | GE | N equals V | greater or equal\n"+
"1011 | LT | N not equals V | less than\n"+
"1100 | GT | Z clear AND (N equals V) | greater that\n"+
"1101 | LE | Z set OR (N not equals V) | less than or equal\n"+
"1110 | AL | (ignored) | always\n";
*/
}
private static String printCBZSimplified(int instructionExpression, int offset){
int conditionalJumpLocation = ((instructionExpression >> 5 & 0x7FFFF) * 4 + offset) & 0xfffff;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " CBZ " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (" + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
(instructionExpression >> 31 == 0) ? "w" : "x", (instructionExpression & 0b11111),
conditionalJumpLocation, (conditionalJumpLocation + 0x100));
}
private static String printCBNZSimplified(int instructionExpression, int offset){
int conditionalJumpLocation = ((instructionExpression >> 5 & 0x7FFFF) * 4 + offset) & 0xfffff;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " CBNZ " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (" + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
(instructionExpression >> 31 == 0) ? "w" : "x", (instructionExpression & 0b11111),
conditionalJumpLocation, (conditionalJumpLocation + 0x100));
}
private static String printBSimplified(int instructionExpression, int offset){
int conditionalJumpLocationPatch = ((instructionExpression & 0x3ffffff) * 4 + offset) & 0xfffff;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " B " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (Real: " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
conditionalJumpLocationPatch, (conditionalJumpLocationPatch + 0x100));
}
private static String printBLSimplified(int instructionExpression, int offset){
int conditionalJumpLocationPatch = ((instructionExpression & 0x3ffffff) * 4 + offset) & 0xfffff;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " BL " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (Real: " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
conditionalJumpLocationPatch, (conditionalJumpLocationPatch + 0x100));
}
private static String printMOVSimplified(int instructionExpression, int offset){
int imm16 = instructionExpression >> 5 & 0xFFFF;
int sfHw = (instructionExpression >> 22 & 1);
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " MOV " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
(sfHw == 0) ? "w" : "x", (instructionExpression & 0b11111), imm16);
}
private static String printNOPSimplified(int instructionExpression, int offset){
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " NOP " + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression);
}
private static String printTBZSimplified(int instructionExpression, int offset){
int xwSelector = (instructionExpression >> 31 & 1);
int imm = instructionExpression >> 18 & 0b11111;
int Rt = instructionExpression & 0b11111;
int label = offset + (instructionExpression >> 5 & 0x3fff) * 4;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " TBZ " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ", " + ANSI_PURPLE + "%x" + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
(xwSelector == 0) ? "w" : "x", Rt, imm, label);
}
private static String printBConditionalSimplified(int instructionExpression, int offset){
int conditionalJumpLocation = ((instructionExpression >> 4 & 0b1111111111111111111) * 4 + offset) & 0xfffff;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " B.%s " + ANSI_BLUE + "#0x%x" + ANSI_RESET + " (Real: " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ")\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
getBConditionalMarker(instructionExpression & 0xf),
conditionalJumpLocation, (conditionalJumpLocation + 0x100));
}
private static String printImTooLazy(String name, int instructionExpression, int offset){
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " "+name+" . . . \n"+ ANSI_RESET,
offset, Integer.reverseBytes(instructionExpression), instructionExpression);
}
private static String printSUBSimplified(int instructionExpression, int offset){
String wx = (instructionExpression >> 31 == 0) ? "W" : "X";
int Rt = instructionExpression & 0x1f;
int Rn = instructionExpression >> 5 & 0x1F;
int imm12 = instructionExpression >> 10 & 0xFFF; // unsigned only
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " SUB (imm) " + ANSI_GREEN + "%s%d, " + ANSI_BLUE + "%s%d, #0x%x" + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
wx, Rt, wx, Rn, imm12);
}
private static String printMOVRegisterSimplified(int instructionExpression, int offset){ //ADD (immediate)
String sfHw = (instructionExpression >> 31 & 1) == 0 ? "W" : "X";
int Rm = instructionExpression >> 16 & 0x1F;
int Rd = instructionExpression & 0x1F;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " MOV (reg) " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "%s%d" + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
sfHw, Rm, sfHw, Rd);
}
private static String printCMNSimplified(int instructionExpression, int offset){
int Rn = instructionExpression >> 5 & 0x1F;
int imm = instructionExpression >> 10 & 0xFFF;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " CMN " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "#0x%x" + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
(instructionExpression >> 31 == 0) ? "w" : "x", Rn, imm);
}
private static String printLRDImmUnsignSimplified(int instructionExpression, int offset){
String wx = (instructionExpression >> 31 == 0) ? "W" : "X";
int Rt = instructionExpression & 0x1f;
int Rn = instructionExpression >> 5 & 0xF;
int imm12 = (instructionExpression >> 10 & 0xFFF) * 8; // unsigned only
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " LDR(imm) " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "[%s%d, #0x%x]" + ANSI_RESET + " (note: unsigned offset)\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
wx, Rt, wx, Rn, imm12);
}
private static String printLRDBImmUnsignSimplified(int instructionExpression, int offset){
String wx = (instructionExpression >> 31 == 0) ? "W" : "X";
int Rt = instructionExpression & 0x1f;
int Rn = instructionExpression >> 5 & 0xF;
int imm12 = (instructionExpression >> 10 & 0xFFF) * 8; // unsigned only
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " LDRB(imm) " + ANSI_GREEN + "%s%d " + ANSI_BLUE + "[%s%d, #0x%x]" + ANSI_RESET + " (note: unsigned offset)\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
wx, Rt, wx, Rn, imm12);
}
private static String printCMPSimplified(int instructionExpression, int offset){
String sf = (instructionExpression >> 31 == 0) ? "W" : "X";
int Rn = instructionExpression >> 5 & 0x1F;
int conditionalJumpLocation = (instructionExpression >> 10) & 0xfff;
int LSL = (instructionExpression >> 22 & 0b1) == 1 ? 12 : 0;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " CMP " + ANSI_GREEN + sf + "%d," +
ANSI_BLUE + "0x%x" + ANSI_RESET + " (Real: " + ANSI_BLUE + "#0x%x" + ANSI_RESET + ") " + ANSI_PURPLE + "LSL #%d" + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
Rn,
conditionalJumpLocation, (conditionalJumpLocation + 0x100),
LSL);
}
private static String printCMPShiftedRegisterSimplified(int instructionExpression, int offset){
String sf = (instructionExpression >> 31 == 0) ? "W" : "X";
int Rn = instructionExpression >> 5 & 0x1F;
int Rm = instructionExpression >> 16 & 0x1F;
int imm6 = instructionExpression >> 10 & 0x3f;
int LSL = (instructionExpression >> 22 & 0b11);
String LSLStr;
switch (LSL){
case 0b00:
LSLStr = "LSL";
break;
case 0b01:
LSLStr = "LSR";
break;
case 0b10:
LSLStr = "ASR";
break;
case 0b11:
LSLStr = "RESERVED";
break;
default:
LSLStr = "?";
}
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " CMP (sr) " + ANSI_GREEN + sf + "%d," +
ANSI_BLUE + sf + "%d " + ANSI_BLUE + LSLStr + ANSI_PURPLE + " %d" + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression,
Rn, Rm, imm6);
}
private static String printANDSimplified(int instructionExpression, int offset){
String sf = (instructionExpression >> 31 == 0) ? "W" : "X";
int Rn = instructionExpression & 0x1F;
int Rd = instructionExpression >> 5 & 0x1F;
int imm;
if (sf.equals("W"))
imm = instructionExpression >> 10 & 0xfff;
else
imm = instructionExpression >> 10 & 0x1fff;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " AND " + ANSI_GREEN + sf + "%d, " + ANSI_BLUE +
sf + "%d" + ANSI_PURPLE + " # ??? 0b%s " + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression, Rn, Rd, Converter.intToBinaryString(imm));
}
private static String printRetSimplified(int instructionExpression, int offset){
int Xn = (instructionExpression >> 5) & 0x1F;
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " RET " + ANSI_GREEN + " X%d" + ANSI_RESET + "\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression, Xn == 0 ? 30 : Xn);
}
private static String printUnknownSimplified(int instructionExpression, int offset){
return String.format(
"%05x "+ANSI_CYAN+"%08x (%08x)"+ANSI_YELLOW + " ??? 0b"+ANSI_RESET+ Converter.intToBinaryString(instructionExpression) +"\n",
offset, Integer.reverseBytes(instructionExpression), instructionExpression);
}
private static String intAsBinString(int number) {
StringBuilder result = new StringBuilder();
for(int i = 31; i >= 0 ; i--) {
int mask = 1 << i;
result.append((number & mask) != 0 ? "1" : "0");
result.append(" ");
if (i % 4 == 0)
result.append(" ");
}
result.replace(result.length() - 1, result.length(), "");
return result.toString();
}
private static String intAsHexString(int number) {
number = Integer.reverseBytes(number);
StringBuilder result = new StringBuilder();
for(int i = 0; i <= 3 ; i++) {
int mask = 0xff << i*8;
result.append(String.format("%02x", (byte)((number & mask) >> i*8)));
result.append(" ");
}
result.replace(result.length() - 1, result.length(), "");
return result.toString();
}
}

View file

@ -0,0 +1,26 @@
/*
Copyright 2019-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches;
public class MalformedIniFileException extends Exception{
public MalformedIniFileException(){}
public MalformedIniFileException(String message){
super(message);
}
}

View file

@ -0,0 +1,161 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches;
import libKonogonka.Converter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SimplyFind {
private String what;
private final byte[] where;
private Matcher matcherHex;
private Matcher matcherDot;
private final List<Integer> findings = new ArrayList<>();
private final int statementLength;
private final List<SearchBlock> searchBlocks = new ArrayList<>();
/**
* Abstraction layer for searching patterns like "..CAFE..BE" in bytes array.
* It's 'String' combination of hex values and '.' which stands for unknown value.
* Returns offset of the first symbol.
* */
public SimplyFind(String what, byte[] where){
this.where = where;
if (! what.contains(".")){
doKMPSearch(Converter.hexStringToByteArray(what), 0);
this.statementLength = what.length()/2;
return;
}
this.what = what.replaceAll("\\.", "\\.\\.");
this.statementLength = this.what.length()/2;
buildSearchingSequence();
complexSearch();
}
private void buildSearchingSequence(){
Pattern patternHex = Pattern.compile("[0-9]|[A-F]|[a-f]");
Pattern patternDot = Pattern.compile("\\.");
this.matcherHex = patternHex.matcher(what);
this.matcherDot = patternDot.matcher(what);
int nextDotPos = 0;
int nextHexPos;
while(true){
nextHexPos = getNextNumberPosition(nextDotPos);
if (nextHexPos == -1)
break;
nextDotPos = getNextDotPosition(nextHexPos);
if (nextDotPos == -1) {
searchBlocks.add(new SearchBlock(what.substring(nextHexPos), nextHexPos));
break;
}
String searchStatement = what.substring(nextHexPos, nextDotPos);
searchBlocks.add(new SearchBlock(searchStatement, nextHexPos));
}
}
private int getNextNumberPosition(int since){
if (matcherHex.find(since))
return matcherHex.start();
return -1;
}
private int getNextDotPosition(int since){
if (matcherDot.find(since))
return matcherDot.start();
return -1;
}
private void complexSearch(){
SearchBlock block = searchBlocks.get(0);
doKMPSearch(block.statement, block.offsetInStatement);
findings.removeIf(this::searchForward);
}
private boolean searchForward(int offset){
for (int i = 1; i < searchBlocks.size(); i++) {
SearchBlock block = searchBlocks.get(i);
if (! doDumbSearch(block.statement, offset+block.offsetInStatement)){
return true;
}
}
return false;
}
private void doKMPSearch(byte[] subject, int skip){
int whereSize = where.length;
int subjectSize = subject.length;
int[] pf = new int[subjectSize];
int j = 0;
for (int i = 1; i < subjectSize; i++ ) {
while ((j > 0) && (subject[j] != subject[i]))
j = pf[j-1];
if (subject[j] == subject[i])
j++;
pf[i] = j;
}
j = 0;
for (int i = 0; i < whereSize; i++){
while ((j > 0) && (subject[j] != where[i]))
j = pf[j - 1];
if (subject[j] == where[i])
j++;
if (j == subjectSize) {
findings.add(i-j+1-skip);
j = 0;
}
}
}
private boolean doDumbSearch(byte[] subject, int since){
for (int i = 0; i < subject.length; i++) {
if (where[since + i] != subject[i])
return false;
}
return true;
}
public int getStatementLength() {
return statementLength;
}
public List<Integer> getResults(){
return findings;
}
private static class SearchBlock{
byte[] statement;
int offsetInStatement;
SearchBlock(String statement, int offset){
if (statement != null) {
this.statement = Converter.hexStringToByteArray(statement);
}
this.offsetInStatement = offset/2;
}
}
}

View file

@ -0,0 +1,50 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.es;
import libKonogonka.Converter;
import libKonogonka.fs.NCA.NCAProvider;
import java.util.List;
import java.util.concurrent.Callable;
class EsNcaSearchTask implements Callable<NCAProvider> {
private final List<NCAProvider> ncaProviders;
EsNcaSearchTask(List<NCAProvider> ncaProviders){
this.ncaProviders = ncaProviders;
}
@Override
public NCAProvider call() {
try {
for (NCAProvider ncaProvider : ncaProviders) {
String titleId = Converter.byteArrToHexStringAsLE(ncaProvider.getTitleId());
if (titleId.startsWith("0100000000000033") && ncaProvider.getContentType() == 0) {
return ncaProvider;
}
}
return null;
}
catch (Exception e){
e.printStackTrace();
return null;
}
}
}

View file

@ -0,0 +1,181 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
---
Based on ES-AutoIPS.py patch script made by GBATemp member MrDude.
Taken from: https://gbatemp.net/threads/info-on-sha-256-hashes-on-fs-patches.581550/
*/
package nsusbloader.Utilities.patches.es;
import libKonogonka.Converter;
import libKonogonka.fs.NCA.NCAProvider;
import libKonogonka.fs.NSO.NSO0Header;
import libKonogonka.fs.NSO.NSO0Provider;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EMsgType;
import nsusbloader.Utilities.patches.BinToAsmPrinter;
import nsusbloader.Utilities.patches.es.finders.HeuristicEsWizard;
import java.io.BufferedOutputStream;
import java.io.File;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class EsPatch {
private static final byte[] HEADER = "PATCH".getBytes(StandardCharsets.US_ASCII);
private static final byte[] FOOTER = "EOF".getBytes(StandardCharsets.US_ASCII);
private final NCAProvider ncaProvider;
private final String saveToLocation;
private final ILogPrinter logPrinter;
private Long fwVersion;
private String buildId;
private byte[] _textSection;
private HeuristicEsWizard wizard;
EsPatch(NCAProvider ncaProvider, String saveToLocation, ILogPrinter logPrinter) throws Exception{
this.ncaProvider = ncaProvider;
this.saveToLocation = saveToLocation + File.separator +
"atmosphere" + File.separator + "exefs_patches" + File.separator + "es_patches";
this.logPrinter = logPrinter;
getPlainFirmwareVersion();
NSO0Provider nso0Provider = new NSO0Provider(ncaProvider.getNCAContentProvider(0).getPfs0().getStreamProducer(0));
getBuildId(nso0Provider);
getTextSection(nso0Provider);
findAllOffsets();
mkDirs();
writeFile();
logPrinter.print(" == Debug information ==\n"+wizard.getDebug(), EMsgType.NULL);
}
private void getPlainFirmwareVersion() throws Exception{
final byte[] byteSdkVersion = ncaProvider.getSdkVersion();
fwVersion = Long.parseLong(""+byteSdkVersion[3]+byteSdkVersion[2]+byteSdkVersion[1]+byteSdkVersion[0]);
logPrinter.print("Internal firmware version: "+byteSdkVersion[3] +"."+byteSdkVersion[2] +"."+byteSdkVersion[1] +"."+byteSdkVersion[0], EMsgType.INFO);
if (byteSdkVersion[3] < 9 || fwVersion < 9300)
logPrinter.print("WARNING! FIRMWARES VERSIONS BEFORE 9.0.0 ARE NOT SUPPORTED! USING PRODUCED ES PATCHES (IF ANY) COULD BREAK SOMETHING! IT'S NEVER BEEN TESTED!", EMsgType.WARNING);
}
private void getBuildId(NSO0Provider nso0Provider) throws Exception{
NSO0Header nso0DecompressedHeader = nso0Provider.getAsDecompressedNSO0().getHeader();
byte[] buildIdBytes = nso0DecompressedHeader.getModuleId();
buildId = Converter.byteArrToHexStringAsLE(buildIdBytes).substring(0, 40).toUpperCase();
logPrinter.print("Build ID: "+buildId, EMsgType.INFO);
}
private void getTextSection(NSO0Provider nso0Provider) throws Exception{
_textSection = nso0Provider.getAsDecompressedNSO0().getTextRaw();
}
private void findAllOffsets() throws Exception{
this.wizard = new HeuristicEsWizard(fwVersion, _textSection);
String errorsAndNotes = wizard.getErrorsAndNotes();
if (errorsAndNotes.length() > 0)
logPrinter.print(errorsAndNotes, EMsgType.WARNING);
}
private void mkDirs(){
File parentFolder = new File(saveToLocation);
parentFolder.mkdirs();
}
private void writeFile() throws Exception{
String patchFileLocation = saveToLocation + File.separator + buildId + ".ips";
int offset1 = wizard.getOffset1();
int offset2 = wizard.getOffset2();
int offset3 = wizard.getOffset3();
ByteBuffer handyEsPatch = ByteBuffer.allocate(0x23).order(ByteOrder.LITTLE_ENDIAN);
handyEsPatch.put(HEADER);
if (offset1 > 0) {
logPrinter.print("Patch component 1 will be used", EMsgType.PASS);
handyEsPatch.put(getPatch1(offset1));
}
if (offset2 > 0) {
logPrinter.print("Patch component 2 will be used", EMsgType.PASS);
handyEsPatch.put(getPatch2(offset2));
}
if (offset3 > 0) {
logPrinter.print("Patch component 3 will be used", EMsgType.PASS);
handyEsPatch.put(getPatch3(offset3));
}
handyEsPatch.put(FOOTER);
byte[] esPatch = new byte[handyEsPatch.position()];
((Buffer) handyEsPatch).rewind();
handyEsPatch.get(esPatch);
try (BufferedOutputStream stream = new BufferedOutputStream(
Files.newOutputStream(Paths.get(patchFileLocation)))){
stream.write(esPatch);
}
logPrinter.print("Patch created at "+patchFileLocation, EMsgType.PASS);
}
// WE EXPECT TO SEE CBZ (for patch 1) INSTRUCTION RIGHT BEFORE FOUND SEQUENCE (requiredInstructionOffsetInternal)
// IN RESULTING FILE InstructionOffset SHOULD BE INCREMENTED by 0x100 to get real offset
// (because header for decompressed NSO0 size = 0x100; it's fixed alignment produced by libKonogonka)
private byte[] getPatch1(int offset) throws Exception{
int requiredInstructionOffsetInternal = offset - 4;
int requiredInstructionOffsetReal = requiredInstructionOffsetInternal + 0x100;
int instructionExpression = Converter.getLEint(_textSection, requiredInstructionOffsetInternal);
int patch = ((0x14 << 24) | (instructionExpression >> 5) & 0x7FFFF);
logPrinter.print(BinToAsmPrinter.printSimplified(patch, requiredInstructionOffsetInternal), EMsgType.NULL);
// Somehow IPS patches uses offsets written as big_endian (0.o) and bytes dat should be patched as LE.
ByteBuffer prePatch = ByteBuffer.allocate(10).order(ByteOrder.BIG_ENDIAN)
.putInt(requiredInstructionOffsetReal)
.putShort((short) 4)
.putInt(Integer.reverseBytes(patch));
return Arrays.copyOfRange(prePatch.array(), 1, 10);
}
private byte[] getPatch2(int offset) throws Exception{
final int NopInstruction = 0x1F2003D5; // reversed
int offsetReal = offset - 4 + 0x100;
logPrinter.print(BinToAsmPrinter.printSimplified(Integer.reverseBytes(NopInstruction), offset - 4), EMsgType.NULL);
ByteBuffer prePatch = ByteBuffer.allocate(10).order(ByteOrder.BIG_ENDIAN)
.putInt(offsetReal)
.putShort((short) 4)
.putInt(NopInstruction);
return Arrays.copyOfRange(prePatch.array(), 1, 10);
}
private byte[] getPatch3(int offset) throws Exception{
int requiredInstructionOffsetInternal = offset - 4;
int requiredInstructionOffsetReal = requiredInstructionOffsetInternal + 0x100;
int instructionExpression = Converter.getLEint(_textSection, requiredInstructionOffsetInternal);
int patch = ((0x14 << 24) | (instructionExpression >> 5) & 0x7FFFF);
logPrinter.print(BinToAsmPrinter.printSimplified(patch, requiredInstructionOffsetInternal), EMsgType.NULL);
ByteBuffer prePatch = ByteBuffer.allocate(10).order(ByteOrder.BIG_ENDIAN)
.putInt(requiredInstructionOffsetReal)
.putShort((short) 4)
.putInt(Integer.reverseBytes(patch));
return Arrays.copyOfRange(prePatch.array(), 1, 10);
}
}

View file

@ -0,0 +1,182 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.es;
import libKonogonka.KeyChainHolder;
import libKonogonka.fs.NCA.NCAProvider;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.ModelControllers.Log;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.NSLDataTypes.EMsgType;
import java.io.File;
import java.util.*;
import java.util.concurrent.*;
public class EsPatchMaker extends CancellableRunnable {
private int THREADS_POOL_SIZE;
private final ILogPrinter logPrinter;
private final String pathToFirmware;
private final String pathToKeysFile;
private final String saveTo;
private File firmware;
private KeyChainHolder keyChainHolder;
private ExecutorService executorService;
private List<String> ncaFilesList; // inside the folder
private boolean oneLinerStatus = false;
public EsPatchMaker(String pathToFirmware, String pathToKeysFile, String saveTo){
this.logPrinter = Log.getPrinter(EModule.PATCHES);
/*
this.logPrinter = new ILogPrinter() {
public void print(String message, EMsgType type) throws InterruptedException {}
public void updateProgress(Double value) throws InterruptedException {}
public void update(HashMap<String, File> nspMap, EFileStatus status) {}
public void update(File file, EFileStatus status) {}
public void updateOneLinerStatus(boolean status) {}
public void close() {}
};
*/
this.pathToFirmware = pathToFirmware;
this.pathToKeysFile = pathToKeysFile;
this.saveTo = saveTo;
}
@Override
public void run() {
try {
logPrinter.print("..:: Make ES Patches ::..", EMsgType.INFO);
receiveFirmware();
buildKeyChainHolder();
receiveNcaFileNamesList();
specifyThreadsPoolSize();
createPool();
executePool();
}
catch (Exception e){
e.printStackTrace();
try{
logPrinter.print(e.getMessage(), EMsgType.FAIL);
} catch (Exception ignore){}
}
finally {
logPrinter.updateOneLinerStatus(oneLinerStatus);
logPrinter.close();
}
}
private void receiveFirmware() throws Exception{
logPrinter.print("Looking at firmware", EMsgType.INFO);
this.firmware = new File(pathToFirmware);
if (! firmware.exists())
throw new Exception("Firmware directory does not exist " + pathToFirmware);
}
private void buildKeyChainHolder() throws Exception{
logPrinter.print("Reading keys", EMsgType.INFO);
this.keyChainHolder = new KeyChainHolder(pathToKeysFile, null);
}
private void receiveNcaFileNamesList() throws Exception{
logPrinter.print("Collecting NCA files", EMsgType.INFO);
String[] fileNamesArray = firmware.list((File directory, String file) -> ( ! file.endsWith(".cnmt.nca") && file.endsWith(".nca")));
ncaFilesList = Arrays.asList(Objects.requireNonNull(fileNamesArray));
if (ncaFilesList.size() == 0)
throw new Exception("No NCA files found in firmware folder");
}
private void specifyThreadsPoolSize(){
THREADS_POOL_SIZE = Math.max(Runtime.getRuntime().availableProcessors()+1, 4);
THREADS_POOL_SIZE = Math.min(THREADS_POOL_SIZE, ncaFilesList.size());
}
private void createPool() throws Exception{
logPrinter.print("Creating sub-tasks pool", EMsgType.INFO);
this.executorService = Executors.newFixedThreadPool(
THREADS_POOL_SIZE,
runnable -> {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
});
}
private void executePool() throws Exception{ //TODO: FIX. Exceptions thrown only by logPrinter
try {
logPrinter.print("Executing sub-tasks pool", EMsgType.INFO);
List<Future<NCAProvider>> futuresResults = executorService.invokeAll(getSubTasksCollection());
for (Future<NCAProvider> future : futuresResults){
NCAProvider ncaProvider = future.get();
if (ncaProvider != null) {
makePatches(ncaProvider);
break;
}
}
executorService.shutdown();
}
catch (InterruptedException ie){
executorService.shutdownNow();
boolean interruptedSuccessfully = false;
try {
interruptedSuccessfully = executorService.awaitTermination(20, TimeUnit.SECONDS);
}
catch (InterruptedException awaitInterrupt){
logPrinter.print("Force interrupting task...", EMsgType.WARNING);
}
logPrinter.print("Task interrupted "+(interruptedSuccessfully?"successfully":"with some issues"), EMsgType.WARNING);
}
catch (Exception e){
e.printStackTrace();
logPrinter.print("Task failed: "+e.getMessage(), EMsgType.FAIL);
}
}
private void makePatches(NCAProvider ncaProvider) throws Exception{
logPrinter.print(String.format("File found: .."+File.separator+"%s"+File.separator+"%s",
ncaProvider.getFile().getParentFile().getName(), ncaProvider.getFile().getName())
, EMsgType.INFO);
new EsPatch(ncaProvider, saveTo, logPrinter);
oneLinerStatus = true;
}
private List<Callable<NCAProvider>> getSubTasksCollection() throws Exception{
logPrinter.print("Forming sub-tasks collection", EMsgType.INFO);
List<Callable<NCAProvider>> subTasks = new ArrayList<>();
int ncaPerThreadAmount = ncaFilesList.size() / THREADS_POOL_SIZE;
Iterator<String> iterator = ncaFilesList.listIterator();
for (int i = 1; i < THREADS_POOL_SIZE; i++){
Callable<NCAProvider> task = new EsNcaSearchTask(getNextSet(iterator, ncaPerThreadAmount));
subTasks.add(task);
}
int leftovers = ncaFilesList.size() % THREADS_POOL_SIZE;
Callable<NCAProvider> task = new EsNcaSearchTask(getNextSet(iterator, ncaPerThreadAmount+leftovers));
subTasks.add(task);
return subTasks;
}
private List<NCAProvider> getNextSet(Iterator<String> iterator, int amount) throws Exception{
List<NCAProvider> ncas = new ArrayList<>();
for (int j = 0; j < amount; j++){
String ncaFileName = iterator.next();
File nca = new File(firmware.getAbsolutePath()+File.separator+ncaFileName);
NCAProvider provider = new NCAProvider(nca, keyChainHolder.getRawKeySet());
ncas.add(provider);
}
return ncas;
}
}

View file

@ -0,0 +1,103 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.es.finders;
import libKonogonka.Converter;
import nsusbloader.AppPreferences;
import nsusbloader.Utilities.patches.AHeuristic;
import nsusbloader.Utilities.patches.BinToAsmPrinter;
import nsusbloader.Utilities.patches.SimplyFind;
import java.util.List;
class HeuristicEs1 extends AHeuristic {
private static final String PATTERN = AppPreferences.getInstance().getPatchPattern("ES", 1, 0);
private final List<Integer> findings;
private final byte[] where;
HeuristicEs1(byte[] where){
this.where = where;
SimplyFind simplyfind = new SimplyFind(PATTERN, where);
this.findings = simplyfind.getResults();
this.findings.removeIf(this::dropStep1);
if(findings.size() < 2)
return;
this.findings.removeIf(this::dropStep2);
}
// Check ranges
private boolean dropStep1(int offsetOfPatternFound){
return ((offsetOfPatternFound < 0x10000 || offsetOfPatternFound > 0xffffc));
}
// Remove non-CBZ
private boolean dropStep2(int offsetOfPatternFound){
return ((where[offsetOfPatternFound - 1] & (byte) 0b01111111) != 0x34);
}
@Override
public boolean isFound(){
return findings.size() == 1;
}
@Override
public boolean wantLessEntropy(){
return findings.size() > 1;
}
@Override
public int getOffset() throws Exception{
if(findings.isEmpty())
throw new Exception("Nothing found");
if (findings.size() > 1)
throw new Exception("Too many offsets");
return findings.get(0);
}
@Override
public boolean setOffsetsNearby(int offsetNearby) {
findings.removeIf(offset -> {
if (offset > offsetNearby)
return ! (offset < offsetNearby - 0xffff);
return ! (offset > offsetNearby - 0xffff);
});
return isFound();
}
@Override
public String getDetails(){
int cbzOffsetInternal = findings.get(0) - 4;
int instructionExpression = Converter.getLEint(where, cbzOffsetInternal);
int conditionalJumpLocation = ((instructionExpression >> 5 & 0x7FFFF) * 4 + cbzOffsetInternal) & 0xfffff;
int secondExpressionsPairElement1 = Converter.getLEint(where, conditionalJumpLocation);
int secondExpressionsPairElement2 = Converter.getLEint(where, conditionalJumpLocation+4);
return BinToAsmPrinter.printSimplified(instructionExpression, cbzOffsetInternal) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, cbzOffsetInternal + 4),
cbzOffsetInternal + 4) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, cbzOffsetInternal + 8),
cbzOffsetInternal + 8) +
"...\n" +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement1, conditionalJumpLocation) +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement2, conditionalJumpLocation + 4);
}
}

View file

@ -0,0 +1,161 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.es.finders;
import libKonogonka.Converter;
import nsusbloader.AppPreferences;
import nsusbloader.Utilities.patches.AHeuristic;
import nsusbloader.Utilities.patches.BinToAsmPrinter;
import nsusbloader.Utilities.patches.SimplyFind;
import java.util.ArrayList;
import java.util.List;
class HeuristicEs2 extends AHeuristic {
private static final String PATTERN = AppPreferences.getInstance().getPatchPattern("ES", 2, 0);
private List<Integer> findings;
private final byte[] where;
HeuristicEs2(byte[] where){
this.where = where;
find();
this.findings.removeIf(this::dropStep1);
if(findings.size() < 2)
return;
this.findings.removeIf(this::dropStep2);
if(findings.size() < 2)
return;
this.findings.removeIf(this::dropStep3);
if(findings.size() < 2)
return;
this.findings.removeIf(this::dropStep4);
if(findings.size() < 2)
return;
this.findings.removeIf(this::dropStep5);
if(findings.size() < 2)
return;
this.findings.removeIf(this::dropStep6);
}
private void find(){
SimplyFind simplyfind = new SimplyFind(PATTERN, where);
findings = new ArrayList<>();
// This approach a bit different. We're looking for pattern we want to patch, not the next one.
// So easier way is just to shift every value and pretend that nothing happened.
for (int offset : simplyfind.getResults())
findings.add(offset+4);
}
// Limit range
private boolean dropStep1(int offsetOfPatternFound){
return ((offsetOfPatternFound < 0x10000 || offsetOfPatternFound > 0xffffc));
}
// Is CBNZ next?
private boolean dropStep2(int offsetOfPatternFound){
return ! isCBNZ(Converter.getLEint(where, offsetOfPatternFound));
}
// Check what's above
private boolean dropStep3(int offsetOfPatternFound){
return ! isMOV(Converter.getLEint(where, offsetOfPatternFound-4));
}
// Check what's beyond or after jump
private boolean dropStep4(int offsetOfPatternFound) {
int nextExpression = Converter.getLEint(where, offsetOfPatternFound + 4);
return ! isLDRB_LDURB(nextExpression); // Drop if not LDRB OR LDURB
}
// Check second after jump if LDR-TBZ
private boolean dropStep5(int offsetOfPatternFound) {
int expression = Converter.getLEint(where, offsetOfPatternFound);
int afterJumpPosition = ((expression >> 5 & 0x7FFFF) * 4 + offsetOfPatternFound) & 0xfffff;
int secondAfterJumpExpression = Converter.getLEint(where, afterJumpPosition+4);
return ! isBL(secondAfterJumpExpression); //Second after jump = BL? No -> Drop
}
// Check second after jump if LDR-TBZ
private boolean dropStep6(int offsetOfPatternFound) {
int expression = Converter.getLEint(where, offsetOfPatternFound);
int afterJumpPosition = ((expression >> 5 & 0x7FFFF) * 4 + offsetOfPatternFound) & 0xfffff;
int forthAfterJumpExpression = Converter.getLEint(where, afterJumpPosition+12);
return ! isBL(forthAfterJumpExpression); //Forth after jump = BL? No -> Drop
}
@Override
public boolean isFound(){
return findings.size() == 1;
}
@Override
public boolean wantLessEntropy(){
return findings.size() > 1;
}
@Override
public int getOffset() throws Exception{
if(findings.isEmpty())
throw new Exception("Nothing found");
if (findings.size() > 1)
throw new Exception("Too many offsets");
return findings.get(0);
}
@Override
public boolean setOffsetsNearby(int offsetNearby) {
findings.removeIf(offset -> {
if (offset > offsetNearby)
return ! (offset < offsetNearby - 0xffff);
return ! (offset > offsetNearby - 0xffff);
});
return isFound();
}
@Override
public String getDetails(){
int secondExpressionOffset = findings.get(0);
int firstExpression = Converter.getLEint(where, secondExpressionOffset-4);
int secondExpression = Converter.getLEint(where, secondExpressionOffset);
int conditionalJumpLocation = 0;
if ((secondExpression >> 24 & 0x7f) == 0x35) {
conditionalJumpLocation = ((secondExpression >> 5 & 0x7FFFF) * 4 + secondExpressionOffset) & 0xfffff;
}
else if ((firstExpression >> 24 & 0x7f) == 0x36) {
conditionalJumpLocation = (secondExpressionOffset-4 + (firstExpression >> 5 & 0x3fff) * 4) & 0xfffff;
}
int secondExpressionsPairElement1 = Converter.getLEint(where, conditionalJumpLocation);
int secondExpressionsPairElement2 = Converter.getLEint(where, conditionalJumpLocation + 4);
int secondExpressionsPairElement3 = Converter.getLEint(where, conditionalJumpLocation + 8);
int secondExpressionsPairElement4 = Converter.getLEint(where, conditionalJumpLocation + 12);
return BinToAsmPrinter.printSimplified(Converter.getLEint(where, secondExpressionOffset - 4), secondExpressionOffset - 4) +
BinToAsmPrinter.printSimplified(secondExpression, secondExpressionOffset) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, secondExpressionOffset + 4), secondExpressionOffset + 4) +
"...\n" +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement1, conditionalJumpLocation) +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement2, conditionalJumpLocation + 4) +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement3, conditionalJumpLocation + 8) +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement4, conditionalJumpLocation + 12);
}
}

View file

@ -0,0 +1,145 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.es.finders;
import libKonogonka.Converter;
import nsusbloader.AppPreferences;
import nsusbloader.Utilities.patches.AHeuristic;
import nsusbloader.Utilities.patches.BinToAsmPrinter;
import nsusbloader.Utilities.patches.SimplyFind;
import java.util.List;
class HeuristicEs3 extends AHeuristic {
private static final String PATTERN0 = AppPreferences.getInstance().getPatchPattern("ES", 3, 0);
private static final String PATTERN1 = AppPreferences.getInstance().getPatchPattern("ES", 3, 1);
private final List<Integer> findings;
private final byte[] where;
HeuristicEs3(long fwVersion, byte[] where){
this.where = where;
String pattern = getPattern(fwVersion);
SimplyFind simplyfind = new SimplyFind(pattern, where);
this.findings = simplyfind.getResults();
this.findings.removeIf(this::dropStep1);
if(findings.size() < 2)
return;
this.findings.removeIf(this::dropStep2);
if(findings.size() < 2)
return;
this.findings.removeIf(this::dropStep3);
}
private String getPattern(long fwVersion){
if (fwVersion < 10400)
return PATTERN0;
return PATTERN1;
}
// Let's focus on CBZ-ONLY statements
private boolean dropStep1(int offsetOfPatternFound){
return ((where[offsetOfPatternFound - 1] & (byte) 0b01111111) != 0x34);
}
private boolean dropStep2(int offsetOfPatternFound){
int conditionalJumpLocation = getCBZConditionalJumpLocation(offsetOfPatternFound - 4);
int afterJumpSecondExpressions = Converter.getLEint(where, conditionalJumpLocation);
int afterJumpThirdExpressions = Converter.getLEint(where, conditionalJumpLocation+4);
// Check first is 'MOV'; second is 'B'
return (! isMOV_REG(afterJumpSecondExpressions)) || ! isB(afterJumpThirdExpressions);
}
private boolean dropStep3(int offsetOfPatternFound){
int conditionalJumpLocation = getCBZConditionalJumpLocation(offsetOfPatternFound-4);
int afterJumpSecondExpressions = Converter.getLEint(where, conditionalJumpLocation+4);
int secondPairConditionalJumpLocation = ((afterJumpSecondExpressions & 0x3ffffff) * 4 + (conditionalJumpLocation+4)) & 0xfffff;
int thirdExpressionsPairElement1 = Converter.getLEint(where, secondPairConditionalJumpLocation);
int thirdExpressionsPairElement2 = Converter.getLEint(where, secondPairConditionalJumpLocation+4);
// Check first is 'ADD'; second is 'BL'
return (! isADD(thirdExpressionsPairElement1)) || (! isBL(thirdExpressionsPairElement2));
}
private int getCBZConditionalJumpLocation(int cbzOffsetInternal){
int cbzExpression = Converter.getLEint(where, cbzOffsetInternal);
return ((cbzExpression >> 5 & 0x7FFFF) * 4 + cbzOffsetInternal) & 0xfffff;
}
@Override
public boolean isFound(){
return findings.size() == 1;
}
@Override
public boolean wantLessEntropy(){
return findings.size() > 1;
}
@Override
public int getOffset() throws Exception{
if(findings.isEmpty())
throw new Exception("Nothing found");
if (findings.size() > 1)
throw new Exception("Too many offsets");
return findings.get(0);
}
@Override
public boolean setOffsetsNearby(int offsetNearby) {
findings.removeIf(offset -> {
if (offset > offsetNearby)
return ! (offset < offsetNearby - 0xffff);
return ! (offset > offsetNearby - 0xffff);
});
return isFound();
}
@Override
public String getDetails(){
int cbzOffsetInternal = findings.get(0) - 4;
int cbzExpression = Converter.getLEint(where, cbzOffsetInternal);
int conditionalJumpLocation = ((cbzExpression >> 5 & 0x7FFFF) * 4 + cbzOffsetInternal) & 0xfffff;
int secondExpressionsPairElement1 = Converter.getLEint(where, conditionalJumpLocation);
int secondExpressionsPairElement2 = Converter.getLEint(where, conditionalJumpLocation+4);
StringBuilder builder = new StringBuilder();
builder.append(BinToAsmPrinter.printSimplified(cbzExpression, cbzOffsetInternal));
builder.append(BinToAsmPrinter.printSimplified(Converter.getLEint(where, cbzOffsetInternal+4), cbzOffsetInternal+4));
builder.append(BinToAsmPrinter.printSimplified(Converter.getLEint(where, cbzOffsetInternal+8), cbzOffsetInternal+8));
builder.append("...\n");
builder.append(BinToAsmPrinter.printSimplified(secondExpressionsPairElement1, conditionalJumpLocation));
builder.append(BinToAsmPrinter.printSimplified(secondExpressionsPairElement2, conditionalJumpLocation+4));
if (((secondExpressionsPairElement2 >> 26 & 0b111111) == 0x5)){
builder.append("...\n");
int conditionalJumpLocation2 = ((secondExpressionsPairElement2 & 0x3ffffff) * 4 + (conditionalJumpLocation+4)) & 0xfffff;
builder.append(BinToAsmPrinter.printSimplified(Converter.getLEint(where, conditionalJumpLocation2), conditionalJumpLocation2));
builder.append(BinToAsmPrinter.printSimplified(Converter.getLEint(where, conditionalJumpLocation2+4), conditionalJumpLocation2+4));
}
else {
builder.append("NO CONDITIONAL JUMP ON 2nd iteration (HeuristicEs3)");
}
return builder.toString();
}
}

View file

@ -0,0 +1,129 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.es.finders;
import nsusbloader.Utilities.patches.AHeuristic;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class HeuristicEsWizard {
private final List<AHeuristic> all;
private final List<AHeuristic> found;
private final List<AHeuristic> wantLessEntropy;
private final StringBuilder errorsAndNotes;
private int offset1 = -1;
private int offset2 = -1;
private int offset3 = -1;
public HeuristicEsWizard(long fwVersion, byte[] where) throws Exception{
this.errorsAndNotes = new StringBuilder();
this.all = Arrays.asList(
new HeuristicEs1(where),
new HeuristicEs2(where),
new HeuristicEs3(fwVersion, where)
);
this.found = all.stream()
.filter(AHeuristic::isFound)
.collect(Collectors.toList());
if (found.isEmpty())
throw new Exception("Nothing found!");
this.wantLessEntropy = all.stream()
.filter(AHeuristic::wantLessEntropy)
.collect(Collectors.toList());
shareOffsetsWithEachOther();
assignOffset1();
assignOffset2();
assignOffset3();
}
private void shareOffsetsWithEachOther(){
for (AHeuristic es : wantLessEntropy) {
if (shareWithNext(es))
return;
}
}
private boolean shareWithNext(AHeuristic es){
try {
for (AHeuristic foundEs : found) {
if (es.setOffsetsNearby(foundEs.getOffset())) {
found.add(es);
wantLessEntropy.remove(es);
shareOffsetsWithEachOther();
return true;
}
}
}
catch (Exception e){ e.printStackTrace(); }
return false;
}
private void assignOffset1(){
try {
offset1 = all.get(0).getOffset();
}
catch (Exception e){ errorsAndNotes.append(e.getLocalizedMessage()).append("\n"); }
}
private void assignOffset2(){
try {
offset2 = all.get(1).getOffset();
}
catch (Exception e){ errorsAndNotes.append(e.getLocalizedMessage()).append("\n"); }
}
private void assignOffset3(){
try {
offset3 = all.get(2).getOffset();
}
catch (Exception e){ errorsAndNotes.append(e.getLocalizedMessage()).append("\n"); }
}
public String getErrorsAndNotes(){
return errorsAndNotes.toString();
}
public String getDebug(){
StringBuilder builder = new StringBuilder();
if (all.get(0).isFound()){
builder.append("\t\t-=== 1 ===-\n");
builder.append(all.get(0).getDetails());
}
if (all.get(1).isFound()){
builder.append("\t\t-=== 2 ===-\n");
builder.append(all.get(1).getDetails());
}
if (all.get(2).isFound()){
builder.append("\t\t-=== 3 ===-\n");
builder.append(all.get(2).getDetails());
}
return builder.toString();
}
public int getOffset1() { return offset1; }
public int getOffset2() { return offset2; }
public int getOffset3() { return offset3; }
}

View file

@ -0,0 +1,163 @@
/*
Copyright 2019-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.fs;
import libKonogonka.Converter;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EMsgType;
import nsusbloader.Utilities.patches.MalformedIniFileException;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
public class FsIniMaker {
private static final String FILE_HEADER_TEXT = "# UTF-8\n" +
"# A KIP section is [kip1_name:sha256_hex_8bytes]\n" +
"# A patchset is .patch_name=kip_section_dec:offset_hex_0x:length_hex_0x:src_data_hex,dst_data_hex\n" +
"# _dec: 1 char decimal | _hex_0x: max u32 prefixed with 0x | _hex: hex array.\n" +
"# Kip1 section decimals: TEXT: 0, RODATA: 1, DATA: 2.\n"; // Sending good vibes to Mr. ITotalJustice
private final ILogPrinter logPrinter;
private final String saveToLocation;
private final int offset1;
private final int offset2;
private String firmwareVersionInformationNotice;
private String sectionDeclaration;
private String patchSet1;
private String patchSet2;
public FsIniMaker(ILogPrinter logPrinter,
String saveToLocation,
byte[] _textSection,
int wizardOffset1,
int wizardOffset2,
byte[] sdkVersion,
String patchName,
boolean filesystemTypeFat32) throws Exception{
this.logPrinter = logPrinter;
this.saveToLocation = saveToLocation;
this.offset1 = wizardOffset1 - 4;
this.offset2 = wizardOffset2 - 4;
mkDirs();
makeFwVersionInformationNotice(filesystemTypeFat32, sdkVersion);
makeSectionDeclaration(patchName);
makePatchSet1(_textSection);
makePatchSet2(_textSection);
writeFile();
}
private void mkDirs(){
File parentFolder = new File(saveToLocation + File.separator + "bootloader");
parentFolder.mkdirs();
}
private void makeFwVersionInformationNotice(boolean isFat32, byte[] fwVersion){
String fwVersionFormatted = fwVersion[3]+"."+fwVersion[2]+"."+fwVersion[1]+"."+fwVersion[0];
if (isFat32)
firmwareVersionInformationNotice = "\n#FS (FAT)"+fwVersionFormatted+"\n";
else
firmwareVersionInformationNotice = "\n#FS (ExFAT) "+fwVersionFormatted+"\n";
}
private void makeSectionDeclaration(String patchName){
sectionDeclaration = "[FS:"+patchName.substring(0, 16)+"]";
}
private void makePatchSet1(byte[] _textSection){
if (offset1 > 0) {
byte[] originalInstruction = Arrays.copyOfRange(_textSection, offset1, offset1 + 4);
patchSet1 = String.format(".nosigchk=0:0x%02X:0x4:%s,1F2003D5",
offset1, Converter.byteArrToHexStringAsLE(originalInstruction, true));
}
}
private void makePatchSet2(byte[] _textSection){
if (offset2 > 0) {
byte[] originalInstruction = Arrays.copyOfRange(_textSection, offset2, offset2 + 4);
patchSet2 = String.format(".nosigchk=0:0x%02X:0x4:%s,E0031F2A",
offset2, Converter.byteArrToHexStringAsLE(originalInstruction, true));
}
}
private void writeFile() throws Exception{
final String iniLocation = saveToLocation + File.separator + "bootloader" + File.separator + "patches.ini";
final Path iniLocationPath = Paths.get(iniLocation);
boolean iniNotExists = Files.notExists(iniLocationPath);
try (RandomAccessFile ini = new RandomAccessFile(iniLocation, "rw")){
if (iniNotExists)
ini.writeBytes(FILE_HEADER_TEXT);
else {
String line;
while ((line = ini.readLine()) != null){
if (! line.startsWith(sectionDeclaration))
continue;
if (offset1 > 0) {
String expression1 = ini.readLine();
if (expression1 == null || ! expression1.startsWith(patchSet1))
throw new MalformedIniFileException("Somewhere near "+ini.getFilePointer());
}
String expression2 = ini.readLine();
if (offset2 > 0) {
if (expression2 == null || ! expression2.startsWith(patchSet2))
throw new MalformedIniFileException("Somewhere near "+ini.getFilePointer());
}
else {
if (expression2 == null || ! expression2.startsWith(".nosigchk"))
return;
throw new MalformedIniFileException("Somewhere near "+ini.getFilePointer());
}
return; // Ini file already contains correct information regarding patch file we made.
}
}
ini.writeBytes(firmwareVersionInformationNotice);
ini.writeBytes(sectionDeclaration);
ini.writeBytes("\n");
if (offset1 > 0) {
ini.writeBytes(patchSet1);
ini.writeBytes("\n");
}
if (offset2 > 0) {
ini.writeBytes(patchSet2);
ini.writeBytes("\n");
}
}
catch (MalformedIniFileException e){
e.printStackTrace();
logPrinter.print(
"Existing patches.ini file is malformed or contains incorrect (outdated) information regarding current patch.\n" +
"It's now saved at "+iniLocation+".OLD\n" +
"New patches.ini file created instead.", EMsgType.WARNING);
Files.move(iniLocationPath, Paths.get(iniLocation+".OLD"),
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
writeFile();
}
}
}

View file

@ -0,0 +1,50 @@
/*
Copyright 2018-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.fs;
import libKonogonka.Converter;
import libKonogonka.fs.NCA.NCAProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
class FsNcaSearchTask implements Callable<List<NCAProvider>> {
private final List<NCAProvider> ncaProviders;
FsNcaSearchTask(List<NCAProvider> ncaProviders){
this.ncaProviders = ncaProviders;
}
@Override
public List<NCAProvider> call() {
List<NCAProvider> result = new ArrayList<>();
try {
for (NCAProvider ncaProvider : ncaProviders) {
String titleId = Converter.byteArrToHexStringAsLE(ncaProvider.getTitleId());
if (titleId.equals("0100000000000819") || titleId.equals("010000000000081b")) // eq. FAT32 || exFAT
result.add(ncaProvider);
}
}
catch (Exception e){
e.printStackTrace();
}
return result;
}
}

View file

@ -0,0 +1,218 @@
/*
Copyright 2018-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
---
Based on https://github.com/mrdude2478/IPS_Patch_Creator patch script made by GBATemp member MrDude.
*/
package nsusbloader.Utilities.patches.fs;
import libKonogonka.Converter;
import libKonogonka.KeyChainHolder;
import libKonogonka.fs.NCA.NCAProvider;
import libKonogonka.fs.RomFs.FileSystemEntry;
import libKonogonka.fs.RomFs.RomFsProvider;
import libKonogonka.fs.other.System2.System2Provider;
import libKonogonka.fs.other.System2.ini1.Ini1Provider;
import libKonogonka.fs.other.System2.ini1.KIP1Provider;
import libKonogonka.aesctr.InFileStreamProducer;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EMsgType;
import nsusbloader.Utilities.patches.BinToAsmPrinter;
import nsusbloader.Utilities.patches.fs.finders.HeuristicFsWizard;
import java.io.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.stream.Collectors;
public class FsPatch {
private static final byte[] HEADER = "PATCH".getBytes(StandardCharsets.US_ASCII);
private static final byte[] FOOTER = "EOF".getBytes(StandardCharsets.US_ASCII);
private final NCAProvider ncaProvider;
private final String saveToLocation;
private final KeyChainHolder keyChainHolder;
private final ILogPrinter logPrinter;
private String patchName;
private byte[] _textSection;
private boolean filesystemTypeFat32;
private HeuristicFsWizard wizard;
// Called twice: once for FAT32, once for ExFAT
FsPatch(NCAProvider ncaProvider,
String saveToLocation,
KeyChainHolder keyChainHolder,
ILogPrinter logPrinter) throws Exception{
this.ncaProvider = ncaProvider;
this.saveToLocation = saveToLocation;
this.keyChainHolder = keyChainHolder;
this.logPrinter = logPrinter;
KIP1Provider kip1Provider = getKIP1Provider();
getPatchName(kip1Provider);
getTextSection(kip1Provider);
checkFirmwareVersion();
getFilesystemType();
findAllOffsets();
mkDirs();
writeFile();
new FsIniMaker(logPrinter,
saveToLocation,
_textSection,
wizard.getOffset1(),
wizard.getOffset2(),
ncaProvider.getSdkVersion(),
patchName,
filesystemTypeFat32);
logPrinter.print(" == Debug information ==\n"+wizard.getDebug(), EMsgType.NULL);
}
private KIP1Provider getKIP1Provider() throws Exception{
RomFsProvider romFsProvider = ncaProvider.getNCAContentProvider(0).getRomfs();
FileSystemEntry package2FsEntry = romFsProvider.getRootEntry().getContent()
.stream()
.filter(e -> e.getName().equals("nx"))
.collect(Collectors.toList())
.get(0)
.getContent()
.stream()
.filter(e -> e.getName().equals("package2"))
.collect(Collectors.toList())
.get(0);
InFileStreamProducer producer = romFsProvider.getStreamProducer(package2FsEntry);
System2Provider system2Provider = new System2Provider(producer, keyChainHolder);
Ini1Provider ini1Provider = system2Provider.getIni1Provider();
KIP1Provider kip1Provider = ini1Provider.getKip1List().stream()
.filter(provider -> provider.getHeader().getName().startsWith("FS"))
.collect(Collectors.toList())
.get(0);
if (kip1Provider == null)
throw new Exception("No FS KIP1");
return kip1Provider;
}
private void getPatchName(KIP1Provider kip1Provider) throws Exception{
int kip1EncryptedSize = (int) kip1Provider.getSize();
byte[] kip1EncryptedRaw = new byte[kip1EncryptedSize];
try (BufferedInputStream kip1ProviderStream = kip1Provider.getStreamProducer().produce()) {
if (kip1EncryptedSize != kip1ProviderStream.read(kip1EncryptedRaw))
throw new Exception("Unencrypted FS KIP1 read failure");
}
byte[] sha256ofKip1 = MessageDigest.getInstance("SHA-256").digest(kip1EncryptedRaw);
patchName = Converter.byteArrToHexStringAsLE(sha256ofKip1, true) + ".ips";
}
private void getTextSection(KIP1Provider kip1Provider) throws Exception{
_textSection = kip1Provider.getAsDecompressed().getTextRaw();
}
private void checkFirmwareVersion() throws Exception{
final byte[] byteSdkVersion = ncaProvider.getSdkVersion();
long fwVersion = Long.parseLong(""+byteSdkVersion[3]+byteSdkVersion[2]+byteSdkVersion[1]+byteSdkVersion[0]);
logPrinter.print("Internal firmware version: " + byteSdkVersion[3] +"."+ byteSdkVersion[2] +"."+ byteSdkVersion[1] +"."+ byteSdkVersion[0], EMsgType.INFO);
if (byteSdkVersion[3] < 9 || fwVersion < 9300)
logPrinter.print("WARNING! FIRMWARES VERSIONS BEFORE 9.0.0 ARE NOT SUPPORTED! " +
"USING PRODUCED ES PATCHES (IF ANY) COULD BREAK SOMETHING! IT'S NEVER BEEN TESTED!", EMsgType.WARNING);
}
private void getFilesystemType() throws Exception{
String titleId = Converter.byteArrToHexStringAsLE(ncaProvider.getTitleId());
filesystemTypeFat32 = titleId.equals("0100000000000819");
if (filesystemTypeFat32)
logPrinter.print("\n\t\t-- [ FAT32 ] --\n", EMsgType.INFO);
else
logPrinter.print("\n\t\t-- [ ExFAT ] --\n", EMsgType.INFO);
}
private void findAllOffsets() throws Exception{
this.wizard = new HeuristicFsWizard(_textSection);
String errorsAndNotes = wizard.getErrorsAndNotes();
if (errorsAndNotes.length() > 0)
logPrinter.print(errorsAndNotes, EMsgType.WARNING);
}
private void mkDirs(){
File parentFolder = new File(saveToLocation + File.separator +
"atmosphere" + File.separator + "kip_patches" + File.separator + "fs_patches");
parentFolder.mkdirs();
}
private void writeFile() throws Exception{
String patchFileLocation = saveToLocation + File.separator +
"atmosphere" + File.separator + "kip_patches" + File.separator + "fs_patches" + File.separator + patchName;
int offset1 = wizard.getOffset1();
int offset2 = wizard.getOffset2();
ByteBuffer handyFsPatch = ByteBuffer.allocate(0x100).order(ByteOrder.LITTLE_ENDIAN);
handyFsPatch.put(HEADER);
if (offset1 > 0) {
logPrinter.print("Patch component 1 will be used", EMsgType.PASS);
handyFsPatch.put(getPatch1(offset1));
}
if (offset2 > 0) {
logPrinter.print("Patch component 2 will be used", EMsgType.PASS);
handyFsPatch.put(getPatch2(offset2));
}
handyFsPatch.put(FOOTER);
byte[] fsPatch = new byte[handyFsPatch.position()];
((Buffer) handyFsPatch).rewind();
handyFsPatch.get(fsPatch);
try (BufferedOutputStream stream = new BufferedOutputStream(
Files.newOutputStream(Paths.get(patchFileLocation)))){
stream.write(fsPatch);
}
logPrinter.print("Patch created at "+patchFileLocation, EMsgType.PASS);
}
private byte[] getPatch1(int offset) throws Exception{
int requiredInstructionOffsetInternal = offset - 4;
int requiredInstructionOffsetReal = requiredInstructionOffsetInternal + 0x100;
final int patch = 0x1F2003D5; // NOP
logPrinter.print(BinToAsmPrinter.printSimplified(Integer.reverseBytes(patch), requiredInstructionOffsetInternal), EMsgType.NULL);
// Somehow IPS patches uses offsets written as big_endian (0.o) and bytes dat should be patched as LE.
ByteBuffer prePatch = ByteBuffer.allocate(10).order(ByteOrder.BIG_ENDIAN)
.putInt(requiredInstructionOffsetReal)
.putShort((short) 4)
.putInt(patch);
return Arrays.copyOfRange(prePatch.array(), 1, 10);
}
private byte[] getPatch2(int offset) throws Exception{
int requiredInstructionOffsetInternal = offset - 4;
int requiredInstructionOffsetReal = requiredInstructionOffsetInternal + 0x100;
final int patch = 0xE0031F2A; // mov w0, wzr
logPrinter.print(BinToAsmPrinter.printSimplified(Integer.reverseBytes(patch), requiredInstructionOffsetInternal), EMsgType.NULL);
// Somehow IPS patches uses offsets written as big_endian (0.o) and bytes dat should be patched as LE.
ByteBuffer prePatch = ByteBuffer.allocate(10).order(ByteOrder.BIG_ENDIAN)
.putInt(requiredInstructionOffsetReal)
.putShort((short) 4)
.putInt(patch);
return Arrays.copyOfRange(prePatch.array(), 1, 10);
}
}

View file

@ -0,0 +1,185 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.fs;
import libKonogonka.KeyChainHolder;
import libKonogonka.fs.NCA.NCAProvider;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.ModelControllers.Log;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.NSLDataTypes.EMsgType;
import java.io.File;
import java.util.*;
import java.util.concurrent.*;
public class FsPatchMaker extends CancellableRunnable {
private int THREADS_POOL_SIZE;
private final ILogPrinter logPrinter;
private final String pathToFirmware;
private final String pathToKeysFile;
private final String saveTo;
private File firmware;
private KeyChainHolder keyChainHolder;
private ExecutorService executorService;
private List<String> ncaFilesList; // inside the folder
private boolean oneLinerStatus = false;
public FsPatchMaker(String pathToFirmware, String pathToKeysFile, String saveTo){
this.logPrinter = Log.getPrinter(EModule.PATCHES);
/*
this.logPrinter = new ILogPrinter() {
public void print(String message, EMsgType type) throws InterruptedException {}
public void updateProgress(Double value) throws InterruptedException {}
public void update(HashMap<String, File> nspMap, EFileStatus status) {}
public void update(File file, EFileStatus status) {}
public void updateOneLinerStatus(boolean status) {}
public void close() {}
};
*/
this.pathToFirmware = pathToFirmware;
this.pathToKeysFile = pathToKeysFile;
this.saveTo = saveTo;
}
@Override
public void run() {
try {
logPrinter.print("..:: Make FS Patches ::..", EMsgType.INFO);
receiveFirmware();
buildKeyChainHolder();
receiveNcaFileNamesList();
specifyThreadsPoolSize();
createPool();
executePool();
}
catch (Exception e){
e.printStackTrace();
try{
logPrinter.print(e.getMessage(), EMsgType.FAIL);
} catch (Exception ignore){}
}
finally {
logPrinter.updateOneLinerStatus(oneLinerStatus);
logPrinter.close();
}
}
private void receiveFirmware() throws Exception{
logPrinter.print("Looking at firmware", EMsgType.INFO);
this.firmware = new File(pathToFirmware);
if (! firmware.exists())
throw new Exception("Firmware directory does not exist " + pathToFirmware);
}
private void buildKeyChainHolder() throws Exception{
logPrinter.print("Reading keys", EMsgType.INFO);
this.keyChainHolder = new KeyChainHolder(pathToKeysFile, null);
}
private void receiveNcaFileNamesList() throws Exception{
logPrinter.print("Collecting NCA files", EMsgType.INFO);
String[] fileNamesArray = firmware.list(
(File directory, String file) -> ( ! file.endsWith(".cnmt.nca") && file.endsWith(".nca")));
ncaFilesList = Arrays.asList(Objects.requireNonNull(fileNamesArray));
if (ncaFilesList.size() == 0)
throw new Exception("No NCA files found in firmware folder");
}
private void specifyThreadsPoolSize(){
THREADS_POOL_SIZE = Math.max(Runtime.getRuntime().availableProcessors()+1, 4);
THREADS_POOL_SIZE = Math.min(THREADS_POOL_SIZE, ncaFilesList.size());
}
private void createPool() throws Exception{
logPrinter.print("Creating sub-tasks pool", EMsgType.INFO);
this.executorService = Executors.newFixedThreadPool(
THREADS_POOL_SIZE,
runnable -> {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
});
}
private void executePool() throws Exception{ //TODO: FIX. Exceptions thrown only by logPrinter
try {
logPrinter.print("Executing sub-tasks pool", EMsgType.INFO);
List<Future<List<NCAProvider>>> futuresResults = executorService.invokeAll(getSubTasksCollection());
int counter = 0;
for (Future<List<NCAProvider>> future : futuresResults){
List<NCAProvider> ncaProviders = future.get();
for (NCAProvider ncaProvider : ncaProviders) {
makePatches(ncaProvider);
if (++counter > 1)
break;
}
}
executorService.shutdown();
}
catch (InterruptedException ie){
executorService.shutdownNow();
boolean interruptedSuccessfully = false;
try {
interruptedSuccessfully = executorService.awaitTermination(20, TimeUnit.SECONDS);
}
catch (InterruptedException awaitInterrupt){
logPrinter.print("Force interrupting task...", EMsgType.WARNING);
}
logPrinter.print("Task interrupted "+(interruptedSuccessfully?"successfully":"with some issues"), EMsgType.WARNING);
}
catch (Exception e){
e.printStackTrace();
logPrinter.print("Task failed: "+e.getMessage(), EMsgType.FAIL);
}
}
private void makePatches(NCAProvider ncaProvider) throws Exception{
final File foundFile = ncaProvider.getFile();
logPrinter.print(String.format("File found: .."+File.separator+"%s"+File.separator+"%s",
foundFile.getParentFile().getName(), foundFile.getName()), EMsgType.INFO);
new FsPatch(ncaProvider, saveTo, keyChainHolder, logPrinter);
oneLinerStatus = true;
}
private List<Callable<List<NCAProvider>>> getSubTasksCollection() throws Exception{
logPrinter.print("Forming sub-tasks collection", EMsgType.INFO);
List<Callable<List<NCAProvider>>> subTasks = new ArrayList<>();
int ncaPerThreadAmount = ncaFilesList.size() / THREADS_POOL_SIZE;
Iterator<String> iterator = ncaFilesList.listIterator();
for (int i = 1; i < THREADS_POOL_SIZE; i++){
Callable<List<NCAProvider>> task = new FsNcaSearchTask(getNextSet(iterator, ncaPerThreadAmount));
subTasks.add(task);
}
int leftovers = ncaFilesList.size() % THREADS_POOL_SIZE;
Callable<List<NCAProvider>> task = new FsNcaSearchTask(getNextSet(iterator, ncaPerThreadAmount+leftovers));
subTasks.add(task);
return subTasks;
}
private List<NCAProvider> getNextSet(Iterator<String> iterator, int amount) throws Exception{
List<NCAProvider> ncas = new ArrayList<>();
for (int j = 0; j < amount; j++){
String ncaFileName = iterator.next();
File nca = new File(firmware.getAbsolutePath()+File.separator+ncaFileName);
NCAProvider provider = new NCAProvider(nca, keyChainHolder.getRawKeySet());
ncas.add(provider);
}
return ncas;
}
}

View file

@ -0,0 +1,90 @@
/*
Copyright 2018-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.fs.finders;
import libKonogonka.Converter;
import nsusbloader.AppPreferences;
import nsusbloader.Utilities.patches.AHeuristic;
import nsusbloader.Utilities.patches.BinToAsmPrinter;
import nsusbloader.Utilities.patches.SimplyFind;
import java.util.ArrayList;
import java.util.List;
class HeuristicFs1 extends AHeuristic {
private static final String PATTERN = AppPreferences.getInstance().getPatchPattern("FS", 1, 0); // TBZ
private final byte[] where;
private final List<Integer> findings;
HeuristicFs1(byte[] where) {
this.where = where;
this.findings = new ArrayList<>();
SimplyFind simplyfind = new SimplyFind(PATTERN, where);
simplyfind.getResults().forEach(var -> findings.add(var + 4));
}
@Override
public boolean isFound() {
return findings.size() == 1;
}
@Override
public boolean wantLessEntropy() {
return findings.size() > 1;
}
@Override
public int getOffset() throws Exception {
if (findings.isEmpty())
throw new Exception("Nothing found");
if (findings.size() > 1)
throw new Exception("Too many offsets");
return findings.get(0);
}
@Override
public boolean setOffsetsNearby(int offsetNearby) {
findings.removeIf(offset -> {
if (offset > offsetNearby)
return !(offset < offsetNearby - 0xffff);
return !(offset > offsetNearby - 0xffff);
});
return isFound();
}
@Override
public String getDetails() {
int offsetInternal = findings.get(0) - 4;
int firstExpression = Converter.getLEint(where, offsetInternal);
int conditionalJumpLocation = offsetInternal + (firstExpression >> 5 & 0x3fff) * 4;
int secondExpressionsPairElement1 = Converter.getLEint(where, conditionalJumpLocation);
int secondExpressionsPairElement2 = Converter.getLEint(where, conditionalJumpLocation + 4);
return BinToAsmPrinter.printSimplified(firstExpression, offsetInternal) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, offsetInternal + 4), offsetInternal + 4) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, offsetInternal + 8), offsetInternal + 8) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, offsetInternal + 12), offsetInternal + 12) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, offsetInternal + 16), offsetInternal + 16) +
"...\n" +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement1, conditionalJumpLocation) +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement2, conditionalJumpLocation + 4);
}
}

View file

@ -0,0 +1,97 @@
/*
Copyright 2018-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.fs.finders;
import libKonogonka.Converter;
import nsusbloader.AppPreferences;
import nsusbloader.Utilities.patches.AHeuristic;
import nsusbloader.Utilities.patches.BinToAsmPrinter;
import nsusbloader.Utilities.patches.SimplyFind;
import java.util.ArrayList;
import java.util.List;
class HeuristicFs2 extends AHeuristic {
private static final String PATTERN = AppPreferences.getInstance().getPatchPattern("FS", 2, 0);
private final byte[] where;
private final List<Integer> findings;
HeuristicFs2(byte[] where){
this.where = where;
this.findings = new ArrayList<>();
SimplyFind simplyfind = new SimplyFind(PATTERN, where);
simplyfind.getResults().forEach(var -> findings.add(var + 4));
if(findings.size() < 2)
return;
this.findings.removeIf(this::dropStep1);
}
// All matches are somewhere in 0x6xxxx-0x7xxxx, then let's just limit search field by 0x80000
private boolean dropStep1(int offsetOfPatternFound){
return (offsetOfPatternFound > 0x80000);
}
@Override
public boolean isFound(){
return findings.size() == 1;
}
@Override
public boolean wantLessEntropy(){
return findings.size() > 1;
}
@Override
public int getOffset() throws Exception{
if(findings.isEmpty())
throw new Exception("Nothing found");
if (findings.size() > 1)
throw new Exception("Too many offsets");
return findings.get(0);
}
@Override
public boolean setOffsetsNearby(int offsetNearby) {
findings.removeIf(offset -> {
if (offset > offsetNearby)
return ! (offset < offsetNearby - 0xffff);
return ! (offset > offsetNearby - 0xffff);
});
return isFound();
}
@Override
public String getDetails(){
int offsetInternal = findings.get(0) - 4;
int firstExpression = Converter.getLEint(where, offsetInternal);
int conditionalJumpLocation = ((firstExpression & 0x3ffffff) * 4 + offsetInternal) & 0xfffff;
int secondExpressionsPairElement1 = Converter.getLEint(where, conditionalJumpLocation);
int secondExpressionsPairElement2 = Converter.getLEint(where, conditionalJumpLocation+4);
return BinToAsmPrinter.printSimplified(firstExpression, offsetInternal) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, offsetInternal + 4), offsetInternal + 4) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, offsetInternal + 8), offsetInternal + 8) +
BinToAsmPrinter.printSimplified(Converter.getLEint(where, offsetInternal + 12), offsetInternal + 12) +
"...\n" +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement1, conditionalJumpLocation) +
BinToAsmPrinter.printSimplified(secondExpressionsPairElement2, conditionalJumpLocation + 4);
}
}

View file

@ -0,0 +1,115 @@
/*
Copyright 2018-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.fs.finders;
import nsusbloader.Utilities.patches.AHeuristic;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class HeuristicFsWizard {
private final List<AHeuristic> all;
private final List<AHeuristic> found;
private final List<AHeuristic> wantLessEntropy;
private final StringBuilder errorsAndNotes;
private int offset1 = -1;
private int offset2 = -1;
public HeuristicFsWizard(byte[] where) throws Exception{
this.errorsAndNotes = new StringBuilder();
this.all = Arrays.asList(
new HeuristicFs1(where),
new HeuristicFs2(where)
);
this.found = all.stream()
.filter(AHeuristic::isFound)
.collect(Collectors.toList());
if (found.isEmpty())
throw new Exception("Nothing found!");
this.wantLessEntropy = all.stream()
.filter(AHeuristic::wantLessEntropy)
.collect(Collectors.toList());
shareOffsetsWithEachOther();
assignOffset1();
assignOffset2();
}
private void shareOffsetsWithEachOther(){
for (AHeuristic es : wantLessEntropy) {
if (shareWithNext(es))
return;
}
}
private boolean shareWithNext(AHeuristic es){
try {
for (AHeuristic foundEs : found) {
if (es.setOffsetsNearby(foundEs.getOffset())) {
found.add(es);
wantLessEntropy.remove(es);
shareOffsetsWithEachOther();
return true;
}
}
}
catch (Exception e){ e.printStackTrace(); }
return false;
}
private void assignOffset1(){
try {
offset1 = all.get(0).getOffset();
}
catch (Exception e){ errorsAndNotes.append(e.getLocalizedMessage()).append("\n"); }
}
private void assignOffset2(){
try {
offset2 = all.get(1).getOffset();
}
catch (Exception e){ errorsAndNotes.append(e.getLocalizedMessage()).append("\n"); }
}
public String getErrorsAndNotes(){
return errorsAndNotes.toString();
}
public String getDebug(){
StringBuilder builder = new StringBuilder();
if (all.get(0).isFound()){
builder.append("\t\t-=== 1 ===-\n");
builder.append(all.get(0).getDetails());
}
if (all.get(1).isFound()){
builder.append("\t\t-=== 2 ===-\n");
builder.append(all.get(1).getDetails());
}
return builder.toString();
}
public int getOffset1() { return offset1; }
public int getOffset2() { return offset2; }
}

View file

@ -0,0 +1,115 @@
/*
Copyright 2019-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.loader;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EMsgType;
import nsusbloader.Utilities.patches.MalformedIniFileException;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class LoaderIniMaker {
private static final String FILE_HEADER_TEXT = "# UTF-8\n" +
"# A KIP section is [kip1_name:sha256_hex_8bytes]\n" +
"# A patchset is .patch_name=kip_section_dec:offset_hex_0x:length_hex_0x:src_data_hex,dst_data_hex\n" +
"# _dec: 1 char decimal | _hex_0x: max u32 prefixed with 0x | _hex: hex array.\n" +
"# Kip1 section decimals: TEXT: 0, RODATA: 1, DATA: 2.\n"; // Sending good vibes to Mr. ITotalJustice
private final ILogPrinter logPrinter;
private final String saveToLocation;
private final int offset;
private String sectionDeclaration;
private String patchSet;
LoaderIniMaker(ILogPrinter logPrinter,
String saveToLocation,
int foundOffset,
String patchName) throws Exception{
this.logPrinter = logPrinter;
this.saveToLocation = saveToLocation;
this.offset = foundOffset + 6;
mkDirs();
makeSectionDeclaration(patchName);
makePatchSet1();
writeFile();
}
private void mkDirs(){
File parentFolder = new File(saveToLocation + File.separator + "bootloader");
parentFolder.mkdirs();
}
private void makeSectionDeclaration(String patchName){
sectionDeclaration = "[Loader:"+patchName.substring(0, 16)+"]";
}
private void makePatchSet1(){
patchSet = String.format(".nosigchk=0:0x%02X:0x1:01,00", offset);
}
private void writeFile() throws Exception{
final String iniLocation = saveToLocation + File.separator + "bootloader" + File.separator + "patches.ini";
final Path iniLocationPath = Paths.get(iniLocation);
boolean iniNotExists = Files.notExists(iniLocationPath);
try (RandomAccessFile ini = new RandomAccessFile(iniLocation, "rw")){
if (iniNotExists)
ini.writeBytes(FILE_HEADER_TEXT);
else {
String line;
while ((line = ini.readLine()) != null){
if (! line.startsWith(sectionDeclaration))
continue;
String expression = ini.readLine();
if (expression == null || ! expression.startsWith(patchSet))
throw new MalformedIniFileException("Somewhere near "+ini.getFilePointer());
return; // Ini file already contains correct information regarding patch file we made.
}
}
ini.writeBytes("\n#Loader (Atmosphere)\n");
ini.writeBytes(sectionDeclaration);
ini.writeBytes("\n");
ini.writeBytes(patchSet);
ini.writeBytes("\n");
}
catch (MalformedIniFileException e){
e.printStackTrace();
logPrinter.print(
"Existing patches.ini file is malformed or contains incorrect (outdated) information regarding current patch.\n" +
"It's now saved at "+iniLocation+".OLD\n" +
"New patches.ini file created instead.", EMsgType.WARNING);
Files.move(iniLocationPath, Paths.get(iniLocation+".OLD"),
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
writeFile();
}
}
}

View file

@ -0,0 +1,148 @@
/*
Copyright 2018-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
---
Based on https://github.com/mrdude2478/IPS_Patch_Creator patch script made by GBATemp member MrDude.
*/
package nsusbloader.Utilities.patches.loader;
import libKonogonka.Converter;
import libKonogonka.fs.other.System2.ini1.KIP1Provider;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EMsgType;
import nsusbloader.Utilities.patches.BinToAsmPrinter;
import nsusbloader.Utilities.patches.SimplyFind;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.Arrays;
public class LoaderPatch {
private static final byte[] HEADER = "PATCH".getBytes(StandardCharsets.US_ASCII);
private static final byte[] FOOTER = "EOF".getBytes(StandardCharsets.US_ASCII);
private static final String ATMOSPHERE_NEW_PATTERN = "01C0BE121F00016B";
//private static final String ATMOSPHERE_OLD_PATTERN = "003C00121F280071"; Must be patched using different (to current implementation) code
private final String saveToLocation;
private final ILogPrinter logPrinter;
private String patchName;
private byte[] _textSection;
private int offset;
LoaderPatch(KIP1Provider loaderProvider,
String saveToLocation,
ILogPrinter logPrinter) throws Exception{
this.saveToLocation = saveToLocation;
this.logPrinter = logPrinter;
getPatchName(loaderProvider);
getTextSection(loaderProvider);
findOffset();
mkDirs();
writeFile();
new LoaderIniMaker(logPrinter, saveToLocation, offset, patchName);
}
private void getPatchName(KIP1Provider kip1Provider) throws Exception{
int kip1EncryptedSize = (int) kip1Provider.getSize();
byte[] kip1EncryptedRaw = new byte[kip1EncryptedSize];
try (BufferedInputStream kip1ProviderStream = kip1Provider.getStreamProducer().produce()) {
if (kip1EncryptedSize != kip1ProviderStream.read(kip1EncryptedRaw))
throw new Exception("Unencrypted FS KIP1 read failure");
}
byte[] sha256ofKip1 = MessageDigest.getInstance("SHA-256").digest(kip1EncryptedRaw);
patchName = Converter.byteArrToHexStringAsLE(sha256ofKip1, true) + ".ips";
}
private void getTextSection(KIP1Provider kip1Provider) throws Exception{
_textSection = kip1Provider.getAsDecompressed().getTextRaw();
}
private void findOffset() throws Exception{
SimplyFind simplyFind = new SimplyFind(ATMOSPHERE_NEW_PATTERN, _textSection); // Atm 13+
if (simplyFind.getResults().size() == 0)
throw new Exception("Offset not found");
offset = simplyFind.getResults().get(0);
if (offset <= 0)
throw new Exception("Found offset is incorrect");
for (int i = 0; i < simplyFind.getResults().size(); i++) {
int offsetInternal = simplyFind.getResults().get(i) + 4;
logPrinter.print("Only first (#1) found record will be patched!", EMsgType.INFO);
logPrinter.print("Found #" + (i+1) +"\n"+
BinToAsmPrinter.printSimplified(Converter.getLEint(_textSection, offsetInternal), offsetInternal) +
BinToAsmPrinter.printSimplified(Converter.getLEint(_textSection, offsetInternal + 4), offsetInternal + 4) +
BinToAsmPrinter.printSimplified(Converter.getLEint(_textSection, offsetInternal + 8), offsetInternal + 8) +
BinToAsmPrinter.printSimplified(Converter.getLEint(_textSection, offsetInternal + 12), offsetInternal + 12),
EMsgType.NULL);
}
}
private void mkDirs(){
File parentFolder = new File(saveToLocation + File.separator +
"atmosphere" + File.separator + "kip_patches" + File.separator + "loader_patches");
parentFolder.mkdirs();
}
private void writeFile() throws Exception{
String patchFileLocation = saveToLocation + File.separator +
"atmosphere" + File.separator + "kip_patches" + File.separator + "loader_patches" + File.separator + patchName;
ByteBuffer handyFsPatch = ByteBuffer.allocate(0x100).order(ByteOrder.LITTLE_ENDIAN);
handyFsPatch.put(HEADER);
handyFsPatch.put(getPatch1(offset));
handyFsPatch.put(FOOTER);
byte[] fsPatch = new byte[handyFsPatch.position()];
((Buffer) handyFsPatch).rewind();
handyFsPatch.get(fsPatch);
try (BufferedOutputStream stream = new BufferedOutputStream(
Files.newOutputStream(Paths.get(patchFileLocation)))){
stream.write(fsPatch);
}
logPrinter.print("Patch created at "+patchFileLocation, EMsgType.PASS);
}
private byte[] getPatch1(int offset) throws Exception{
int requiredInstructionOffsetInternal = offset + 6;
int requiredInstructionOffsetReal = requiredInstructionOffsetInternal + 0x100;
final byte[] patch = new byte[]{0x00, 0x01, 0x00};
int instructionPatched = Converter.getLEint(_textSection, offset + 4) & 0xff00ffff;
logPrinter.print("Patch will be applied", EMsgType.PASS);
logPrinter.print(BinToAsmPrinter.printSimplified(instructionPatched, offset+4), EMsgType.NULL);
ByteBuffer prePatch = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN)
.putInt(requiredInstructionOffsetReal)
.put(patch);
return Arrays.copyOfRange(prePatch.array(), 1, 7);
}
}

View file

@ -0,0 +1,125 @@
/*
Copyright 2018-2022 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.patches.loader;
import libKonogonka.Converter;
import libKonogonka.fs.other.System2.ini1.KIP1Provider;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.ModelControllers.Log;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.NSLDataTypes.EMsgType;
import nsusbloader.Utilities.patches.SimplyFind;
import java.io.BufferedInputStream;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class LoaderPatchMaker extends CancellableRunnable {
private final ILogPrinter logPrinter;
private final String atmosphereLocation;
private final String saveTo;
private String package3Location;
private KIP1Provider loaderProvider;
private boolean oneLinerStatus = false;
public LoaderPatchMaker(String atmosphereLocation, String saveTo){
this.logPrinter = Log.getPrinter(EModule.PATCHES);
/*
this.logPrinter = new ILogPrinter() {
public void print(String message, EMsgType type) throws InterruptedException {}
public void updateProgress(Double value) throws InterruptedException {}
public void update(HashMap<String, File> nspMap, EFileStatus status) {}
public void update(File file, EFileStatus status) {}
public void updateOneLinerStatus(boolean status) {}
public void close() {}
};
//*/
this.atmosphereLocation = atmosphereLocation;
this.saveTo = saveTo;
}
@Override
public void run() {
try {
logPrinter.print("..:: Make Loader Patches ::..", EMsgType.INFO);
checkPackage3();
createLoaderKip1Provider();
makePatches();
}
catch (Exception e){
e.printStackTrace();
try{
logPrinter.print(e.getMessage(), EMsgType.FAIL);
} catch (Exception ignore){}
}
finally {
logPrinter.updateOneLinerStatus(oneLinerStatus);
logPrinter.close();
}
}
private void checkPackage3() throws Exception{
logPrinter.print("Looking at Atmosphere", EMsgType.INFO);
if (Files.notExists(Paths.get(atmosphereLocation)))
throw new Exception("Atmosphere directory does not exist at " + atmosphereLocation);
package3Location = atmosphereLocation +File.separator+"package3";
if (Files.exists(Paths.get(package3Location)))
return;
package3Location = atmosphereLocation +File.separator+"fusee-secondary.bin";
if (Files.notExists(Paths.get(package3Location)))
throw new Exception("package3 / fusee-secondary.bin file not found at " + atmosphereLocation);
}
private void createLoaderKip1Provider() throws Exception{
Path package3Path = Paths.get(package3Location);
try (BufferedInputStream stream = new BufferedInputStream(Files.newInputStream(package3Path))) {
byte[] data = new byte[0x400];
if (0x400 != stream.read(data))
throw new Exception("Failed to read first 0x400 bytes of package3 / fusee-secondary file.");
SimplyFind simplyFind = new SimplyFind(".6f61646572", data); // eq. '.oader'
List<Integer> results = simplyFind.getResults();
if (results.size() == 0)
throw new Exception("Failed to find 'Loader' offset at package3 / fusee-secondary file.");
int offset = results.get(0);
int kip1Offset = Converter.getLEint(data, offset - 0x10);
int kip1Size = Converter.getLEint(data, offset - 0xC);
loaderProvider = new KIP1Provider(package3Location, kip1Offset);
if (kip1Size != loaderProvider.getSize())
throw new Exception("Incorrect calculations for KIP1. PK31 value: "+kip1Size+"KIP1Provider value: "+loaderProvider.getSize());
logPrinter.print("Loader KIP1 found", EMsgType.PASS);
}
}
private void makePatches() throws Exception{
new LoaderPatch(loaderProvider, saveTo, logPrinter);
oneLinerStatus = true;
}
}

View file

@ -0,0 +1,178 @@
/*
Copyright 2019-2021 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.splitmerge;
import nsusbloader.NSLDataTypes.EMsgType;
import java.io.*;
import java.util.Arrays;
import java.util.concurrent.Callable;
public class MergeSubTask implements Callable<Boolean> {
private final int id;
private final String saveToPath;
private final MultithreadingPrintAdapter printAdapter;
private final File splitFile;
private File[] chunkFiles;
private long chunksTotalSize;
private File resultFile;
public MergeSubTask(int id, File splitFile, String saveToPath, MultithreadingPrintAdapter printAdapter){
this.id = id;
this.splitFile = splitFile;
this.saveToPath = saveToPath;
this.printAdapter = printAdapter;
}
@Override
public Boolean call(){
try{
collectChunks();
validateChunks();
sortChunks();
calculateChunksSizeSum();
createFile();
mergeChunksToFile();
validateFile();
return true;
}
catch (InterruptedException ie){
cleanup();
return false;
}
catch (Exception e){
e.printStackTrace();
try {
printAdapter.print("["+id+"] "+e.getMessage(), EMsgType.FAIL);
}
catch (InterruptedException ignore) {}
return false;
}
}
private void collectChunks(){
chunkFiles = splitFile.listFiles((file, s) -> s.matches("^[0-9][0-9]$"));
}
private void validateChunks() throws Exception{
if (chunkFiles == null || chunkFiles.length == 0){
throw new Exception("Selected folder doesn't have any chunks. Nothing to do here.");
}
}
private void sortChunks(){
Arrays.sort(chunkFiles);
}
private void calculateChunksSizeSum() throws InterruptedException{
StringBuilder builder = new StringBuilder("["+id+"] Next files will be merged in following order: ");
for (File cnk : chunkFiles){
builder.append(cnk.getName());
builder.append(" ");
chunksTotalSize += cnk.length();
}
printAdapter.print(builder.toString(), EMsgType.INFO);
}
private void createFile() throws Exception{
final String splitFileName = splitFile.getName();
resultFile = new File(saveToPath+File.separator+"!_"+splitFileName);
for (int i = 0; i < 50 ; i++){
if (interrupted())
throw new InterruptedException();
if (resultFile.exists()){
printAdapter.print("["+id+"] Trying to create a good new file...", EMsgType.WARNING);
resultFile = new File(saveToPath+File.separator+"!_"+i+"_"+splitFileName);
continue;
}
printAdapter.print("["+id+"] Save results to: "+resultFile.getAbsolutePath(), EMsgType.INFO);
return;
}
throw new Exception("Can't create new file.");
}
private void mergeChunksToFile() throws Exception{
if ( interrupted())
throw new InterruptedException();
try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(resultFile))){
BufferedInputStream bis;
byte[] chunk;
int readBytesCnt;
printAdapter.reportFileSize(chunksTotalSize);
for (File chunkFile : chunkFiles){
bis = new BufferedInputStream(new FileInputStream(chunkFile));
while (true){
chunk = new byte[4194240];
readBytesCnt = bis.read(chunk);
if (readBytesCnt < 4194240){
if (readBytesCnt > 0)
bos.write(chunk, 0, readBytesCnt);
break;
}
if (interrupted())
throw new InterruptedException();
bos.write(chunk);
printAdapter.updateProgressBySize(readBytesCnt);
}
bis.close();
}
}
}
private void validateFile() throws Exception{
if ( interrupted())
throw new Exception("Merge task interrupted!");
long resultFileSize = resultFile.length();
printAdapter.print("["+id+"] Total chunks size: " + chunksTotalSize
+"\n Merged file size: " + resultFileSize, EMsgType.INFO);
if (chunksTotalSize != resultFileSize)
throw new Exception("Sizes are different! Do NOT use this file for installations!");
printAdapter.print("["+id+"] Sizes are the same! Resulting file should be good!", EMsgType.PASS);
}
private void cleanup(){
boolean isDeleted = resultFile.delete();
try {
printAdapter.print(
"[" + id + "] Merge task interrupted and file "
+ (isDeleted ? "deleted." : "is NOT deleted."), EMsgType.FAIL);
}
catch (InterruptedException ignore) {}
}
private boolean interrupted(){
return Thread.interrupted(); // NOTE: it's not isInterrupted(); And it's handled properly for now.
}
}

View file

@ -1,169 +0,0 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.splitmerge;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.ModelControllers.Log;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.NSLDataTypes.EMsgType;
import java.io.*;
import java.util.Arrays;
public class MergeTask extends CancellableRunnable {
private final ILogPrinter logPrinter;
private final String saveToPath;
private final String filePath;
private File splitFile;
private File[] chunkFiles;
private long chunksTotalSize;
private File resultFile;
public MergeTask(String filePath, String saveToPath) {
this.filePath = filePath;
this.saveToPath = saveToPath;
logPrinter = Log.getPrinter(EModule.SPLIT_MERGE_TOOL);
}
@Override
public void run() {
try {
logPrinter.print("Merge file: " + filePath, EMsgType.INFO);
splitFile = new File(filePath);
collectChunks();
validateChunks();
sortChunks();
calculateChunksSizeSum();
createFile();
mergeChunksToFile();
validateFile();
logPrinter.print(".:: Merge complete ::.", EMsgType.INFO);
logPrinter.updateOneLinerStatus(true);
logPrinter.close();
}
catch (Exception e){
logPrinter.print(e.getMessage(), EMsgType.FAIL);
logPrinter.updateOneLinerStatus(false);
logPrinter.close();
}
}
private void collectChunks(){
chunkFiles = splitFile.listFiles((file, s) -> s.matches("^[0-9][0-9]$"));
}
private void validateChunks() throws Exception{
if (chunkFiles == null || chunkFiles.length == 0){
throw new Exception("Selected folder doesn't have any chunks. Nothing to do here.");
}
}
private void sortChunks(){
Arrays.sort(chunkFiles);
}
private void calculateChunksSizeSum(){
logPrinter.print("Next files will be merged in following order: ", EMsgType.INFO);
for (File cnk : chunkFiles){
logPrinter.print(" "+cnk.getName(), EMsgType.INFO);
chunksTotalSize += cnk.length();
}
}
private void createFile() throws Exception{
final String splitFileName = splitFile.getName();
resultFile = new File(saveToPath+File.separator+"!_"+splitFileName);
for (int i = 0; i < 50 ; i++){
if (isCancelled()){
throw new InterruptedException("Split task interrupted!");
}
if (resultFile.exists()){
logPrinter.print("Trying to create a good new file...", EMsgType.WARNING);
resultFile = new File(saveToPath+File.separator+"!_"+i+"_"+splitFileName);
continue;
}
logPrinter.print("Save results to: "+resultFile.getAbsolutePath(), EMsgType.INFO);
return;
}
throw new Exception("Can't create new file.");
}
private void mergeChunksToFile() throws Exception{
double chunkPercent = (4194240.0 / (chunksTotalSize / 100.0) / 100.0);
long totalSizeCnt = 0;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(resultFile));
BufferedInputStream bis;
byte[] chunk;
int readBytesCnt;
for (File chunkFile : chunkFiles){
bis = new BufferedInputStream(new FileInputStream(chunkFile));
while (true){
if (isCancelled()){
bos.close();
bis.close();
boolean isDeleted = resultFile.delete();
throw new InterruptedException("Merge task interrupted and file "
+ (isDeleted ? "deleted." : "is not deleted."));
}
chunk = new byte[4194240];
readBytesCnt = bis.read(chunk);
logPrinter.updateProgress(chunkPercent * totalSizeCnt);
totalSizeCnt++;
if (readBytesCnt < 4194240){
if (readBytesCnt > 0)
bos.write(chunk, 0, readBytesCnt);
break;
}
bos.write(chunk);
}
bis.close();
}
bos.close();
}
private void validateFile() throws Exception{
long resultFileSize = resultFile.length();
logPrinter.print("Total chunks size: " + chunksTotalSize, EMsgType.INFO);
logPrinter.print("Merged file size: " + resultFileSize, EMsgType.INFO);
if (chunksTotalSize != resultFileSize)
throw new Exception("Sizes are different! Do NOT use this file for installations!");
logPrinter.print("Sizes are the same! Resulting file should be good!", EMsgType.PASS);
}
}

View file

@ -0,0 +1,44 @@
/*
Copyright 2019-2021 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.splitmerge;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.NSLDataTypes.EMsgType;
public class MultithreadingPrintAdapter {
private final ILogPrinter printer;
private long totalFilesSize;
private long bytesComplete;
public MultithreadingPrintAdapter(ILogPrinter printer){
this.printer = printer;
}
public void print(String message, EMsgType type) throws InterruptedException{
printer.print(message, type);
}
public void reportFileSize(long fileSize){
totalFilesSize += fileSize;
}
public void updateProgressBySize(long chunkSize) throws InterruptedException{
bytesComplete += chunkSize;
printer.updateProgress((double) bytesComplete / (double) totalFilesSize);
}
}

View file

@ -0,0 +1,147 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.splitmerge;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.ModelControllers.Log;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.NSLDataTypes.EMsgType;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/*
* TODO: Kill this on application exit (?)
*/
public class SplitMergeTaskExecutor implements Runnable {
private final boolean isSplit;
private final List<File> files;
private final String saveToPath;
private final ILogPrinter logPrinter;
private final ExecutorService executorService;
private final MultithreadingPrintAdapter printAdapter;
public SplitMergeTaskExecutor(boolean isSplit, List<File> files, String saveToPath){
this.isSplit = isSplit;
this.files = files;
this.saveToPath = saveToPath;
this.logPrinter = Log.getPrinter(EModule.SPLIT_MERGE_TOOL);
this.executorService = Executors.newFixedThreadPool(
files.size(),
runnable -> {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
});
this.printAdapter = new MultithreadingPrintAdapter(logPrinter);
}
public void run(){
try {
List<Future<Boolean>> futuresResults = executorService.invokeAll(getSubTasksCollection());
boolean onelinerResult = true;
for (Future<Boolean> future : futuresResults){
onelinerResult &= future.get();
}
executorService.shutdown();
logPrinter.updateOneLinerStatus(onelinerResult);
}
catch (InterruptedException ie){
//ie.printStackTrace();
executorService.shutdownNow();
boolean interruptedSuccessfully = false;
try {
interruptedSuccessfully = executorService.awaitTermination(20, TimeUnit.SECONDS);
}
catch (InterruptedException awaitInterrupt){
print("Force interrupting task...", EMsgType.WARNING);
}
logPrinter.updateOneLinerStatus(false);
print((
isSplit?
"Split tasks interrupted ":
"Merge tasks interrupted ")+
(interruptedSuccessfully?
"successfully":
"with some issues"), EMsgType.WARNING);
}
catch (Exception e){
logPrinter.updateOneLinerStatus(false);
print(
isSplit?
"Split task failed: ":
"Merge task failed: "+e.getMessage(), EMsgType.FAIL);
e.printStackTrace();
}
print(
isSplit?
".:: Split complete ::.":
".:: Merge complete ::.", EMsgType.INFO);
logPrinter.close();
}
private List<Callable<Boolean>> getSubTasksCollection() throws InterruptedException{
List<Callable<Boolean>> subTasks = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
// TODO: Optimize?
if (isSplit){
stringBuilder.append("Split files:\n");
for (int i = 0; i < files.size(); i++){
File file = files.get(i);
stringBuilder.append("[");
stringBuilder.append(i);
stringBuilder.append("] ");
stringBuilder.append(file.getName());
stringBuilder.append("\n");
Callable<Boolean> task = new SplitSubTask(i, file, saveToPath, printAdapter);
subTasks.add(task);
}
}
else {
stringBuilder.append("Merge files:\n");
for (int i = 0; i < files.size(); i++){
File file = files.get(i);
stringBuilder.append("[");
stringBuilder.append(i);
stringBuilder.append("] ");
stringBuilder.append(file.getName());
stringBuilder.append("\n");
Callable<Boolean> task = new MergeSubTask(i, file, saveToPath, printAdapter);
subTasks.add(task);
}
}
logPrinter.print(stringBuilder.toString(), EMsgType.INFO);
return subTasks;
}
private void print(String message, EMsgType type){
try {
logPrinter.print(message, type);
}
catch (InterruptedException ie){
ie.printStackTrace();
}
}
}

View file

@ -0,0 +1,186 @@
/*
Copyright 2019-2021 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.splitmerge;
import nsusbloader.NSLDataTypes.EMsgType;
import java.io.*;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
public class SplitSubTask implements Callable<Boolean> {
private final int id;
private final String saveToPath;
private final File file;
private File splitFile;
private long originalFileLen;
private final MultithreadingPrintAdapter printAdapter;
SplitSubTask(int id, File file, String saveToPath, MultithreadingPrintAdapter printAdapter){
this.id = id;
this.file = file;
this.saveToPath = saveToPath;
this.printAdapter = printAdapter;
}
@Override
public Boolean call(){
try {
createSplitFile();
splitFileToChunks();
validateSplitFile();
return true;
}
catch (InterruptedException | ExecutionException ie){
ie.printStackTrace();
cleanup();
return false;
}
catch (Exception e){
e.printStackTrace();
try {
printAdapter.print("["+id+"] "+e.getMessage(), EMsgType.FAIL);
}
catch (InterruptedException ignore) {}
return false;
}
}
private void createSplitFile() throws Exception{
if ( interrupted())
throw new Exception("Split task interrupted!");
splitFile = new File(saveToPath+File.separator+"!_"+file.getName());
for (int i = 0; i < 50; i++){
if (splitFile.mkdirs()){
printAdapter.print("["+id+"] Save results to: "+splitFile.getAbsolutePath(), EMsgType.INFO);
return;
}
if (splitFile.exists()){
printAdapter.print("["+id+"] Trying to create a good new folder...", EMsgType.WARNING);
splitFile = new File(saveToPath+File.separator+"!_"+i+"_"+file.getName());
continue;
}
throw new Exception("Folder " + splitFile.getAbsolutePath()
+ " could not be created. Not enough rights or something like that?");
}
throw new Exception("Can't create new file.");
}
private void splitFileToChunks() throws Exception{
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){
long counter;
originalFileLen = file.length();
printAdapter.reportFileSize(originalFileLen);
byte[] chunk;
int readBytesCnt;
main_loop:
for (int i = 0; ; i++){
String pathname = splitFile.getAbsolutePath()+File.separator+String.format("%02d", i);
BufferedOutputStream fragmentBos = new BufferedOutputStream(new FileOutputStream(pathname));
counter = 0;
while (counter < 1024){ // 0xffff0000 total
chunk = new byte[4194240];
if ((readBytesCnt = bis.read(chunk)) < 4194240){
if (readBytesCnt > 0)
fragmentBos.write(chunk, 0, readBytesCnt);
fragmentBos.close();
printAdapter.updateProgressBySize(readBytesCnt);
break main_loop;
}
if (interrupted())
throw new InterruptedException();
fragmentBos.write(chunk);
counter++;
printAdapter.updateProgressBySize(readBytesCnt);
}
fragmentBos.close();
}
}
}
private void validateSplitFile() throws Exception{
if (interrupted())
throw new Exception("Split task interrupted!");
printAdapter.print("["+id+"] Original file: "+splitFile.getAbsolutePath()+" (size: "+originalFileLen+")", EMsgType.INFO);
long totalChunksSize = 0;
File[] chunkFileArr = splitFile.listFiles();
if (chunkFileArr == null)
throw new Exception("Unable to check results. It means that something went wrong.");
Arrays.sort(chunkFileArr);
StringBuilder stringBuilder = new StringBuilder("["+id+"] Chunks");
for (File chunkFile : chunkFileArr) {
stringBuilder.append("\n");
stringBuilder.append(" ");
stringBuilder.append(chunkFile.getName());
stringBuilder.append(" size: ");
stringBuilder.append(chunkFile.length());
totalChunksSize += chunkFile.length();
}
stringBuilder.append("\n");
stringBuilder.append("Total chunks size: ");
stringBuilder.append(totalChunksSize);
printAdapter.print(stringBuilder.toString(), EMsgType.INFO);
if (originalFileLen != totalChunksSize)
throw new Exception("Sizes are different! Do NOT use this file for installations!");
printAdapter.print("["+id+"] Sizes are the same! Split file should be good!", EMsgType.PASS);
}
private void cleanup(){
boolean isDeleted = splitFile.delete();
File[] chunksToDelete = splitFile.listFiles();
if (! isDeleted && chunksToDelete != null){
isDeleted = true;
for (File chunkFile : chunksToDelete)
isDeleted &= chunkFile.delete();
isDeleted &= splitFile.delete();
}
try {
printAdapter.print(
"["+id+"] Split task interrupted and folder "
+ (isDeleted?"deleted.":"is NOT deleted.")
, EMsgType.FAIL);
}
catch (InterruptedException ignore) {}
}
private boolean interrupted(){
return Thread.interrupted(); // NOTE: it's not isInterrupted(); And it's handled properly for now.
}
}

View file

@ -1,173 +0,0 @@
/*
Copyright 2019-2020 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.Utilities.splitmerge;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.ModelControllers.ILogPrinter;
import nsusbloader.ModelControllers.Log;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.NSLDataTypes.EMsgType;
import java.io.*;
import java.util.Arrays;
public class SplitTask extends CancellableRunnable {
private final ILogPrinter logPrinter;
private final String saveToPath;
private final String filePath;
private File file;
private File splitFile;
private long originalFileLen;
public SplitTask(String filePath, String saveToPath){
this.filePath = filePath;
this.saveToPath = saveToPath;
this.logPrinter = Log.getPrinter(EModule.SPLIT_MERGE_TOOL);
}
@Override
public void run() {
try {
logPrinter.print("Split file: "+filePath, EMsgType.INFO);
this.file = new File(filePath);
createSplitFile();
splitFileToChunks();
validateSplitFile();
logPrinter.print(".:: Split complete ::.", EMsgType.INFO);
logPrinter.updateOneLinerStatus(true);
logPrinter.close();
}
catch (Exception e){
logPrinter.print(e.getMessage(), EMsgType.FAIL);
logPrinter.updateOneLinerStatus(false);
logPrinter.close();
}
}
private void createSplitFile() throws Exception{
splitFile = new File(saveToPath+File.separator+"!_"+file.getName());
for (int i = 0; i < 50 ; i++){
if (isCancelled()){
throw new InterruptedException("Split task interrupted!");
}
if (splitFile.mkdir()){
logPrinter.print("Save results to: "+splitFile.getAbsolutePath(), EMsgType.INFO);
return;
}
if (splitFile.exists()){
logPrinter.print("Trying to create a good new folder...", EMsgType.WARNING);
splitFile = new File(saveToPath+File.separator+"!_"+i+"_"+file.getName());
continue;
}
throw new Exception("Folder " + splitFile.getAbsolutePath()
+ " could not be created. Not enough rights or something like that?");
}
throw new Exception("Can't create new file.");
}
private void splitFileToChunks() throws Exception{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
long counter;
originalFileLen = file.length();
double chunkPercent = (4194240.0 / (originalFileLen / 100.0) / 100.0);
long totalSizeCnt = 0;
byte[] chunk;
int readBytesCnt;
main_loop:
for (int i = 0; ; i++){
String pathname = splitFile.getAbsolutePath()+File.separator+String.format("%02d", i);
BufferedOutputStream fragmentBos = new BufferedOutputStream(new FileOutputStream(new File(pathname)));
counter = 0;
while (counter < 1024){ // 0xffff0000 total
if (isCancelled()){
fragmentBos.close();
bis.close();
boolean isDeleted = splitFile.delete();
File[] chunksToDelete = splitFile.listFiles();
if (! isDeleted && chunksToDelete != null){
isDeleted = true;
for (File chunkFile : chunksToDelete)
isDeleted &= chunkFile.delete();
isDeleted &= splitFile.delete();
}
throw new InterruptedException("Split task interrupted and folder "
+ (isDeleted?"deleted.":"is not deleted."));
}
chunk = new byte[4194240];
if ((readBytesCnt = bis.read(chunk)) < 4194240){
if (readBytesCnt > 0)
fragmentBos.write(chunk, 0, readBytesCnt);
fragmentBos.close();
logPrinter.updateProgress(1.0);
break main_loop;
}
fragmentBos.write(chunk);
logPrinter.updateProgress(chunkPercent * totalSizeCnt);
counter++; // NOTE: here we have some redundancy of variables. It has to be fixed one day.
totalSizeCnt++;
}
fragmentBos.close();
}
bis.close();
}
private void validateSplitFile() throws Exception{
logPrinter.print("Original file size: "+originalFileLen, EMsgType.INFO);
long totalChunksSize = 0;
File[] chunkFileArr = splitFile.listFiles();
if (chunkFileArr == null)
throw new Exception("Unable to check results. It means that something went wrong.");
Arrays.sort(chunkFileArr);
for (File chunkFile : chunkFileArr) {
logPrinter.print("Chunk " + chunkFile.getName() + " size: " + chunkFile.length(), EMsgType.INFO);
totalChunksSize += chunkFile.length();
}
logPrinter.print("Total chunks size: " + totalChunksSize, EMsgType.INFO);
if (originalFileLen != totalChunksSize)
throw new Exception("Sizes are different! Do NOT use this file for installations!");
logPrinter.print("Sizes are the same! Split file should be good!", EMsgType.PASS);
}
}

View file

@ -32,7 +32,6 @@ public class CommandLineInterface {
}
final Options cliOptions = createCliOptions();
CommandLineParser cliParser = new DefaultParser();
try{
CommandLine cli = cliParser.parse(cliOptions, args);
@ -68,6 +67,11 @@ public class CommandLineInterface {
new GoldLeafCli(arguments);
return;
}
if (cli.hasOption("experimental")){
final String[] arguments = cli.getOptionValues("experimental");
new ExperimentalCli(arguments);
return;
}
/*
if (cli.hasOption("x") || cli.hasOption("nxdt")){
final String[] arguments = cli.getOptionValues("nxdt");
@ -136,14 +140,14 @@ public class CommandLineInterface {
/* Tinfoil network mode options */
final Option tinfoilNetOption = Option.builder("n")
.longOpt("tfn")
.desc("Install via Tinfoil/Awoo Network mode. Check '-n help' for information.")
.desc("Install via Awoo Network mode. Check '-n help' for information.")
.hasArgs()
.argName("...")
.build();
/* Tinfoil/Awoo USB */
final Option tinfoilOption = Option.builder("t")
.longOpt("tinfoil")
.desc("Install via Tinfoil/Awoo USB mode.")
.desc("Install via Awoo USB mode.")
.hasArgs()
.argName("FILE...")
.build();
@ -154,6 +158,12 @@ public class CommandLineInterface {
.hasArgs()
.argName("...")
.build();
final Option experimentalOption = Option.builder()
.longOpt("experimental")
.desc("Enable testing and experimental functions")
.hasArgs()
.argName("y|n")
.build();
/* nxdumptool */
/*
final Option nxdtOption = Option.builder("x")
@ -184,6 +194,7 @@ public class CommandLineInterface {
group.addOption(helpOption);
group.addOption(tinfoilOption);
group.addOption(glOption);
group.addOption(experimentalOption);
//group.addOption(nxdtOption);
group.addOption(splitOption);
group.addOption(mergeOption);

View file

@ -0,0 +1,46 @@
/*
Copyright 2019-2023 Dmitry Isaenko
This file is part of NS-USBloader.
NS-USBloader 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.
NS-USBloader 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 NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.cli;
import nsusbloader.AppPreferences;
public class ExperimentalCli {
ExperimentalCli(String[] arguments) throws IncorrectSetupException{
if (arguments == null || arguments.length == 0)
throw new IncorrectSetupException("No arguments.\nShould be 'y' or 'n'");
if (arguments.length > 1)
throw new IncorrectSetupException("Too many arguments.\nShould be 'y' or 'n' only");
String arg = arguments[0].toLowerCase().substring(0, 1);
if (arg.equals("y")) {
AppPreferences.getInstance().setPatchesTabInvisible(false);
System.out.println("Experimental functions enabled");
return;
}
if (arg.equals("n")) {
AppPreferences.getInstance().setPatchesTabInvisible(true);
System.out.println("Experimental functions disabled");
return;
}
throw new IncorrectSetupException("Incorrect arguments.\nCould be 'y' or 'n' only");
}
}

View file

@ -19,8 +19,7 @@
package nsusbloader.cli;
import nsusbloader.AppPreferences;
import nsusbloader.COM.USB.UsbCommunications;
import nsusbloader.Controllers.SettingsController;
import nsusbloader.com.usb.UsbCommunications;
import java.io.File;
import java.util.ArrayList;
@ -35,7 +34,7 @@ public class GoldLeafCli {
private int parseFileSince = 1;
public GoldLeafCli(String[] arguments) throws InterruptedException, IncorrectSetupException{
GoldLeafCli(String[] arguments) throws InterruptedException, IncorrectSetupException{
this.arguments = arguments;
checkArguments();
@ -44,7 +43,7 @@ public class GoldLeafCli {
runGoldLeafBackend();
}
public void checkArguments() throws IncorrectSetupException{
private void checkArguments() throws IncorrectSetupException{
if (arguments == null || arguments.length == 0) {
throw new IncorrectSetupException("No arguments.\n" +
"Try 'ns-usbloader -g help' for more information.");
@ -76,7 +75,7 @@ public class GoldLeafCli {
private String getGlSupportedVersions(){
StringBuilder builder = new StringBuilder("Supported versions: \n");
for (String a : AppPreferences.goldleafSupportedVersions){
for (String a : AppPreferences.GOLDLEAF_SUPPORTED_VERSIONS){
builder.append("\t");
builder.append(a);
builder.append("\n");
@ -84,7 +83,7 @@ public class GoldLeafCli {
return builder.toString();
}
public void parseGoldLeafVersion() throws IncorrectSetupException{
private void parseGoldLeafVersion() throws IncorrectSetupException{
String argument1 = arguments[0];
if (! argument1.startsWith("ver=")) {
@ -99,7 +98,7 @@ public class GoldLeafCli {
"Try 'ns-usbloader -g help' for more information.");
}
for (String version : AppPreferences.goldleafSupportedVersions){
for (String version : AppPreferences.GOLDLEAF_SUPPORTED_VERSIONS){
if (version.equals(goldLeafVersion))
return;
}
@ -108,7 +107,7 @@ public class GoldLeafCli {
getGlSupportedVersions());
}
public void parseFilesArguments() throws IncorrectSetupException{
private void parseFilesArguments() throws IncorrectSetupException{
filesList = new ArrayList<>();
File file;
@ -124,7 +123,7 @@ public class GoldLeafCli {
}
}
public void runGoldLeafBackend() throws InterruptedException {
private void runGoldLeafBackend() throws InterruptedException {
Runnable task = new UsbCommunications(filesList,
"GoldLeaf"+goldLeafVersion,
filterForNsp);

View file

@ -18,8 +18,7 @@
*/
package nsusbloader.cli;
import nsusbloader.Utilities.splitmerge.MergeTask;
import nsusbloader.Utilities.splitmerge.SplitTask;
import nsusbloader.Utilities.splitmerge.SplitMergeTaskExecutor;
import java.io.File;
import java.util.ArrayList;
@ -27,7 +26,7 @@ import java.util.List;
public class MergeCli {
private String[] arguments;
private final String[] arguments;
private String saveTo;
private String[] splitFiles;
@ -97,12 +96,20 @@ public class MergeCli {
}
private void runBackend() throws InterruptedException{
for (String filePath : splitFiles){
Runnable mergeTask = new MergeTask(filePath, saveTo);
Runnable mergeTask = new SplitMergeTaskExecutor(
false,
getFilesFromStrings(),
saveTo);
Thread thread = new Thread(mergeTask);
thread.setDaemon(true);
thread.start();
thread.join();
}
private List<File> getFilesFromStrings(){
ArrayList<File> realFiles = new ArrayList<>();
for (String splitFileString : splitFiles){
realFiles.add(new File(splitFileString));
}
return realFiles;
}
}

View file

@ -27,7 +27,7 @@ public class NxdtCli {
private final String[] arguments;
private String saveTo;
public NxdtCli(String[] arguments) throws InterruptedException, IncorrectSetupException{
NxdtCli(String[] arguments) throws InterruptedException, IncorrectSetupException{
this.arguments = arguments;
parseArgument();
runBackend();

View file

@ -18,16 +18,14 @@
*/
package nsusbloader.cli;
import nsusbloader.Utilities.splitmerge.SplitTask;
import nsusbloader.Utilities.splitmerge.SplitMergeTaskExecutor;
import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
public class SplitCli {
private String[] arguments;
private final String[] arguments;
private String saveTo;
private String[] files;
@ -95,12 +93,20 @@ public class SplitCli {
}
private void runBackend() throws InterruptedException{
for (String filePath : files){
Runnable splitTaks = new SplitTask(filePath, saveTo);
Thread thread = new Thread(splitTaks);
Runnable splitTasks = new SplitMergeTaskExecutor(
true,
getFilesFromStrings(),
saveTo);
Thread thread = new Thread(splitTasks);
thread.setDaemon(true);
thread.start();
thread.join();
}
private List<File> getFilesFromStrings(){
ArrayList<File> realFiles = new ArrayList<>();
for (String fileString : files){
realFiles.add(new File(fileString));
}
return realFiles;
}
}

View file

@ -18,7 +18,7 @@
*/
package nsusbloader.cli;
import nsusbloader.COM.NET.NETCommunications;
import nsusbloader.com.net.NETCommunications;
import java.io.File;
import java.util.ArrayList;

View file

@ -18,7 +18,7 @@
*/
package nsusbloader.cli;
import nsusbloader.COM.USB.UsbCommunications;
import nsusbloader.com.usb.UsbCommunications;
import java.io.File;
import java.util.ArrayList;
@ -29,7 +29,7 @@ public class TinfoilUsbCli {
private final String[] arguments;
private List<File> filesList;
public TinfoilUsbCli(String[] arguments) throws InterruptedException, IncorrectSetupException{
TinfoilUsbCli(String[] arguments) throws InterruptedException, IncorrectSetupException{
this.arguments = arguments;
checkArguments();
parseFilesArguments();

View file

@ -16,7 +16,7 @@
You should have received a copy of the GNU General Public License
along with NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.COM.Helpers;
package nsusbloader.com.helpers;
import java.io.*;

View file

@ -16,7 +16,7 @@
You should have received a copy of the GNU General Public License
along with NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.COM.NET;
package nsusbloader.com.net;
import nsusbloader.ModelControllers.CancellableRunnable;
import nsusbloader.ModelControllers.ILogPrinter;
@ -24,7 +24,7 @@ import nsusbloader.NSLDataTypes.EFileStatus;
import nsusbloader.ModelControllers.Log;
import nsusbloader.NSLDataTypes.EModule;
import nsusbloader.NSLDataTypes.EMsgType;
import nsusbloader.COM.Helpers.NSSplitReader;
import nsusbloader.com.helpers.NSSplitReader;
import java.io.*;
import java.net.*;
@ -52,6 +52,8 @@ public class NETCommunications extends CancellableRunnable {
private OutputStream currSockOS;
private PrintWriter currSockPW;
private boolean jobInProgress = true;
/**
* Simple constructor that everybody uses
* */
@ -88,7 +90,7 @@ public class NETCommunications extends CancellableRunnable {
if (! isValid || isCancelled() )
return;
logPrinter.print("\tStart chain", EMsgType.INFO);
print("\tStart chain", EMsgType.INFO);
final String handshakeContent = buildHandshakeContent();
@ -100,11 +102,11 @@ public class NETCommunications extends CancellableRunnable {
// Check if we should serve requests
if (this.doNotServe){
logPrinter.print("List of files transferred. Replies won't be served.", EMsgType.PASS);
print("List of files transferred. Replies won't be served.", EMsgType.PASS);
close(EFileStatus.UNKNOWN);
return;
}
logPrinter.print("Initiation files list has been sent to NS.", EMsgType.PASS);
print("Initiation files list has been sent to NS.", EMsgType.PASS);
// Go transfer
serveRequestsLoop();
@ -140,7 +142,7 @@ public class NETCommunications extends CancellableRunnable {
handshakeSocket.close();
}
catch (IOException uhe){
logPrinter.print("Unable to connect to NS and send files list:\n "
print("Unable to connect to NS and send files list:\n "
+ uhe.getMessage(), EMsgType.FAIL);
close(EFileStatus.UNKNOWN);
return true;
@ -149,7 +151,7 @@ public class NETCommunications extends CancellableRunnable {
}
private void serveRequestsLoop(){
try {
while (true){
while (jobInProgress){
clientSocket = serverSocket.accept();
BufferedReader br = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream())
@ -160,9 +162,7 @@ public class NETCommunications extends CancellableRunnable {
String line;
LinkedList<String> tcpPacket = new LinkedList<>();
while ((line = br.readLine()) != null) {
//System.out.println(line); // Debug
if (line.trim().isEmpty()) { // If TCP packet is ended
handleRequest(tcpPacket); // Proceed required things
tcpPacket.clear(); // Clear data and wait for next TCP packet
@ -170,30 +170,36 @@ public class NETCommunications extends CancellableRunnable {
else
tcpPacket.add(line); // Otherwise collect data
}
//System.out.println("<Socket Closed>");
// and reopen client sock
clientSocket.close();
}
}
catch (Exception e){
if (isCancelled())
logPrinter.print("Interrupted by user.", EMsgType.INFO);
print("Interrupted by user.", EMsgType.INFO);
else
logPrinter.print(e.getMessage(), EMsgType.INFO);
print(e.getMessage(), EMsgType.INFO);
close(EFileStatus.UNKNOWN);
return;
}
print("All transfers complete", EMsgType.PASS);
close(EFileStatus.UPLOADED);
}
/**
* Handle requests
* @return true if failed
* */
private void handleRequest(LinkedList<String> packet) throws Exception{
if (packet.get(0).startsWith("DROP")){
jobInProgress = false;
return;
}
File requestedFile;
String reqFileName = packet.get(0).replaceAll("(^[A-z\\s]+/)|(\\s+?.*$)", "");
if (! files.containsKey(reqFileName)){
writeToSocket(NETPacket.getCode404());
logPrinter.print("File "+reqFileName+" doesn't exists or have 0 size. Returning 404", EMsgType.FAIL);
print("File "+reqFileName+" doesn't exists or have 0 size. Returning 404", EMsgType.FAIL);
return;
}
@ -202,25 +208,24 @@ public class NETCommunications extends CancellableRunnable {
if (! requestedFile.exists() || reqFileSize == 0){ // well.. tell 404 if file exists with 0 length is against standard, but saves time
writeToSocket(NETPacket.getCode404());
logPrinter.print("File "+requestedFile.getName()+" doesn't exists or have 0 size. Returning 404", EMsgType.FAIL);
print("File "+requestedFile.getName()+" doesn't exists or have 0 size. Returning 404", EMsgType.FAIL);
logPrinter.update(requestedFile, EFileStatus.FAILED);
return;
}
if (packet.get(0).startsWith("HEAD")){
writeToSocket(NETPacket.getCode200(reqFileSize));
logPrinter.print("Replying for requested file: "+requestedFile.getName(), EMsgType.INFO);
print("Replying for requested file: "+requestedFile.getName(), EMsgType.INFO);
return;
}
if (packet.get(0).startsWith("GET")) {
for (String line: packet) {
if (! line.toLowerCase().startsWith("range")) //todo: fix
continue;
if (line.toLowerCase().startsWith("range")){
parseGETrange(requestedFile, reqFileName, reqFileSize, line);
return;
}
}
}
}
private void parseGETrange(File file, String fileName, long fileSize, String rangeDirective) throws Exception{
try {
@ -232,7 +237,7 @@ public class NETCommunications extends CancellableRunnable {
if (fromRange > toRange){ // If start bytes greater then end bytes
writeToSocket(NETPacket.getCode400());
logPrinter.print("Requested range for "
print("Requested range for "
+ file.getName()
+ " is incorrect. Returning 400", EMsgType.FAIL);
logPrinter.update(file, EFileStatus.FAILED);
@ -249,7 +254,7 @@ public class NETCommunications extends CancellableRunnable {
if (rangeStr[1].isEmpty()) { // If Range not defined: like "Range: bytes=-"
writeToSocket(NETPacket.getCode400());
logPrinter.print("Requested range for "
print("Requested range for "
+ file.getName()
+ " is incorrect (empty start & end). Returning 400", EMsgType.FAIL);
logPrinter.update(file, EFileStatus.FAILED);
@ -262,7 +267,7 @@ public class NETCommunications extends CancellableRunnable {
}
// If file smaller than 500 bytes
writeToSocket(NETPacket.getCode416());
logPrinter.print("File size requested for "
print("File size requested for "
+ file.getName()
+ " while actual size of it: "
+ fileSize+". Returning 416", EMsgType.FAIL);
@ -270,7 +275,7 @@ public class NETCommunications extends CancellableRunnable {
}
catch (NumberFormatException nfe){
writeToSocket(NETPacket.getCode400());
logPrinter.print("Requested range for "
print("Requested range for "
+ file.getName()
+ " has incorrect format. Returning 400\n\t"
+ nfe.getMessage(), EMsgType.FAIL);
@ -288,7 +293,7 @@ public class NETCommunications extends CancellableRunnable {
private void writeToSocket(String fileName, long start, long end) throws Exception{
File file = files.get(fileName).getFile();
logPrinter.print("Reply to range: "+start+"-"+end, EMsgType.INFO);
print("Reply to range: "+start+"-"+end, EMsgType.INFO);
writeToSocket(NETPacket.getCode206(files.get(fileName).getSize(), start, end));
try{
@ -374,11 +379,11 @@ public class NETCommunications extends CancellableRunnable {
try {
if (serverSocket != null && ! serverSocket.isClosed()) {
serverSocket.close();
logPrinter.print("Closing server socket.", EMsgType.PASS);
print("Closing server socket.", EMsgType.PASS);
}
}
catch (IOException ioe){
logPrinter.print("Closing server socket failed. Sometimes it's not an issue.", EMsgType.WARNING);
print("Closing server socket failed. Sometimes it's not an issue.", EMsgType.WARNING);
}
HashMap<String, File> tempMap = new HashMap<>();
@ -387,7 +392,15 @@ public class NETCommunications extends CancellableRunnable {
logPrinter.update(tempMap, status);
logPrinter.print("\tEnd chain", EMsgType.INFO);
print("\tEnd chain", EMsgType.INFO);
logPrinter.close();
}
private void print(String message, EMsgType type){
try {
logPrinter.print(message, type);
}
catch (InterruptedException ie){
ie.printStackTrace();
}
}
}

View file

@ -16,7 +16,7 @@
You should have received a copy of the GNU General Public License
along with NS-USBloader. If not, see <https://www.gnu.org/licenses/>.
*/
package nsusbloader.COM.NET;
package nsusbloader.com.net;
import nsusbloader.NSLMain;

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