├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .prettierrc.js ├── .ts-for-girrc.js ├── LICENSE ├── README.md ├── package.json ├── resources ├── metadata.json ├── schemas │ └── org.gnome.shell.extensions.minimize-to-tray.gschema.xml └── ui │ ├── prefs.glade │ └── row_template.glade ├── rollup.config.js ├── src ├── extension.ts ├── index.d.ts ├── prefs │ └── prefs.ts ├── shell │ ├── index.ts │ └── keyManager.ts ├── styles │ └── stylesheet.scss ├── utils │ └── index.ts └── window │ └── listener.ts ├── tsconfig.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | charset = utf-8 7 | trim_trailing_whitespace = false 8 | insert_final_newline = false 9 | 10 | [*.{js,ts}] 11 | quote_type = single 12 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | # don't ever lint node_modules 2 | node_modules/ 3 | # don't lint build output (make sure it's set to your correct build folder name) 4 | lib/ 5 | tmp/ 6 | test/*.js 7 | # don't lint templates 8 | templates/ 9 | # temporary ignore examples 10 | # examples/ 11 | # temporary ignore generated types, remove this if the heap out of memory bug is fixed 12 | @types/ 13 | *.js 14 | */*.js 15 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | // see https://www.robertcooper.me/using-eslint-and-prettier-in-a-typescript-project 2 | module.exports = { 3 | root: true, 4 | parser: '@typescript-eslint/parser', // Specifies the ESLint parser 5 | extends: [ 6 | 'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin 7 | 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier 8 | 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. 9 | ], 10 | rules: { 11 | 'quotes': [2, 'single', { 'avoidEscape': true }], 12 | 'no-debugger': 'off', 13 | '@typescript-eslint/no-explicit-any': 'off', 14 | '@typescript-eslint/no-misused-new': 'off', 15 | '@typescript-eslint/triple-slash-reference': 'off', 16 | '@typescript-eslint/no-unused-vars': 'error', 17 | // For Gjs 18 | 'camelcase': 'off', 19 | '@typescript-eslint/camelcase': 'off' 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/node,linux,webstorm,sublimetext,visualstudiocode 3 | # Edit at https://www.gitignore.io/?templates=node,linux,webstorm,sublimetext,visualstudiocode 4 | 5 | ### Linux ### 6 | *~ 7 | 8 | # temporary files which can be created if a process still has a handle open of a deleted file 9 | .fuse_hidden* 10 | 11 | # KDE directory preferences 12 | .directory 13 | 14 | # Linux trash folder which might appear on any partition or disk 15 | .Trash-* 16 | 17 | # .nfs files are created when an open file is removed but is still being accessed 18 | .nfs* 19 | 20 | ### Node ### 21 | # Logs 22 | logs 23 | *.log 24 | npm-debug.log* 25 | yarn-debug.log* 26 | yarn-error.log* 27 | lerna-debug.log* 28 | 29 | # Diagnostic reports (https://nodejs.org/api/report.html) 30 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 31 | 32 | # Runtime data 33 | pids 34 | *.pid 35 | *.seed 36 | *.pid.lock 37 | 38 | # Directory for instrumented libs generated by jscoverage/JSCover 39 | lib-cov 40 | 41 | # Coverage directory used by tools like istanbul 42 | coverage 43 | *.lcov 44 | 45 | # nyc test coverage 46 | .nyc_output 47 | 48 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 49 | .grunt 50 | 51 | # Bower dependency directory (https://bower.io/) 52 | bower_components 53 | 54 | # node-waf configuration 55 | .lock-wscript 56 | 57 | # Compiled binary addons (https://nodejs.org/api/addons.html) 58 | build/Release 59 | 60 | # Dependency directories 61 | node_modules/ 62 | jspm_packages/ 63 | 64 | # TypeScript v1 declaration files 65 | typings/ 66 | 67 | # TypeScript cache 68 | *.tsbuildinfo 69 | 70 | # Optional npm cache directory 71 | .npm 72 | 73 | # Optional eslint cache 74 | .eslintcache 75 | 76 | # Optional REPL history 77 | .node_repl_history 78 | 79 | # Output of 'npm pack' 80 | *.tgz 81 | 82 | # Yarn Integrity file 83 | .yarn-integrity 84 | 85 | # dotenv environment variables file 86 | .env 87 | .env.test 88 | 89 | # parcel-bundler cache (https://parceljs.org/) 90 | .cache 91 | 92 | # next.js build output 93 | .next 94 | 95 | # nuxt.js build output 96 | .nuxt 97 | 98 | # rollup.js default build output 99 | dist/ 100 | 101 | # Uncomment the public line if your project uses Gatsby 102 | # https://nextjs.org/blog/next-9-1#public-directory-support 103 | # https://create-react-app.dev/docs/using-the-public-folder/#docsNav 104 | # public 105 | 106 | # Storybook build outputs 107 | .out 108 | .storybook-out 109 | 110 | # vuepress build output 111 | .vuepress/dist 112 | 113 | # Serverless directories 114 | .serverless/ 115 | 116 | # FuseBox cache 117 | .fusebox/ 118 | 119 | # DynamoDB Local files 120 | .dynamodb/ 121 | 122 | # Temporary folders 123 | tmp/ 124 | temp/ 125 | 126 | ### SublimeText ### 127 | # Cache files for Sublime Text 128 | *.tmlanguage.cache 129 | *.tmPreferences.cache 130 | *.stTheme.cache 131 | 132 | # Workspace files are user-specific 133 | *.sublime-workspace 134 | 135 | # Project files should be checked into the repository, unless a significant 136 | # proportion of contributors will probably not be using Sublime Text 137 | # *.sublime-project 138 | 139 | # SFTP configuration file 140 | sftp-config.json 141 | 142 | # Package control specific files 143 | Package Control.last-run 144 | Package Control.ca-list 145 | Package Control.ca-bundle 146 | Package Control.system-ca-bundle 147 | Package Control.cache/ 148 | Package Control.ca-certs/ 149 | Package Control.merged-ca-bundle 150 | Package Control.user-ca-bundle 151 | oscrypto-ca-bundle.crt 152 | bh_unicode_properties.cache 153 | 154 | # Sublime-github package stores a github token in this file 155 | # https://packagecontrol.io/packages/sublime-github 156 | GitHub.sublime-settings 157 | 158 | ### Vim ### 159 | # Swap 160 | [._]*.s[a-v][a-z] 161 | [._]*.sw[a-p] 162 | [._]s[a-rt-v][a-z] 163 | [._]ss[a-gi-z] 164 | [._]sw[a-p] 165 | 166 | # Session 167 | Session.vim 168 | 169 | # Temporary 170 | .netrwhist 171 | # Auto-generated tag files 172 | tags 173 | # Persistent undo 174 | [._]*.un~ 175 | 176 | ### VisualStudioCode ### 177 | .vscode/* 178 | !.vscode/settings.json 179 | !.vscode/tasks.json 180 | !.vscode/launch.json 181 | !.vscode/extensions.json 182 | 183 | 184 | # End of https://www.gitignore.io/api/vim,linux,sublimetext,visualstudiocode 185 | gschemas.compiled 186 | extensions-sync@elhan.io*.zip 187 | _build 188 | node_modules 189 | @types 190 | dist 191 | ### VisualStudioCode Patch ### 192 | # Ignore all local history of files 193 | .history 194 | 195 | ### WebStorm ### 196 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 197 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 198 | 199 | # User-specific stuff 200 | .idea/**/workspace.xml 201 | .idea/**/tasks.xml 202 | .idea/**/usage.statistics.xml 203 | .idea/**/dictionaries 204 | .idea/**/shelf 205 | 206 | # Generated files 207 | .idea/**/contentModel.xml 208 | 209 | # Sensitive or high-churn files 210 | .idea/**/dataSources/ 211 | .idea/**/dataSources.ids 212 | .idea/**/dataSources.local.xml 213 | .idea/**/sqlDataSources.xml 214 | .idea/**/dynamic.xml 215 | .idea/**/uiDesigner.xml 216 | .idea/**/dbnavigator.xml 217 | 218 | # Gradle 219 | .idea/**/gradle.xml 220 | .idea/**/libraries 221 | 222 | # Gradle and Maven with auto-import 223 | # When using Gradle or Maven with auto-import, you should exclude module files, 224 | # since they will be recreated, and may cause churn. Uncomment if using 225 | # auto-import. 226 | # .idea/modules.xml 227 | # .idea/*.iml 228 | # .idea/modules 229 | # *.iml 230 | # *.ipr 231 | 232 | # CMake 233 | cmake-build-*/ 234 | 235 | # Mongo Explorer plugin 236 | .idea/**/mongoSettings.xml 237 | 238 | # File-based project format 239 | *.iws 240 | 241 | # IntelliJ 242 | out/ 243 | 244 | # mpeltonen/sbt-idea plugin 245 | .idea_modules/ 246 | 247 | # JIRA plugin 248 | atlassian-ide-plugin.xml 249 | 250 | # Cursive Clojure plugin 251 | .idea/replstate.xml 252 | 253 | # Crashlytics plugin (for Android Studio and IntelliJ) 254 | com_crashlytics_export_strings.xml 255 | crashlytics.properties 256 | crashlytics-build.properties 257 | fabric.properties 258 | 259 | # Editor-based Rest Client 260 | .idea/httpRequests 261 | 262 | # Android studio 3.1+ serialized cache file 263 | .idea/caches/build_file_checksums.ser 264 | 265 | ### WebStorm Patch ### 266 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 267 | 268 | # *.iml 269 | # modules.xml 270 | # .idea/misc.xml 271 | # *.ipr 272 | 273 | # Sonarlint plugin 274 | .idea/**/sonarlint/ 275 | 276 | # SonarQube Plugin 277 | .idea/**/sonarIssues.xml 278 | 279 | # Markdown Navigator plugin 280 | .idea/**/markdown-navigator.xml 281 | .idea/**/markdown-navigator/ 282 | 283 | # End of https://www.gitignore.io/api/node,linux,webstorm,sublimetext,visualstudiocode 284 | 285 | # ts-for-gjs output 286 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | semi: true, 3 | trailingComma: 'all', 4 | singleQuote: true, 5 | printWidth: 120, 6 | tabWidth: 2, 7 | }; -------------------------------------------------------------------------------- /.ts-for-girrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | environments: ['gjs'], 3 | modules: ['Gtk-3.0', 'St-1.0', 'Shell-0.1', 'Wnck-3.0'], 4 | prettify: true, 5 | girDirectories: [ 6 | '/usr/share/gir-1.0', 7 | '/usr/share/gnome-shell', 8 | '/usr/lib/mutter-6' 9 | ], 10 | outdir: './@types', 11 | ignore: [] 12 | } 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation"s software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author"s protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors" reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone"s free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program"s 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients" exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w". 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c" for details. 319 | 320 | The hypothetical commands `show w" and `show c" should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w" and `show c"; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision" (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Minimize to Tray 2 | 3 | [![ts](https://badgen.net/badge/icon/typescript?icon=typescript&label)](#) 4 | [![deps](https://img.shields.io/david/oae/gnome-shell-minimize-to-tray)](#) 5 | [![opensource](https://badges.frapsoft.com/os/v1/open-source.png?v=103)](#) 6 | [![licence](https://badges.frapsoft.com/os/gpl/gpl.png?v=103)](https://github.com/oae/gnome-shell-minimize-to-tray/blob/master/LICENSE) 7 | [![latest](https://img.shields.io/github/v/release/oae/gnome-shell-minimize-to-tray)](https://github.com/oae/gnome-shell-minimize-to-tray/releases/latest) 8 | [![compare](https://img.shields.io/github/commits-since/oae/gnome-shell-minimize-to-tray/latest/master)](https://github.com/oae/gnome-shell-minimize-to-tray/compare) 9 | 10 | Minimize any app to tray 11 | 12 | ![SS](https://i.imgur.com/Z9TnedC.png) 13 | 14 | ## Requirements 15 | 16 | Make sure you have `xdotool`, `xwininfo`, `xprop`, `libwnck3` installed on your system. 17 | 18 | ## Installation 19 | 20 | ### From [Git](https://github.com/oae/gnome-shell-minimize-to-tray) 21 | 22 | ```bash 23 | git clone https://github.com/oae/gnome-shell-minimize-to-tray.git 24 | cd ./gnome-shell-minimize-to-tray 25 | yarn install 26 | yarn build 27 | ln -s "$PWD/dist" "$HOME/.local/share/gnome-shell/extensions/minimize-to-tray@elhan.io" 28 | ``` 29 | 30 | ### From [Ego](extensions.gnome.org) 31 | 32 | - You can install it from link below 33 | https://extensions.gnome.org/extension/1750/minimize-to-tray/ 34 | 35 | ## Usage 36 | 37 | - From the extension settings, you can click add button and select any opened window to put them in to tray 38 | - There are three options for each application. 39 | - **Change active status**: You can disable the minimization for specific application 40 | - **Minimize window on start**: Whenever a new window opens for the application, it will automatically hide and minimize to tray 41 | - **Keyboard shorcut support**: This adds global keybindings to application window visibility. It currently supports ``, ``, `` and `0-9`, `a-z` keys. If there are are more than one window for specific application, it will focus to last used window. 42 | 43 | ![SS](https://i.imgur.com/78JUYQI.png) 44 | 45 | ## Development 46 | 47 | - This extension is written in Typescript and uses webpack to compile it into javascript. 48 | - Most dependencies have auto completion support thanks to [this amazing project](https://github.com/sammydre/ts-for-gjs) by [@sammydre](https://github.com/sammydre) 49 | - To start development, you need nodejs installed on your system; 50 | 51 | - Clone the project 52 | 53 | ```sh 54 | git clone https://github.com/oae/gnome-shell-minimize-to-tray.git 55 | cd ./gnome-shell-minimize-to-tray 56 | ``` 57 | 58 | - Install dependencies and build it 59 | 60 | ```sh 61 | yarn install 62 | yarn build 63 | ``` 64 | 65 | - During development you can use `yarn watch` command to keep generated code up-to-date. 66 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "minimize-to-tray", 3 | "version": "1.0.0", 4 | "author": "Alperen Elhan ", 5 | "license": "MIT", 6 | "scripts": { 7 | "build": "yarn run build:types && yarn run build:ts && yarn run build:extension", 8 | "clean": "yarn run clean:ts && yarn run build:types", 9 | "build:types": "yarn run clean:types && ts-for-gir generate", 10 | "clean:types": "rm -rf ./@types", 11 | "build:ts": "yarn run clean:ts && rollup -c", 12 | "clean:ts": "rm -rf ./dist", 13 | "build:extension": "yarn run build:schema", 14 | "build:schema": "yarn run clean:schema && glib-compile-schemas ./resources/schemas --targetdir=./dist/schemas/", 15 | "clean:schema": "rm -rf ./dist/schemas/*.compiled", 16 | "build:package": "rm -rf './dist/minimize-to-tray@elhan.io.zip' && cd ./dist && zip -qr 'minimize-to-tray@elhan.io.zip' .", 17 | "watch": "yarn run build && yarn run rollup -c --watch", 18 | "test": "echo \"Error: no test specified\" && exit 1", 19 | "lint": "eslint --ext .ts src/" 20 | }, 21 | "commitlint": { 22 | "extends": [ 23 | "@commitlint/config-conventional" 24 | ] 25 | }, 26 | "husky": { 27 | "hooks": { 28 | "pre-commit": "yarn run lint", 29 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" 30 | } 31 | }, 32 | "devDependencies": { 33 | "@commitlint/cli": "^9.1.2", 34 | "@commitlint/config-conventional": "^9.1.2", 35 | "@rollup/plugin-commonjs": "^15.0.0", 36 | "@rollup/plugin-node-resolve": "^9.0.0", 37 | "@rollup/plugin-typescript": "^5.0.2", 38 | "@types/events": "^3.0.0", 39 | "@typescript-eslint/eslint-plugin": "^3.9.1", 40 | "@typescript-eslint/parser": "^3.9.1", 41 | "eslint": "^7.7.0", 42 | "eslint-config-prettier": "^6.11.0", 43 | "eslint-plugin-prettier": "^3.1.4", 44 | "husky": "^4.2.5", 45 | "node-sass": "^4.14.1", 46 | "prettier": "^2.0.5", 47 | "rollup": "^2.26.4", 48 | "rollup-plugin-copy": "^3.3.0", 49 | "rollup-plugin-scss": "^2.6.0", 50 | "ts-for-gir": "https://github.com/oae/ts-for-gjs", 51 | "typescript": "^4.0.2" 52 | }, 53 | "dependencies": {} 54 | } 55 | -------------------------------------------------------------------------------- /resources/metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Minimize to Tray", 3 | "description": "Minimize any app to tray", 4 | "uuid": "minimize-to-tray@elhan.io", 5 | "version": 6, 6 | "settings-schema": "org.gnome.shell.extensions.minimize-to-tray", 7 | "url": "https://github.com/oae/gnome-shell-minimize-to-tray", 8 | "shell-version": ["3.36"] 9 | } 10 | -------------------------------------------------------------------------------- /resources/schemas/org.gnome.shell.extensions.minimize-to-tray.gschema.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | "[]" 6 | Minimize to tray data 7 | Minimize to tray data 8 | 9 | 10 | "[]" 11 | Minimize to tray extension state 12 | Minimize to tray extension state 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /resources/ui/prefs.glade: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 480 7 | -1 8 | True 9 | False 10 | True 11 | True 12 | vertical 13 | 10 14 | bottom 15 | 16 | 17 | True 18 | False 19 | 12 20 | 12 21 | 24 22 | 24 23 | 24 | 25 | 50 26 | True 27 | True 28 | False 29 | 30 | 31 | True 32 | True 33 | True 34 | none 35 | 36 | 37 | 38 | True 39 | False 40 | list-add-symbolic 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | False 50 | True 51 | 0 52 | 53 | 54 | 55 | 56 | True 57 | False 58 | end 59 | end 60 | 12 61 | 12 62 | 10 63 | bottom 64 | end 65 | 66 | 67 | Close 68 | True 69 | True 70 | True 71 | 72 | 73 | 74 | True 75 | True 76 | 0 77 | 78 | 79 | 80 | 81 | Save 82 | True 83 | True 84 | True 85 | 86 | 87 | 88 | True 89 | True 90 | 1 91 | 92 | 93 | 94 | 95 | False 96 | False 97 | end 98 | 1 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /resources/ui/row_template.glade: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | False 7 | keybinding-button 8 | left 9 | 10 | 11 | 40 12 | True 13 | False 14 | 10 15 | 16 | 17 | True 18 | True 19 | False 20 | 21 | 22 | True 23 | True 24 | 0 25 | 26 | 27 | 28 | 29 | Done 30 | True 31 | True 32 | True 33 | 34 | 35 | False 36 | False 37 | end 38 | 1 39 | 40 | 41 | 42 | 43 | main 44 | 45 | 46 | 47 | 48 | True 49 | True 50 | False 51 | False 52 | 53 | 54 | True 55 | False 56 | 57 | 58 | True 59 | False 60 | 6 61 | 6 62 | 6 63 | 6 64 | 6 65 | 6 66 | 67 | 68 | 50 69 | 50 70 | True 71 | False 72 | 48 73 | preferences-desktop-multimedia 74 | 75 | 76 | False 77 | False 78 | 0 79 | 80 | 81 | 82 | 83 | 120 84 | True 85 | False 86 | 10 87 | Spotify 88 | 0 89 | 90 | 91 | 92 | 93 | 94 | False 95 | False 96 | 1 97 | 98 | 99 | 100 | 101 | True 102 | True 103 | 1 104 | 105 | 106 | 107 | 108 | True 109 | False 110 | center 111 | center 112 | 10 113 | 114 | 115 | True 116 | False 117 | 118 | 119 | 120 | 121 | 122 | False 123 | True 124 | 0 125 | 126 | 127 | 128 | 129 | True 130 | True 131 | False 132 | True 133 | keybinding-popover 134 | 135 | 136 | True 137 | False 138 | input-keyboard-symbolic 139 | 140 | 141 | 142 | 143 | False 144 | True 145 | 1 146 | 147 | 148 | 149 | 150 | True 151 | True 152 | True 153 | Minimize window on start 154 | 155 | 156 | True 157 | False 158 | window-minimize-symbolic 159 | 160 | 161 | 162 | 163 | False 164 | True 165 | 2 166 | 167 | 168 | 169 | 170 | True 171 | True 172 | Toggle active 173 | center 174 | center 175 | 20 176 | True 177 | 178 | 179 | False 180 | False 181 | 3 182 | 183 | 184 | 185 | 186 | True 187 | True 188 | True 189 | Remove 190 | center 191 | center 192 | 6 193 | True 194 | 195 | 196 | 197 | True 198 | False 199 | user-trash-symbolic 200 | 201 | 202 | 203 | 204 | False 205 | True 206 | 4 207 | 208 | 209 | 210 | 211 | False 212 | False 213 | end 214 | 2 215 | 216 | 217 | 218 | 219 | 220 | 221 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import typescript from '@rollup/plugin-typescript'; 2 | import { nodeResolve } from '@rollup/plugin-node-resolve'; 3 | import commonjs from '@rollup/plugin-commonjs'; 4 | import scss from 'rollup-plugin-scss'; 5 | import copy from 'rollup-plugin-copy'; 6 | 7 | const buildPath = 'dist'; 8 | 9 | const globals = { 10 | '@imports/Gio-2.0': 'imports.gi.Gio', 11 | '@imports/Gdk-3.0': 'imports.gi.Gdk', 12 | '@imports/Gtk-3.0': 'imports.gi.Gtk', 13 | '@imports/GdkPixbuf-2.0': 'imports.gi.GdkPixbuf', 14 | '@imports/GLib-2.0': 'imports.gi.GLib', 15 | '@imports/St-1.0': 'imports.gi.St', 16 | '@imports/Shell-0.1': 'imports.gi.Shell', 17 | '@imports/Meta-6': 'imports.gi.Meta', 18 | '@imports/Wnck-3.0': 'imports.gi.Wnck', 19 | '@imports/Clutter-6': 'imports.gi.Clutter', 20 | }; 21 | 22 | const external = Object.keys(globals); 23 | 24 | const banner = [ 25 | 'imports.gi.versions.Wnck = \'3.0\';', 26 | ].join('\n'); 27 | 28 | const prefsFooter = [ 29 | 'var init = prefs.init;', 30 | 'var buildPrefsWidget = prefs.buildPrefsWidget;', 31 | ].join('\n') 32 | 33 | export default [ 34 | { 35 | input: 'src/extension.ts', 36 | output: { 37 | file: `${buildPath}/extension.js`, 38 | format: 'iife', 39 | name: 'init', 40 | banner, 41 | exports: 'default', 42 | globals, 43 | }, 44 | external, 45 | plugins: [ 46 | commonjs(), 47 | nodeResolve({ 48 | preferBuiltins: false, 49 | }), 50 | typescript({ 51 | tsconfig: './tsconfig.json', 52 | }), 53 | scss({ 54 | output: `${buildPath}/stylesheet.css`, 55 | failOnError: true, 56 | watch: 'src/styles', 57 | }), 58 | copy({ 59 | targets: [ 60 | { src: './resources/metadata.json', dest: `${buildPath}` }, 61 | { src: './resources/schemas', dest: `${buildPath}` }, 62 | ], 63 | }), 64 | ], 65 | }, 66 | { 67 | input: 'src/prefs/prefs.ts', 68 | output: { 69 | file: `${buildPath}/prefs.js`, 70 | format: 'iife', 71 | exports: 'default', 72 | name: 'prefs', 73 | banner, 74 | footer: prefsFooter, 75 | globals, 76 | }, 77 | external, 78 | plugins: [ 79 | commonjs(), 80 | nodeResolve({ 81 | preferBuiltins: false, 82 | }), 83 | typescript({ 84 | tsconfig: './tsconfig.json', 85 | }), 86 | copy({ 87 | targets: [{ src: './resources/ui', dest: `${buildPath}` }], 88 | }), 89 | ], 90 | }, 91 | ]; 92 | -------------------------------------------------------------------------------- /src/extension.ts: -------------------------------------------------------------------------------- 1 | import { getMissingDeps, logger } from '@mtt/utils'; 2 | import { WindowListener } from '@mtt/window/listener'; 3 | import './styles/stylesheet.scss'; 4 | 5 | const { notifyError } = imports.ui.main; 6 | const debug = logger('extension'); 7 | 8 | class MttExtension { 9 | private listener: WindowListener; 10 | 11 | constructor() { 12 | const missingDeps = getMissingDeps(); 13 | 14 | if (missingDeps.length > 0) { 15 | debug(`Failed to enable minimize-to-tray extension. ${missingDeps.join(', ')} application/s are not installed`); 16 | notifyError('Dependencies are not satisfied.', `Please install ${missingDeps.join(', ')}.`); 17 | 18 | throw new Error(`Failed to enable minimize-to-tray. ${missingDeps.join(', ')} application/s are not installed`); 19 | } 20 | 21 | this.listener = new WindowListener(); 22 | debug('extension is initialized'); 23 | } 24 | 25 | enable(): void { 26 | this.listener.enable(); 27 | debug('extension is enabled'); 28 | } 29 | 30 | disable(): void { 31 | this.listener.disable(); 32 | debug('extension is disabled'); 33 | } 34 | } 35 | 36 | export default function (): MttExtension { 37 | return new MttExtension(); 38 | } 39 | -------------------------------------------------------------------------------- /src/index.d.ts: -------------------------------------------------------------------------------- 1 | declare global { 2 | function _(arg: string): string; 3 | } 4 | 5 | export type MttInfo = { 6 | className: string; 7 | icon?: string; 8 | enabled: boolean; 9 | startHidden: boolean; 10 | keybinding: Array; 11 | }; 12 | 13 | export type MttWindow = { 14 | xid: string; 15 | hidden: boolean; 16 | className: string; 17 | lastUpdatedAt: Date; 18 | }; 19 | 20 | export {}; 21 | -------------------------------------------------------------------------------- /src/prefs/prefs.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Event, 3 | keyval_name, 4 | KEY_Alt_L, 5 | KEY_Alt_R, 6 | KEY_Control_L, 7 | KEY_Control_R, 8 | KEY_Shift_L, 9 | KEY_Shift_R, 10 | } from '@imports/Gdk-3.0'; 11 | import { Colorspace, Pixbuf } from '@imports/GdkPixbuf-2.0'; 12 | import { Settings } from '@imports/Gio-2.0'; 13 | import { base64_decode, base64_encode } from '@imports/GLib-2.0'; 14 | import { 15 | Box, 16 | Builder, 17 | Button, 18 | CssProvider, 19 | Entry, 20 | IconLookupFlags, 21 | IconSize, 22 | IconTheme, 23 | Image, 24 | Label, 25 | ListBox, 26 | ListBoxRow, 27 | MenuButton, 28 | Popover, 29 | StyleContext, 30 | STYLE_PROVIDER_PRIORITY_USER, 31 | Switch, 32 | ToggleButton, 33 | } from '@imports/Gtk-3.0'; 34 | import { Screen, Window } from '@imports/Wnck-3.0'; 35 | import { MttInfo } from '@mtt/index'; 36 | import { getCurrentExtension, getCurrentExtensionSettings, ShellExtension } from '@mtt/shell'; 37 | import { getWindowClassName, getWindowXid, logger } from '@mtt/utils'; 38 | 39 | const debug = logger('prefs'); 40 | 41 | class Preferences { 42 | extension: ShellExtension; 43 | private settings: Settings; 44 | private builder: Builder; 45 | private trackedClassesListBox: ListBox; 46 | private mttData: Array; 47 | 48 | widget: Box; 49 | 50 | constructor() { 51 | this.mttData = []; 52 | this.extension = getCurrentExtension(); 53 | this.settings = getCurrentExtensionSettings(); 54 | 55 | // Create a parent widget 56 | this.widget = new Box(); 57 | 58 | // Load ui from glade file 59 | this.builder = Builder.new_from_file(`${this.extension.path}/ui/prefs.glade`); 60 | 61 | // Connect all events 62 | this.builder.connect_signals_full((builder, object, signal, handler) => { 63 | object.connect(signal, this[handler].bind(this)); 64 | }); 65 | 66 | this.trackedClassesListBox = this.builder.get_object('tracked-classes-listbox') as ListBox; 67 | const settingsBox = this.builder.get_object('mtt-settings') as Box; 68 | 69 | this.widget.pack_start(settingsBox, true, true, 0); 70 | this.widget.get_parent_window()?.set_title(this.extension.metadata.name); 71 | 72 | // Initialize values 73 | this.initValues(); 74 | } 75 | 76 | private initValues(): void { 77 | try { 78 | // Get the already saved data 79 | this.mttData = JSON.parse(this.settings.get_string('mtt-data')); 80 | } catch (_) { 81 | debug('could not parse the settings data, resetting it.'); 82 | this.mttData = []; 83 | } 84 | 85 | // Create ui row for each item 86 | this.mttData.forEach((data) => this.addRow(data)); 87 | debug('initialized values'); 88 | } 89 | 90 | private async onAddApplication(): Promise { 91 | try { 92 | // Get the window id and the window 93 | const windowId = await getWindowXid(); 94 | 95 | if (!windowId) { 96 | return; 97 | } 98 | 99 | // Get the class name 100 | const className = await getWindowClassName(windowId); 101 | 102 | // Check if we have a className 103 | if (!className) { 104 | return; 105 | } 106 | 107 | // Check if class name is already included 108 | if (this.mttData.findIndex((data) => data.className === className) >= 0) { 109 | return; 110 | } 111 | 112 | // Get the icon 113 | const icon = this.getIconFromWindow(windowId); 114 | 115 | const mttInfo = { 116 | className, 117 | enabled: true, 118 | startHidden: false, 119 | icon: icon && base64_encode(icon.get_pixels()), 120 | keybinding: [], 121 | }; 122 | 123 | // Add row to list 124 | this.addRow(mttInfo); 125 | 126 | // Add data to mttData 127 | this.mttData.push(mttInfo); 128 | } catch (ex) { 129 | debug(`exception: ${ex}`); 130 | } 131 | } 132 | 133 | private onSave(): void { 134 | this.settings.set_string('mtt-data', JSON.stringify(this.mttData)); 135 | this.onClose(); 136 | } 137 | 138 | private onClose(): void { 139 | this.widget.get_toplevel().destroy(); 140 | } 141 | 142 | private addRow(info: MttInfo): void { 143 | const rowBuilder = Builder.new_from_file(`${this.extension.path}/ui/row_template.glade`); 144 | 145 | // Get the template 146 | const row = rowBuilder.get_object('row-template') as ListBoxRow; 147 | 148 | // Set the class name 149 | const classNameLabel = rowBuilder.get_object('class-name-label') as Label; 150 | classNameLabel.set_text(info.className); 151 | 152 | // Set the icon 153 | if (info.icon) { 154 | const iconImage = rowBuilder.get_object('icon-image') as Image; 155 | iconImage.set_from_pixbuf(this.createIcon(info.icon)); 156 | } 157 | 158 | // Set the enabled switch 159 | const enabledSwitch = rowBuilder.get_object('enabled-switch') as Switch; 160 | enabledSwitch.set_active(info.enabled); 161 | 162 | // Connect to state set event for changes 163 | enabledSwitch.connect('state-set', (_, state) => { 164 | const currentInfo = this.mttData.find((data) => data.className === info.className); 165 | if (currentInfo) { 166 | currentInfo.enabled = state; 167 | } 168 | }); 169 | 170 | // Connect remove event 171 | const removeButton = rowBuilder.get_object('remove-button') as Button; 172 | removeButton.connect('clicked', () => { 173 | this.trackedClassesListBox.remove(row); 174 | this.mttData = this.mttData.filter((data) => data.className !== info.className); 175 | }); 176 | 177 | // Read keybinding widgets from builder 178 | const keybindingsContainer = rowBuilder.get_object('keybinding-container') as Box; 179 | const keybindingButton = rowBuilder.get_object('keybinding-button') as MenuButton; 180 | const keybindingButtonImage = keybindingButton.get_child() as Image; 181 | const keybindingAddButton = rowBuilder.get_object('keybinding-add-button') as Button; 182 | const keybindingEntry = rowBuilder.get_object('keybinding-entry') as Entry; 183 | const keybindingPopover = rowBuilder.get_object('keybinding-popover') as Popover; 184 | 185 | // If keybinding is assigned to info, then show it in ui 186 | if (info.keybinding && info.keybinding.length > 0) { 187 | info.keybinding.forEach((key) => { 188 | const label = new Label(); 189 | keybindingButton.set_tooltip_text('Remove keyboard shortcut'); 190 | keybindingButtonImage.set_from_icon_name('edit-undo-symbolic', IconSize.BUTTON); 191 | label.get_style_context().add_class('keycap'); 192 | label.get_style_context().add_class('mtt-keybinding'); 193 | label.set_text(key); 194 | label.show_all(); 195 | keybindingsContainer.add_child(rowBuilder, label, null); 196 | }); 197 | } 198 | 199 | // Clear and toggle popover on button click 200 | keybindingButton.connect('clicked', () => { 201 | if (info.keybinding && info.keybinding.length > 0) { 202 | debug('removing keybinding'); 203 | info.keybinding = []; 204 | keybindingPopover.hide(); 205 | keybindingsContainer.get_children().forEach((child) => child.destroy()); 206 | keybindingButtonImage.set_from_icon_name('input-keyboard-symbolic', IconSize.BUTTON); 207 | keybindingButton.set_tooltip_text('Add keyboard shortcut'); 208 | } else { 209 | debug('adding keybinding'); 210 | keybindingPopover.show(); 211 | } 212 | }); 213 | 214 | // Detect keys 215 | let keys = new Array<{ value: number; name: string }>(); 216 | keybindingEntry.connect('key-press-event', (_, event: Event) => { 217 | const keyVal = event.get_keyval()[1]; 218 | let keyName = keyval_name(keyVal); 219 | if (!keyName) { 220 | return; 221 | } 222 | debug(`pressed key: ${keyVal}/${keyName}`); 223 | 224 | // Check if pressed is supported or not 225 | if (this.isSupportedModifier(keyVal)) { 226 | try { 227 | keyName = `<${keyName.split('_')[0].toLowerCase()}>`; 228 | } catch (ex) { 229 | return; 230 | } 231 | } else if (!this.isSupportedAlphaNumericKey(keyVal)) { 232 | return; 233 | } 234 | 235 | if (keys.findIndex((key) => key.value == keyVal) >= 0) { 236 | return; 237 | } 238 | 239 | keys.push({ 240 | value: keyVal, 241 | name: keyName, 242 | }); 243 | (keybindingEntry as any).keys = [...keys]; 244 | keybindingEntry.set_text(`${keys.map((key) => key.name).join(' ')}`); 245 | }); 246 | 247 | // Clear keys on key release 248 | keybindingEntry.connect('key-release-event', () => { 249 | keys = []; 250 | }); 251 | 252 | // When clicked to `Done` button, save the keybinding 253 | keybindingAddButton.connect('clicked', () => { 254 | const keybindingArr = [...((keybindingEntry as any).keys as [{ value: number; name: string }])]; 255 | (keybindingEntry as any).keys = []; 256 | keybindingPopover.hide(); 257 | keybindingEntry.set_text(''); 258 | if (!keybindingArr) { 259 | return; 260 | } 261 | if ( 262 | keybindingArr.findIndex((key) => this.isSupportedModifier(key.value)) < 0 || 263 | keybindingArr.findIndex((key) => this.isSupportedAlphaNumericKey(key.value)) < 0 264 | ) { 265 | return; 266 | } 267 | info.keybinding = keybindingArr.map((key) => key.name); 268 | keybindingButton.set_tooltip_text('Remove keyboard shortcut'); 269 | info.keybinding.forEach((key) => { 270 | const label = new Label(); 271 | label.get_style_context().add_class('keycap'); 272 | label.get_style_context().add_class('mtt-keybinding'); 273 | label.set_text(key); 274 | keybindingButtonImage.set_from_icon_name('edit-undo-symbolic', IconSize.BUTTON); 275 | keybindingsContainer.add_child(rowBuilder, label, null); 276 | label.show_all(); 277 | }); 278 | }); 279 | 280 | // Set startHidden switch 281 | const startHiddenToggle = rowBuilder.get_object('start-hidden-toggle') as ToggleButton; 282 | startHiddenToggle.set_active(info.startHidden); 283 | startHiddenToggle.connect('toggled', () => { 284 | const currentInfo = this.mttData.find((data) => data.className === info.className); 285 | if (currentInfo) { 286 | currentInfo.startHidden = startHiddenToggle.get_active(); 287 | } 288 | }); 289 | 290 | // Add to existing list 291 | this.trackedClassesListBox.insert(row, 0); 292 | } 293 | 294 | private isSupportedModifier(keyVal: number): boolean { 295 | const supportedModifiers = [KEY_Control_L, KEY_Control_R, KEY_Shift_L, KEY_Shift_R, KEY_Alt_L, KEY_Alt_R]; 296 | 297 | return supportedModifiers.indexOf(keyVal) >= 0; 298 | } 299 | 300 | private isSupportedAlphaNumericKey(keyVal: number): boolean { 301 | const supportedAlphaNumericalRange = [ 302 | [65, 90], // uppercase alphabet 303 | [97, 122], // lowercase alphabet, 304 | [48, 57], // digits 305 | ]; 306 | 307 | return supportedAlphaNumericalRange.findIndex((range) => keyVal >= range[0] && keyVal <= range[1]) >= 0; 308 | } 309 | 310 | private createIcon(iconBase64?: string): Pixbuf | undefined { 311 | if (iconBase64) { 312 | return Pixbuf.new_from_bytes(base64_decode(iconBase64), Colorspace.RGB, true, 8, 32, 32, 128); 313 | } 314 | } 315 | 316 | private getIconFromWindow(xid: string): Pixbuf | undefined { 317 | Screen.get_default()?.force_update(); 318 | const window = Window.get(parseInt(xid)); 319 | if (!window || window.get_icon_is_fallback()) { 320 | debug(`getting icon for window ${xid}`); 321 | // Get the icon from window 322 | const defaulIcon = IconTheme.get_default().lookup_icon( 323 | 'applications-system-symbolic', 324 | 32, 325 | IconLookupFlags.USE_BUILTIN, 326 | ); 327 | 328 | return defaulIcon?.load_icon(); 329 | } 330 | 331 | return window.get_icon(); 332 | } 333 | } 334 | 335 | const init = (): void => { 336 | debug('prefs initialized'); 337 | }; 338 | 339 | const buildPrefsWidget = (): any => { 340 | const prefs = new Preferences(); 341 | const styleProvider = new CssProvider(); 342 | styleProvider.load_from_path(`${prefs.extension.path}/stylesheet.css`); 343 | StyleContext.add_provider_for_screen(prefs.widget.get_screen(), styleProvider, STYLE_PROVIDER_PRIORITY_USER); 344 | prefs.widget.show_all(); 345 | 346 | return prefs.widget; 347 | }; 348 | 349 | export default { init, buildPrefsWidget }; 350 | -------------------------------------------------------------------------------- /src/shell/index.ts: -------------------------------------------------------------------------------- 1 | import { File, Settings } from '@imports/Gio-2.0'; 2 | 3 | export enum ExtensionType { 4 | SYSTEM = 1, 5 | PER_USER = 2, 6 | } 7 | 8 | export enum ExtensionState { 9 | ENABLED = 1, 10 | DISABLED = 2, 11 | ERROR = 3, 12 | OUT_OF_DATE = 4, 13 | DOWNLOADING = 5, 14 | INITIALIZED = 6, 15 | 16 | // Used as an error state for operations on unknown extensions, 17 | // should never be in a real extensionMeta object. 18 | UNINSTALLED = 99, 19 | } 20 | 21 | export interface ShellExtension { 22 | canChange: boolean; 23 | dir: File; 24 | error: any; 25 | hasPrefs: boolean; 26 | hasUpdate: boolean; 27 | imports: any; 28 | metadata: { 29 | name: string; 30 | description: string; 31 | uuid: string; 32 | 'settings-schema': string; 33 | 'shell-version': Array; 34 | }; 35 | path: string; 36 | state: ExtensionState; 37 | stateObj: any; 38 | stylesheet: File; 39 | type: ExtensionType; 40 | uuid: string; 41 | } 42 | 43 | export const getCurrentExtension = (): ShellExtension => imports.misc.extensionUtils.getCurrentExtension(); 44 | 45 | export const getCurrentExtensionSettings = (): Settings => imports.misc.extensionUtils.getSettings(); 46 | -------------------------------------------------------------------------------- /src/shell/keyManager.ts: -------------------------------------------------------------------------------- 1 | import { external_binding_name_for_action, KeyBindingAction, KeyBindingFlags } from '@imports/Meta-6'; 2 | import { ActionMode, Global } from '@imports/Shell-0.1'; 3 | import { logger } from '@mtt/utils'; 4 | const { wm } = imports.ui.main; 5 | 6 | const debug = logger('key-manager'); 7 | 8 | /** 9 | * From https://superuser.com/questions/471606/gnome-shell-extension-key-binding 10 | */ 11 | export class KeyManager { 12 | private grabbers: any; 13 | 14 | constructor() { 15 | this.grabbers = {}; 16 | 17 | Global.get().display.connect('accelerator-activated', (_, action) => { 18 | this.onAccelerator(action); 19 | }); 20 | } 21 | 22 | stopListening(): void { 23 | Object.keys(this.grabbers).forEach((grabberAction) => { 24 | const grabber = this.grabbers[grabberAction]; 25 | Global.get().display.ungrab_accelerator(grabber.action); 26 | wm.allowKeybinding(grabber.name, ActionMode.NONE); 27 | }); 28 | } 29 | 30 | listenFor(accelerator: string, callback: () => any): void { 31 | debug(`Trying to listen for hot key [accelerator=${accelerator}]`); 32 | const action = Global.get().display.grab_accelerator(accelerator, KeyBindingFlags.NONE); 33 | 34 | if (action == KeyBindingAction.NONE) { 35 | debug(`Unable to grab accelerator [binding=${accelerator}]`); 36 | } else { 37 | debug(`Grabbed accelerator [action=${action}]`); 38 | const name = external_binding_name_for_action(action); 39 | debug(`Received binding name for action [name=${name}, action=${action}]`); 40 | 41 | wm.allowKeybinding(name, ActionMode.ALL); 42 | 43 | this.grabbers[action] = { 44 | name: name, 45 | accelerator: accelerator, 46 | callback: callback, 47 | action: action, 48 | }; 49 | } 50 | } 51 | 52 | private onAccelerator(action: number): void { 53 | const grabber = this.grabbers[action]; 54 | 55 | if (grabber) { 56 | grabber.callback(); 57 | } else { 58 | debug(`No listeners [action=${action}]`); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/styles/stylesheet.scss: -------------------------------------------------------------------------------- 1 | /* Add your custom extension styling here */ 2 | .mtt-keybinding { 3 | margin-left: 5px; 4 | } 5 | -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | import { AsyncResult, Subprocess, SubprocessFlags } from '@imports/Gio-2.0'; 2 | import { find_program_in_path, PRIORITY_DEFAULT, Source, timeout_add } from '@imports/GLib-2.0'; 3 | import { Window } from '@imports/Meta-6'; 4 | 5 | const REQUIRED_PROGRAMS = ['xwininfo', 'xdotool', 'xprop']; 6 | 7 | export const getMissingDeps = (): Array => { 8 | return REQUIRED_PROGRAMS.filter((program) => find_program_in_path(program) === null); 9 | }; 10 | 11 | export const logger = (prefix: string) => (content: string): void => log(`[mtt] [${prefix}] ${content}`); 12 | 13 | const debug = logger('utils'); 14 | 15 | export const setInterval = (func: () => any, millis: number): number => { 16 | const id = timeout_add(PRIORITY_DEFAULT, millis, () => { 17 | func(); 18 | 19 | return true; 20 | }); 21 | 22 | return id; 23 | }; 24 | 25 | export const clearInterval = (id: number): boolean => Source.remove(id); 26 | 27 | export const setTimeout = (func: () => any, millis: number): number => { 28 | return timeout_add(PRIORITY_DEFAULT, millis, () => { 29 | func(); 30 | 31 | return false; 32 | }); 33 | }; 34 | 35 | export const clearTimeout = (id: number): boolean => Source.remove(id); 36 | 37 | export const execute = async (command: string): Promise => { 38 | const process = new Subprocess({ 39 | argv: ['bash', '-c', command], 40 | flags: SubprocessFlags.STDOUT_PIPE, 41 | }); 42 | 43 | process.init(null); 44 | 45 | return new Promise((resolve, reject) => { 46 | process.communicate_utf8_async(null, null, (_, result: AsyncResult) => { 47 | const [, stdout, stderr] = process.communicate_utf8_finish(result); 48 | if (stderr) { 49 | reject(stderr); 50 | } else if (stdout) { 51 | resolve(stdout.trim()); 52 | } else { 53 | resolve(); 54 | } 55 | }); 56 | }); 57 | }; 58 | 59 | export const getWindowClassName = async (xid: string): Promise => { 60 | try { 61 | if (xid) { 62 | const xpropOut = await execute(`xprop -id ${xid} WM_CLASS`); 63 | if (xpropOut != null) { 64 | return xpropOut.split('=')[1].split(',')[0].trim().split('"')[1]; 65 | } 66 | } 67 | } catch (ex) { 68 | debug(`error occured while getting window className: ${ex}`); 69 | } 70 | }; 71 | 72 | export const getWindowXid = async (): Promise => { 73 | try { 74 | return execute('xdotool selectwindow'); 75 | } catch (ex) { 76 | debug(`error occured while getting windowXid: ${ex}`); 77 | } 78 | }; 79 | 80 | /** 81 | * Taken from pixel saver extension. https://github.com/pixel-saver/pixel-saver 82 | * 83 | * Guesses the X ID of a window. 84 | */ 85 | export const guessWindowXID = async (window: Window): Promise => { 86 | // We cache the result so we don't need to redetect. 87 | if (!window) { 88 | return; 89 | } 90 | 91 | if ((window as any)._mttWindowId) { 92 | return (window as any)._mttWindowId; 93 | } 94 | 95 | /** 96 | * If window title has non-utf8 characters, get_description() complains 97 | * "Failed to convert UTF-8 string to JS string: Invalid byte sequence in conversion input", 98 | * event though get_title() works. 99 | */ 100 | try { 101 | const m = window.get_description().match(/0x[0-9a-f]+/); 102 | if (m && m[0]) { 103 | (window as any)._mttWindowId = m[0]; 104 | 105 | return m[0]; 106 | } 107 | } catch (err) { 108 | debug('failed to get xid from window description, now trying xwininfo'); 109 | } 110 | 111 | // use xwininfo, take first child. 112 | const act = window.get_compositor_private(); 113 | const xwindow = act && act['x-window']; 114 | if (xwindow) { 115 | try { 116 | const xwininfo = await execute(`xwininfo -children -id 0x${xwindow}`); 117 | if (xwininfo[0]) { 118 | const str = xwininfo[1].toString(); 119 | 120 | /** 121 | * The X ID of the window is the one preceding the target window's title. 122 | * This is to handle cases where the window has no frame and so 123 | * act['x-window'] is actually the X ID we want, not the child. 124 | */ 125 | const regexp = new RegExp(`(0x[0-9a-f]+) +"${window.title}"`); 126 | let m = str.match(regexp); 127 | if (m && m[1]) { 128 | (window as any)._mttWindowId = m[1]; 129 | return m[1]; 130 | } 131 | 132 | // Otherwise, just grab the child and hope for the best 133 | m = str.split(/child(?:ren)?:/)[1].match(/0x[0-9a-f]+/); 134 | if (m && m[0]) { 135 | (window as any)._mttWindowId = m[0]; 136 | 137 | return m[0]; 138 | } 139 | } 140 | } catch (err) { 141 | debug('failed to get xid from xwininfo, now trying xprop'); 142 | } 143 | } 144 | 145 | // Try enumerating all available windows and match the title. Note that this 146 | // may be necessary if the title contains special characters and `x-window` 147 | // is not available. 148 | try { 149 | const result = await execute('xprop -root _NET_CLIENT_LIST'); 150 | if (result[0]) { 151 | const str = result[1].toString(); 152 | 153 | // Get the list of window IDs. 154 | const windowList = str.match(/0x[0-9a-f]+/g); 155 | 156 | if (windowList) { 157 | // For each window ID, check if the title matches the desired title. 158 | for (let i = 0; i < windowList.length; ++i) { 159 | const result = await execute(`xprop -id "${windowList[i]}" _NET_WM_NAME`); 160 | 161 | if (result[0]) { 162 | const output = result[1].toString(); 163 | 164 | const title = output.match(/_NET_WM_NAME(\(\w+\))? = "(([^\\"]|\\"|\\\\)*)"/); 165 | 166 | // Is this our guy? 167 | if (title && title[2] == window.title) { 168 | return windowList[i]; 169 | } 170 | } 171 | } 172 | } 173 | } 174 | } catch (err) { 175 | debug('failed to get xid from xprop too. giving up.'); 176 | } 177 | }; 178 | -------------------------------------------------------------------------------- /src/window/listener.ts: -------------------------------------------------------------------------------- 1 | import { ActorAlign } from '@imports/Clutter-6'; 2 | import { Settings } from '@imports/Gio-2.0'; 3 | import { Window, WindowType } from '@imports/Meta-6'; 4 | import { Global, WindowTracker } from '@imports/Shell-0.1'; 5 | import { Bin, Icon as StIcon } from '@imports/St-1.0'; 6 | import { Screen, Window as WnckWindow } from '@imports/Wnck-3.0'; 7 | import { MttInfo, MttWindow } from '@mtt/index'; 8 | import { getCurrentExtensionSettings } from '@mtt/shell'; 9 | import { KeyManager } from '@mtt/shell/keyManager'; 10 | import { guessWindowXID, logger, setTimeout } from '@mtt/utils'; 11 | 12 | const { Button } = imports.ui.panelMenu; 13 | const { panel } = imports.ui.main; 14 | 15 | const debug = logger(_('window-listener')); 16 | 17 | export class WindowListener { 18 | private keyManager: KeyManager; 19 | private settings: Settings; 20 | private mttData: Array; 21 | private trackedWindows: Array; 22 | private windowOpenedListenerId?: number; 23 | private windowClosedListenerId?: number; 24 | private windowChangedListenerId?: number; 25 | private windowMinimizedListenerId?: number; 26 | 27 | constructor() { 28 | this.settings = getCurrentExtensionSettings(); 29 | this.keyManager = new KeyManager(); 30 | this.mttData = []; 31 | this.trackedWindows = []; 32 | 33 | // Initialize values 34 | this.initValues(); 35 | } 36 | 37 | async enable(): Promise { 38 | await this.initExtensionState(); 39 | 40 | // Watch for settings changes 41 | this.settings.connect('changed::mtt-data', this.onSettingsChanged.bind(this)); 42 | 43 | // Check for currently opened windows, if they match our data, we track the window 44 | const existingWindows = Global.get().get_window_actors(); 45 | for (let i = 0; i < existingWindows.length; i++) { 46 | const window = existingWindows[i].get_meta_window(); 47 | if (this.shouldIgnoreWindow(window)) { 48 | continue; 49 | } 50 | const xid = await guessWindowXID(window); 51 | if (xid) { 52 | await this.trackWindow(xid, window); 53 | } 54 | } 55 | 56 | // Watch for window-opened events 57 | this.windowOpenedListenerId = Global.get().display.connect('window-created', async (_, window) => { 58 | if (this.shouldIgnoreWindow(window)) { 59 | return; 60 | } 61 | const xid = await guessWindowXID(window); 62 | if (xid) { 63 | debug(`new window opened for class: ${window.get_id()}/${window.get_wm_class_instance()}`); 64 | await this.trackWindow(xid, window); 65 | } 66 | }); 67 | 68 | // Watch for window-closed events 69 | this.windowClosedListenerId = Global.get().window_manager.connect('destroy', async (_, windowActor) => { 70 | const window = windowActor.get_meta_window(); 71 | if (this.shouldIgnoreWindow(window)) { 72 | return; 73 | } 74 | const xid = await guessWindowXID(window); 75 | if (xid) { 76 | await this.unTrackWindow(xid); 77 | this.settings.set_string('extension-state', JSON.stringify(this.trackedWindows)); 78 | } 79 | }); 80 | 81 | // Watch for window-changed events 82 | this.windowChangedListenerId = WindowTracker.get_default().connect('tracked-windows-changed', async () => { 83 | const existingWindows = Global.get().get_window_actors(); 84 | for (let i = 0; i < existingWindows.length; i++) { 85 | const window = existingWindows[i].get_meta_window(); 86 | if (this.shouldIgnoreWindow(window)) { 87 | continue; 88 | } 89 | const xid = await guessWindowXID(window); 90 | if (xid) { 91 | await this.trackWindow(xid, window); 92 | } 93 | } 94 | }); 95 | 96 | // Watch for window-minimized events 97 | this.windowMinimizedListenerId = Global.get().window_manager.connect('minimize', async (_, windowActor) => { 98 | const window = windowActor.get_meta_window(); 99 | if (this.shouldIgnoreWindow(window)) { 100 | return; 101 | } 102 | const xid = await guessWindowXID(window); 103 | if (xid) { 104 | const trackedWindow = this.trackedWindows.find((trackedWindow) => trackedWindow.xid === xid); 105 | if (trackedWindow) { 106 | this.hideWindow(xid); 107 | } 108 | } 109 | }); 110 | 111 | // Rebind keyboard shortcuts 112 | this.rebindShortcuts(); 113 | 114 | debug('started listening for windows'); 115 | } 116 | 117 | disable(): void { 118 | // Dont watch for window-opened event anymore 119 | if (this.windowOpenedListenerId != undefined) { 120 | Global.get().display.disconnect(this.windowOpenedListenerId); 121 | this.windowOpenedListenerId = undefined; 122 | } 123 | // Dont watch for window-closed event anymore 124 | if (this.windowClosedListenerId != undefined) { 125 | Global.get().window_manager.disconnect(this.windowClosedListenerId); 126 | this.windowClosedListenerId = undefined; 127 | } 128 | // Dont watch for windows-changed event anymore 129 | if (this.windowChangedListenerId != undefined) { 130 | WindowTracker.get_default().disconnect(this.windowChangedListenerId); 131 | this.windowChangedListenerId = undefined; 132 | } 133 | // Dont watch for windows-minimized event anymore 134 | if (this.windowMinimizedListenerId != undefined) { 135 | Global.get().window_manager.disconnect(this.windowMinimizedListenerId); 136 | this.windowMinimizedListenerId = undefined; 137 | } 138 | 139 | // Save the state 140 | this.settings.set_string('extension-state', JSON.stringify(this.trackedWindows)); 141 | 142 | // Untrack windows 143 | this.trackedWindows.forEach((trackedWindow) => this.unTrackWindow(trackedWindow.xid)); 144 | 145 | // Disable keybindings. 146 | this.keyManager.stopListening(); 147 | 148 | debug('stopped listening for windows'); 149 | } 150 | 151 | private shouldIgnoreWindow(window: Window): boolean { 152 | return !window || !window.get_wm_class_instance() || window.get_window_type() != WindowType.NORMAL; 153 | } 154 | 155 | private async initExtensionState(): Promise { 156 | try { 157 | const oldState: Array = JSON.parse(this.settings.get_string('extension-state')); 158 | 159 | await new Promise((resolve) => setTimeout(resolve, 200)); 160 | for (let i = 0; i < oldState.length; i++) { 161 | const oldWindowState = oldState[i]; 162 | const window = await this.getWindow(oldWindowState.xid); 163 | if (!window || this.shouldIgnoreWindow(window)) { 164 | continue; 165 | } 166 | 167 | debug(`restoring window: ${JSON.stringify(oldWindowState)}`); 168 | 169 | await this.trackWindow(oldWindowState.xid, window); 170 | 171 | if (oldWindowState.hidden) { 172 | this.hideWindow(oldWindowState.xid); 173 | } else { 174 | this.showWindow(oldWindowState.xid); 175 | } 176 | } 177 | } catch (ex) { 178 | debug(`failed to parse initial state: ${ex}`); 179 | } 180 | } 181 | 182 | private initValues(): void { 183 | try { 184 | // Get the already saved data 185 | this.mttData = JSON.parse(this.settings.get_string('mtt-data')); 186 | } catch (_) { 187 | debug('could not parse the settings data, resetting it.'); 188 | this.mttData = []; 189 | } 190 | } 191 | 192 | private async trackWindow(xid: string, metaWindow: Window): Promise { 193 | // Get the class name 194 | const className = metaWindow.get_wm_class_instance(); 195 | if (className == null) { 196 | debug(`className is null for xid: ${xid}`); 197 | return; 198 | } 199 | 200 | // Get the mtt infor from the data 201 | const mttInfo = this.mttData.find((data) => data.className === className); 202 | 203 | // Check if we have the class name in our mtt data 204 | if (mttInfo && mttInfo.enabled && this.trackedWindows.findIndex((trackedWindow) => trackedWindow.xid == xid) < 0) { 205 | // Find the app from pid 206 | const app = WindowTracker.get_default().get_window_app(metaWindow); 207 | 208 | if (app == null) { 209 | debug(`app is null for xid/className: ${xid}/${className}`); 210 | return; 211 | } 212 | 213 | // Get the icon 214 | const icon = app.create_icon_texture(16) as StIcon; 215 | this.addTray(xid, icon); 216 | 217 | // Add window info to tracked windows 218 | this.trackedWindows = [ 219 | ...this.trackedWindows, 220 | { 221 | hidden: mttInfo.startHidden, 222 | className, 223 | xid, 224 | lastUpdatedAt: new Date(), 225 | }, 226 | ]; 227 | 228 | // Check if start hidden flag is set 229 | if (mttInfo.startHidden) { 230 | debug(`start hidden flag is set for ${mttInfo.className}. Hiding it.`); 231 | setTimeout(() => this.hideWindow(xid), 500); 232 | } 233 | 234 | this.settings.set_string('extension-state', JSON.stringify(this.trackedWindows)); 235 | } 236 | } 237 | 238 | private async unTrackWindow(xid: string): Promise { 239 | // Get the tracked window 240 | const trackedWindow = this.trackedWindows.find((trackedWindow) => trackedWindow.xid === xid); 241 | // Check if tracked window exist 242 | if (trackedWindow) { 243 | debug(`tracked window is closed: ${JSON.stringify(trackedWindow)}`); 244 | const window = await this.getWindow(xid); 245 | if (window && trackedWindow.hidden == true) { 246 | this.showWindow(trackedWindow.xid); 247 | } 248 | this.removeTray(xid); 249 | this.trackedWindows = this.trackedWindows.filter((trackedWindow) => trackedWindow.xid !== xid); 250 | } 251 | } 252 | 253 | private async onSettingsChanged(): Promise { 254 | // Load mtt state from settings 255 | this.initValues(); 256 | 257 | // Find currently tracked window classes 258 | const trackedClassNames = this.mttData 259 | .filter((mttInfo) => mttInfo.enabled === true) 260 | .map((mttInfo) => mttInfo.className); 261 | 262 | // Get the removed windows from tracked classnames 263 | const nonExistingWindows = this.trackedWindows.filter( 264 | (trackedWindow) => trackedClassNames.indexOf(trackedWindow.className) < 0, 265 | ); 266 | 267 | // Untrack them 268 | for (let i = 0; i < nonExistingWindows.length; i++) { 269 | const window = nonExistingWindows[i]; 270 | await this.unTrackWindow(window.xid); 271 | } 272 | 273 | // Track the new windows 274 | const existingWindows = Global.get().get_window_actors(); 275 | for (let i = 0; i < existingWindows.length; i++) { 276 | const window = existingWindows[i].get_meta_window(); 277 | if (this.shouldIgnoreWindow(window)) { 278 | continue; 279 | } 280 | const xid = await guessWindowXID(window); 281 | if (xid) { 282 | await this.trackWindow(xid, window); 283 | } 284 | } 285 | 286 | // Rebind keyboard shortcuts 287 | this.rebindShortcuts(); 288 | } 289 | 290 | private rebindShortcuts(): void { 291 | // Stop old listeners 292 | this.keyManager.stopListening(); 293 | 294 | // For each new className, create keybinding 295 | this.mttData.forEach((mttInfo) => { 296 | // Check if keyboard shortcut is assigned 297 | if (mttInfo.enabled && mttInfo.keybinding && mttInfo.keybinding.length > 0) { 298 | try { 299 | this.keyManager.listenFor(mttInfo.keybinding.join(''), () => { 300 | const windows = this.trackedWindows.filter( 301 | (trackedWindow) => trackedWindow.className === mttInfo.className, 302 | ); 303 | if (windows.length > 0) { 304 | const windowTobeToggled = windows 305 | .slice() 306 | .sort((a, b) => b.lastUpdatedAt.getTime() - a.lastUpdatedAt.getTime())[0]; 307 | if (windowTobeToggled.hidden == true) { 308 | this.showWindow(windowTobeToggled.xid); 309 | } else { 310 | this.hideWindow(windowTobeToggled.xid); 311 | } 312 | } 313 | }); 314 | } catch (ex) { 315 | debug('failed to add keybinding'); 316 | } 317 | } 318 | }); 319 | } 320 | 321 | private addTray(xid: string, icon: StIcon): any { 322 | // Create a new button from given window id 323 | const newButton = new Button(0, xid); 324 | 325 | const iconBox = new Bin({ 326 | style_class: 'system-status-icon', 327 | y_align: ActorAlign.CENTER, 328 | }); 329 | iconBox.set_child(icon); 330 | 331 | newButton.add_actor(iconBox); 332 | 333 | // Connect to click event for hiding/showing 334 | newButton.connect('button-press-event', () => { 335 | // Get the tracked window 336 | const trackedWindow = this.trackedWindows.find((trackedWindow) => trackedWindow.xid === xid); 337 | 338 | // Check if tracked window exist 339 | if (trackedWindow) { 340 | // If window is hiden, show it else hide it 341 | if (trackedWindow.hidden) { 342 | this.showWindow(trackedWindow.xid); 343 | } else { 344 | this.hideWindow(trackedWindow.xid); 345 | } 346 | this.settings.set_string('extension-state', JSON.stringify(this.trackedWindows)); 347 | } 348 | }); 349 | 350 | // Add actor to status area 351 | panel.addToStatusArea(xid, newButton); 352 | 353 | return newButton; 354 | } 355 | 356 | private removeTray(xid: string): void { 357 | // If actor exists in status area, destroy it 358 | if (panel.statusArea[xid]) { 359 | panel.statusArea[xid].destroy(); 360 | } 361 | } 362 | 363 | private hideWindow(xid: string): void { 364 | // Get the window for given id 365 | const window = this.trackedWindows.find((mttWindow) => mttWindow.xid === xid); 366 | 367 | // Do nothing if window does not exists 368 | if (window == null) { 369 | return; 370 | } 371 | 372 | // Hide the window from user 373 | debug(`hiding window: ${window.xid}/${window.className}`); 374 | Screen.get_default()?.force_update(); 375 | const wnckWindow = WnckWindow.get(parseInt(xid)); 376 | if (wnckWindow) { 377 | wnckWindow.set_skip_pager(true); 378 | wnckWindow.set_skip_tasklist(true); 379 | wnckWindow.minimize(); 380 | window.hidden = true; 381 | window.lastUpdatedAt = new Date(); 382 | } 383 | } 384 | 385 | private showWindow(xid: string): void { 386 | // Get the window for given id 387 | const window = this.trackedWindows.find((mttWindow) => mttWindow.xid === xid); 388 | 389 | // Do nothing if window does not exists 390 | if (window == null) { 391 | return; 392 | } 393 | 394 | // Show the window to user 395 | debug(`showing window: ${window.xid}/${window.className}`); 396 | Screen.get_default()?.force_update(); 397 | const wnckWindow = WnckWindow.get(parseInt(xid)); 398 | if (wnckWindow) { 399 | wnckWindow.set_skip_pager(false); 400 | wnckWindow.set_skip_tasklist(false); 401 | wnckWindow.unminimize(Math.floor(Date.now() / 1000)); 402 | window.hidden = false; 403 | window.lastUpdatedAt = new Date(); 404 | } 405 | } 406 | 407 | private async getWindow(xid: string): Promise { 408 | const currentWindowsActors = Global.get().get_window_actors(); 409 | for (let i = 0; i < currentWindowsActors.length; i++) { 410 | const currentWindow = currentWindowsActors[i].get_meta_window(); 411 | if (this.shouldIgnoreWindow(currentWindow)) { 412 | continue; 413 | } 414 | const currentXid = await guessWindowXID(currentWindow); 415 | if (currentXid === xid) { 416 | return currentWindow; 417 | } 418 | } 419 | } 420 | } 421 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "lib": ["ES2017"], 4 | "target": "ES2017", 5 | "strict": true, 6 | "noImplicitAny": false, 7 | "strictNullChecks": true, 8 | "noImplicitThis": true, 9 | "alwaysStrict": true, 10 | "baseUrl": "./src/", 11 | "moduleResolution": "Node", 12 | "paths": { 13 | "@imports/*": ["../@types/Gjs/*"], 14 | "@mtt/*": ["./*"] 15 | } 16 | } 17 | } 18 | --------------------------------------------------------------------------------