diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..2ea37b6 --- /dev/null +++ b/.drone.yml @@ -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 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..92b14c1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +offsets.txt +environment.txt \ No newline at end of file diff --git a/.make_legacy b/.make_legacy new file mode 100644 index 0000000..890cd0c --- /dev/null +++ b/.make_legacy @@ -0,0 +1,3 @@ +sed -z -i -e 's/org.usb4java<\/groupId>\n\s*usb4java<\/artifactId>\s*1.3.0<\/version>/org.usb4java<\/groupId>\nusb4java<\/artifactId>\n1.2.0<\/version>/g' pom.xml +sed -z -i -e 's/${project.artifactId}-${project.version}-${maven.build.timestamp}<\/finalName>/${project.artifactId}-${project.version}-legacy-${maven.build.timestamp}<\/finalName>/g' pom.xml +sed -z -i -e 's/target\/${project.artifactId}-${project.version}-${maven.build.timestamp}.jar<\/jar>/target\/${project.artifactId}-${project.version}-legacy-${maven.build.timestamp}.jar<\/jar>/g' pom.xml diff --git a/.make_m1 b/.make_m1 new file mode 100644 index 0000000..5ac4f07 --- /dev/null +++ b/.make_m1 @@ -0,0 +1,5 @@ +sed -z -i -e 's/org.usb4java<\/groupId>\nusb4java<\/artifactId>\n1.2.0<\/version>/org.usb4java<\/groupId>\nusb4java<\/artifactId>\n1.3.0<\/version>/g' pom.xml +sed -z -i -e 's/mac<\/classifier>/mac-aarch64<\/classifier>/g' pom.xml +sed -z -i -e 's/${project.artifactId}-${project.version}-legacy-${maven.build.timestamp}<\/finalName>/${project.artifactId}-${project.version}-m1-${maven.build.timestamp}<\/finalName>/g' pom.xml +sed -i -e '/com.akathist.maven.plugins.launch4j/,/<\/executions>/d' pom.xml +sed -z -i -e 's/\n\s*<\/plugin>//g' pom.xml \ No newline at end of file diff --git a/.woodpecker/woodpecker.yml b/.woodpecker/woodpecker.yml new file mode 100644 index 0000000..11eea07 --- /dev/null +++ b/.woodpecker/woodpecker.yml @@ -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 \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile deleted file mode 100644 index e85efc8..0000000 --- a/Jenkinsfile +++ /dev/null @@ -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 - } - } -} \ No newline at end of file diff --git a/README.md b/README.md index 5c27cac..8c6161e 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,30 @@ -# NS-USBloader +

NS-USBloader

-![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) -screenshot screenshot -screenshot screenshot +Sometimes I add new posts about this project [on my blog page](https://developersu.blogspot.com/search/label/NS-USBloader). + +screenshot screenshot +screenshot screenshot +screenshot #### 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 Install via Tinfoil/Awoo USB mode. + -t,--tinfoil 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. -Donate using Liberapay - -PayPal Logo - -[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. diff --git a/misc/freedesktop_entry/ns-usbloader.desktop b/misc/freedesktop_entry/ns-usbloader.desktop new file mode 100755 index 0000000..d402210 --- /dev/null +++ b/misc/freedesktop_entry/ns-usbloader.desktop @@ -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; diff --git a/misc/freedesktop_entry/ns-usbloader.svg b/misc/freedesktop_entry/ns-usbloader.svg new file mode 100644 index 0000000..75a45a7 --- /dev/null +++ b/misc/freedesktop_entry/ns-usbloader.svg @@ -0,0 +1,118 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + diff --git a/misc/windows/HOWTO_JRE.md b/misc/windows/HOWTO_JRE.md new file mode 100644 index 0000000..5916b6e --- /dev/null +++ b/misc/windows/HOWTO_JRE.md @@ -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' \ No newline at end of file diff --git a/misc/windows/NSIS/installer.nsi b/misc/windows/NSIS/installer.nsi new file mode 100644 index 0000000..67c1073 --- /dev/null +++ b/misc/windows/NSIS/installer.nsi @@ -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 diff --git a/misc/windows/NSIS/installer_logo.ico b/misc/windows/NSIS/installer_logo.ico new file mode 100644 index 0000000..b64874c Binary files /dev/null and b/misc/windows/NSIS/installer_logo.ico differ diff --git a/misc/windows/NSIS/leftbar.bmp b/misc/windows/NSIS/leftbar.bmp new file mode 100644 index 0000000..6e5fe08 Binary files /dev/null and b/misc/windows/NSIS/leftbar.bmp differ diff --git a/misc/windows/NSIS/leftbar_uninstall.bmp b/misc/windows/NSIS/leftbar_uninstall.bmp new file mode 100644 index 0000000..5ac42bf Binary files /dev/null and b/misc/windows/NSIS/leftbar_uninstall.bmp differ diff --git a/misc/windows/NSIS/license.txt b/misc/windows/NSIS/license.txt new file mode 100644 index 0000000..e11bdec --- /dev/null +++ b/misc/windows/NSIS/license.txt @@ -0,0 +1,1070 @@ +1. OpenJDK distibuted under GNU General Public License, version 2, +with the Classpath Exception + +2. NS-USBloader distibuted under GNU General Public License version 3, +or any later version. + *** +The GNU General Public License (GPL) + +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share +and change it. By contrast, the GNU General Public License is intended to +guarantee your freedom to share and change free software--to make sure the +software is free for all its users. This General Public License applies to +most of the Free Software Foundation's software and to any other program whose +authors commit to using it. (Some other Free Software Foundation software is +covered by the GNU Library General Public License instead.) You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom to +distribute copies of free software (and charge for this service if you wish), +that you receive source code or can get it if you want it, that you can change +the software or use pieces of it in new free programs; and that you know you +can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny +you these rights or to ask you to surrender the rights. These restrictions +translate to certain responsibilities for you if you distribute copies of the +software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for +a fee, you must give the recipients all the rights that you have. You must +make sure that they, too, receive or can get the source code. And you must +show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) +offer you this license which gives you legal permission to copy, distribute +and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that +everyone understands that there is no warranty for this free software. If the +software is modified by someone else and passed on, we want its recipients to +know that what they have is not the original, so that any problems introduced +by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We +wish to avoid the danger that redistributors of a free program will +individually obtain patent licenses, in effect making the program proprietary. +To prevent this, we have made it clear that any patent must be licensed for +everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice +placed by the copyright holder saying it may be distributed under the terms of +this General Public License. The "Program", below, refers to any such program +or work, and a "work based on the Program" means either the Program or any +derivative work under copyright law: that is to say, a work containing the +Program or a portion of it, either verbatim or with modifications and/or +translated into another language. (Hereinafter, translation is included +without limitation in the term "modification".) Each licensee is addressed as +"you". + +Activities other than copying, distribution and modification are not covered by +this License; they are outside its scope. The act of running the Program is +not restricted, and the output from the Program is covered only if its contents +constitute a work based on the Program (independent of having been made by +running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as +you receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice and +disclaimer of warranty; keep intact all the notices that refer to this License +and to the absence of any warranty; and give any other recipients of the +Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may +at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus +forming a work based on the Program, and copy and distribute such modifications +or work under the terms of Section 1 above, provided that you also meet all of +these conditions: + + a) You must cause the modified files to carry prominent notices stating + that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or + in part contains or is derived from the Program or any part thereof, to be + licensed as a whole at no charge to all third parties under the terms of + this License. + + c) If the modified program normally reads commands interactively when run, + you must cause it, when started running for such interactive use in the + most ordinary way, to print or display an announcement including an + appropriate copyright notice and a notice that there is no warranty (or + else, saying that you provide a warranty) and that users may redistribute + the program under these conditions, and telling the user how to view a copy + of this License. (Exception: if the Program itself is interactive but does + not normally print such an announcement, your work based on the Program is + not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable +sections of that work are not derived from the Program, and can be reasonably +considered independent and separate works in themselves, then this License, and +its terms, do not apply to those sections when you distribute them as separate +works. But when you distribute the same sections as part of a whole which is a +work based on the Program, the distribution of the whole must be on the terms +of this License, whose permissions for other licensees extend to the entire +whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your +rights to work written entirely by you; rather, the intent is to exercise the +right to control the distribution of derivative or collective works based on +the Program. + +In addition, mere aggregation of another work not based on the Program with the +Program (or with a work based on the Program) on a volume of a storage or +distribution medium does not bring the other work under the scope of this +License. + +3. You may copy and distribute the Program (or a work based on it, under +Section 2) in object code or executable form under the terms of Sections 1 and +2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source + code, which must be distributed under the terms of Sections 1 and 2 above + on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to + give any third party, for a charge no more than your cost of physically + performing source distribution, a complete machine-readable copy of the + corresponding source code, to be distributed under the terms of Sections 1 + and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to + distribute corresponding source code. (This alternative is allowed only + for noncommercial distribution and only if you received the program in + object code or executable form with such an offer, in accord with + Subsection b above.) + +The source code for a work means the preferred form of the work for making +modifications to it. For an executable work, complete source code means all +the source code for all modules it contains, plus any associated interface +definition files, plus the scripts used to control compilation and installation +of the executable. However, as a special exception, the source code +distributed need not include anything that is normally distributed (in either +source or binary form) with the major components (compiler, kernel, and so on) +of the operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the source +code from the same place counts as distribution of the source code, even though +third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as +expressly provided under this License. Any attempt otherwise to copy, modify, +sublicense or distribute the Program is void, and will automatically terminate +your rights under this License. However, parties who have received copies, or +rights, from you under this License will not have their licenses terminated so +long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. +However, nothing else grants you permission to modify or distribute the Program +or its derivative works. These actions are prohibited by law if you do not +accept this License. Therefore, by modifying or distributing the Program (or +any work based on the Program), you indicate your acceptance of this License to +do so, and all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), +the recipient automatically receives a license from the original licensor to +copy, distribute or modify the Program subject to these terms and conditions. +You may not impose any further restrictions on the recipients' exercise of the +rights granted herein. You are not responsible for enforcing compliance by +third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), conditions +are imposed on you (whether by court order, agreement or otherwise) that +contradict the conditions of this License, they do not excuse you from the +conditions of this License. If you cannot distribute so as to satisfy +simultaneously your obligations under this License and any other pertinent +obligations, then as a consequence you may not distribute the Program at all. +For example, if a patent license would not permit royalty-free redistribution +of the Program by all those who receive copies directly or indirectly through +you, then the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply and +the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or +other property right claims or to contest validity of any such claims; this +section has the sole purpose of protecting the integrity of the free software +distribution system, which is implemented by public license practices. Many +people have made generous contributions to the wide range of software +distributed through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing to +distribute software through any other system and a licensee cannot impose that +choice. + +This section is intended to make thoroughly clear what is believed to be a +consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain +countries either by patents or by copyrighted interfaces, the original +copyright holder who places the Program under this License may add an explicit +geographical distribution limitation excluding those countries, so that +distribution is permitted only in or among countries not thus excluded. In +such case, this License incorporates the limitation as if written in the body +of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the +General Public License from time to time. Such new versions will be similar in +spirit to the present version, but may differ in detail to address new problems +or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any later +version", you have the option of following the terms and conditions either of +that version or of any later version published by the Free Software Foundation. +If the Program does not specify a version number of this License, you may +choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs +whose distribution conditions are different, write to the author to ask for +permission. For software which is copyrighted by the Free Software Foundation, +write to the Free Software Foundation; we sometimes make exceptions for this. +Our decision will be guided by the two goals of preserving the free status of +all derivatives of our free software and of promoting the sharing and reuse of +software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR +THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE +STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE +PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, +YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE +PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR +INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA +BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER +OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively convey the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + + One line to give the program's name and a brief idea of what it does. + + Copyright (C) + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the Free + Software Foundation; either version 2 of the License, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it +starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision comes + with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free + software, and you are welcome to redistribute it under certain conditions; + type 'show c' for details. + +The hypothetical commands 'show w' and 'show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may be +called something other than 'show w' and 'show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, +if any, to sign a "copyright disclaimer" for the program, if necessary. Here +is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + 'Gnomovision' (which makes passes at compilers) written by James Hacker. + + signature of Ty Coon, 1 April 1989 + + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General Public +License instead of this License. + + +"CLASSPATH" EXCEPTION TO THE GPL + +Certain source files distributed by Oracle America and/or its affiliates are +subject to the following clarification and special exception to the GPL, but +only where Oracle has expressly included in the particular source file's header +the words "Oracle designates this particular file as subject to the "Classpath" +exception as provided by Oracle in the LICENSE file that accompanied this code." + + Linking this library statically or dynamically with other modules is making + a combined work based on this library. Thus, the terms and conditions of + the GNU General Public License cover the whole combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent modules, + and to copy and distribute the resulting executable under terms of your + choice, provided that you also meet, for each linked independent module, + the terms and conditions of the license of that module. An independent + module is a module which is not derived from or based on this library. If + you modify this library, you may extend this exception to your version of + the library, but you are not obligated to do so. If you do not wish to do + so, delete this exception statement from your version. + + + + +ADDITIONAL INFORMATION ABOUT LICENSING + +Certain files distributed by Oracle America, Inc. and/or its affiliates are +subject to the following clarification and special exception to the GPLv2, +based on the GNU Project exception for its Classpath libraries, known as the +GNU Classpath Exception. + +Note that Oracle includes multiple, independent programs in this software +package. Some of those programs are provided under licenses deemed +incompatible with the GPLv2 by the Free Software Foundation and others. +For example, the package includes programs licensed under the Apache +License, Version 2.0 and may include FreeType. Such programs are licensed +to you under their original licenses. + +Oracle facilitates your further distribution of this package by adding the +Classpath Exception to the necessary parts of its GPLv2 code, which permits +you to use that code in combination with other independent modules not +licensed under the GPLv2. However, note that this would not permit you to +commingle code under an incompatible license with Oracle's GPLv2 licensed +code by, for example, cutting and pasting such code into a file also +containing Oracle's GPLv2 licensed code and then distributing the result. + +Additionally, if you were to remove the Classpath Exception from any of the +files to which it applies and distribute the result, you would likely be +required to license some or all of the other code in that distribution under +the GPLv2 as well, and since the GPLv2 is incompatible with the license terms +of some items included in the distribution by Oracle, removing the Classpath +Exception could therefore effectively compromise your ability to further +distribute the package. + +Failing to distribute notices associated with some files may also create +unexpected legal consequences. + +Proceed with caution and we recommend that you obtain the advice of a lawyer +skilled in open source matters before removing the Classpath Exception or +making modifications to this package which may subsequently be redistributed +and/or involve the use of third party software. + +============================================================================ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/misc/windows/NSIS/logo.ico b/misc/windows/NSIS/logo.ico new file mode 100644 index 0000000..9bc9867 Binary files /dev/null and b/misc/windows/NSIS/logo.ico differ diff --git a/misc/windows/NSIS/uninstaller_logo.ico b/misc/windows/NSIS/uninstaller_logo.ico new file mode 100644 index 0000000..49688a8 Binary files /dev/null and b/misc/windows/NSIS/uninstaller_logo.ico differ diff --git a/misc/windows/update_version.sh b/misc/windows/update_version.sh new file mode 100755 index 0000000..0ffe6d4 --- /dev/null +++ b/misc/windows/update_version.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +TIMESTAMP=`date +%Y%m%d.%H%M%S` +VERSIONMAJOR=`grep '' pom.xml | head -1 | sed -e 's/^.*//g' -e 's/\..*$//g'` +VERSIONMINOR=`grep '' pom.xml | head -1 | sed -E 's/^.*[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 diff --git a/pom.xml b/pom.xml index 8db9597..d39d2f5 100644 --- a/pom.xml +++ b/pom.xml @@ -8,12 +8,10 @@ NS-USBloader ns-usbloader - 4.3-SNAPSHOT + 7.3 - https://github.com/developersu/ns-usbloader/ - - NSP USB loader for TinFoil (USB and Network) and GoldLeaf - + https://redrise.ru + NS multi-tool 2019 Dmitry Isaenko @@ -40,106 +38,96 @@ + + + redrise + redrise.ru repository + https://repo.redrise.ru/releases + + + UTF-8 + yyyyMMdd.HHmmss + 19.0.2.1 + 11 GitHub - https://github.com/developer_su/${project.artifactId}/issues + https://github.com/developersu/${project.artifactId}/issues - commons-cli commons-cli - 1.4 + 1.5.0 compile + org.openjfx - javafx-controls - 11 + javafx-graphics + ${javafx.version} linux compile org.openjfx - javafx-media - 11 + javafx-controls + ${javafx.version} linux compile org.openjfx javafx-fxml - 11 - linux - compile - - - org.openjfx - javafx-graphics - 11 + ${javafx.version} linux compile org.openjfx - javafx-controls - 11 + javafx-graphics + ${javafx.version} win compile org.openjfx - javafx-media - 11 + javafx-controls + ${javafx.version} win compile org.openjfx javafx-fxml - 11 - win - compile - - - org.openjfx - javafx-graphics - 11 + ${javafx.version} win compile org.openjfx - javafx-controls - 11 + javafx-graphics + ${javafx.version} mac compile org.openjfx - javafx-media - 11 + javafx-controls + ${javafx.version} mac compile org.openjfx javafx-fxml - 11 - mac - compile - - - org.openjfx - javafx-graphics - 11 + ${javafx.version} mac compile @@ -150,22 +138,88 @@ 1.3.0 compile + + + org.junit.jupiter + junit-jupiter-engine + 5.9.0 + test + + + org.junit.jupiter + junit-jupiter-api + 5.9.0 + test + + + org.junit.jupiter + junit-jupiter-params + 5.9.0 + test + + + + ru.redrise + libKonogonka + 0.1 + compile + + ${project.artifactId}-${project.version}-${maven.build.timestamp} + + + src/main/resources + false + + + src/main/resources-filtered + true + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.22.2 + org.apache.maven.plugins maven-compiler-plugin - 3.1 + 3.10.1 - 1.8 - 1.8 + 11 + org.apache.maven.plugins maven-jar-plugin - 2.4 + 3.1.2 + default-jar @@ -187,6 +241,7 @@ jar-with-dependencies + false @@ -198,14 +253,13 @@ - + Launching error + - 1.8 + %PWD%/jdk + 11.0.0 - 1.0.0.0 + ${project.version}.0.0 ${project.version} - TinFoil and GoldLeaf installer for your NS - GNU General Public License v3, 2019 ${project.organization.name}. Russia/LPR. - 1.0.0.0 + NS multi-tool + GNU General Public License v3, ${project.inceptionYear} ${project.organization.name}, Russia. + ${project.version}.0.0 ${project.version} ${project.organization.name} ${project.name} ${project.name} ${project.name}.exe + + Startup error + JDK not found + JDK Version mismatch + Launcher Error +
- --> \ No newline at end of file diff --git a/screenshots/1.png b/screenshots/1.png index dfa03c6..6225c73 100644 Binary files a/screenshots/1.png and b/screenshots/1.png differ diff --git a/screenshots/3.png b/screenshots/3.png index a884984..35e6dc0 100644 Binary files a/screenshots/3.png and b/screenshots/3.png differ diff --git a/screenshots/4.png b/screenshots/4.png index 632b199..1e1fac6 100644 Binary files a/screenshots/4.png and b/screenshots/4.png differ diff --git a/screenshots/ApplicationLogo.svg b/screenshots/ApplicationLogo.svg index 222de82..852045a 100644 --- a/screenshots/ApplicationLogo.svg +++ b/screenshots/ApplicationLogo.svg @@ -1,19 +1,19 @@ + 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/"> + inkscape:document-rotation="0" + inkscape:showpageshadow="0" + inkscape:pagecheckerboard="0" + inkscape:deskcolor="#d1d1d1"> + originx="-40.99399" + originy="-37.999752" /> @@ -54,7 +57,6 @@ image/svg+xml - @@ -114,145 +116,65 @@ inkscape:connector-curvature="0" style="fill:#ffffff;stroke-width:0.0680452" inkscape:label="usb_logo" /> - NS-USBloader + 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"> + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Dmitry Isaenko diff --git a/src/main/java/nsusbloader/AppPreferences.java b/src/main/java/nsusbloader/AppPreferences.java index a2e6828..ceb9542 100644 --- a/src/main/java/nsusbloader/AppPreferences.java +++ b/src/main/java/nsusbloader/AppPreferences.java @@ -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); + } } diff --git a/src/main/java/nsusbloader/COM/USB/TransferModule.java b/src/main/java/nsusbloader/COM/USB/TransferModule.java deleted file mode 100644 index f7a734b..0000000 --- a/src/main/java/nsusbloader/COM/USB/TransferModule.java +++ /dev/null @@ -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 . -*/ -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 nspMap; - ILogPrinter logPrinter; - DeviceHandle handlerNS; - CancellableRunnable task; - - TransferModule(DeviceHandle handler, LinkedHashMap 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> 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; } -} diff --git a/src/main/java/nsusbloader/Controllers/BlockListViewController.java b/src/main/java/nsusbloader/Controllers/BlockListViewController.java new file mode 100644 index 0000000..bba5d6b --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/BlockListViewController.java @@ -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 . + */ +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 splitMergeListView; + private ObservableList filesList; + + private ResourceBundle resourceBundle; + + private static class FileListCell extends ListCell{ + @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 item = new FileListCell(); + setContextMenuToItem(item); + return item; + }); + } + + private void setContextMenuToItem(ListCell 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 files){ + for (File file : files) { + add(file); + } + } + public ObservableList getItems(){ return filesList; } + public void clear(){ + filesList.clear(); + splitMergeListView.refresh(); + } +} diff --git a/src/main/java/nsusbloader/Controllers/FilesDropHandle.java b/src/main/java/nsusbloader/Controllers/FilesDropHandle.java new file mode 100644 index 0000000..d2042cc --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/FilesDropHandle.java @@ -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 . +*/ +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 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 allFiles = filesDropHandleTask.getValue(); + + if (! allFiles.isEmpty()) { + tableController.setFiles(allFiles); + } + stage.close(); + }); + + new Thread(filesDropHandleTask).start(); + + cancelButton.setOnAction(actionEvent -> { + filesDropHandleTask.cancel(true); + stage.close(); + }); + } +} diff --git a/src/main/java/nsusbloader/Controllers/FilesDropHandleTask.java b/src/main/java/nsusbloader/Controllers/FilesDropHandleTask.java new file mode 100644 index 0000000..598bc41 --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/FilesDropHandleTask.java @@ -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 . +*/ +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> { + private final String filesRegex; + private final String foldersRegex; + + private final List filesDropped; + private final List allFiles; + + private final String messageTemplate; + private long filesScanned = 0; + private long filesAdded = 0; + + FilesDropHandleTask(List 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 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)); + } + } + +} diff --git a/src/main/java/nsusbloader/Controllers/FontSettings.java b/src/main/java/nsusbloader/Controllers/FontSettings.java new file mode 100644 index 0000000..9f5fb15 --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/FontSettings.java @@ -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 . + */ +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(); + } +} diff --git a/src/main/java/nsusbloader/Controllers/FontSettingsController.java b/src/main/java/nsusbloader/Controllers/FontSettingsController.java new file mode 100644 index 0000000..98c20a6 --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/FontSettingsController.java @@ -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 . + */ +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 fontsLv; + + @FXML + private Spinner 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 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 getFonts(){ + ObservableList fonts = FXCollections.observableArrayList(); + fonts.addAll(Font.getFamilies()); + + return fonts; + } + + private SpinnerValueFactory 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(); + } +} diff --git a/src/main/java/nsusbloader/Controllers/FrontController.java b/src/main/java/nsusbloader/Controllers/FrontController.java deleted file mode 100644 index 96ddf07..0000000 --- a/src/main/java/nsusbloader/Controllers/FrontController.java +++ /dev/null @@ -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 . -*/ -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 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 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 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 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 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 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 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()); - } -} diff --git a/src/main/java/nsusbloader/Controllers/GamesController.java b/src/main/java/nsusbloader/Controllers/GamesController.java new file mode 100644 index 0000000..364cb08 --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/GamesController.java @@ -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 . +*/ +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 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 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 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 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
+ * tinfoil + xcinszxcz
+ * tinfoil + nsponly
+ * goldleaf
+ * 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 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 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 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 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 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 void performInBackgroundAndUpdate(Supplier background, Consumer 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 statusMap = payload.getStatusMap(); + + if (! statusMap.isEmpty()) { + for (String key : statusMap.keySet()) + tableFilesListController.setFileStatus(key, statusMap.get(key)); + } + } +} \ No newline at end of file diff --git a/src/main/java/nsusbloader/Controllers/ISubscriber.java b/src/main/java/nsusbloader/Controllers/ISubscriber.java new file mode 100644 index 0000000..1e1ba59 --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/ISubscriber.java @@ -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 . + */ +package nsusbloader.Controllers; + +import nsusbloader.NSLDataTypes.EModule; + +public interface ISubscriber { + void notify(EModule type, boolean status, Payload payload); +} diff --git a/src/main/java/nsusbloader/Controllers/NSLMainController.java b/src/main/java/nsusbloader/Controllers/NSLMainController.java index 4e564bf..a159c9e 100644 --- a/src/main/java/nsusbloader/Controllers/NSLMainController.java +++ b/src/main/java/nsusbloader/Controllers/NSLMainController.java @@ -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()){ - Task> updTask = new UpdatesChecker(); - updTask.setOnSucceeded(event->{ - List 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)); - } + 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> updTask = new UpdatesChecker(); + updTask.setOnSucceeded(event->{ + List 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)); } - else - ServiceWindow.getInfoNotification(resourceBundle.getString("windowTitleNewVersionUnknown"), resourceBundle.getString("windowBodyNewVersionUnknown")); - }); - Thread updates = new Thread(updTask); - updates.setDaemon(true); - updates.start(); - } + } + else + 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); } } diff --git a/src/main/java/nsusbloader/Controllers/NSTableViewController.java b/src/main/java/nsusbloader/Controllers/NSTableViewController.java index e7368ba..379ba79 100644 --- a/src/main/java/nsusbloader/Controllers/NSTableViewController.java +++ b/src/main/java/nsusbloader/Controllers/NSTableViewController.java @@ -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 table; private ObservableList 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 newFiles){ + public synchronized void setFiles(List newFiles){ if (!rowsObsLst.isEmpty()){ List 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(); diff --git a/src/main/java/nsusbloader/Controllers/NxdtController.java b/src/main/java/nsusbloader/Controllers/NxdtController.java index 7d696ec..a6439c6 100644 --- a/src/main/java/nsusbloader/Controllers/NxdtController.java +++ b/src/main/java/nsusbloader/Controllers/NxdtController.java @@ -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()); - } } diff --git a/src/main/java/nsusbloader/Controllers/PatchesController.java b/src/main/java/nsusbloader/Controllers/PatchesController.java new file mode 100644 index 0000000..a2f0b8c --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/PatchesController.java @@ -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 . + */ +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 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()); + } + +} \ No newline at end of file diff --git a/src/main/java/nsusbloader/Controllers/Payload.java b/src/main/java/nsusbloader/Controllers/Payload.java new file mode 100644 index 0000000..3b37fc1 --- /dev/null +++ b/src/main/java/nsusbloader/Controllers/Payload.java @@ -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 . + */ +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 statusMap; + + public Payload(){ + this(""); + } + public Payload(String message){ + this(message, Collections.emptyMap()); + } + public Payload(String message, Map statusMap){ + this.message = message; + this.statusMap = statusMap; + } + + public String getMessage() { + return message; + } + + public Map getStatusMap() { + return statusMap; + } +} diff --git a/src/main/java/nsusbloader/Controllers/RcmController.java b/src/main/java/nsusbloader/Controllers/RcmController.java index 3fc6b5e..de29650 100644 --- a/src/main/java/nsusbloader/Controllers/RcmController.java +++ b/src/main/java/nsusbloader/Controllers/RcmController.java @@ -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()); } } diff --git a/src/main/java/nsusbloader/Controllers/SettingsBlockGenericController.java b/src/main/java/nsusbloader/Controllers/SettingsBlockGenericController.java index 00a416b..fc4b584 100644 --- a/src/main/java/nsusbloader/Controllers/SettingsBlockGenericController.java +++ b/src/main/java/nsusbloader/Controllers/SettingsBlockGenericController.java @@ -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 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()); } } diff --git a/src/main/java/nsusbloader/Controllers/SettingsBlockGoldleafController.java b/src/main/java/nsusbloader/Controllers/SettingsBlockGoldleafController.java index b5ba33d..2be959c 100644 --- a/src/main/java/nsusbloader/Controllers/SettingsBlockGoldleafController.java +++ b/src/main/java/nsusbloader/Controllers/SettingsBlockGoldleafController.java @@ -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()); } } diff --git a/src/main/java/nsusbloader/Controllers/SettingsBlockTinfoilController.java b/src/main/java/nsusbloader/Controllers/SettingsBlockTinfoilController.java index 8c28be3..ec6c5f9 100644 --- a/src/main/java/nsusbloader/Controllers/SettingsBlockTinfoilController.java +++ b/src/main/java/nsusbloader/Controllers/SettingsBlockTinfoilController.java @@ -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()); diff --git a/src/main/java/nsusbloader/Controllers/SplitMergeController.java b/src/main/java/nsusbloader/Controllers/SplitMergeController.java index 46be04f..10e1de3 100644 --- a/src/main/java/nsusbloader/Controllers/SplitMergeController.java +++ b/src/main/java/nsusbloader/Controllers/SplitMergeController.java @@ -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 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 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 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()); - } } \ No newline at end of file diff --git a/src/main/java/nsusbloader/FilesHelper.java b/src/main/java/nsusbloader/FilesHelper.java new file mode 100644 index 0000000..739a375 --- /dev/null +++ b/src/main/java/nsusbloader/FilesHelper.java @@ -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 . +*/ +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"); + } + } +} diff --git a/src/main/java/nsusbloader/MediatorControl.java b/src/main/java/nsusbloader/MediatorControl.java index e14564a..af2cb27 100644 --- a/src/main/java/nsusbloader/MediatorControl.java +++ b/src/main/java/nsusbloader/MediatorControl.java @@ -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(); } } diff --git a/src/main/java/nsusbloader/ModelControllers/ILogPrinter.java b/src/main/java/nsusbloader/ModelControllers/ILogPrinter.java index 09b1e8e..7c96ac4 100644 --- a/src/main/java/nsusbloader/ModelControllers/ILogPrinter.java +++ b/src/main/java/nsusbloader/ModelControllers/ILogPrinter.java @@ -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 nspMap, EFileStatus status); void update(File file, EFileStatus status); void updateOneLinerStatus(boolean status); diff --git a/src/main/java/nsusbloader/ModelControllers/LogPrinterGui.java b/src/main/java/nsusbloader/ModelControllers/LogPrinterGui.java index a18d544..606771d 100644 --- a/src/main/java/nsusbloader/ModelControllers/LogPrinterGui.java +++ b/src/main/java/nsusbloader/ModelControllers/LogPrinterGui.java @@ -1,5 +1,5 @@ /* - Copyright 2019-2020 Dmitry Isaenko + Copyright 2019-2024 Dmitry Isaenko This file is part of NS-USBloader. @@ -32,53 +32,51 @@ public class LogPrinterGui implements ILogPrinter { private final MessagesConsumer msgConsumer; private final BlockingQueue msgQueue; private final BlockingQueue progressQueue; - private final HashMap statusMap; // BlockingQueue for literally one object. TODO: read more books ; replace to hashMap + private final HashMap 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.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 { - switch (type){ - case PASS: - msgQueue.put("[ PASS ] "+message+"\n"); - break; - case FAIL: - msgQueue.put("[ FAIL ] "+message+"\n"); - break; - case INFO: - msgQueue.put("[ INFO ] "+message+"\n"); - break; - case WARNING: - msgQueue.put("[ WARN ] "+message+"\n"); - break; - default: - msgQueue.put(message); - } - } - catch (InterruptedException ie){ - ie.printStackTrace(); + public void print(String message, EMsgType type) throws InterruptedException{ + switch (type){ + case PASS: + msgQueue.put("[ PASS ] "+message+"\n"); + break; + case FAIL: + msgQueue.put("[ FAIL ] "+message+"\n"); + break; + case INFO: + msgQueue.put("[ INFO ] "+message+"\n"); + break; + case WARNING: + msgQueue.put("[ WARN ] "+message+"\n"); + break; + default: + msgQueue.put(message); } } /** * Update progress for progress bar * */ @Override - public void updateProgress(Double value) { - try { - progressQueue.put(value); - } - catch (InterruptedException ignored){} // TODO: Do something with this + public void updateProgress(Double value) throws InterruptedException { + progressQueue.put(value); } /** * When we're done - update status diff --git a/src/main/java/nsusbloader/ModelControllers/MessagesConsumer.java b/src/main/java/nsusbloader/ModelControllers/MessagesConsumer.java index 25549d1..491d5ad 100644 --- a/src/main/java/nsusbloader/ModelControllers/MessagesConsumer.java +++ b/src/main/java/nsusbloader/ModelControllers/MessagesConsumer.java @@ -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 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 msgQueue; private final BlockingQueue progressQueue; - private final ProgressBar progressBar; private final HashMap statusMap; - private final NSTableViewController tableViewController; private final EModule appModuleType; - private AtomicBoolean oneLinerStatus; + private final AtomicBoolean oneLinerStatus; private boolean isInterrupted; @@ -51,37 +52,31 @@ public class MessagesConsumer extends AnimationTimer { BlockingQueue msgQueue, BlockingQueue progressQueue, HashMap statusMap, - AtomicBoolean oneLinerStatus) { + 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) { + public void handle(long l){ ArrayList messages = new ArrayList<>(); - int msgRecieved = msgQueue.drainTo(messages); - if (msgRecieved > 0) + int msgReceived = msgQueue.drainTo(messages); + if (msgReceived > 0) messages.forEach(logsArea::appendText); ArrayList 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,29 +85,19 @@ 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); - progressBar.setProgress(0.0); + if (isInterrupted) // safe, could not be interrupted while HashMap populating + updateElementsAndStop(); + } - if (statusMap.size() > 0){ - for (String key : statusMap.keySet()) - tableViewController.setFileStatus(key, statusMap.get(key)); - } + private void updateElementsAndStop(){ + Payload payload = new Payload( + resourceBundle.getString(oneLinerStatus.get() ? "done_txt" : "failure_txt"), + statusMap); - 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; - } + mediator.setTransferActive(appModuleType, false, payload); + progressBar.setProgress(0.0); - this.stop(); - } + this.stop(); } public void interrupt(){ diff --git a/src/main/java/nsusbloader/NSLDataTypes/EModule.java b/src/main/java/nsusbloader/NSLDataTypes/EModule.java index b8331a0..b144d7b 100644 --- a/src/main/java/nsusbloader/NSLDataTypes/EModule.java +++ b/src/main/java/nsusbloader/NSLDataTypes/EModule.java @@ -22,5 +22,6 @@ public enum EModule { USB_NET_TRANSFERS, SPLIT_MERGE_TOOL, RCM, - NXDT + NXDT, + PATCHES } diff --git a/src/main/java/nsusbloader/NSLMain.java b/src/main/java/nsusbloader/NSLMain.java index 0dc65fb..ce98308 100644 --- a/src/main/java/nsusbloader/NSLMain.java +++ b/src/main/java/nsusbloader/NSLMain.java @@ -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); } diff --git a/src/main/java/nsusbloader/RainbowHexDump.java b/src/main/java/nsusbloader/RainbowHexDump.java deleted file mode 100644 index ebdd277..0000000 --- a/src/main/java/nsusbloader/RainbowHexDump.java +++ /dev/null @@ -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 . -*/ -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"); - } -} diff --git a/src/main/java/nsusbloader/ServiceWindow.java b/src/main/java/nsusbloader/ServiceWindow.java index 0565448..3355a32 100644 --- a/src/main/java/nsusbloader/ServiceWindow.java +++ b/src/main/java/nsusbloader/ServiceWindow.java @@ -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 result = alertBox.showAndWait(); diff --git a/src/main/java/nsusbloader/TransfersPublisher.java b/src/main/java/nsusbloader/TransfersPublisher.java new file mode 100644 index 0000000..246cbb8 --- /dev/null +++ b/src/main/java/nsusbloader/TransfersPublisher.java @@ -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 . + */ +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 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(); + } +} diff --git a/src/main/java/nsusbloader/UI/LocaleHolder.java b/src/main/java/nsusbloader/UI/LocaleHolder.java index 5095ded..f1b2319 100644 --- a/src/main/java/nsusbloader/UI/LocaleHolder.java +++ b/src/main/java/nsusbloader/UI/LocaleHolder.java @@ -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; diff --git a/src/main/java/nsusbloader/Utilities/Rcm.java b/src/main/java/nsusbloader/Utilities/Rcm.java index fddb849..33a9268 100644 --- a/src/main/java/nsusbloader/Utilities/Rcm.java +++ b/src/main/java/nsusbloader/Utilities/Rcm.java @@ -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; diff --git a/src/main/java/nsusbloader/Utilities/WindowsDrivers/DownloadDriversTask.java b/src/main/java/nsusbloader/Utilities/WindowsDrivers/DownloadDriversTask.java index 0c023a8..eec25cc 100644 --- a/src/main/java/nsusbloader/Utilities/WindowsDrivers/DownloadDriversTask.java +++ b/src/main/java/nsusbloader/Utilities/WindowsDrivers/DownloadDriversTask.java @@ -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 { + 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 { } 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 { 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(); diff --git a/src/main/java/nsusbloader/Utilities/WindowsDrivers/DriversInstall.java b/src/main/java/nsusbloader/Utilities/WindowsDrivers/DriversInstall.java index 0526134..f973e75 100644 --- a/src/main/java/nsusbloader/Utilities/WindowsDrivers/DriversInstall.java +++ b/src/main/java/nsusbloader/Utilities/WindowsDrivers/DriversInstall.java @@ -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; } diff --git a/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtHostIOException.java b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtHostIOException.java new file mode 100644 index 0000000..54d7392 --- /dev/null +++ b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtHostIOException.java @@ -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 . +*/ +package nsusbloader.Utilities.nxdumptool; + +class NxdtHostIOException extends Exception { + NxdtHostIOException(){ + super(); + } + NxdtHostIOException(String message){ + super(message); + } +} diff --git a/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtMalformedException.java b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtMalformedException.java new file mode 100644 index 0000000..43409dd --- /dev/null +++ b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtMalformedException.java @@ -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 . +*/ +package nsusbloader.Utilities.nxdumptool; + +class NxdtMalformedException extends Exception { + NxdtMalformedException(){ + super(); + } + NxdtMalformedException(String message){ + super(message); + } +} diff --git a/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtNspFile.java b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtNspFile.java new file mode 100644 index 0000000..8cf1911 --- /dev/null +++ b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtNspFile.java @@ -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 . +*/ +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; } +} diff --git a/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtTask.java b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtTask.java index 04b76ff..4ea63b3 100644 --- a/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtTask.java +++ b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtTask.java @@ -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(); + } + } } \ No newline at end of file diff --git a/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtUsbAbi1.java b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtUsbAbi1.java index dd2a1bc..b01a571 100644 --- a/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtUsbAbi1.java +++ b/src/main/java/nsusbloader/Utilities/nxdumptool/NxdtUsbAbi1.java @@ -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); - final int fileNameLen = getLEint(message, 0x18); - String filename = new String(message, 0x20, fileNameLen, StandardCharsets.UTF_8); + 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); - 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("/", "\\\\"); + 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; + } + else { + // 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); + } + + writeUsb(USBSTATUS_SUCCESS); + + if (fullSize == 0) + return; + + if (isNspTransfer()) + dumpNspFile(fullSize); else - filename = saveToPath + filename; + dumpFile(fileToDump, fullSize); - createPath(filename); + writeUsb(USBSTATUS_SUCCESS); } - else { - //logPrinter.print("Receiving: '"+filename+"' ("+fileSize+" b)", EMsgType.INFO); // TODO: see above - filename = saveToPath + filename; + catch (NxdtMalformedException malformed){ + logPrinter.print(malformed.getMessage(), EMsgType.FAIL); + writeUsb(USBSTATUS_MALFORMED_REQUEST); } - - File fileToDump = new File(filename); + 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,30 +288,67 @@ 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 private void dumpFile(File file, long size) throws Exception{ FileOutputStream fos = new FileOutputStream(file, true); + try (BufferedOutputStream bos = new BufferedOutputStream(fos)){ + 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; + logPrinter.updateProgress((double)received / (double)size); + } + int lastChunkSize = (int)(size - received) + 1; + readBuffer = readUsbFileDebug(lastChunkSize); + bos.write(readBuffer); + if (isWindows10) + fd.sync(); + } + finally { + logPrinter.updateProgress(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; @@ -296,22 +363,54 @@ class NxdtUsbAbi1 { bufferSize = readBuffer.length; received += bufferSize; - logPrinter.updateProgress((double)received / (double)size); + 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(); - } finally { - logPrinter.updateProgress(1.0); + nspRemainingSize -= (lastChunkSize - 1); + nspFile.setNspRemainingSize(nspRemainingSize); } } - /* Handle Zero-length terminator - private boolean isAligned(long size){ - return ((size & (endpointMaxPacketSize - 1)) == 0); + + 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]); + } } diff --git a/src/main/java/nsusbloader/Utilities/patches/AHeuristic.java b/src/main/java/nsusbloader/Utilities/patches/AHeuristic.java new file mode 100644 index 0000000..1d1b6ea --- /dev/null +++ b/src/main/java/nsusbloader/Utilities/patches/AHeuristic.java @@ -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 . + */ +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); +} diff --git a/src/main/java/nsusbloader/Utilities/patches/BinToAsmPrinter.java b/src/main/java/nsusbloader/Utilities/patches/BinToAsmPrinter.java new file mode 100644 index 0000000..0109258 --- /dev/null +++ b/src/main/java/nsusbloader/Utilities/patches/BinToAsmPrinter.java @@ -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 . + */ +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 ? else \n" + + "CBZ ,