├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitattributes ├── .github ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── ci-cd.yml │ └── signature-assistant.yml ├── .gitignore ├── .npmignore ├── .nvmrc ├── LICENSE ├── README.md ├── TRADEMARK ├── buildResources ├── .gitignore ├── ScratchDesktop.icns ├── ScratchDesktop.ico ├── appx │ ├── Square150x150Logo.png │ ├── Square44x44Logo.png │ ├── StoreLogo.png │ └── Wide310x150Logo.png ├── entitlements.mac.plist ├── entitlements.mas.inherit.plist ├── entitlements.mas.plist ├── make-icons.sh └── screenshot.png ├── electron-builder.yaml ├── fastlane ├── Appfile ├── Fastfile ├── Matchfile ├── README-match.md └── README.md ├── package-lock.json ├── package.json ├── renovate.json5 ├── scripts ├── .eslintrc.js ├── afterSign.js ├── electron-builder-wrapper.js ├── fetchMediaLibraryAssets.js ├── lib │ └── libraries.js └── start.js ├── src ├── .eslintrc.js ├── common │ ├── ElectronStorageHelper.js │ └── log.js ├── icon │ ├── ScratchDesktop.png │ └── ScratchDesktop.svg ├── main │ ├── .eslintrc.js │ ├── FileFilters.js │ ├── MacOSMenu.js │ ├── ScratchDesktopTelemetry.js │ ├── argv.js │ ├── index.js │ └── telemetry │ │ └── TelemetryClient.js └── renderer │ ├── .eslintrc.js │ ├── ScratchDesktopAppStateHOC.jsx │ ├── ScratchDesktopGUIHOC.jsx │ ├── about.css │ ├── about.jsx │ ├── app.css │ ├── app.jsx │ ├── index.html │ ├── index.js │ ├── privacy.css │ ├── privacy.jsx │ ├── showPrivacyPolicy.js │ ├── usb.css │ └── usb.jsx ├── webpack.main.js ├── webpack.makeConfig.js └── webpack.renderer.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["@babel/preset-env", { 4 | "targets": { 5 | "browsers": [ 6 | "node >= 16", // Electron's main process 7 | "chrome >= 63" // Electron's render process (see Scratch FAQ) 8 | ] 9 | } 10 | }], 11 | "@babel/preset-react" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | 10 | [*.{js,html}] 11 | indent_style = space 12 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/* 2 | dist/* 3 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | node: true 5 | }, 6 | extends: ['scratch', 'scratch/es6', 'scratch/node'] 7 | }; 8 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Explicitly specify line endings for as many files as possible. 5 | # People who (for example) rsync between Windows and Linux need this. 6 | 7 | # File types which we know are binary 8 | 9 | # Prefer LF for most file types 10 | *.css text eol=lf 11 | *.htm text eol=lf 12 | *.html text eol=lf 13 | *.js text eol=lf 14 | *.js.map text eol=lf 15 | *.json text eol=lf 16 | *.json5 text eol=lf 17 | *.jsx text eol=lf 18 | *.md text eol=lf 19 | *.plist text eol=lf 20 | *.xml text eol=lf 21 | *.yml text eol=lf 22 | *.yaml text eol=lf 23 | 24 | # Prefer LF for these files 25 | .editorconfig text eol=lf 26 | .eslintignore text eol=lf 27 | .gitattributes text eol=lf 28 | .gitignore text eol=lf 29 | .npmignore text eol=lf 30 | LICENSE text eol=lf 31 | Makefile text eol=lf 32 | TRADEMARK text eol=lf 33 | 34 | # Use CRLF for Windows-specific file types 35 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | The development of Scratch is an ongoing process, and we love to have people in the Scratch and open source communities help us along the way. 3 | 4 | ### Ways to Help 5 | 6 | * **Documenting bugs** 7 | * If you've identified a bug in Scratch you should first check to see if it's been filed as an issue, if not you can file one. Make sure you follow the issue template. 8 | * It's important that we can consistently reproduce issues. When writing an issue, be sure to follow our [reproduction step guidelines](https://github.com/LLK/scratch-gui/wiki/Writing-good-repro-steps). 9 | * Some issues are marked "Needs Repro". Adding a comment with good reproduction steps to those issues is a great way to help. 10 | * If you don't have an issue in mind already, you can look through the [Bugs & Glitches forum.](https://scratch.mit.edu/discuss/3/) Look for users reporting problems, reproduce the problem yourself, and file new issues following our guidelines. 11 | 12 | * **Fixing bugs** 13 | * You can request to fix a bug in a comment on the issue if you at mention the repo coordinator, who for this repo is @cwillisf. 14 | * If the issue is marked "Help Wanted" you can go ahead and start working on it! 15 | * **We will only accept Pull Requests for bugs that have an issue filed that has a priority label** 16 | * If you're interested in fixing a bug with no issue, file the issue first and wait for it to have a priority added to it. 17 | 18 | * We are not looking for Pull Requests ("PR") for every issue and may deny a PR if it doesn't fit our criteria. 19 | * We are far more likely to accept a PR if it is for an issue marked with Help Wanted. 20 | * We will not accept PRs for issues marked with "Needs Discussion" or "Needs Design." 21 | * Wait until the Repo Coordinator assigns the issue to you before you begin work or submit a PR. 22 | 23 | ### Learning Git and Github 24 | 25 | If you want to work on fixing issues, you should be familiar with Git and Github. 26 | 27 | * [Learn Git branching](https://learngitbranching.js.org/) includes an introduction to basic git commands and useful branching features. 28 | * Here's a general introduction to [contributing to an open source project](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github). 29 | 30 | **Important:** we follow the [Github Flow process](https://guides.github.com/introduction/flow/) as our development process. 31 | 32 | ### How to Fix Bugs 33 | 1. Identify which Github issue you are working on. Leave a comment on the issue to let us (and other contributors) know you're working on it. 34 | 2. Make sure you have a fork of this repo (see [Github's forking a repo](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) for details) 35 | 3. Switch to the `develop` branch, and pull down the latest changes from upstream 36 | 4. Run the code, and reproduce the problem 37 | 5. Create your branch from the `develop` branch 38 | 6. Make code changes to fix the problem 39 | 7. Run `npm test` to make sure that your changes pass our tests 40 | 8. Commit your changes 41 | 9. Push your branch to your fork 42 | 10. Create your pull request 43 | 1. Make sure to follow the template in the PR description 44 | 1. Remember to check the “[Allow edits from maintainers](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork)” box 45 | 46 | When submitting pull requests keep in mind: 47 | * please be patient -- it can take a while to find time to review them 48 | * try to change the least amount of code necessary to fix the bug 49 | * the code can't be radically changed without significant coordination with the Scratch Team, so these types of changes should be avoided 50 | * if you find yourself changing a substantial amount of code or considering radical changes, please ask for clarification -- we may have envisioned a different approach, or underestimated the amount of effort 51 | 52 | ### Suggestions 53 | ![Block sketch](https://user-images.githubusercontent.com/3431616/77192550-1dcebe00-6ab3-11ea-9606-8ecd8500c958.png) 54 | 55 | Please note: **_we are unlikely to accept PRs with new features that haven't been thought through and discussed as a group_**. 56 | 57 | Why? Because we have a strong belief in the value of keeping things simple for new users. It's been said that the Scratch Team spends about one hour of design discussion for every pixel in Scratch. To learn more about our design philosophy, see [the Scratch Developers page](https://scratch.mit.edu/developers), or [this paper](http://web.media.mit.edu/~mres/papers/Scratch-CACM-final.pdf). 58 | 59 | We welcome suggestions! If you want to suggest a feature, please post in our [suggestions forum](https://scratch.mit.edu/discuss/1/). Your suggestion will be helped if you include a mockup design; this can be simple, even hand-drawn. 60 | 61 | ### Other resources 62 | Beyond this repo, there are also some other resources that you might want to take a look at: 63 | * [Community Guidelines](https://github.com/LLK/scratch-www/wiki/Community-Guidelines) (we find it important to maintain a constructive and welcoming community, just like on Scratch) 64 | * [Open Source forum](https://scratch.mit.edu/discuss/49/) on Scratch 65 | * [Suggestions forum](https://scratch.mit.edu/discuss/1/) on Scratch 66 | * [Bugs & Glitches forum](https://scratch.mit.edu/discuss/3/) on Scratch 67 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Expected Behavior 2 | 3 | _Please describe what should happen_ 4 | 5 | ### Actual Behavior 6 | 7 | _Describe what actually happens_ 8 | 9 | ### Steps to Reproduce 10 | 11 | _Explain what someone needs to do in order to see what's described in *Actual behavior* above_ 12 | 13 | ### Operating System and Browser 14 | 15 | _e.g. Mac OS 10.11.6 Safari 10.0_ 16 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Resolves 2 | 3 | _What Github issue does this resolve (please include link)?_ 4 | 5 | - Resolves # 6 | 7 | ### Proposed Changes 8 | 9 | _Describe what this Pull Request does_ 10 | 11 | ### Reason for Changes 12 | 13 | _Explain why these changes should be made_ 14 | 15 | ### Test Coverage 16 | 17 | _Please show how you have added tests to cover your changes_ 18 | -------------------------------------------------------------------------------- /.github/workflows/ci-cd.yml: -------------------------------------------------------------------------------- 1 | name: CI/CD 2 | on: 3 | push: 4 | 5 | concurrency: 6 | group: '${{ github.workflow }} @ ${{ github.head_ref || github.ref }}' 7 | 8 | permissions: 9 | contents: write # publish a GitHub release 10 | pages: write # deploy to GitHub Pages 11 | issues: write # comment on released issues 12 | pull-requests: write # comment on released pull requests 13 | 14 | jobs: 15 | ci-cd: 16 | strategy: 17 | matrix: 18 | os: 19 | - macos-latest 20 | - windows-latest 21 | runs-on: ${{ matrix.os }} 22 | defaults: 23 | run: 24 | shell: bash 25 | env: 26 | # This is a temporary workaround. We're currently having issues signing windows builds 27 | # due to a change of the security policy (see https://github.com/electron/windows-installer/issues/473) 28 | SCRATCH_SHOULD_SIGN: ${{ github.ref_name == 'develop' && matrix.os != 'windows-latest' }} 29 | AC_USERNAME: ${{ (github.ref_name == 'develop' && secrets.AC_USERNAME) || '' }} 30 | AC_PASSWORD: ${{ (github.ref_name == 'develop' && secrets.AC_PASSWORD) || '' }} 31 | # Required for notarization on Mac 32 | AC_TEAM_ID: ${{ secrets.AC_TEAM_ID || 'W7AR3WMP87' }} 33 | steps: 34 | - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3 35 | - uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3 36 | with: 37 | cache: 'npm' 38 | node-version-file: '.nvmrc' 39 | - name: Debug info 40 | run: | 41 | cat < 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scratch-desktop 2 | 3 | Scratch 3.0 as a standalone desktop application 4 | 5 | ## Developer Instructions 6 | 7 | ### Releasing a new version 8 | # TODO: Update readme once scratch-desktop uses scratch-gui from an npm package 9 | 10 | Let's assume that you want to make a new release, version `3.999.0`, corresponding to `scratch-gui` version 11 | `0.1.0-prerelease.20yymmdd`. 12 | 13 | 1. Merge `scratch-gui`: 14 | 1. `cd scratch-gui` 15 | 2. `git pull --all --tags` 16 | 3. `git checkout scratch-desktop` 17 | 4. `git merge 0.1.0-prerelease.20yymmdd` 18 | 5. Resolve conflicts if necessary 19 | 6. `git tag scratch-desktop-v3.999.0` 20 | 7. `git push` 21 | 8. `git push --tags` 22 | 2. Prep `scratch-desktop`: 23 | 1. `cd scratch-desktop` 24 | 2. `git pull --all --tags` 25 | 3. `git checkout develop` 26 | 4. `npm install --save-dev 'scratch-gui@github:scratchfoundation/scratch-gui#scratch-desktop-v3.999.0'` 27 | 5. `git add package.json package-lock.json` 28 | 6. Make sure the app works, the diffs look reasonable, etc. 29 | 7. `git commit -m "bump scratch-gui to scratch-desktop-v3.999.0"` 30 | 8. `npm version 3.999.0` 31 | 9. `git push` 32 | 10. `git push --tags` 33 | 3. Wait for the CI build and collect the release from the build artifacts 34 | 35 | ### A note about `scratch-gui` 36 | 37 | Eventually, the `scratch-desktop` branch of the Scratch GUI repository will be merged with that repository's main 38 | development line. For now, though, the `scratch-desktop` branch holds a few changes that are necessary for the Scratch 39 | app to function correctly but are not yet merged into the main development branch. If you only intend to build or work 40 | on the `scratch-desktop` repository then you can ignore this, but if you intend to work on `scratch-gui` as well, make 41 | sure you use the `scratch-desktop` branch there. 42 | 43 | Previously it was necessary to explicitly build `scratch-gui` before building `scratch-desktop`. This is no longer 44 | necessary and the related build scripts, such as `build-gui`, have been removed. 45 | 46 | ### Prepare media library assets 47 | 48 | In the `scratch-desktop` directory, run `npm run fetch`. Re-run this any time you update `scratch-gui` or make any 49 | other changes which might affect the media libraries. 50 | 51 | ### Run in development mode 52 | 53 | `npm start` 54 | 55 | ### Make a packaged build 56 | 57 | `npm run dist` 58 | 59 | Node that on macOS this will require installing various certificates. 60 | 61 | #### Signing the NSIS installer (Windows, non-store) 62 | 63 | *This section is relevant only to members of the Scratch Team.* 64 | 65 | By default all Windows installers are unsigned. An APPX package for the Microsoft Store shouldn't be signed: it will 66 | be signed automatically as part of the store submission process. On the other hand, the non-Store NSIS installer 67 | should be signed. 68 | 69 | To generate a signed NSIS installer: 70 | 71 | 1. Acquire our latest digital signing certificate and save it on your computer as a `p12` file. 72 | 2. Set `WIN_CSC_LINK` to the path to your certificate file. For maximum compatibility I use forward slashes. 73 | - CMD: `set WIN_CSC_LINK=C:/Users/You/Somewhere/Certificate.p12` 74 | - PowerShell: `$env:WIN_CSC_LINK = "C:/Users/You/Somewhere/Certificate.p12"` 75 | 3. Set `WIN_CSC_KEY_PASSWORD` to the password string associated with your P12 file. 76 | - CMD: `set WIN_CSC_KEY_PASSWORD=superSecret` 77 | - PowerShell: `$env:WIN_CSC_KEY_PASSWORD = "superSecret"` 78 | 4. Build the NSIS installer only: building the APPX installer will fail if these environment variables are set. 79 | - `npm run dist -- -w nsis` 80 | 81 | #### Workaround for code signing issue in macOS 82 | 83 | Sometimes the macOS build process will result in a build which crashes on startup. If this happens, check in `Console` 84 | for an entry similar to this: 85 | 86 | ```text 87 | failed to parse entitlements for Scratch[12345]: OSUnserializeXML: syntax error near line 1 88 | ``` 89 | 90 | This appears to be an issue with `codesign` itself. Rebooting your computer and trying to build again might help. Yes, 91 | really. 92 | 93 | See this issue for more detail: 94 | 95 | ### Make a semi-packaged build 96 | 97 | This will simulate a packaged build without actually packaging it: instead the files will be copied to a subdirectory 98 | of `dist`. 99 | 100 | `npm run dist:dir` 101 | 102 | ### Debugging 103 | 104 | You can debug the renderer process by opening the Chromium development console. This should be the same keyboard 105 | shortcut as Chrome on your platform. This won't work on a packaged build. 106 | 107 | You can debug the main process the same way as any Node.js process. I like to use Visual Studio Code with a 108 | configuration like this: 109 | 110 | ```jsonc 111 | "launch": { 112 | "version": "0.2.0", 113 | "configurations": [ 114 | { 115 | "name": "Desktop", 116 | "type": "node", 117 | "request": "launch", 118 | "cwd": "${workspaceFolder:scratch-desktop}", 119 | "runtimeExecutable": "npm", 120 | "autoAttachChildProcesses": true, 121 | "runtimeArgs": ["start", "--"], 122 | "protocol": "inspector", 123 | "skipFiles": [ 124 | // it seems like skipFiles only reliably works with 1 entry :( 125 | //"/**", 126 | "${workspaceFolder:scratch-desktop}/node_modules/electron/dist/resources/*.asar/**" 127 | ], 128 | "sourceMaps": true, 129 | "timeout": 30000, 130 | "outputCapture": "std" 131 | } 132 | ] 133 | }, 134 | ``` 135 | 136 | ### Resetting the Telemetry System 137 | 138 | This application includes a telemetry system which is only active if the user opts in. When testing this system, it's 139 | sometimes helpful to reset it by deleting the `telemetry.json` file. 140 | 141 | The location of this file depends on your operating system and whether or not you're running a packaged build. Running 142 | from `npm start` or equivalent is a non-packaged build. 143 | 144 | In addition, macOS may store the file in one of two places depending on the OS version and a few other variables. If 145 | in doubt, I recommend removing both. 146 | 147 | - Windows, packaged build: `%APPDATA%\Scratch\telemetry.json` 148 | - Windows, non-packaged: `%APPDATA%\Electron\telemetry.json` 149 | - macOS, packaged build: `~/Library/Application Support/Scratch/telemetry.json` or 150 | `~/Library/Containers/edu.mit.scratch.scratch-desktop/Data/Library/Application Support/Scratch/telemetry.json` 151 | - macOS, non-packaged build: `~/Library/Application Support/Electron/telemetry.json` or 152 | `~/Library/Containers/edu.mit.scratch.scratch-desktop/Data/Library/Application Support/Electron/telemetry.json` 153 | 154 | Deleting this file will: 155 | 156 | - Remove any pending telemetry packets 157 | - Reset the opt in/out state: the app should display the opt in/out modal on next launch 158 | - Remove the random client UUID: the app will generate a new one on next launch 159 | -------------------------------------------------------------------------------- /TRADEMARK: -------------------------------------------------------------------------------- 1 | The Scratch trademarks, including the Scratch name, logo, the Scratch Cat, Gobo, Pico, Nano, Tera and Giga graphics (the "Marks"), are property of the Scratch Foundation. Marks may not be used to endorse or promote products derived from this software without specific prior written permission. 2 | -------------------------------------------------------------------------------- /buildResources/.gitignore: -------------------------------------------------------------------------------- 1 | /ScratchDesktop.iconset 2 | /tmp 3 | -------------------------------------------------------------------------------- /buildResources/ScratchDesktop.icns: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-desktop/2d1fee1723baca029f6168ffd8791eb601fd5a36/buildResources/ScratchDesktop.icns -------------------------------------------------------------------------------- /buildResources/ScratchDesktop.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-desktop/2d1fee1723baca029f6168ffd8791eb601fd5a36/buildResources/ScratchDesktop.ico -------------------------------------------------------------------------------- /buildResources/appx/Square150x150Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-desktop/2d1fee1723baca029f6168ffd8791eb601fd5a36/buildResources/appx/Square150x150Logo.png -------------------------------------------------------------------------------- /buildResources/appx/Square44x44Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-desktop/2d1fee1723baca029f6168ffd8791eb601fd5a36/buildResources/appx/Square44x44Logo.png -------------------------------------------------------------------------------- /buildResources/appx/StoreLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-desktop/2d1fee1723baca029f6168ffd8791eb601fd5a36/buildResources/appx/StoreLogo.png -------------------------------------------------------------------------------- /buildResources/appx/Wide310x150Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-desktop/2d1fee1723baca029f6168ffd8791eb601fd5a36/buildResources/appx/Wide310x150Logo.png -------------------------------------------------------------------------------- /buildResources/entitlements.mac.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.cs.allow-dyld-environment-variables 6 | 7 | com.apple.security.cs.allow-jit 8 | 9 | com.apple.security.cs.allow-unsigned-executable-memory 10 | 11 | com.apple.security.device.audio-input 12 | 13 | com.apple.security.device.camera 14 | 15 | com.apple.security.device.microphone 16 | 17 | com.apple.security.device.usb 18 | 19 | com.apple.security.files.user-selected.read-only 20 | 21 | com.apple.security.files.user-selected.read-write 22 | 23 | com.apple.security.network.client 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /buildResources/entitlements.mas.inherit.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.inherit 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /buildResources/entitlements.mas.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.cs.allow-dyld-environment-variables 8 | 9 | com.apple.security.cs.allow-jit 10 | 11 | com.apple.security.cs.allow-unsigned-executable-memory 12 | 13 | com.apple.security.device.audio-input 14 | 15 | com.apple.security.device.camera 16 | 17 | com.apple.security.device.microphone 18 | 19 | com.apple.security.device.usb 20 | 21 | com.apple.security.files.user-selected.read-only 22 | 23 | com.apple.security.files.user-selected.read-write 24 | 25 | com.apple.security.network.client 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /buildResources/make-icons.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | SRC=../src/icon/ScratchDesktop.svg 3 | OUT_ICONSET=ScratchDesktop.iconset 4 | OUT_ICNS=ScratchDesktop.icns 5 | OUT_ICO=ScratchDesktop.ico 6 | TMP_ICO=tmp 7 | 8 | ICO_BASIC_SIZES="16 24 32 48 256" 9 | ICO_EXTRA_SIZES="20 30 36 40 60 64 72 80 96 512" 10 | 11 | if command -v pngcrush >/dev/null 2>&1; then 12 | function optimize () { 13 | pngcrush -new -brute -ow "$@" 14 | } 15 | else 16 | echo "pngcrush is not available - skipping PNG optimization" 17 | function optimize () { 18 | echo "Not optimizing:" "$@" 19 | } 20 | fi 21 | 22 | # usage: resize newWidth newHeight input output [otherOptions...] 23 | function resize () { 24 | WIDTH=$1 25 | HEIGHT=$2 26 | SRC=$3 27 | DST=$4 28 | shift 4 29 | convert -background none -resize "${WIDTH}x${HEIGHT}" -extent "${WIDTH}x${HEIGHT}" -gravity center "$@" "${SRC}" "${DST}" 30 | optimize "${DST}" 31 | } 32 | 33 | if command -v convert >/dev/null 2>&1; then 34 | # Mac 35 | if command -v iconutil >/dev/null 2>&1; then 36 | mkdir -p "${OUT_ICONSET}" 37 | for SIZE in 16 32 128 256 512; do 38 | SIZE2=`expr "${SIZE}" '*' 2` 39 | resize "${SIZE}" "${SIZE}" "${SRC}" "${OUT_ICONSET}/icon_${SIZE}x${SIZE}.png" -density 72 -units PixelsPerInch 40 | resize "${SIZE2}" "${SIZE2}" "${SRC}" "${OUT_ICONSET}/icon_${SIZE}x${SIZE}@2x.png" -density 144 -units PixelsPerInch 41 | done 42 | iconutil -c icns --output "${OUT_ICNS}" "${OUT_ICONSET}" 43 | else 44 | echo "iconutil is not available - skipping ICNS and ICONSET" 45 | fi 46 | 47 | # Windows ICO 48 | mkdir -p "${TMP_ICO}" 49 | for SIZE in ${ICO_BASIC_SIZES} ${ICO_EXTRA_SIZES}; do 50 | resize "${SIZE}" "${SIZE}" "${SRC}" "${TMP_ICO}/icon_${SIZE}x${SIZE}.png" 51 | done 52 | # Asking for "Zip" compression actually results in PNG compression 53 | convert "${TMP_ICO}"/icon_*.png -colorspace sRGB -compress Zip "${OUT_ICO}" 54 | 55 | # Windows AppX 56 | mkdir -p "appx" 57 | resize 44 44 "${SRC}" 'appx/Square44x44Logo.png' 58 | resize 50 50 "${SRC}" 'appx/StoreLogo.png' 59 | resize 150 150 "${SRC}" 'appx/Square150x150Logo.png' 60 | resize 310 150 "${SRC}" 'appx/Wide310x150Logo.png' 61 | else 62 | echo "ImageMagick is not available - cannot convert icons" 63 | fi 64 | -------------------------------------------------------------------------------- /buildResources/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-desktop/2d1fee1723baca029f6168ffd8791eb601fd5a36/buildResources/screenshot.png -------------------------------------------------------------------------------- /electron-builder.yaml: -------------------------------------------------------------------------------- 1 | directories: 2 | buildResources: buildResources 3 | output: dist 4 | appId: edu.mit.scratch.scratch-desktop 5 | productName: "Scratch 3" 6 | publish: # empty provider list = don't publish 7 | files: 8 | - dist/main/ 9 | - dist/renderer/ 10 | - package.json 11 | extraResources: # copy the downloaded static assets to make sure they are available for the artifact 12 | - from: static/ 13 | to: static/ 14 | filter: 15 | - "**/*" 16 | mac: 17 | category: public.app-category.education 18 | entitlements: buildResources/entitlements.mac.plist 19 | extendInfo: 20 | ITSAppUsesNonExemptEncryption: false 21 | NSCameraUsageDescription: >- 22 | This app requires camera access when using the video sensing blocks. 23 | NSMicrophoneUsageDescription: >- 24 | This app requires microphone access when recording sounds or detecting loudness. 25 | gatekeeperAssess: true 26 | hardenedRuntime: true 27 | icon: buildResources/ScratchDesktop.icns 28 | provisioningProfile: build/AppStore_edu.mit.scratch.scratch-desktop.provisionprofile 29 | artifactName: "Scratch ${version}.${ext}" 30 | target: 31 | - dmg 32 | - mas 33 | dmg: 34 | title: "Scratch ${version}" 35 | mas: 36 | category: public.app-category.education 37 | entitlements: buildResources/entitlements.mas.plist 38 | entitlementsInherit: buildResources/entitlements.mas.inherit.plist 39 | hardenedRuntime: false 40 | icon: buildResources/ScratchDesktop.icns 41 | masDev: 42 | type: development 43 | provisioningProfile: build/Development_edu.mit.scratch.scratch-desktop.provisionprofile 44 | win: 45 | icon: buildResources/ScratchDesktop.ico 46 | target: 47 | - appx 48 | - nsis 49 | appx: 50 | identityName: ScratchFoundation.ScratchDesktop 51 | publisherDisplayName: "Scratch Foundation" 52 | publisher: "CN=2EC43DF1-469A-4119-9AB9-568A0A1FF65F" 53 | artifactName: "Scratch ${version} ${arch}.${ext}" 54 | nsis: 55 | oneClick: false # allow user to choose per-user or per-machine 56 | artifactName: "Scratch ${version} Setup.${ext}" 57 | linux: 58 | target: AppImage 59 | executableName: scratch-desktop 60 | # Currently Linux builds are supported only for development and have 61 | # not been tested in a production environment. 62 | category: development 63 | # Ensure sandbox permissions are set 64 | asarUnpack: 65 | - chrome-sandbox 66 | -------------------------------------------------------------------------------- /fastlane/Appfile: -------------------------------------------------------------------------------- 1 | app_identifier("edu.mit.scratch.scratch-desktop") # The bundle identifier of your app 2 | apple_id("bot-apple@scratch.mit.edu") # Your Apple email address 3 | team_id(ENV.fetch("AC_TEAM_ID")) 4 | -------------------------------------------------------------------------------- /fastlane/Fastfile: -------------------------------------------------------------------------------- 1 | # This file contains the fastlane.tools configuration 2 | # You can find the documentation at https://docs.fastlane.tools 3 | # 4 | # For a list of all available actions, check out 5 | # 6 | # https://docs.fastlane.tools/actions 7 | # 8 | # For a list of all available plugins, check out 9 | # 10 | # https://docs.fastlane.tools/plugins/available-plugins 11 | # 12 | 13 | # Uncomment the line if you want fastlane to automatically update itself 14 | # update_fastlane 15 | 16 | default_platform(:mac) 17 | 18 | platform :mac do 19 | desc "Use Fastlane Match to install development certificates" 20 | lane :match_dev do 21 | match(type: "development", platform: "macos", output_path: "build", readonly: is_ci) 22 | end 23 | 24 | desc "Use Fastlane Match to install distribution certificates" 25 | lane :match_dist do 26 | match(type: "appstore", platform: "macos", output_path: "build", readonly: is_ci, additional_cert_types: "mac_installer_distribution") 27 | match(type: "developer_id", platform: "macos", output_path: "build", readonly: is_ci, additional_cert_types: "developer_id_installer") 28 | end 29 | 30 | desc "Prepare for a CircleCI signed build" 31 | lane :circleci do 32 | setup_circle_ci 33 | match_dev 34 | match_dist 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /fastlane/Matchfile: -------------------------------------------------------------------------------- 1 | git_url(ENV.fetch("GIT_URL")) 2 | storage_mode(ENV.fetch("STORAGE_MODE")) 3 | type("development") # The default type, can be: appstore, adhoc, enterprise or development 4 | # app_identifier(["tools.fastlane.app", "tools.fastlane.app2"]) 5 | # username("user@fastlane.tools") # Your Apple Developer Portal username 6 | app_identifier("edu.mit.scratch.scratch-desktop") # The bundle identifier of your app 7 | username("bot-apple@scratch.mit.edu") # Your Apple email address 8 | -------------------------------------------------------------------------------- /fastlane/README-match.md: -------------------------------------------------------------------------------- 1 | # Fastlane Match setup 2 | 3 | ## You might not need to do this! 4 | 5 | If you don't plan to build this application, you don't need Fastlane Match. 6 | 7 | If you don't plan to build this application for macOS, you don't need Fastlane Match. 8 | 9 | If you plan to only run your builds locally for your own debug purposes, you don't need Fastlane Match. 10 | 11 | If you don't have access to a Fastlane Match storage repository or bucket, you don't need Fastlane Match. 12 | 13 | ## Initial Configuration 14 | 15 | The `Matchfile` containing settings for Fastlane Match includes private information about our storage, so it's set to be ignored by `git`. 16 | 17 | This means that you'll need to initialize Fastlane Match yourself when you clone this repository in a new place. 18 | 19 | To initialize Fastlane Match: 20 | 21 | 1. Enter this repository's base directory (not the `fastlane` subdirectory) 22 | 2. Run `fastlane match init` and answer the questions 23 | 24 | ...yep, that's it. 25 | 26 | ## Obtaining & Updating Certs 27 | 28 | 1. If you plan to make and internally share development builds for testing purposes, run: 29 | * `fastlane match_dev` 30 | 2. If you plan to make builds for release, run: 31 | * `fastlane match_dist` 32 | -------------------------------------------------------------------------------- /fastlane/README.md: -------------------------------------------------------------------------------- 1 | fastlane documentation 2 | ---- 3 | 4 | # Installation 5 | 6 | Make sure you have the latest version of the Xcode command line tools installed: 7 | 8 | ```sh 9 | xcode-select --install 10 | ``` 11 | 12 | For _fastlane_ installation instructions, see [Installing _fastlane_](https://docs.fastlane.tools/#installing-fastlane) 13 | 14 | # Available Actions 15 | 16 | ## Mac 17 | 18 | ### mac match_dev 19 | 20 | ```sh 21 | [bundle exec] fastlane mac match_dev 22 | ``` 23 | 24 | Use Fastlane Match to install development certificates 25 | 26 | ### mac match_dist 27 | 28 | ```sh 29 | [bundle exec] fastlane mac match_dist 30 | ``` 31 | 32 | Use Fastlane Match to install distribution certificates 33 | 34 | ### mac circleci 35 | 36 | ```sh 37 | [bundle exec] fastlane mac circleci 38 | ``` 39 | 40 | Prepare for a CircleCI signed build 41 | 42 | ---- 43 | 44 | This README.md is auto-generated and will be re-generated every time [_fastlane_](https://fastlane.tools) is run. 45 | 46 | More information about _fastlane_ can be found on [fastlane.tools](https://fastlane.tools). 47 | 48 | The documentation of _fastlane_ can be found on [docs.fastlane.tools](https://docs.fastlane.tools). 49 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scratch-desktop", 3 | "productName": "Scratch", 4 | "description": "Scratch 3.0 as a self-contained desktop application", 5 | "author": "Scratch Foundation", 6 | "version": "3.31.1", 7 | "license": "AGPL-3.0-only", 8 | "main": "./dist/main/main.js", 9 | "scripts": { 10 | "clean": "rimraf ./dist ./static/fetched", 11 | "start": "node scripts/start.js", 12 | "compile:renderer": "webpack --config webpack.renderer.js", 13 | "compile:main": "webpack --config webpack.main.js", 14 | "compile": "npm run compile:renderer && npm run compile:main", 15 | "fetch": "rimraf ./static/fetched/ && mkdirp ./static/fetched/ && node ./scripts/fetchMediaLibraryAssets.js", 16 | "build": "npm run build:dev", 17 | "build:dev": "cross-env NODE_ENV=production npm run compile && npm run doBuild -- --mode=dev", 18 | "build:dir": "cross-env NODE_ENV=production npm run compile && npm run doBuild -- --mode=dir", 19 | "build:dist": "cross-env NODE_ENV=production npm run compile && npm run doBuild -- --mode=dist", 20 | "doBuild": "node ./scripts/electron-builder-wrapper.js", 21 | "dist": "npm run clean && npm run fetch && npm run build:dist", 22 | "distDev": "npm run clean && npm run fetch && npm run build:dev", 23 | "test": "npm run test:lint", 24 | "test:lint": "eslint --cache --color --ext .jsx,.js ." 25 | }, 26 | "repository": { 27 | "type": "git", 28 | "url": "git+ssh://git@github.com/scratchfoundation/scratch-desktop.git" 29 | }, 30 | "dependencies": { 31 | "source-map-support": "0.5.19" 32 | }, 33 | "devDependencies": { 34 | "@babel/core": "7.27.3", 35 | "@babel/plugin-proposal-object-rest-spread": "7.20.7", 36 | "@babel/plugin-syntax-dynamic-import": "7.8.3", 37 | "@babel/plugin-transform-async-to-generator": "7.27.1", 38 | "@babel/plugin-transform-nullish-coalescing-operator": "7.27.1", 39 | "@babel/plugin-transform-optional-chaining": "7.27.1", 40 | "@babel/preset-env": "7.27.2", 41 | "@babel/preset-react": "7.27.1", 42 | "@scratch/scratch-gui": "11.2.0-svg-sanitization.2", 43 | "async": "3.2.6", 44 | "autoprefixer": "10.4.21", 45 | "babel-eslint": "10.1.0", 46 | "babel-loader": "9.2.1", 47 | "babel-plugin-react-intl": "7.9.4", 48 | "chalk": "4.1.2", 49 | "copy-webpack-plugin": "6.4.1", 50 | "cross-env": "7.0.3", 51 | "css-loader": "5.2.7", 52 | "electron": "25.9.8", 53 | "electron-builder": "26.0.12", 54 | "electron-devtools-installer": "3.2.1", 55 | "electron-notarize": "1.2.2", 56 | "electron-store": "8.2.0", 57 | "eslint": "8.57.1", 58 | "eslint-config-scratch": "9.0.9", 59 | "eslint-plugin-import": "2.31.0", 60 | "eslint-plugin-react": "7.37.5", 61 | "fs-extra": "9.1.0", 62 | "html-loader": "0.5.5", 63 | "html-webpack-plugin": "5.6.3", 64 | "intl": "1.2.5", 65 | "lodash.bindall": "4.4.0", 66 | "lodash.defaultsdeep": "4.6.1", 67 | "lodash.omit": "4.5.0", 68 | "mini-css-extract-plugin": "1.6.2", 69 | "minilog": "3.1.0", 70 | "minimist": "1.2.8", 71 | "mkdirp": "1.0.4", 72 | "nets": "3.2.0", 73 | "postcss-import": "12.0.1", 74 | "postcss-loader": "4.3.0", 75 | "postcss-simple-vars": "5.0.2", 76 | "react": "16.14.0", 77 | "react-dom": "16.14.0", 78 | "react-intl": "2.9.0", 79 | "react-redux": "5.1.2", 80 | "redux": "3.7.2", 81 | "rimraf": "3.0.2", 82 | "style-loader": "4.0.0", 83 | "url-loader": "4.1.1", 84 | "uuid": "8.3.2", 85 | "wait-on": "8.0.3", 86 | "webpack": "5.99.9", 87 | "webpack-cli": "5.1.4", 88 | "webpack-dev-server": "5.2.1", 89 | "webpack-merge": "4.2.2" 90 | }, 91 | "resolutions": { 92 | "upath": "1.2.0" 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /renovate.json5: -------------------------------------------------------------------------------- 1 | { 2 | $schema: 'https://docs.renovatebot.com/renovate-schema.json', 3 | extends: [ 4 | 'github>scratchfoundation/scratch-renovate-config:js-app', 5 | ], 6 | } 7 | -------------------------------------------------------------------------------- /scripts/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | rules: { 3 | 'no-console': 'off' 4 | } 5 | }; 6 | -------------------------------------------------------------------------------- /scripts/afterSign.js: -------------------------------------------------------------------------------- 1 | const {notarize} = require('electron-notarize'); 2 | 3 | const notarizeMacBuild = async function (context) { 4 | // keep this in sync with appId in the electron-builder config 5 | const appId = 'edu.mit.scratch.scratch-desktop'; 6 | 7 | if (!process.env.AC_USERNAME) { 8 | console.error([ 9 | 'This build is not notarized and will not run on newer versions of macOS!', 10 | 'Notarizing the macOS build requires an Apple ID. To notarize future builds:', 11 | '* Set the environment variable AC_USERNAME to your@apple.id and', 12 | '* Either set AC_PASSWORD or ensure your keychain has an item for "Application Loader: your@apple.id"' 13 | ].join('\n')); 14 | return; 15 | } 16 | 17 | const appleId = process.env.AC_USERNAME; 18 | const appleIdKeychainItem = `Application Loader: ${appleId}`; 19 | 20 | if (process.env.AC_PASSWORD) { 21 | console.log(`Notarizing with Apple ID "${appleId}" and a password`); 22 | } else { 23 | console.log(`Notarizing with Apple ID "${appleId}" and keychain item "${appleIdKeychainItem}"`); 24 | } 25 | 26 | const {appOutDir} = context; 27 | const productFilename = context.packager.appInfo.productFilename; 28 | await notarize({ 29 | appBundleId: appId, 30 | appPath: `${appOutDir}/${productFilename}.app`, 31 | appleId, 32 | appleIdPassword: process.env.AC_PASSWORD || `@keychain:${appleIdKeychainItem}`, 33 | teamId: process.env.AC_TEAM_ID || '', 34 | tool: 'notarytool' 35 | }); 36 | }; 37 | 38 | const afterSign = async function (context) { 39 | const {electronPlatformName} = context; 40 | 41 | switch (electronPlatformName) { 42 | case 'mas': // macOS build for Mac App Store 43 | break; 44 | case 'darwin': // macOS build NOT for Mac App Store 45 | await notarizeMacBuild(context); 46 | break; 47 | } 48 | }; 49 | 50 | module.exports = afterSign; 51 | -------------------------------------------------------------------------------- /scripts/electron-builder-wrapper.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @overview This script runs `electron-builder` with special management of code signing configuration on Windows. 3 | * Running this script with no command line parameters should build all targets for the current platform. 4 | * On Windows, make sure to set CSC_* or WIN_CSC_* environment variables or the NSIS build will fail. 5 | * On Mac, the CSC_* variables are optional but will be respected if present. 6 | * See also: https://www.electron.build/code-signing 7 | */ 8 | 9 | const {spawnSync} = require('child_process'); 10 | const fs = require('fs'); 11 | 12 | const masDevProfile = 'build/Development_edu.mit.scratch.scratch-desktop.provisionprofile'; 13 | 14 | /** 15 | * Strip any code signing configuration (CSC) from a set of environment variables. 16 | * @param {object} environment - a collection of environment variables which might include code signing configuration. 17 | * @returns {object} - a collection of environment variables which does not include code signing configuration. 18 | */ 19 | const stripCSC = function (environment) { 20 | const { 21 | CSC_LINK: _CSC_LINK, 22 | CSC_KEY_PASSWORD: _CSC_KEY_PASSWORD, 23 | WIN_CSC_LINK: _WIN_CSC_LINK, 24 | WIN_CSC_KEY_PASSWORD: _WIN_CSC_KEY_PASSWORD, 25 | ...strippedEnvironment 26 | } = environment; 27 | return strippedEnvironment; 28 | }; 29 | 30 | /** 31 | * @returns {string} - an `electron-builder` flag to build for the current platform, based on `process.platform`. 32 | */ 33 | const getPlatformFlag = function () { 34 | switch (process.platform) { 35 | case 'win32': return '--windows'; 36 | case 'darwin': return '--macos'; 37 | case 'linux': return '--linux'; 38 | } 39 | throw new Error(`Could not determine platform flag for platform: ${process.platform}`); 40 | }; 41 | 42 | /** 43 | * Run `electron-builder` once to build one or more target(s). 44 | * @param {object} wrapperConfig - overall configuration object for the wrapper script. 45 | * @param {object} target - the target to build in this call. 46 | * If the `target.name` is `'nsis'` then the environment must contain code-signing config (CSC_* or WIN_CSC_*). 47 | * If the `target.name` is `'appx'` then code-signing config will be stripped from the environment if present. 48 | */ 49 | const runBuilder = function (wrapperConfig, target) { 50 | // the AppX build fails if CSC_* or WIN_CSC_* variables are set 51 | const shouldStripCSC = (target.name.indexOf('appx') === 0) || (!wrapperConfig.doSign); 52 | const childEnvironment = shouldStripCSC ? stripCSC(process.env) : process.env; 53 | if (wrapperConfig.doSign && 54 | (target.name.indexOf('nsis') === 0) && 55 | !(childEnvironment.CSC_LINK || childEnvironment.WIN_CSC_LINK)) { 56 | throw new Error(`Signing NSIS build requires CSC_LINK or WIN_CSC_LINK`); 57 | } 58 | const platformFlag = getPlatformFlag(); 59 | let allArgs = [platformFlag, target.name]; 60 | if (target.platform === 'darwin') { 61 | allArgs.push(`--c.mac.type=${wrapperConfig.mode === 'dist' ? 'distribution' : 'development'}`); 62 | // this needs to be built on an arm64 mac, in order for the executable to be able 63 | // to run on both x86-64 and arm64 architectures. 64 | allArgs.push('--universal'); 65 | if (target.name === 'mas-dev') { 66 | allArgs.push(`--c.mac.provisioningProfile=${masDevProfile}`); 67 | } 68 | if (wrapperConfig.doSign) { 69 | // really this is "notarize only if we also sign" 70 | allArgs.push('--c.afterSign=scripts/afterSign.js'); 71 | } else { 72 | allArgs.push('--c.mac.identity=null'); 73 | } 74 | } 75 | if (!wrapperConfig.doPackage) { 76 | allArgs.push('--dir', '--c.compression=store'); 77 | } 78 | allArgs = allArgs.concat(wrapperConfig.builderArgs); 79 | console.log(`running electron-builder with arguments: ${allArgs}`); 80 | const result = spawnSync('electron-builder', allArgs, { 81 | env: childEnvironment, 82 | shell: true, 83 | stdio: 'inherit' 84 | }); 85 | if (result.error) { 86 | throw result.error; 87 | } 88 | if (result.signal) { 89 | throw new Error(`Child process terminated due to signal ${result.signal}`); 90 | } 91 | if (result.status) { 92 | throw new Error(`Child process returned status code ${result.status}`); 93 | } 94 | }; 95 | 96 | /** 97 | * @param {object} wrapperConfig - overall configuration object for the wrapper script. 98 | * @returns {Array.} - the default list of targets on this platform. Each item in the array represents one 99 | * call to `runBuilder` for exactly one build target. In theory electron-builder can build two or more targets at the 100 | * same time but doing so limits has unwanted side effects on both macOS and Windows (see function body). 101 | */ 102 | const calculateTargets = function (wrapperConfig) { 103 | const availableTargets = { 104 | macAppStore: { 105 | name: 'mas', 106 | platform: 'darwin' 107 | }, 108 | macAppStoreDev: { 109 | name: 'mas-dev', 110 | platform: 'darwin' 111 | }, 112 | macDirectDownload: { 113 | name: 'dmg', 114 | platform: 'darwin' 115 | }, 116 | microsoftStore: { 117 | name: 'appx:ia32 appx:x64', 118 | platform: 'win32' 119 | }, 120 | windowsDirectDownload: { 121 | name: 'nsis:ia32', 122 | platform: 'win32' 123 | }, 124 | linuxAppImage: { 125 | name: 'appimage', 126 | platform: 'linux' 127 | } 128 | }; 129 | const targets = []; 130 | switch (process.platform) { 131 | case 'win32': 132 | // Run in two passes so we can skip signing the AppX for distribution through the MS Store. 133 | targets.push(availableTargets.microsoftStore); 134 | targets.push(availableTargets.windowsDirectDownload); 135 | break; 136 | case 'darwin': 137 | // Running 'dmg' and 'mas' in the same pass causes electron-builder to skip signing the non-MAS app copy. 138 | // Running them as separate passes means they can both get signed. 139 | // Seems like a bug in electron-builder... 140 | // Running the 'mas' build first means that its output is available while we wait for 'dmg' notarization. 141 | // Add macAppStoreDev here to test a MAS-like build locally. You'll need a Mac Developer provisioning profile. 142 | if (fs.existsSync(masDevProfile)) { 143 | targets.push(availableTargets.macAppStoreDev); 144 | } else { 145 | console.log(`skipping target "${availableTargets.macAppStoreDev.name}": ${masDevProfile} missing`); 146 | } 147 | if (wrapperConfig.doSign) { 148 | targets.push(availableTargets.macAppStore); 149 | } else { 150 | // electron-builder doesn't seem to support this configuration even if mac.type is "development" 151 | console.log(`skipping target "${availableTargets.macAppStore.name}" because code-signing is disabled`); 152 | } 153 | targets.push(availableTargets.macDirectDownload); 154 | break; 155 | case 'linux': 156 | targets.push(availableTargets.linuxAppImage); 157 | break; 158 | default: 159 | throw new Error(`Could not determine targets for platform: ${process.platform}`); 160 | } 161 | return targets; 162 | }; 163 | 164 | const parseArgs = function () { 165 | const scriptArgs = process.argv.slice(2); // remove `node` and `this-script.js` 166 | const builderArgs = []; 167 | let mode = 'dev'; // default 168 | 169 | for (const arg of scriptArgs) { 170 | const modeSplit = arg.split(/--mode(\s+|=)/); 171 | if (modeSplit.length === 3) { 172 | mode = modeSplit[2]; 173 | } else { 174 | builderArgs.push(arg); 175 | } 176 | } 177 | 178 | let doPackage; 179 | let doSign; 180 | 181 | switch (mode) { 182 | case 'dev': 183 | doPackage = true; 184 | doSign = false; 185 | break; 186 | case 'dir': 187 | doPackage = false; 188 | doSign = false; 189 | break; 190 | case 'dist': 191 | doPackage = true; 192 | doSign = true; 193 | } 194 | 195 | return { 196 | builderArgs, 197 | doPackage, // false = build to directory 198 | doSign, 199 | mode 200 | }; 201 | }; 202 | 203 | const main = function () { 204 | const wrapperConfig = parseArgs(); 205 | 206 | // TODO: allow user to specify targets? We could theoretically build NSIS on Mac, for example. 207 | wrapperConfig.targets = calculateTargets(wrapperConfig); 208 | 209 | for (const target of wrapperConfig.targets) { 210 | runBuilder(wrapperConfig, target); 211 | } 212 | }; 213 | 214 | main(); 215 | -------------------------------------------------------------------------------- /scripts/fetchMediaLibraryAssets.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const https = require('https'); 3 | const path = require('path'); 4 | const util = require('util'); 5 | 6 | const async = require('async'); 7 | 8 | const libraries = require('./lib/libraries'); 9 | 10 | const ASSET_HOST = 'cdn.assets.scratch.mit.edu'; 11 | const NUM_SIMULTANEOUS_DOWNLOADS = 5; 12 | const OUT_PATH = path.resolve('static', 'fetched'); 13 | 14 | 15 | const describe = function (object) { 16 | return util.inspect(object, false, Infinity, true); 17 | }; 18 | 19 | const collectSimple = function (library, dest, debugLabel = 'Item') { 20 | library.forEach(item => { 21 | let md5Count = 0; 22 | if (item.md5) { 23 | ++md5Count; 24 | dest.add(item.md5); 25 | } 26 | if (item.baseLayerMD5) { // 2.0 library syntax for costumes 27 | ++md5Count; 28 | dest.add(item.baseLayerMD5); 29 | } 30 | if (item.md5ext) { // 3.0 library syntax for costumes 31 | ++md5Count; 32 | dest.add(item.md5ext); 33 | } 34 | if (md5Count < 1) { 35 | console.warn(`${debugLabel} has no MD5 property:\n${describe(item)}`); 36 | } else if (md5Count > 1) { 37 | // is this actually bad? 38 | console.warn(`${debugLabel} has multiple MD5 properties:\n${describe(item)}`); 39 | } 40 | }); 41 | return dest; 42 | }; 43 | 44 | const collectAssets = function (dest) { 45 | collectSimple(libraries.backdrops, dest, 'Backdrop'); 46 | collectSimple(libraries.costumes, dest, 'Costume'); 47 | collectSimple(libraries.sounds, dest, 'Sound'); 48 | libraries.sprites.forEach(sprite => { 49 | if (sprite.costumes) { 50 | collectSimple(sprite.costumes, dest, `Costume for sprite ${sprite.name}`); 51 | } 52 | if (sprite.sounds) { 53 | collectSimple(sprite.sounds, dest, `Sound for sprite ${sprite.name}`); 54 | } 55 | }); 56 | return dest; 57 | }; 58 | 59 | const connectionPool = []; 60 | 61 | const fetchAsset = function (md5, callback) { 62 | const myAgent = connectionPool.pop() || new https.Agent({keepAlive: true}); 63 | const getOptions = { 64 | host: ASSET_HOST, 65 | path: `/internalapi/asset/${md5}/get/`, 66 | agent: myAgent 67 | }; 68 | const urlHuman = `//${getOptions.host}${getOptions.path}`; 69 | https.get(getOptions, response => { 70 | if (response.statusCode !== 200) { 71 | callback(new Error(`Request failed: status code ${response.statusCode} for ${urlHuman}`)); 72 | return; 73 | } 74 | 75 | const stream = fs.createWriteStream(path.resolve(OUT_PATH, md5), {encoding: 'binary'}); 76 | stream.on('error', callback); 77 | response.on('data', chunk => { 78 | stream.write(chunk); 79 | }); 80 | response.on('end', () => { 81 | connectionPool.push(myAgent); 82 | stream.end(); 83 | console.log(`Fetched ${urlHuman}`); 84 | callback(); 85 | }); 86 | }); 87 | }; 88 | 89 | const fetchAllAssets = function () { 90 | const allAssets = collectAssets(new Set()); 91 | console.log(`Total library assets: ${allAssets.size}`); 92 | 93 | async.forEachLimit(allAssets, NUM_SIMULTANEOUS_DOWNLOADS, fetchAsset, err => { 94 | if (err) { 95 | console.error(`Fetch failed:\n${describe(err)}`); 96 | } else { 97 | console.log('Fetch succeeded.'); 98 | } 99 | 100 | console.log(`Shutting down ${connectionPool.length} agents.`); 101 | while (connectionPool.length > 0) { 102 | connectionPool.pop().destroy(); 103 | } 104 | }); 105 | }; 106 | 107 | fetchAllAssets(); 108 | -------------------------------------------------------------------------------- /scripts/lib/libraries.js: -------------------------------------------------------------------------------- 1 | const backdrops = require('@scratch/scratch-gui/backdrops'); 2 | const costumes = require('@scratch/scratch-gui/costumes'); 3 | const sounds = require('@scratch/scratch-gui/sounds'); 4 | const sprites = require('@scratch/scratch-gui/sprites'); 5 | 6 | const libraries = { 7 | backdrops, 8 | costumes, 9 | sounds, 10 | sprites 11 | }; 12 | 13 | module.exports = libraries; 14 | -------------------------------------------------------------------------------- /scripts/start.js: -------------------------------------------------------------------------------- 1 | const {spawn} = require('child_process'); 2 | const webpack = require('webpack'); 3 | const WebpackDevServer = require('webpack-dev-server'); 4 | const chalk = require('chalk'); 5 | const waitOn = require('wait-on'); 6 | 7 | const rendererConfig = require('../webpack.renderer.js'); 8 | 9 | const PORT = process.env.PORT || 8601; 10 | 11 | const buildRenderer = () => new Promise((resolve, reject) => { 12 | console.log(chalk.cyan('Building renderer process...')); 13 | 14 | const compiler = webpack(rendererConfig); 15 | compiler.run((err, stats) => { 16 | if (err || stats.hasErrors()) { 17 | console.error(chalk.red('Renderer build failed:', err || stats.toString())); 18 | reject(err || new Error('Renderer build failed.')); 19 | } else { 20 | console.log(chalk.green('Renderer built successfully!')); 21 | resolve(); 22 | } 23 | }); 24 | }); 25 | 26 | const startRenderer = async () => { 27 | console.log(chalk.cyan('Starting Webpack Dev Server...')); 28 | 29 | const compiler = webpack(rendererConfig); 30 | const server = new WebpackDevServer( 31 | { 32 | hot: true, 33 | compress: true, 34 | port: PORT, 35 | headers: {'Access-Control-Allow-Origin': '*'}, 36 | historyApiFallback: true 37 | }, 38 | compiler 39 | ); 40 | 41 | try { 42 | await server.start(); 43 | console.log(chalk.green(`Renderer is running at http://localhost:${PORT}`)); 44 | } catch (err) { 45 | console.error(chalk.red('Failed to start Webpack Dev Server:', err)); 46 | throw err; 47 | } 48 | }; 49 | 50 | const startElectron = async () => { 51 | console.log(chalk.cyan('Starting Electron...')); 52 | 53 | await waitOn({resources: [`http://localhost:${PORT}`]}); 54 | 55 | spawn('electron', ['.'], { 56 | stdio: 'inherit', 57 | shell: true 58 | }); 59 | }; 60 | 61 | const start = () => { 62 | console.log(chalk.green('Building main process...')); 63 | 64 | const mainProcess = spawn('npm', ['run', 'compile:main'], { 65 | stdio: 'inherit', 66 | shell: true 67 | }); 68 | 69 | mainProcess.on('exit', async code => { 70 | if (code === 0) { 71 | console.log(chalk.green('Main process built successfully!')); 72 | 73 | await buildRenderer(); 74 | await startRenderer(); 75 | await startElectron(); 76 | } else { 77 | console.log(chalk.red('Main process build failed!')); 78 | process.exit(1); 79 | } 80 | }); 81 | }; 82 | 83 | start(); 84 | -------------------------------------------------------------------------------- /src/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | node: true 5 | }, 6 | extends: ['scratch', 'scratch/es6'], 7 | globals: { 8 | __static: false // electron-webpack provides this constant to access bundled static assets 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /src/common/ElectronStorageHelper.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | 4 | const staticAssets = path.resolve(__static, 'fetched'); 5 | 6 | /** 7 | * Allow the storage module to load files bundled in the Electron application. 8 | */ 9 | class ElectronStorageHelper { 10 | constructor (storageInstance) { 11 | this.parent = storageInstance; 12 | } 13 | 14 | /** 15 | * Fetch an asset but don't process dependencies. 16 | * @param {AssetType} assetType - The type of asset to fetch. 17 | * @param {string} assetId - The ID of the asset to fetch: a project ID, MD5, etc. 18 | * @param {DataFormat} dataFormat - The file format / file extension of the asset to fetch: PNG, JPG, etc. 19 | * @return {Promise.} A promise for the contents of the asset. 20 | */ 21 | load (assetType, assetId, dataFormat) { 22 | assetId = path.basename(assetId); 23 | dataFormat = path.basename(dataFormat); 24 | 25 | return new Promise((resolve, reject) => { 26 | fs.readFile( 27 | path.resolve(staticAssets, `${assetId}.${dataFormat}`), 28 | (err, data) => { 29 | if (err) { 30 | reject(err); 31 | } else { 32 | resolve(new this.parent.Asset(assetType, assetId, dataFormat, data)); 33 | } 34 | } 35 | ); 36 | }); 37 | } 38 | } 39 | 40 | module.exports = ElectronStorageHelper; 41 | -------------------------------------------------------------------------------- /src/common/log.js: -------------------------------------------------------------------------------- 1 | import minilog from 'minilog'; 2 | minilog.enable(); 3 | 4 | const namespace = (() => { 5 | switch (process.type) { 6 | case 'browser': return 'main'; 7 | case 'renderer': return 'web'; 8 | default: return process.type; // probably 'worker' for a web worker 9 | } 10 | })(); 11 | 12 | export default minilog(`app-${namespace}`); 13 | -------------------------------------------------------------------------------- /src/icon/ScratchDesktop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scratchfoundation/scratch-desktop/2d1fee1723baca029f6168ffd8791eb601fd5a36/src/icon/ScratchDesktop.png -------------------------------------------------------------------------------- /src/icon/ScratchDesktop.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Master 1024x1024 5 | Created with Sketch. 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/main/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | node: true 5 | }, 6 | extends: ['scratch', 'scratch/es6', 'scratch/node'] 7 | }; 8 | -------------------------------------------------------------------------------- /src/main/FileFilters.js: -------------------------------------------------------------------------------- 1 | const saveFilters = { 2 | JPEG: { 3 | name: 'JPEG Image', 4 | extensions: ['jpg', 'jpeg'] 5 | }, 6 | MP3: { 7 | name: 'MP3 Sound', 8 | extensions: ['mp3'] 9 | }, 10 | PNG: { 11 | name: 'PNG Image', 12 | extensions: ['png'] 13 | }, 14 | SB: { 15 | name: 'Scratch 1 Project', 16 | extensions: ['sb'] 17 | }, 18 | SB2: { 19 | name: 'Scratch 2 Project', 20 | extensions: ['sb2'] 21 | }, 22 | SB3: { 23 | name: 'Scratch 3 Project', 24 | extensions: ['sb3'] 25 | }, 26 | Sprite2: { 27 | name: 'Scratch 2 Sprite', 28 | extensions: ['sprite2'] 29 | }, 30 | Sprite3: { 31 | name: 'Scratch 3 Sprite', 32 | extensions: ['sprite3'] 33 | }, 34 | SVG: { 35 | name: 'SVG Image', 36 | extensions: ['svg'] 37 | }, 38 | WAV: { 39 | name: 'WAV Sound', 40 | extensions: ['wav'] 41 | } 42 | }; 43 | 44 | const loadFilters = { 45 | ...saveFilters, 46 | AllBitmaps: { 47 | name: 'All Bitmaps', 48 | extensions: [ 49 | ...saveFilters.JPEG.extensions, 50 | ...saveFilters.PNG.extensions 51 | ] 52 | }, 53 | AllImages: { 54 | name: 'All Images', 55 | extensions: [ 56 | ...saveFilters.JPEG.extensions, 57 | ...saveFilters.PNG.extensions, 58 | ...saveFilters.SVG.extensions 59 | ] 60 | }, 61 | AllProjects: { 62 | name: 'All Scratch Projects', 63 | extensions: [ 64 | ...saveFilters.SB3.extensions, 65 | ...saveFilters.SB2.extensions, 66 | ...saveFilters.SB.extensions 67 | ] 68 | }, 69 | AllSounds: { 70 | name: 'All Sounds', 71 | extensions: [ 72 | ...saveFilters.MP3.extensions, 73 | ...saveFilters.WAV.extensions 74 | ] 75 | }, 76 | AllSprites: { 77 | name: 'All Sprites', 78 | extensions: [ 79 | ...saveFilters.Sprite3.extensions, 80 | ...saveFilters.Sprite2.extensions 81 | ] 82 | } 83 | }; 84 | 85 | const filtersByExtension = Object.values(saveFilters).reduce((result, filter) => { 86 | for (const extension of filter.extensions) { 87 | result[extension] = filter; 88 | } 89 | return result; 90 | }, {}); 91 | 92 | const getFilterForExtension = extNameNoDot => 93 | filtersByExtension[extNameNoDot] || { 94 | name: `${extNameNoDot.toUpperCase()} Files`, 95 | extensions: [extNameNoDot] 96 | }; 97 | 98 | export { 99 | saveFilters, 100 | loadFilters, 101 | getFilterForExtension 102 | }; 103 | -------------------------------------------------------------------------------- /src/main/MacOSMenu.js: -------------------------------------------------------------------------------- 1 | // Include the standard keyboard shortcuts in the edit menu 2 | // so they can be used within the app. Only needed on Mac. 3 | export default app => ([ 4 | { 5 | label: 'App', // Always overridden by app name 6 | submenu: [{ 7 | label: 'Quit', 8 | accelerator: 'CmdOrCtrl+Q', 9 | click: () => app.quit() 10 | }] 11 | }, 12 | { 13 | label: 'Edit', 14 | submenu: [ 15 | { 16 | label: 'Undo', 17 | accelerator: 'CmdOrCtrl+Z', 18 | role: 'undo' 19 | }, 20 | { 21 | label: 'Redo', 22 | accelerator: 'Shift+CmdOrCtrl+Z', 23 | role: 'redo' 24 | }, 25 | { 26 | type: 'separator' 27 | }, 28 | { 29 | label: 'Cut', 30 | accelerator: 'CmdOrCtrl+X', 31 | role: 'cut' 32 | }, 33 | { 34 | label: 'Copy', 35 | accelerator: 'CmdOrCtrl+C', 36 | role: 'copy' 37 | }, 38 | { 39 | label: 'Paste', 40 | accelerator: 'CmdOrCtrl+V', 41 | role: 'paste' 42 | }, 43 | { 44 | label: 'Select All', 45 | accelerator: 'CmdOrCtrl+A', 46 | role: 'selectall' 47 | } 48 | ] 49 | } 50 | ]); 51 | -------------------------------------------------------------------------------- /src/main/ScratchDesktopTelemetry.js: -------------------------------------------------------------------------------- 1 | import {app, ipcMain} from 'electron'; 2 | import defaultsDeep from 'lodash.defaultsdeep'; 3 | import packageJson from '../../package.json'; 4 | 5 | import TelemetryClient from './telemetry/TelemetryClient'; 6 | 7 | const EVENT_TEMPLATE = { 8 | version: packageJson.version, 9 | projectName: '', 10 | language: '', 11 | metadata: { 12 | scriptCount: -1, 13 | spriteCount: -1, 14 | variablesCount: -1, 15 | blocksCount: -1, 16 | costumesCount: -1, 17 | listsCount: -1, 18 | soundsCount: -1 19 | } 20 | }; 21 | 22 | const APP_ID = 'scratch-desktop'; 23 | const APP_VERSION = app.getVersion(); 24 | const APP_INFO = Object.freeze({ 25 | projectName: `${APP_ID} ${APP_VERSION}` 26 | }); 27 | 28 | class ScratchDesktopTelemetry { 29 | constructor () { 30 | this._telemetryClient = new TelemetryClient(); 31 | } 32 | 33 | get didOptIn () { 34 | return this._telemetryClient.didOptIn; 35 | } 36 | set didOptIn (value) { 37 | this._telemetryClient.didOptIn = value; 38 | } 39 | 40 | appWasOpened () { 41 | this._telemetryClient.addEvent('app::open', {...EVENT_TEMPLATE, ...APP_INFO}); 42 | } 43 | 44 | appWillClose () { 45 | this._telemetryClient.addEvent('app::close', {...EVENT_TEMPLATE, ...APP_INFO}); 46 | } 47 | 48 | projectDidLoad (metadata = {}) { 49 | this._telemetryClient.addEvent('project::load', this._buildMetadata(metadata)); 50 | } 51 | 52 | projectDidSave (metadata = {}) { 53 | // Since the save dialog appears on the main process the GUI does not wait for the actual save to complete. 54 | // That means the GUI sends this event before we know the file name used for the save, which is where the new 55 | // project title comes from. Instead, just hold on to this metadata pending a `projectSaveCompleted` event 56 | // from the save code on the main process. If the user cancels the save this data will be cleared. 57 | this._pendingProjectSave = metadata; 58 | } 59 | 60 | projectSaveCompleted (newProjectTitle) { 61 | const metadata = this._pendingProjectSave; 62 | this._pendingProjectSave = null; 63 | 64 | metadata.projectName = newProjectTitle; 65 | this._telemetryClient.addEvent('project::save', this._buildMetadata(metadata)); 66 | } 67 | 68 | projectSaveCanceled () { 69 | this._pendingProjectSave = null; 70 | } 71 | 72 | projectWasCreated (metadata = {}) { 73 | this._telemetryClient.addEvent('project::create', this._buildMetadata(metadata)); 74 | } 75 | 76 | projectWasUploaded (metadata = {}) { 77 | this._telemetryClient.addEvent('project::upload', this._buildMetadata(metadata)); 78 | } 79 | 80 | _buildMetadata (metadata) { 81 | const {projectName, language, ...codeMetadata} = metadata; 82 | return defaultsDeep({ 83 | projectName, 84 | language, 85 | metadata: codeMetadata 86 | }, EVENT_TEMPLATE); 87 | } 88 | } 89 | 90 | // make a singleton so it's easy to share across both Electron processes 91 | const scratchDesktopTelemetrySingleton = new ScratchDesktopTelemetry(); 92 | 93 | // `handle` works with `invoke` 94 | ipcMain.handle('getTelemetryDidOptIn', () => 95 | scratchDesktopTelemetrySingleton.didOptIn 96 | ); 97 | // `on` works with `sendSync` (and `send`) 98 | ipcMain.on('getTelemetryDidOptIn', event => { 99 | event.returnValue = scratchDesktopTelemetrySingleton.didOptIn; 100 | }); 101 | ipcMain.on('setTelemetryDidOptIn', (event, arg) => { 102 | scratchDesktopTelemetrySingleton.didOptIn = arg; 103 | }); 104 | ipcMain.on('projectDidLoad', (event, arg) => { 105 | scratchDesktopTelemetrySingleton.projectDidLoad(arg); 106 | }); 107 | ipcMain.on('projectDidSave', (event, arg) => { 108 | scratchDesktopTelemetrySingleton.projectDidSave(arg); 109 | }); 110 | ipcMain.on('projectWasCreated', (event, arg) => { 111 | scratchDesktopTelemetrySingleton.projectWasCreated(arg); 112 | }); 113 | ipcMain.on('projectWasUploaded', (event, arg) => { 114 | scratchDesktopTelemetrySingleton.projectWasUploaded(arg); 115 | }); 116 | 117 | export default scratchDesktopTelemetrySingleton; 118 | -------------------------------------------------------------------------------- /src/main/argv.js: -------------------------------------------------------------------------------- 1 | import minimist from 'minimist'; 2 | 3 | // inspired by yargs' process-argv 4 | export const isElectronApp = () => !!process.versions.electron; 5 | export const isElectronBundledApp = () => isElectronApp() && !process.defaultApp; 6 | 7 | export const parseAndTrimArgs = argv => { 8 | // bundled Electron app: ignore 1 from "my-app arg1 arg2" 9 | // unbundled Electron app: ignore 2 from "electron main/index.js arg1 arg2" 10 | // node.js app: ignore 2 from "node src/index.js arg1 arg2" 11 | const ignoreCount = isElectronBundledApp() ? 1 : 2; 12 | 13 | const parsed = minimist(argv); 14 | 15 | // ignore arguments AFTER parsing to handle cases like "electron --inspect=42 my.js arg1 arg2" 16 | parsed._ = parsed._.slice(ignoreCount); 17 | 18 | return parsed; 19 | }; 20 | 21 | const argv = parseAndTrimArgs(process.argv); 22 | 23 | export default argv; 24 | -------------------------------------------------------------------------------- /src/main/index.js: -------------------------------------------------------------------------------- 1 | import {BrowserWindow, Menu, app, dialog, ipcMain, shell, systemPreferences} from 'electron'; 2 | import fs from 'fs-extra'; 3 | import path from 'path'; 4 | import {URL} from 'url'; 5 | import {promisify} from 'util'; 6 | 7 | import argv from './argv'; 8 | import {getFilterForExtension} from './FileFilters'; 9 | import telemetry from './ScratchDesktopTelemetry'; 10 | import MacOSMenu from './MacOSMenu'; 11 | import log from '../common/log.js'; 12 | import packageJson from '../../package.json'; 13 | 14 | // suppress deprecation warning; this will be the default in Electron 9 15 | app.allowRendererProcessReuse = true; 16 | 17 | telemetry.appWasOpened(); 18 | 19 | // const defaultSize = {width: 1096, height: 715}; // minimum 20 | const defaultSize = {width: 1280, height: 800}; // good for MAS screenshots 21 | 22 | const isDevelopment = process.env.NODE_ENV !== 'production'; 23 | const devToolKey = ((process.platform === 'darwin') ? 24 | { // macOS: command+option+i 25 | alt: true, // option 26 | control: false, 27 | meta: true, // command 28 | shift: false, 29 | code: 'KeyI' 30 | } : { // Windows / linux: control+shift+i 31 | alt: false, 32 | control: true, 33 | meta: false, // Windows key 34 | shift: true, 35 | code: 'KeyI' 36 | } 37 | ); 38 | 39 | // global window references prevent them from being garbage-collected 40 | const _windows = {}; 41 | const PORT = process.env.PORT || 8601; 42 | 43 | // enable connecting to Scratch Link even if we DNS / Internet access is not available 44 | // this must happen BEFORE the app ready event! 45 | app.commandLine.appendSwitch('host-resolver-rules', 'MAP device-manager.scratch.mit.edu 127.0.0.1'); 46 | 47 | const displayPermissionDeniedWarning = (browserWindow, permissionType) => { 48 | let title; 49 | let message; 50 | switch (permissionType) { 51 | case 'camera': 52 | title = 'Camera Permission Denied'; 53 | message = 'Permission to use the camera has been denied. ' + 54 | 'Scratch will not be able to take a photo or use video sensing blocks.'; 55 | break; 56 | case 'microphone': 57 | title = 'Microphone Permission Denied'; 58 | message = 'Permission to use the microphone has been denied. ' + 59 | 'Scratch will not be able to record sounds or detect loudness.'; 60 | break; 61 | default: // shouldn't ever happen... 62 | title = 'Permission Denied'; 63 | message = 'A permission has been denied.'; 64 | } 65 | 66 | let instructions; 67 | switch (process.platform) { 68 | case 'darwin': 69 | instructions = 'To change Scratch permissions, please check "Security & Privacy" in System Preferences.'; 70 | break; 71 | default: 72 | instructions = 'To change Scratch permissions, please check your system settings and restart Scratch.'; 73 | break; 74 | } 75 | message = `${message}\n\n${instructions}`; 76 | 77 | dialog.showMessageBox(browserWindow, {type: 'warning', title, message}); 78 | }; 79 | 80 | /** 81 | * Build an absolute URL from a relative one, optionally adding search query parameters. 82 | * The base of the URL will depend on whether or not the application is running in development mode. 83 | * @param {string} url - the relative URL, like 'index.html' 84 | * @param {*} search - the optional "search" parameters (the part of the URL after '?'), like "route=about" 85 | * @returns {string} - an absolute URL as a string 86 | */ 87 | const makeFullUrl = (url, search = null) => { 88 | const baseUrl = (isDevelopment ? 89 | `http://localhost:${PORT}/` : 90 | `file://${path.join(__dirname, '../renderer')}/` 91 | ); 92 | const fullUrl = new URL(url, baseUrl); 93 | if (search) { 94 | fullUrl.search = search; // automatically percent-encodes anything that needs it 95 | } 96 | return fullUrl.toString(); 97 | }; 98 | 99 | /** 100 | * Prompt in a platform-specific way for permission to access the microphone or camera, if Electron supports doing so. 101 | * Any application-level checks, such as whether or not a particular frame or document should be allowed to ask, 102 | * should be done before calling this function. 103 | * This function may return a Promise! 104 | * 105 | * @param {string} mediaType - one of Electron's media types, like 'microphone' or 'camera' 106 | * @returns {boolean|Promise.} - true if permission granted, false otherwise. 107 | */ 108 | const askForMediaAccess = mediaType => { 109 | if (systemPreferences.askForMediaAccess) { 110 | // Electron currently only implements this on macOS 111 | // This returns a Promise 112 | return systemPreferences.askForMediaAccess(mediaType); 113 | } 114 | // For other platforms we can't reasonably do anything other than assume we have access. 115 | return true; 116 | }; 117 | 118 | const handlePermissionRequest = async (webContents, permission, callback, details) => { 119 | if (webContents !== _windows.main.webContents) { 120 | // deny: request came from somewhere other than the main window's web contents 121 | return callback(false); 122 | } 123 | if (!details.isMainFrame) { 124 | // deny: request came from a subframe of the main window, not the main frame 125 | return callback(false); 126 | } 127 | if (permission !== 'media') { 128 | // deny: request is for some other kind of access like notifications or pointerLock 129 | return callback(false); 130 | } 131 | const requiredBase = makeFullUrl(''); 132 | if (details.requestingUrl.indexOf(requiredBase) !== 0) { 133 | // deny: request came from a URL outside of our "sandbox" 134 | return callback(false); 135 | } 136 | let askForMicrophone = false; 137 | let askForCamera = false; 138 | for (const mediaType of details.mediaTypes) { 139 | switch (mediaType) { 140 | case 'audio': 141 | askForMicrophone = true; 142 | break; 143 | case 'video': 144 | askForCamera = true; 145 | break; 146 | default: 147 | // deny: unhandled media type 148 | return callback(false); 149 | } 150 | } 151 | const parentWindow = _windows.main; // if we ever allow media in non-main windows we'll also need to change this 152 | if (askForMicrophone) { 153 | const microphoneResult = await askForMediaAccess('microphone'); 154 | if (!microphoneResult) { 155 | displayPermissionDeniedWarning(parentWindow, 'microphone'); 156 | return callback(false); 157 | } 158 | } 159 | if (askForCamera) { 160 | const cameraResult = await askForMediaAccess('camera'); 161 | if (!cameraResult) { 162 | displayPermissionDeniedWarning(parentWindow, 'camera'); 163 | return callback(false); 164 | } 165 | } 166 | return callback(true); 167 | }; 168 | 169 | const createWindow = ({search = null, url = 'index.html', ...browserWindowOptions}) => { 170 | const window = new BrowserWindow({ 171 | useContentSize: true, 172 | show: false, 173 | webPreferences: { 174 | contextIsolation: false, 175 | nodeIntegration: true 176 | }, 177 | ...browserWindowOptions 178 | }); 179 | const webContents = window.webContents; 180 | 181 | webContents.session.setPermissionRequestHandler(handlePermissionRequest); 182 | 183 | webContents.on('before-input-event', (event, input) => { 184 | if (input.code === devToolKey.code && 185 | input.alt === devToolKey.alt && 186 | input.control === devToolKey.control && 187 | input.meta === devToolKey.meta && 188 | input.shift === devToolKey.shift && 189 | input.type === 'keyDown' && 190 | !input.isAutoRepeat && 191 | !input.isComposing) { 192 | event.preventDefault(); 193 | webContents.openDevTools({mode: 'detach', activate: true}); 194 | } 195 | }); 196 | 197 | webContents.on('new-window', (event, newWindowUrl) => { 198 | shell.openExternal(newWindowUrl); 199 | event.preventDefault(); 200 | }); 201 | 202 | const fullUrl = makeFullUrl(url, search); 203 | window.loadURL(fullUrl); 204 | window.once('ready-to-show', () => { 205 | webContents.send('ready-to-show'); 206 | }); 207 | 208 | return window; 209 | }; 210 | 211 | const createAboutWindow = () => { 212 | const window = createWindow({ 213 | width: 400, 214 | height: 400, 215 | parent: _windows.main, 216 | search: 'route=about', 217 | title: `About ${packageJson.productName}` 218 | }); 219 | return window; 220 | }; 221 | 222 | const createPrivacyWindow = () => { 223 | const window = createWindow({ 224 | width: _windows.main.width * 0.8, 225 | height: _windows.main.height * 0.8, 226 | parent: _windows.main, 227 | search: 'route=privacy', 228 | title: `${packageJson.productName} Privacy Policy` 229 | }); 230 | return window; 231 | }; 232 | 233 | const createUsbWindow = () => { 234 | const window = createWindow({ 235 | width: 400, 236 | height: 300, 237 | parent: _windows.main, 238 | search: 'route=usb', 239 | modal: true, 240 | frame: false 241 | }); 242 | 243 | // Filters from navigator.usb.requestDevice do not appear to be available here. 244 | // Hard code to micro:bit since that is the only device that currently uses this api. 245 | const getIsMicroBit = device => device.vendorId === 0x0d28 && device.productId === 0x0204; 246 | let deviceList = []; 247 | let selectedDeviceCallback; 248 | 249 | _windows.main.webContents.session.on('select-usb-device', (event, details, callback) => { 250 | deviceList = details.deviceList.filter(getIsMicroBit); 251 | selectedDeviceCallback = callback; 252 | 253 | window.webContents.send('usb-device-list', deviceList); 254 | window.show(); 255 | 256 | event.preventDefault(); 257 | }); 258 | 259 | _windows.main.webContents.session.on('usb-device-added', (_event, device) => { 260 | if (!getIsMicroBit(device)) return; 261 | deviceList.push(device); 262 | window.webContents.send('usb-device-list', deviceList); 263 | }); 264 | 265 | _windows.main.webContents.session.on('usb-device-removed', (_event, device) => { 266 | if (!getIsMicroBit(device)) return; 267 | deviceList = deviceList.filter(existing => existing.deviceId !== device.deviceId); 268 | window.webContents.send('usb-device-list', deviceList); 269 | }); 270 | 271 | ipcMain.on('usb-device-selected', (_event, message) => { 272 | selectedDeviceCallback(message); 273 | window.hide(); 274 | }); 275 | 276 | return window; 277 | }; 278 | 279 | const getIsProjectSave = downloadItem => { 280 | switch (downloadItem.getMimeType()) { 281 | case 'application/x.scratch.sb3': 282 | return true; 283 | } 284 | return false; 285 | }; 286 | 287 | const createMainWindow = () => { 288 | const window = createWindow({ 289 | width: defaultSize.width, 290 | height: defaultSize.height, 291 | title: `${packageJson.productName} ${packageJson.version}` // something like "Scratch 3.14" 292 | }); 293 | const webContents = window.webContents; 294 | 295 | webContents.session.on('will-download', (willDownloadEvent, downloadItem) => { 296 | const isProjectSave = getIsProjectSave(downloadItem); 297 | const itemPath = downloadItem.getFilename(); 298 | const baseName = path.basename(itemPath); 299 | const extName = path.extname(baseName); 300 | const options = { 301 | defaultPath: baseName 302 | }; 303 | if (extName) { 304 | const extNameNoDot = extName.replace(/^\./, ''); 305 | options.filters = [getFilterForExtension(extNameNoDot)]; 306 | } 307 | const userChosenPath = dialog.showSaveDialogSync(window, options); 308 | // this will be falsy if the user canceled the save 309 | if (userChosenPath) { 310 | const userBaseName = path.basename(userChosenPath); 311 | const tempPath = path.join(app.getPath('temp'), userBaseName); 312 | 313 | // WARNING: `setSavePath` on this item is only valid during the `will-download` event. Calling the async 314 | // version of `showSaveDialog` means the event will finish before we get here, so `setSavePath` will be 315 | // ignored. For that reason we need to call `showSaveDialogSync` above. 316 | downloadItem.setSavePath(tempPath); 317 | 318 | downloadItem.on('done', async (doneEvent, doneState) => { 319 | try { 320 | if (doneState !== 'completed') { 321 | // The download was canceled or interrupted. Cancel the telemetry event and delete the file. 322 | throw new Error(`save ${doneState}`); // "save cancelled" or "save interrupted" 323 | } 324 | await fs.move(tempPath, userChosenPath, {overwrite: true}); 325 | if (isProjectSave) { 326 | const newProjectTitle = path.basename(userChosenPath, extName); 327 | webContents.send('setTitleFromSave', {title: newProjectTitle}); 328 | 329 | // "setTitleFromSave" will set the project title but GUI has already reported the telemetry 330 | // event using the old title. This call lets the telemetry client know that the save was 331 | // actually completed and the event should be committed to the event queue with this new title. 332 | telemetry.projectSaveCompleted(newProjectTitle); 333 | } 334 | } catch (e) { 335 | if (isProjectSave) { 336 | telemetry.projectSaveCanceled(); 337 | } 338 | // don't clean up until after the message box to allow troubleshooting / recovery 339 | await dialog.showMessageBox(window, { 340 | type: 'error', 341 | title: 'Failed to save project', 342 | message: `Save failed:\n${userChosenPath}`, 343 | detail: e.message 344 | }); 345 | fs.exists(tempPath).then(exists => { 346 | if (exists) { 347 | fs.unlink(tempPath); 348 | } 349 | }); 350 | } 351 | }); 352 | } else { 353 | downloadItem.cancel(); 354 | if (isProjectSave) { 355 | telemetry.projectSaveCanceled(); 356 | } 357 | } 358 | }); 359 | 360 | webContents.on('will-prevent-unload', ev => { 361 | const choice = dialog.showMessageBoxSync(window, { 362 | title: packageJson.productName, 363 | type: 'question', 364 | message: 'Leave Scratch?', 365 | detail: 'Any unsaved changes will be lost.', 366 | buttons: ['Stay', 'Leave'], 367 | cancelId: 0, // closing the dialog means "stay" 368 | defaultId: 0 // pressing enter or space without explicitly selecting something means "stay" 369 | }); 370 | const shouldQuit = (choice === 1); 371 | if (shouldQuit) { 372 | ev.preventDefault(); 373 | } 374 | }); 375 | 376 | window.once('ready-to-show', () => { 377 | window.show(); 378 | }); 379 | 380 | return window; 381 | }; 382 | 383 | if (process.platform === 'darwin') { 384 | const osxMenu = Menu.buildFromTemplate(MacOSMenu(app)); 385 | Menu.setApplicationMenu(osxMenu); 386 | } else { 387 | // disable menu for other platforms 388 | Menu.setApplicationMenu(null); 389 | } 390 | 391 | // quit application when all windows are closed 392 | app.on('window-all-closed', () => { 393 | app.quit(); 394 | }); 395 | 396 | app.on('will-quit', () => { 397 | telemetry.appWillClose(); 398 | }); 399 | 400 | // work around https://github.com/MarshallOfSound/electron-devtools-installer/issues/122 401 | // which seems to be a result of https://github.com/electron/electron/issues/19468 402 | if (process.platform === 'win32') { 403 | const appUserDataPath = app.getPath('userData'); 404 | const devToolsExtensionsPath = path.join(appUserDataPath, 'DevTools Extensions'); 405 | try { 406 | fs.unlinkSync(devToolsExtensionsPath); 407 | } catch (_) { 408 | // don't complain if the file doesn't exist 409 | } 410 | } 411 | 412 | // create main BrowserWindow when electron is ready 413 | app.on('ready', () => { 414 | if (isDevelopment) { 415 | import('electron-devtools-installer').then(importedModule => { 416 | const {default: installExtension, ...devToolsExtensions} = importedModule; 417 | const extensionsToInstall = [ 418 | devToolsExtensions.REACT_DEVELOPER_TOOLS, 419 | devToolsExtensions.REDUX_DEVTOOLS 420 | ]; 421 | for (const extension of extensionsToInstall) { 422 | // WARNING: depending on a lot of things including the version of Electron `installExtension` might 423 | // return a promise that never resolves, especially if the extension is already installed. 424 | installExtension(extension).then( 425 | extensionName => log(`Installed dev extension: ${extensionName}`), 426 | errorMessage => log.error(`Error installing dev extension: ${errorMessage}`) 427 | ); 428 | } 429 | }); 430 | } 431 | 432 | _windows.main = createMainWindow(); 433 | _windows.main.on('closed', () => { 434 | delete _windows.main; 435 | }); 436 | _windows.about = createAboutWindow(); 437 | _windows.about.on('close', event => { 438 | event.preventDefault(); 439 | _windows.about.hide(); 440 | }); 441 | _windows.privacy = createPrivacyWindow(); 442 | _windows.privacy.on('close', event => { 443 | event.preventDefault(); 444 | _windows.privacy.hide(); 445 | }); 446 | 447 | _windows.usb = createUsbWindow(); 448 | }); 449 | 450 | ipcMain.on('open-about-window', () => { 451 | _windows.about.show(); 452 | }); 453 | 454 | ipcMain.on('open-privacy-policy-window', () => { 455 | _windows.privacy.show(); 456 | }); 457 | 458 | // start loading initial project data before the GUI needs it so the load seems faster 459 | const initialProjectDataPromise = (async () => { 460 | if (argv._.length === 0) { 461 | // no command line argument means no initial project data 462 | return; 463 | } 464 | if (argv._.length > 1) { 465 | log.warn(`Expected 1 command line argument but received ${argv._.length}.`); 466 | } 467 | const projectPath = argv._[argv._.length - 1]; 468 | try { 469 | const projectData = await promisify(fs.readFile)(projectPath, null); 470 | return projectData; 471 | } catch (e) { 472 | log.error(`Error loading project data: ${e}`); 473 | dialog.showMessageBox(_windows.main, { 474 | type: 'error', 475 | title: 'Failed to load project', 476 | message: `Could not load project from file:\n${projectPath}`, 477 | detail: e.message 478 | }); 479 | } 480 | // load failed: initial project data undefined 481 | })(); // IIFE 482 | 483 | ipcMain.handle('get-initial-project-data', () => initialProjectDataPromise); 484 | -------------------------------------------------------------------------------- /src/main/telemetry/TelemetryClient.js: -------------------------------------------------------------------------------- 1 | import ElectronStore from 'electron-store'; 2 | import nets from 'nets'; 3 | import * as os from 'os'; 4 | import { 5 | v1 as uuidv1, // semi-persistent client ID 6 | v4 as uuidv4 // random ID 7 | } from 'uuid'; 8 | 9 | /** 10 | * Basic telemetry event data. These fields are filled automatically by the `addEvent` call. 11 | * @typedef {object} BasicTelemetryEvent 12 | * @property {string} clientID - a UUID for this client 13 | * @property {string} id - a UUID for this event/packet 14 | * @property {string} name - the name of this event (taken from `addEvent`'s `eventName` parameter) 15 | * @property {int} timestamp - a Unix epoch timestamp for this event 16 | * @property {int} userTimezone - the difference in minutes between UTC and local time 17 | */ 18 | 19 | /** 20 | * Default telemetry service URLs 21 | */ 22 | const TelemetryServerURL = Object.freeze({ 23 | staging: 'http://scratch-telemetry-staging.us-east-1.elasticbeanstalk.com/', 24 | production: 'https://telemetry.scratch.mit.edu/' 25 | }); 26 | const DefaultServerURL = ( 27 | process.env.NODE_ENV === 'production' ? TelemetryServerURL.production : TelemetryServerURL.staging 28 | ); 29 | 30 | /** 31 | * Default name for persistent configuration & queue storage 32 | */ 33 | const DefaultStoreName = 'telemetry'; 34 | 35 | /** 36 | * Default interval, in seconds, between delivery attempts 37 | */ 38 | const DefaultDeliveryInterval = 60; 39 | 40 | /** 41 | * Default interval, in seconds, between connectivity checks 42 | */ 43 | const DefaultNetworkCheckInterval = 300; 44 | 45 | /** 46 | * Default limit on the number of queued events 47 | */ 48 | const DefaultQueueLimit = 100; 49 | 50 | /** 51 | * Default limit on the number of delivery attempts for each event 52 | */ 53 | const DeliveryAttemptLimit = 3; 54 | 55 | const platform = [ 56 | `${os.platform()} ${os.release()}`, // "win32 10.0.18362", "darwin 18.7.0", etc. 57 | `Electron ${process.versions.electron}`, // "Electron 4.2.6" 58 | `Store=${process.mas || process.windowsStore || false}` // "Store=true" or "Store=false" 59 | ].join(', '); 60 | 61 | 62 | /** 63 | * Client interface for the Scratch telemetry service. 64 | * 65 | * This class supports delivering generic telemetry events and is designed to be used by any application or service 66 | * in the Scratch family. 67 | */ 68 | class TelemetryClient { 69 | /** 70 | * Construct and initialize a TelemetryClient instance, optionally overriding configuration defaults. Delivery 71 | * intervals will begin immediately; if the user has not opted in events will be dropped each interval. 72 | * 73 | * @param {object} [options] - optional configuration settings for this client 74 | * @property {string} [storeName] - optional name for persistent config/queue storage (default: 'telemetry') 75 | * @property {string} [clientId] - optional UUID for this client (default: automatically determine a UUID) 76 | * @property {string} [serverURL] - optional telemetry service endpoint URL (default: automatically choose a server) 77 | * @property {boolean} [didOptIn] - optional flag for whether the user opted into telemetry service (default: false) 78 | * @property {int} [deliveryInterval] - optional number of seconds between delivery attempts (default: 60) 79 | * @property {int} [networkCheckInterval] - optional number of seconds between connectivity checks (default: 300) 80 | * @property {int} [queueLimit] - optional limit on the number of queued events (default: 100) 81 | * @property {int} [deliveryAttemptLimit] - optional limit on delivery attempts for each event (default: 3) 82 | */ 83 | constructor ({ 84 | storeName = DefaultStoreName, 85 | clientID, // undefined = load or create 86 | serverURL, // undefined = automatic 87 | didOptIn, // undefined = show prompt 88 | deliveryInterval = DefaultDeliveryInterval, 89 | networkCheckInterval = DefaultNetworkCheckInterval, 90 | queueLimit = DefaultQueueLimit, 91 | deliveryAttemptLimit = DeliveryAttemptLimit 92 | } = {}) { 93 | /** 94 | * Persistent storage for the client ID, opt in flag, and packet queue. 95 | */ 96 | this._store = new ElectronStore({ 97 | name: storeName 98 | }); 99 | 100 | if (clientID) { 101 | this.clientID = clientID; 102 | } else if (!this._store.has('clientID')) { 103 | this.clientID = uuidv1(); 104 | } 105 | 106 | if (typeof didOptIn !== 'undefined') { 107 | this.didOptIn = didOptIn; 108 | } 109 | 110 | /** 111 | * Queue for outgoing event packets 112 | */ 113 | this._packetQueue = this._store.get('packetQueue', []); 114 | 115 | /** 116 | * Server URL 117 | */ 118 | this._serverURL = serverURL || DefaultServerURL; 119 | 120 | /** 121 | * Can we currently reach the telemetry service? 122 | */ 123 | this._networkIsOnline = false; 124 | 125 | /** 126 | * Try to deliver telemetry packets at this interval 127 | */ 128 | this._deliveryInterval = (deliveryInterval > 0) ? deliveryInterval : DefaultDeliveryInterval; 129 | 130 | /** 131 | * Check for connectivity at this interval 132 | */ 133 | this._networkCheckInterval = (networkCheckInterval > 0) ? networkCheckInterval : DefaultNetworkCheckInterval; 134 | 135 | /** 136 | * Queue at most this many events 137 | */ 138 | this._queueLimit = (queueLimit > 0) ? queueLimit : DefaultQueueLimit; 139 | 140 | /** 141 | * Attempt to deliver an event at most this many times 142 | */ 143 | this._deliveryAttemptLimit = (deliveryAttemptLimit > 0) ? deliveryAttemptLimit : DeliveryAttemptLimit; 144 | 145 | /** 146 | * Bind event handlers 147 | */ 148 | this._attemptDelivery = this._attemptDelivery.bind(this); 149 | this._updateNetworkStatus = this._updateNetworkStatus.bind(this); 150 | 151 | /** 152 | * Begin monitoring network status 153 | */ 154 | this._networkTimer = setInterval(this._updateNetworkStatus, this._networkCheckInterval * 1000); 155 | setTimeout(this._updateNetworkStatus, 0); 156 | 157 | /** 158 | * Begin the delivery interval 159 | */ 160 | this._deliveryTimer = setInterval(this._attemptDelivery, this._deliveryInterval * 1000); 161 | } 162 | 163 | /** 164 | * Stop this client. Do not use this object after disposal. 165 | */ 166 | dispose () { 167 | if (this._networkTimer !== null) { 168 | clearInterval(this._networkTimer); 169 | this._networkTimer = null; 170 | } 171 | if (this._deliveryTimer !== null) { 172 | clearInterval(this._deliveryTimer); 173 | this._deliveryTimer = null; 174 | } 175 | } 176 | 177 | /** 178 | * Has the user explicitly opted into this service? 179 | * @type {boolean} 180 | */ 181 | get didOptIn () { 182 | // don't supply a default here: we want to track "opt out" separately from "undecided" 183 | return this._store.get('optIn'); 184 | } 185 | set didOptIn (value) { 186 | this._store.set('optIn', !!value); 187 | } 188 | 189 | /** 190 | * Semi-persistent unique ID for this client 191 | * @type {string} 192 | */ 193 | get clientID () { 194 | return this._store.get('clientID'); 195 | } 196 | set clientID (value) { 197 | this._store.set('clientID', value); 198 | } 199 | 200 | /** 201 | * Save the packet queue to the config store. 202 | * Call this any time the queue is modified. 203 | */ 204 | saveQueue () { 205 | this._store.set('packetQueue', this._packetQueue); 206 | } 207 | 208 | /** 209 | * Add an event to the telemetry system. If the user has opted into the telemetry service, this event will be 210 | * delivered to the telemetry service when possible. Otherwise the event will be ignored. 211 | * 212 | * @see {@link BasicTelemetryEvent} for the list of fields which are filled automatically by this method. 213 | * 214 | * @param {string} eventName - the name of this telemetry event, such as 'app::open'. 215 | * @param {object} additionalFields - optional event fields to add or override before sending the event. 216 | */ 217 | addEvent (eventName, additionalFields = null) { 218 | const packetId = uuidv4(); 219 | const now = new Date(); 220 | 221 | const packet = Object.assign({ 222 | clientID: this.clientID, 223 | id: packetId, 224 | name: eventName, 225 | platform, 226 | timestamp: now.getTime(), 227 | userTimezone: now.getTimezoneOffset() 228 | }, additionalFields); 229 | const packetInfo = { 230 | attempts: 0, 231 | packet 232 | }; 233 | this._packetQueue.push(packetInfo); 234 | this._packetQueue.splice(0, this._packetQueue.length - this._queueLimit); // enforce queue length limit 235 | this.saveQueue(); 236 | } 237 | 238 | /** 239 | * Attempt to deliver events to the telemetry service. If telemetry is disabled, this will do nothing. 240 | */ 241 | _attemptDelivery () { 242 | if (this._busy) { 243 | return; 244 | } 245 | 246 | /** 247 | * Attempt to deliver one event then asynchronously recurse, reenqueueing the event if delivery fails and the 248 | * event has not yet reached its retry limit. Sets `this._busy` before doing anything else and clears it once 249 | * the queue is empty or `this.didOptIn` is cleared. 250 | */ 251 | const stepDelivery = () => { 252 | this._busy = true; 253 | if (!this.didOptIn || !this._networkIsOnline || this._packetQueue.length < 1) { 254 | this._busy = false; 255 | return; 256 | } 257 | // don't saveQueue() here: 258 | // - if the app exits or crashes before the network request finishes, we'll lose the packet 259 | // - if the request finishes, we'll save at that time (see below) 260 | const packetInfo = this._packetQueue.shift(); 261 | ++packetInfo.attempts; 262 | const packet = packetInfo.packet; 263 | nets({ 264 | body: JSON.stringify(packet), 265 | headers: {'Content-Type': 'application/json'}, 266 | method: 'POST', 267 | url: this._serverURL 268 | }, (err, res) => { 269 | // TODO: check if the failure is because there's no Internet connection and if so refund the attempt 270 | const packetFailed = err || (res.statusCode !== 200); 271 | if (packetFailed) { 272 | if (packetInfo.attempts < this._deliveryAttemptLimit) { 273 | this._packetQueue.push(packetInfo); 274 | } else { 275 | // eslint-disable-next-line no-console 276 | console.warn('Dropping packet which exceeded retry limit', packet); 277 | } 278 | } 279 | this.saveQueue(); 280 | stepDelivery(); 281 | }); 282 | }; 283 | 284 | stepDelivery(); 285 | } 286 | 287 | /** 288 | * Check if the telemetry service is available 289 | */ 290 | _updateNetworkStatus () { 291 | nets({ 292 | method: 'GET', 293 | url: this._serverURL 294 | }, (err, res) => { 295 | this._networkIsOnline = !err && (res.statusCode === 200); 296 | }); 297 | } 298 | } 299 | 300 | export default TelemetryClient; 301 | -------------------------------------------------------------------------------- /src/renderer/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | browser: true, 5 | node: true 6 | }, 7 | extends: ['scratch', 'scratch/es6', 'scratch/react'], 8 | settings: { 9 | react: { 10 | version: '16.2' // Prevent 16.3 lifecycle method errors 11 | } 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /src/renderer/ScratchDesktopAppStateHOC.jsx: -------------------------------------------------------------------------------- 1 | import {ipcRenderer} from 'electron'; 2 | import bindAll from 'lodash.bindall'; 3 | import React from 'react'; 4 | 5 | /** 6 | * Higher-order component to add desktop logic to AppStateHOC. 7 | * @param {Component} WrappedComponent - an AppStateHOC-like component to wrap. 8 | * @returns {Component} - a component similar to AppStateHOC with desktop-specific logic added. 9 | */ 10 | const ScratchDesktopAppStateHOC = function (WrappedComponent) { 11 | class ScratchDesktopAppStateComponent extends React.Component { 12 | constructor (props) { 13 | super(props); 14 | bindAll(this, [ 15 | 'handleTelemetryModalOptIn', 16 | 'handleTelemetryModalOptOut' 17 | ]); 18 | this.state = { 19 | // use `sendSync` because this should be set before first render 20 | telemetryDidOptIn: ipcRenderer.sendSync('getTelemetryDidOptIn') 21 | }; 22 | } 23 | handleTelemetryModalOptIn () { 24 | ipcRenderer.send('setTelemetryDidOptIn', true); 25 | ipcRenderer.invoke('getTelemetryDidOptIn').then(telemetryDidOptIn => { 26 | this.setState({telemetryDidOptIn}); 27 | }); 28 | } 29 | handleTelemetryModalOptOut () { 30 | ipcRenderer.send('setTelemetryDidOptIn', false); 31 | ipcRenderer.invoke('getTelemetryDidOptIn').then(telemetryDidOptIn => { 32 | this.setState({telemetryDidOptIn}); 33 | }); 34 | } 35 | render () { 36 | const shouldShowTelemetryModal = (typeof ipcRenderer.sendSync('getTelemetryDidOptIn') !== 'boolean'); 37 | 38 | return (); 47 | } 48 | } 49 | 50 | return ScratchDesktopAppStateComponent; 51 | }; 52 | 53 | export default ScratchDesktopAppStateHOC; 54 | -------------------------------------------------------------------------------- /src/renderer/ScratchDesktopGUIHOC.jsx: -------------------------------------------------------------------------------- 1 | import {ipcRenderer, remote} from 'electron'; 2 | import bindAll from 'lodash.bindall'; 3 | import omit from 'lodash.omit'; 4 | import PropTypes from 'prop-types'; 5 | import React from 'react'; 6 | import {connect} from 'react-redux'; 7 | 8 | import { 9 | GUIComponent, 10 | LoadingStates, 11 | onFetchedProjectData, 12 | onLoadedProject, 13 | defaultProjectId, 14 | requestNewProject, 15 | requestProjectUpload, 16 | setProjectId, 17 | openLoadingProject, 18 | closeLoadingProject, 19 | openTelemetryModal 20 | } from '@scratch/scratch-gui'; 21 | 22 | import ElectronStorageHelper from '../common/ElectronStorageHelper'; 23 | 24 | import showPrivacyPolicy from './showPrivacyPolicy'; 25 | 26 | /** 27 | * Higher-order component to add desktop logic to the GUI. 28 | * @param {Component} WrappedComponent - a GUI-like component to wrap. 29 | * @returns {Component} - a component similar to GUI with desktop-specific logic added. 30 | */ 31 | const ScratchDesktopGUIHOC = function (WrappedComponent) { 32 | class ScratchDesktopGUIComponent extends React.Component { 33 | constructor (props) { 34 | super(props); 35 | bindAll(this, [ 36 | 'handleProjectTelemetryEvent', 37 | 'handleSetTitleFromSave', 38 | 'handleStorageInit', 39 | 'handleUpdateProjectTitle' 40 | ]); 41 | this.props.onLoadingStarted(); 42 | ipcRenderer.invoke('get-initial-project-data').then(initialProjectData => { 43 | const hasInitialProject = initialProjectData && (initialProjectData.length > 0); 44 | this.props.onHasInitialProject(hasInitialProject, this.props.loadingState); 45 | if (!hasInitialProject) { 46 | this.props.onLoadingCompleted(); 47 | return; 48 | } 49 | this.props.vm.loadProject(initialProjectData).then( 50 | () => { 51 | this.props.onLoadingCompleted(); 52 | this.props.onLoadedProject(this.props.loadingState, true); 53 | }, 54 | e => { 55 | this.props.onLoadingCompleted(); 56 | this.props.onLoadedProject(this.props.loadingState, false); 57 | remote.dialog.showMessageBox(remote.getCurrentWindow(), { 58 | type: 'error', 59 | title: 'Failed to load project', 60 | message: 'Invalid or corrupt project file.', 61 | detail: e.message 62 | }); 63 | 64 | // this effectively sets the default project ID 65 | // TODO: maybe setting the default project ID should be implicit in `requestNewProject` 66 | this.props.onHasInitialProject(false, this.props.loadingState); 67 | 68 | // restart as if we didn't have an initial project to load 69 | this.props.onRequestNewProject(); 70 | } 71 | ); 72 | }); 73 | } 74 | componentDidMount () { 75 | ipcRenderer.on('setTitleFromSave', this.handleSetTitleFromSave); 76 | } 77 | componentWillUnmount () { 78 | ipcRenderer.removeListener('setTitleFromSave', this.handleSetTitleFromSave); 79 | } 80 | handleClickAbout () { 81 | ipcRenderer.send('open-about-window'); 82 | } 83 | handleProjectTelemetryEvent (event, metadata) { 84 | ipcRenderer.send(event, metadata); 85 | } 86 | handleSetTitleFromSave (event, args) { 87 | this.handleUpdateProjectTitle(args.title); 88 | } 89 | handleStorageInit (storageInstance) { 90 | storageInstance.addHelper(new ElectronStorageHelper(storageInstance)); 91 | } 92 | handleUpdateProjectTitle (newTitle) { 93 | this.setState({projectTitle: newTitle}); 94 | } 95 | render () { 96 | const childProps = omit(this.props, Object.keys(ScratchDesktopGUIComponent.propTypes)); 97 | 98 | return ( this.handleClickAbout() 106 | }, 107 | { 108 | title: 'Privacy Policy', 109 | onClick: () => showPrivacyPolicy() 110 | }, 111 | { 112 | title: 'Data Settings', 113 | onClick: () => this.props.onTelemetrySettingsClicked() 114 | } 115 | ]} 116 | onProjectTelemetryEvent={this.handleProjectTelemetryEvent} 117 | onShowPrivacyPolicy={showPrivacyPolicy} 118 | onStorageInit={this.handleStorageInit} 119 | onUpdateProjectTitle={this.handleUpdateProjectTitle} 120 | platform="DESKTOP" 121 | 122 | // allow passed-in props to override any of the above 123 | {...childProps} 124 | />); 125 | } 126 | } 127 | 128 | ScratchDesktopGUIComponent.propTypes = { 129 | loadingState: PropTypes.oneOf(LoadingStates), 130 | onFetchedInitialProjectData: PropTypes.func, 131 | onHasInitialProject: PropTypes.func, 132 | onLoadedProject: PropTypes.func, 133 | onLoadingCompleted: PropTypes.func, 134 | onLoadingStarted: PropTypes.func, 135 | onRequestNewProject: PropTypes.func, 136 | onTelemetrySettingsClicked: PropTypes.func, 137 | vm: GUIComponent.WrappedComponent.propTypes.vm 138 | }; 139 | const mapStateToProps = state => { 140 | const loadingState = state.scratchGui.projectState.loadingState; 141 | return { 142 | loadingState: loadingState, 143 | vm: state.scratchGui.vm 144 | }; 145 | }; 146 | const mapDispatchToProps = dispatch => ({ 147 | onLoadingStarted: () => dispatch(openLoadingProject()), 148 | onLoadingCompleted: () => dispatch(closeLoadingProject()), 149 | onHasInitialProject: (hasInitialProject, loadingState) => { 150 | if (hasInitialProject) { 151 | // emulate sb-file-uploader 152 | return dispatch(requestProjectUpload(loadingState)); 153 | } 154 | 155 | // `createProject()` might seem more appropriate but it's not a valid state transition here 156 | // setting the default project ID is a valid transition from NOT_LOADED and acts like "create new" 157 | return dispatch(setProjectId(defaultProjectId)); 158 | }, 159 | onFetchedInitialProjectData: (projectData, loadingState) => 160 | dispatch(onFetchedProjectData(projectData, loadingState)), 161 | onLoadedProject: (loadingState, loadSuccess) => { 162 | const canSaveToServer = false; 163 | return dispatch(onLoadedProject(loadingState, canSaveToServer, loadSuccess)); 164 | }, 165 | onRequestNewProject: () => dispatch(requestNewProject(false)), 166 | onTelemetrySettingsClicked: () => dispatch(openTelemetryModal()) 167 | }); 168 | 169 | return connect(mapStateToProps, mapDispatchToProps)(ScratchDesktopGUIComponent); 170 | }; 171 | 172 | export default ScratchDesktopGUIHOC; 173 | -------------------------------------------------------------------------------- /src/renderer/about.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | background-color: #855CD6; 3 | color: white; 4 | font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; 5 | font-weight: bolder; 6 | } 7 | 8 | a:active, a:hover, a:link, a:visited { 9 | color: currentColor; 10 | } 11 | 12 | a:active, a:hover { 13 | filter: brightness(0.9); 14 | } 15 | 16 | .aboutBox { 17 | margin: 0; 18 | position: absolute; 19 | top: 50%; 20 | left: 50%; 21 | transform: translate(-50%, -50%); 22 | } 23 | 24 | .aboutLogo { 25 | max-width: 10rem; 26 | max-height: 10rem; 27 | } 28 | 29 | .aboutText { 30 | margin: 1.5rem; 31 | } 32 | 33 | .aboutDetails { 34 | font-size: x-small; 35 | } 36 | 37 | .aboutFooter { 38 | font-size: small; 39 | } 40 | -------------------------------------------------------------------------------- /src/renderer/about.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import packageJson from '../../package.json'; 3 | 4 | import logo from '../icon/ScratchDesktop.svg'; 5 | import styles from './about.css'; 6 | 7 | const AboutElement = () => ( 8 |
9 |
{`${packageJson.productName}
14 |
15 |

{packageJson.productName}

16 | Version {packageJson.version} 17 | 18 | { 19 | ['Electron', 'Chrome', 'Node'].map(component => { 20 | const componentVersion = process.versions[component.toLowerCase()]; 21 | return ; 22 | }) 23 | } 24 |
{component}{componentVersion}
25 |
26 |
27 | ); 28 | 29 | export default ; 30 | -------------------------------------------------------------------------------- /src/renderer/app.css: -------------------------------------------------------------------------------- 1 | /* Adapted from @scratch/scratch-gui/src/playground/index.css */ 2 | html, 3 | body, 4 | .app { 5 | width: 100%; 6 | height: 100%; 7 | margin: 0; 8 | 9 | /* Setting min height/width makes the UI scroll below those sizes */ 10 | min-width: 1024px; 11 | min-height: 640px; /* Min height to fit sprite/backdrop button */ 12 | } 13 | -------------------------------------------------------------------------------- /src/renderer/app.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import {compose} from 'redux'; 3 | import GUI, {AppStateHOC} from '@scratch/scratch-gui'; 4 | 5 | import ScratchDesktopAppStateHOC from './ScratchDesktopAppStateHOC.jsx'; 6 | import ScratchDesktopGUIHOC from './ScratchDesktopGUIHOC.jsx'; 7 | import styles from './app.css'; 8 | 9 | const appTarget = document.getElementById('app'); 10 | appTarget.className = styles.app || 'app'; 11 | 12 | GUI.setAppElement(appTarget); 13 | 14 | // note that redux's 'compose' function is just being used as a general utility to make 15 | // the hierarchy of HOC constructor calls clearer here; it has nothing to do with redux's 16 | // ability to compose reducers. 17 | const WrappedGui = compose( 18 | ScratchDesktopAppStateHOC, 19 | AppStateHOC, 20 | ScratchDesktopGUIHOC 21 | )(GUI); 22 | 23 | export default ; 24 | -------------------------------------------------------------------------------- /src/renderer/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 21 | 22 | 23 |

Scratch is loading...

24 | 25 | 26 | -------------------------------------------------------------------------------- /src/renderer/index.js: -------------------------------------------------------------------------------- 1 | // This file does async imports of the heavy JSX, especially app.jsx, to avoid blocking the first render. 2 | // The main index.html just contains a loading/splash screen which will display while this import loads. 3 | 4 | import {ipcRenderer} from 'electron'; 5 | 6 | import ReactDOM from 'react-dom'; 7 | import log from '../common/log.js'; 8 | 9 | ipcRenderer.on('ready-to-show', () => { 10 | // Start without any element in focus, otherwise the first link starts with focus and shows an orange box. 11 | // We shouldn't disable that box or the focus behavior in case someone wants or needs to navigate that way. 12 | // This seems like a hack... maybe there's some better way to do avoid any element starting with focus? 13 | document.activeElement.blur(); 14 | }); 15 | 16 | const route = new URLSearchParams(window.location.search).get('route') || 'app'; 17 | let routeModulePromise; 18 | switch (route) { 19 | case 'app': 20 | routeModulePromise = import('./app.jsx'); 21 | break; 22 | case 'about': 23 | routeModulePromise = import('./about.jsx'); 24 | break; 25 | case 'privacy': 26 | routeModulePromise = import('./privacy.jsx'); 27 | break; 28 | case 'usb': 29 | routeModulePromise = import('./usb.jsx'); 30 | break; 31 | } 32 | 33 | routeModulePromise.then(routeModule => { 34 | const appTarget = document.getElementById('app'); 35 | const routeElement = routeModule.default; 36 | ReactDOM.render(routeElement, appTarget); 37 | }).catch(error => log.error('Error rendering app: ', error)); 38 | -------------------------------------------------------------------------------- /src/renderer/privacy.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | background-color: #855CD6; 3 | color: white; 4 | font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; 5 | font-weight: normal; 6 | line-height: 150%; 7 | } 8 | 9 | a:active, a:hover, a:link, a:visited { 10 | color: #855CD6; 11 | } 12 | 13 | .privacyBox { 14 | background-color: white; 15 | color: #575e75; 16 | margin: 3rem; 17 | padding: 2rem 3rem; 18 | } 19 | -------------------------------------------------------------------------------- /src/renderer/privacy.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import styles from './privacy.css'; 4 | 5 | const PrivacyElement = () => ( 6 |
7 |

Privacy Policy

8 | The Scratch Privacy Policy was last updated: October 5, 2020 9 |

10 | The Scratch Foundation (“Scratch”, “we” or “us”) understands how 11 | important privacy is to our community. We wrote this Privacy Policy to explain what Personal Information 12 | (“Information”) we collect through our offline editor (the “Scratch App”), how we use, process, and share it, and what we're doing to keep it safe. It 17 | also tells you about your rights and choices with respect to your Personal Information, and how you can contact us if you have any questions or concerns. 22 |

23 |

What Information Does Scratch Collect About Me?

24 |

25 | For the purpose of this Privacy Policy, “Information” means any information relating to an 26 | identified or identifiable individual. The Scratch App automatically collects and stores locally the 27 | following Information through its telemetry system: the title of your project in text form, language 28 | setting, time zone and events related to your use of the Scratch App (namely when the Scratch App was 29 | opened and closed, if a project file has been loaded or saved, or if a new project is created). If you 30 | choose to turn on the telemetry sharing feature, the Scratch App will transmit this information to Scratch. 31 | Projects created in the Scratch App are not transmitted to or accessible by Scratch. 32 |

33 |

How Does Scratch Use My Information?

34 |

We use this Information for the following purposes:

35 |
    36 |
  • 37 | Analytics and Improving the Scratch App - We use the Information to analyze use of the Scratch 38 | App and to enhance your learning experience on the Scratch App. 39 |
  • 40 |
  • 41 | Academic and Scientific Research - We de-identify and aggregate Information for statistical 42 | analysis in the context of scientific and academic research. For example, to help us understand how 43 | people learn through the Scratch App and how we can enhance learning tools for young people. The 44 | results of such research are shared with educators and researchers through conferences, journals, and 45 | other academic or scientific publications. You can find out more on our Research page. 50 |
  • 51 |
  • 52 | Legal - We may use your Information to enforce our Terms of Use, to defend our legal rights, and to comply with our legal obligations and internal 57 | policies. We may do this by analyzing your use of the Scratch App. 58 |
  • 59 |
60 |

What Are The Legal Grounds For Processing Your Information?

61 |

62 | If you are located in the European Economic Area, the United Kingdom or Switzerland, we only process your 63 | Information based on a valid legal ground. A “legal ground” is a reason that justifies our use 64 | of your Information. In this case, we or a third party have a legitimate interest in using your Information 65 | (if you choose to allow the Scratch App to send the Scratch team your Information) to create, analyze and 66 | share your aggregated or de-identified Information for research purposes, to analyze and enhance your 67 | learning experience on the Scratch App and otherwise ensure and improve the safety, security, and 68 | performance of the Scratch App. We only rely on our or a third party’s legitimate interests to process your 69 | Information when these interests are not overridden by your rights and interests. 70 |

71 |

How Does Scratch Share My Information?

72 |

73 | We disclose information that we collect through the Scratch App to third parties in the following 74 | circumstances: 75 |

76 |
    77 |
  • 78 | Service Providers - To third parties who provide services such as website hosting, data 79 | analysis, Information technology and related infrastructure provisions, customer service, email 80 | delivery, and other services. 81 |
  • 82 |
  • 83 | Academic and Scientific Research - To research institutions, such as the Massachusetts Institute 84 | of Technology (MIT), to learn about how our users learn through the Scratch App and develop new 85 | learning tools. The results of this research or the statistical analysis may be shared through 86 | conferences, journals, and other publications. 87 |
  • 88 |
  • 89 | Merger - To a potential or actual acquirer, successor, or assignee as part of any 90 | reorganization, merger, sale, joint venture, assignment, transfer, or other disposition of all or any 91 | portion of our organization or assets. You will have the opportunity to opt out of any such transfer if 92 | the new entity's planned processing of your Information differs materially from that set forth in 93 | this Privacy Policy. 94 |
  • 95 |
  • 96 | Legal - If required to do so by law or in the good faith belief that such action is appropriate: 97 | (a) under applicable law, including laws outside your country of residence; (b) to comply with legal 98 | process; (c) to respond to requests from public and government authorities, such as school, school 99 | districts, and law enforcement, including public and government authorities outside your country of 100 | residence; (d) to enforce our terms and conditions; (e) to protect our operations or those of any of 101 | our affiliates; (f) to protect our rights, privacy, safety, or property, and/or that of our affiliates, 102 | you, or others; and (g) to allow us to pursue available remedies or limit the damages that we may 103 | sustain. 104 |
  • 105 |
106 |

Children and Student Privacy

107 |

108 | The Scratch Foundation is a 501(c)(3) nonprofit organization. As such, the Children's Online Privacy 109 | Protection Act (COPPA) does not apply to Scratch. Nevertheless, Scratch takes children's privacy 110 | seriously. Scratch collects only minimal information from its users, and only uses and discloses 111 | information to provide the services and for limited other purposes, such as research, as described in this 112 | Privacy Policy. 113 |

114 |

115 | Scratch does not collect information from a student's education record, as defined by the Family 116 | Educational Rights and Privacy Act (FERPA). Scratch does not disclose information of students to any third 117 | parties except as described in this Privacy Policy. 118 |

119 |

Your Data Protection Rights (EEA)

120 |

121 | If you are located in the European Economic Area, the United Kingdom or Switzerland, you have certain 122 | rights in relation to your Information: 123 |

124 |
    125 |
  • 126 | Access, Correction and Data Portability - You may ask for an overview of the Information we 127 | process about you and to receive a copy of your Information. You also have the right to request to 128 | correct incomplete, inaccurate or outdated Information. To the extent required by applicable law, you 129 | may request us to provide your Information to another company. 130 |
  • 131 |
  • 132 | Objection – You may object to (this means “ask us to stop”) any use of your 133 | Information that is not (i) processed to comply with a legal obligation, (ii) necessary to do what is 134 | provided in a contract between Scratch and you, or (iii) if we have a compelling reason to do so (such 135 | as, to ensure safety and security in our online community). If you do object, we will work with you to 136 | find a reasonable solution. 137 |
  • 138 |
  • 139 | Deletion - You may also request the deletion of your Information, as permitted under applicable 140 | law. This applies, for instance, where your Information is outdated or the processing is not necessary 141 | or is unlawful; where you withdraw your consent to our processing based on such consent; or where you 142 | have objected to our processing. In some situations, we may need to retain your Information due to 143 | legal obligations or for litigation purposes. If you want to have all of your Information removed from 144 | our servers, please contact help@scratch.mit.edu for assistance. 149 |
  • 150 |
  • 151 | Restriction Of Processing - You may request that we restrict processing of your Information 152 | while we are processing a request relating to (i) the accuracy of your Information, (ii) the lawfulness 153 | of the processing of your Information, or (iii) our legitimate interests to process this Information. 154 | You may also request that we restrict processing of your Information if you wish to use the Information 155 | for litigation purposes. 156 |
  • 157 |
  • 158 | Withdrawal Of Consent – Where we rely on consent for the processing of your Information, you 159 | have the right to withdraw it at any time and free of charge. When you do so, this will not affect the 160 | lawfulness of the processing before your consent withdrawal. 161 |
  • 162 |
163 |

164 | In addition to the above-mentioned rights, you also have the right to lodge a complaint with a competent 165 | supervisory authority subject to applicable law. However, there are exceptions and limitations to each of 166 | these rights. We may, for example, refuse to act on a request if the request is manifestly unfounded or 167 | excessive, or if the request is likely to adversely affect the rights and freedoms of others, prejudice the 168 | execution or enforcement of the law, interfere with pending or future litigation, or infringe applicable 169 | law. To submit a request to exercise your rights, please contact help@scratch.mit.edu for assistance. 174 |

175 |

Data Retention

176 |

177 | We take measures to delete your Information or keep it in a form that does not allow you to be identified 178 | when this Information is no longer necessary for the purposes for which we process it, unless we are 179 | required by law to keep this Information for a longer period. When determining the retention period, we 180 | take into account various criteria, such as the type of services requested by or provided to you, the 181 | nature and length of our relationship with you, possible re-enrollment with our services, the impact on the 182 | services we provide to you if we delete some Information from or about you, mandatory retention periods 183 | provided by law and the statute of limitations. 184 |

185 |

How Does Scratch Protect My Information?

186 |

187 | Scratch has in place administrative, physical, and technical procedures that are intended to protect the 188 | Information we collect on the Scratch App against accidental or unlawful destruction, accidental loss, 189 | unauthorized alteration, unauthorized disclosure or access, misuse, and any other unlawful form of 190 | processing of the Information. However, as effective as these measures are, no security system is 191 | impenetrable. We cannot completely guarantee the security of our databases, nor can we guarantee that the 192 | Information you supply will not be intercepted while being transmitted to us over the Internet. 193 |

194 |

International Data Transfer

195 |

196 | We may transfer your Information to countries other than the country where you are located, including to 197 | the U.S. (where our Scratch servers are located) or any other country in which we or our service providers 198 | maintain facilities. If you are located in the European Economic Area, the United Kingdom or Switzerland, 199 | or other regions with laws governing data collection and use that may differ from U.S. law, please note 200 | that we may transfer your Information to a country and jurisdiction that does not have the same data 201 | protection laws as your jurisdiction. We apply appropriate safeguards to the Information processed and 202 | transferred on our behalf. Please contact us for more information on the safeguards used. 203 |

204 |

Notifications Of Changes To The Privacy Policy

205 |

206 | We review our Privacy Policy on a periodic basis, and we may modify our policies as appropriate. We will 207 | notify you of any material changes. We encourage you to review our Privacy Policy on a regular basis. The 208 | “Last Updated” date at the top of this page indicates when this Privacy Policy was last 209 | revised. Your continued use of the Scratch App following these changes means that you accept the revised 210 | Privacy Policy. 211 |

212 |

Contact Us

213 |

214 | The Scratch Foundation is the entity responsible for the processing of your Information. If you have any 215 | questions about this Privacy Policy, or if you would like to exercise your rights to your Information, you 216 | may contact us at help@scratch.mit.edu or via mail at: 221 |

222 |
223 |
Scratch Foundation
224 |
ATTN: Privacy Policy
225 |
226 |
201 South Street
227 | Boston, MA 02111 230 |
231 |
232 |
233 | ); 234 | 235 | export default ; 236 | -------------------------------------------------------------------------------- /src/renderer/showPrivacyPolicy.js: -------------------------------------------------------------------------------- 1 | import {ipcRenderer} from 'electron'; 2 | 3 | const showPrivacyPolicy = event => { 4 | if (event) { 5 | // Probably a click on a link; don't actually follow the link in the `href` attribute. 6 | event.preventDefault(); 7 | } 8 | // tell the main process to open the privacy policy window 9 | ipcRenderer.send('open-privacy-policy-window'); 10 | return false; 11 | }; 12 | 13 | export default showPrivacyPolicy; 14 | -------------------------------------------------------------------------------- /src/renderer/usb.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | background-color: white; 3 | color: #575E75; 4 | font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; 5 | font-weight: normal; 6 | line-height: 150%; 7 | margin: 0; 8 | } 9 | 10 | html, body, :global(#app), main { 11 | height: 100%; 12 | } 13 | 14 | :global(#app) { 15 | box-sizing: border-box; 16 | padding: 1rem; 17 | } 18 | 19 | main { 20 | display: flex; 21 | flex-direction: column; 22 | } 23 | 24 | .devices { 25 | border: 1px solid hsla(0, 0%, 0%, 0.15); 26 | flex-grow: 1; 27 | margin-block: 1em; 28 | overflow-y: auto; 29 | padding: 0; 30 | } 31 | 32 | .device.selected { 33 | background-color: #855CD6; 34 | color: white; 35 | } 36 | 37 | .device input[type="radio"] { 38 | /* Hide the radio button but keep it accessible for keyboard */ 39 | opacity: 0; 40 | position: absolute; 41 | } 42 | 43 | .device label { 44 | box-sizing: border-box; 45 | display: block; 46 | padding-inline: .5em; 47 | } 48 | 49 | .buttons { 50 | align-self: flex-end; 51 | } 52 | 53 | button { 54 | border-radius: .25rem; 55 | cursor: pointer; 56 | font-weight: 600; 57 | margin: 0.25rem; 58 | padding: 0.6rem 0.75rem; 59 | } 60 | 61 | .cancelButton { 62 | background: white; 63 | border: 1px solid #855CD6; 64 | color: #855CD6; 65 | } 66 | 67 | .connectButton { 68 | background: #855CD6; 69 | border: 1px solid #855CD6; 70 | color: white; 71 | } 72 | 73 | .connectButton:disabled { 74 | opacity: 50%; 75 | } 76 | -------------------------------------------------------------------------------- /src/renderer/usb.jsx: -------------------------------------------------------------------------------- 1 | import React, {useEffect, useState} from 'react'; 2 | import {ipcRenderer} from 'electron'; 3 | 4 | import styles from './usb.css'; 5 | 6 | const UsbElement = () => { 7 | const [deviceList, setDeviceList] = useState([]); 8 | const [selectedDeviceId, setSelectedDeviceId] = useState(null); 9 | 10 | useEffect(() => { 11 | const listener = (_event, usbDeviceList) => { 12 | setDeviceList(usbDeviceList); 13 | if (!usbDeviceList.some(device => device.deviceId === selectedDeviceId)) { 14 | setSelectedDeviceId(null); 15 | } 16 | }; 17 | 18 | ipcRenderer.on('usb-device-list', listener); 19 | 20 | return () => ipcRenderer.removeListener('usb-device-list', listener); 21 | }, []); 22 | 23 | const selectHandler = deviceId => () => { 24 | setSelectedDeviceId(deviceId); 25 | }; 26 | 27 | const deviceHandler = deviceId => () => { 28 | ipcRenderer.send('usb-device-selected', deviceId); 29 | setSelectedDeviceId(null); 30 | }; 31 | 32 | return ( 33 |
34 | Select your USB device: 35 |
38 | {deviceList.map(device => ( 39 |
43 | 51 | 52 |
53 | ))} 54 |
55 |
56 | 60 | 65 |
66 |
67 | ); 68 | }; 69 | 70 | export default ; 71 | -------------------------------------------------------------------------------- /webpack.main.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | const makeConfig = require('./webpack.makeConfig.js'); 4 | 5 | module.exports = makeConfig( 6 | { 7 | target: 'electron-main', 8 | entry: { 9 | main: './src/main/index.js' 10 | }, 11 | context: path.resolve(__dirname), 12 | externals: [ 13 | 'source-map-support', 14 | 'electron', 15 | 'webpack', 16 | 'webpack/hot/log-apply-result', 17 | 'electron-webpack/out/electron-main-hmr/HmrClient', 18 | 'source-map-support/source-map-support.js' 19 | ], 20 | output: { 21 | filename: '[name].js', 22 | chunkFilename: '[name].bundle.js', 23 | assetModuleFilename: 'static/assets/[name].[hash][ext]', 24 | libraryTarget: 'commonjs2', 25 | path: path.resolve(__dirname, 'dist/main') 26 | }, 27 | module: {rules: []}, 28 | node: {__dirname: false, __filename: false} 29 | }, 30 | { 31 | name: 'main', 32 | useReact: false, 33 | disableDefaultRulesForExtensions: ['js'], 34 | babelPaths: [ 35 | path.resolve(__dirname, 'src', 'main') 36 | ] 37 | } 38 | ); 39 | -------------------------------------------------------------------------------- /webpack.makeConfig.js: -------------------------------------------------------------------------------- 1 | const childProcess = require('child_process'); 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const util = require('util'); 5 | 6 | const electronPath = require('electron'); 7 | const webpack = require('webpack'); 8 | const merge = require('webpack-merge'); 9 | 10 | const isProduction = (process.env.NODE_ENV === 'production'); 11 | 12 | const electronVersion = childProcess.execSync(`${electronPath} --version`, {encoding: 'utf8'}).trim(); 13 | console.log(`Targeting Electron ${electronVersion}`); // eslint-disable-line no-console 14 | 15 | const makeConfig = function (defaultConfig, options) { 16 | const babelOptions = { 17 | // Explicitly disable babelrc so we don't catch various config in much lower dependencies. 18 | babelrc: false, 19 | plugins: [ 20 | '@babel/plugin-syntax-dynamic-import', 21 | '@babel/plugin-transform-async-to-generator', 22 | '@babel/plugin-proposal-object-rest-spread', 23 | '@babel/plugin-transform-nullish-coalescing-operator', 24 | '@babel/plugin-transform-optional-chaining' 25 | ], 26 | presets: [ 27 | ['@babel/preset-env', {targets: {electron: electronVersion}}] 28 | ] 29 | }; 30 | 31 | if (options.useReact) { 32 | babelOptions.presets = babelOptions.presets.concat('@babel/preset-react'); 33 | babelOptions.plugins.push(['react-intl', { 34 | messagesDir: './translations/messages/' 35 | }]); 36 | } 37 | 38 | // TODO: consider adjusting these rules instead of discarding them in at least some cases 39 | if (options.disableDefaultRulesForExtensions) { 40 | defaultConfig.module.rules = defaultConfig.module.rules.filter(rule => { 41 | if (!(rule.test instanceof RegExp)) { 42 | // currently we don't support overriding other kinds of rules 43 | return true; 44 | } 45 | // disable default rules for any file extension listed here 46 | // we will handle these files in some other way (see below) 47 | // OR we want to avoid any processing at all (such as with fonts) 48 | const shouldDisable = options.disableDefaultRulesForExtensions.some( 49 | ext => rule.test.test(`test.${ext}`) 50 | ); 51 | const statusWord = shouldDisable ? 'Discarding' : 'Keeping'; 52 | console.log(`${options.name}: ${statusWord} electron-webpack default rule for ${rule.test}`); 53 | return !shouldDisable; 54 | }); 55 | } 56 | 57 | const config = merge.smart(defaultConfig, { 58 | devtool: 'cheap-module-source-map', 59 | mode: isProduction ? 'production' : 'development', 60 | module: { 61 | rules: [ 62 | { 63 | test: options.useReact ? /\.jsx?$/ : /\.js$/, 64 | include: options.babelPaths, 65 | loader: 'babel-loader', 66 | options: babelOptions 67 | }, 68 | { 69 | 70 | test: /\.css$/, 71 | use: [ 72 | { 73 | loader: 'style-loader' 74 | }, 75 | { 76 | loader: 'css-loader', 77 | options: { 78 | modules: { 79 | localIdentName: '[name]_[local]_[hash:base64:5]', 80 | exportLocalsConvention: 'camelCase' 81 | }, 82 | importLoaders: 1, 83 | esModule: false 84 | } 85 | }, 86 | { 87 | loader: 'postcss-loader', 88 | options: { 89 | postcssOptions: { 90 | plugins: [ 91 | 'postcss-import', 92 | 'postcss-simple-vars', 93 | 'autoprefixer' 94 | ] 95 | } 96 | } 97 | } 98 | ] 99 | }, 100 | { 101 | test: /\.(svg|png|wav|gif|jpg)$/, 102 | type: 'asset/resource', 103 | generator: { 104 | filename: 'static/assets/[name].[hash][ext]' 105 | } 106 | }, 107 | { 108 | test: /\.hex$/, 109 | use: [{ 110 | loader: 'url-loader', 111 | options: { 112 | limit: 16 * 1024 113 | } 114 | }] 115 | } 116 | ] 117 | }, 118 | plugins: [ 119 | new webpack.SourceMapDevToolPlugin({ 120 | filename: '[file].map' 121 | }), 122 | new webpack.DefinePlugin({ 123 | __static: isProduction ? 124 | 'process.resourcesPath + "/static"' : 125 | JSON.stringify(path.resolve(process.cwd(), 'static')) 126 | }) 127 | ].concat(options.plugins || []), 128 | resolve: { 129 | cacheWithContext: false, 130 | symlinks: false, 131 | // attempt to resolve file extensions in this order 132 | // (allows leaving off the extension when importing) 133 | extensions: ['.js', '.jsx', '.json', '.node', '.css'] 134 | } 135 | }); 136 | 137 | // If we're not on CI, enable Webpack progress output 138 | if (!process.env.CI) { 139 | config.plugins.push(new webpack.ProgressPlugin()); 140 | } 141 | 142 | fs.writeFileSync( 143 | `dist/webpack.${options.name}.js`, 144 | `module.exports = ${util.inspect(config, {depth: null})};\n` 145 | ); 146 | 147 | return config; 148 | }; 149 | 150 | module.exports = makeConfig; 151 | -------------------------------------------------------------------------------- /webpack.renderer.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const fsExtra = require('fs-extra'); 3 | 4 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 5 | 6 | const CopyWebpackPlugin = require('copy-webpack-plugin'); 7 | 8 | const makeConfig = require('./webpack.makeConfig.js'); 9 | 10 | const getModulePath = moduleName => path.dirname(require.resolve(`${moduleName}`)); 11 | 12 | const generateIndexFile = template => { 13 | let html = template; 14 | 15 | html = html.replace( 16 | '', '' 17 | ); 18 | 19 | const filePath = path.join('dist', '.renderer-index-template.html'); 20 | fsExtra.outputFileSync(filePath, html); 21 | return `!!html-loader?minimize=false&attributes=false!${filePath}`; 22 | }; 23 | 24 | const template = fsExtra.readFileSync('src/renderer/index.html', {encoding: 'utf8'}); 25 | 26 | module.exports = makeConfig( 27 | { 28 | target: 'electron-renderer', 29 | entry: { 30 | renderer: './src/renderer/index.js' 31 | }, 32 | context: path.resolve(__dirname), 33 | externals: [ 34 | 'source-map-support', 35 | 'electron', 36 | 'webpack' 37 | ], 38 | output: { 39 | filename: '[name].js', 40 | assetModuleFilename: 'static/assets/[name].[hash][ext]', 41 | chunkFilename: '[name].bundle.js', 42 | libraryTarget: 'commonjs2', 43 | path: path.resolve(__dirname, 'dist/renderer') 44 | }, 45 | module: { 46 | rules: [ 47 | { 48 | test: /\.node$/, 49 | use: 'node-loader' 50 | }, 51 | { 52 | test: /\.(html)$/, 53 | use: {loader: 'html-loader'} 54 | } 55 | ] 56 | } 57 | }, 58 | { 59 | name: 'renderer', 60 | useReact: true, 61 | disableDefaultRulesForExtensions: ['js', 'jsx', 'css', 'svg', 'png', 'wav', 'gif', 'jpg', 'ttf'], 62 | babelPaths: [ 63 | path.resolve(__dirname, 'src', 'renderer'), 64 | /node_modules[\\/]+@scratch[\\/]+[^\\/]+[\\/]+src/, 65 | /node_modules[\\/]+pify/, 66 | /node_modules[\\/]+@vernier[\\/]+godirect/ 67 | ], 68 | plugins: [ 69 | new HtmlWebpackPlugin({ 70 | filename: 'index.html', 71 | template: generateIndexFile(template), 72 | minify: false 73 | }), 74 | new CopyWebpackPlugin({ 75 | patterns: [ 76 | { 77 | from: path.join(getModulePath('@scratch/scratch-gui'), 'static'), 78 | to: 'static' 79 | }, 80 | { 81 | from: 'extension-worker.{js,js.map}', 82 | context: getModulePath('@scratch/scratch-gui') 83 | }, 84 | { 85 | from: path.join(getModulePath('@scratch/scratch-gui'), 'libraries'), 86 | to: 'static/libraries', 87 | flatten: true 88 | }, 89 | { 90 | // We need to copy the chunks for translating tutorial images for 91 | // the tutorial translations to work. 92 | from: path.join(getModulePath('@scratch/scratch-gui'), 'chunks'), 93 | to: 'chunks' 94 | } 95 | // This still results in a missing fetch worker error, because the fetch-worker 96 | // is attempted to be resolved on an absolute path (e.g. file:///chunks/fetch-worker..) 97 | // That is still fine, because we don't need the fetch-worker to retrieve information. 98 | // TODO: For a long term fix, change how the fetch-worker is resolved in `scratch-storage` 99 | // { 100 | // context: getModulePath('@scratch/scratch-gui'), 101 | // from: 'chunks/fetch-worker.*.{js,js.map}', 102 | // noErrorOnMissing: true 103 | // } 104 | ] 105 | }) 106 | ] 107 | } 108 | ); 109 | --------------------------------------------------------------------------------