├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── pull_request_template.md
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── assets
├── gifs
│ └── email.gif
├── screenshots
│ └── ConsoleWindow.PNG
└── textscript.ico
├── conftest.py
├── requirements.txt
├── requirements_dev.txt
├── tests
├── test_ConfigUtils.py
├── test_TextController.py
└── test_glib.py
└── textscript
├── ConfigUtils.py
├── Gui.py
├── Logger.py
├── TextController.py
├── config
└── config.ini
├── glib.py
├── text-script.py
└── textblocks
└── Examples
├── #example.txt
└── #sigexample.txt
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Additional context**
32 | Add any other context about the problem here.
33 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | # Description
2 |
3 | Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.
4 |
5 | Fixes # (issue)
6 |
7 | ## Type of change
8 |
9 | Please delete options that are not relevant. You can check the options by putting x in between the brackets.
10 |
11 | - [ ] Bug fix (non-breaking change which fixes an issue)
12 | - [ ] New feature (non-breaking change which adds functionality)
13 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
14 | - [ ] This change requires a documentation update
15 |
16 | # How Has This Been Tested?
17 |
18 | Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration
19 |
20 | - [ ] Test A:
21 | - [ ] Test B:
22 |
23 | **Test Configuration**:
24 | * OS:
25 | * IDE:
26 |
27 | # Checklist:
28 |
29 | - [ ] My code follows the style guidelines of this project
30 | - [ ] I have performed a self-review of my own code
31 | - [ ] I have commented my code, particularly in hard-to-understand areas
32 | - [ ] I have made corresponding changes to the documentation
33 | - [ ] My changes generate no new warnings
34 | - [ ] I have added tests that prove my fix is effective or that my feature works
35 | - [ ] New and existing unit tests pass locally with my changes
36 | - [ ] Any dependent changes have been merged and published in downstream modules
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | __pycache__/
3 | textscript/Logs/*
4 | !textscript/Logs/.logfolder.txt
5 | venv/
6 | textscript/build/*
7 | textscript/dist/*
8 | textscript/text-script.spec
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 |
2 | language: python
3 |
4 | python:
5 | - "3.7"
6 |
7 | install: pip install -r requirements_dev.txt
8 |
9 | script: pytest
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 | All notable changes to this project will be documented in this file.
3 |
4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6 |
7 | ## [Planned Updates]
8 | - Check for duplicate shortcuts & handle
9 | - Ability to correct shortcut typos using arrow keys instead of just backspace
10 | - GUI support
11 |
12 | ## [Unreleased] - Date TBA
13 | # Added
14 | - Last clipboard item is preserved during textblock paste
15 | - OSX is now supported. Text-script identifies your OS and uses the correct paste shortcut.
16 | - A Gui has been added to text-script to replace the console window.
17 | # Changed
18 | - Improved testing so that modules are correctly imported now.
19 | - Removed the !exit command, replaced this with simply closing the window.
20 |
21 | ## [1.3.1] - 2020-03-12
22 | #Added
23 | - Implemented Continuous Integration
24 | - Added command delimiter (!)
25 | - Added functions to predict the codec and decode textblocks with greater accuracy. This should
26 | resolve bugs encountered when using non unicode textblocks.
27 | - Added better compatibility check for textblock naming convention.
28 | #Changed
29 | - Updated logging to better capture errors which occur during textblock decoding
30 | - Moved commands from shortcut delimiter (#) to command delimiter (!)
31 |
32 | ## [1.3.0] - 2020-02-21
33 | # Changed
34 | - Added reload function which adds shortcuts without restarting the program
35 | - Added mechanism to update config file and repair broken sections
36 | - Added better exception handling for issues in config file
37 | - Added contributions file
38 | - Moved source files into textscript subdirectory and refactored code
39 | - Added notifications for added or removed textblocks
40 | - Reorganized classes so that methods make more sense
41 | - Renamed internal use methods according to PEP-8
42 | - Renamed Settings.py as ConfigUtils.py as this is more accurate
43 |
44 | ## [1.2.0] - 2020-01-23
45 | ### Added
46 | - Support for three directories: default, local, and remote
47 | - Usage statistic printout during program start
48 |
49 | ## [1.1.0] - 2020-01-17
50 | ### Added
51 | - Statistics tracking for shortcuts used, total shortcut characters typed, and total textblock characters pasted
52 | - Help and Exit commands have been added
53 |
54 | ## [1.0.0] - 2020-01-16
55 | ### Added
56 | - App prints all of the shortcuts and directories during start
57 | ### Changed
58 | - Debugging print lines removed
59 | - Better logging to track potential issues
60 |
61 | ## [0.0.1] - 2020-01-14
62 | ### Added
63 | - Created first basic version
64 | - Functional textblock printing and shortcut recognition
65 | - Released as alpha for testing purposes
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity and expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at george.ciesin@gmail.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
77 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | When contributing to this repository, please first discuss the change you wish to make via issue,
4 | email, or any other method with the owners of this repository before making a change.
5 |
6 | Please note we have a code of conduct, please follow it in all your interactions with the project.
7 |
8 | ## Code Style and Coding Practices
9 |
10 | - Please ensure you follow [PEP 8](https://www.python.org/dev/peps/pep-0008/) whenever possible.
11 | - Ensure you include a docstring comment in each function so the purpose and behaviour can be easily understood. See the other functions for an example of this if needed.
12 | - Ensure that you name variables and functions only used locally as _name (single underscore) as per PEP 8.
13 | - Ensure that you use professional language in the code & comments. For example, including swear words in the project is unprofessional.
14 |
15 | ## Logging
16 |
17 | - If you make new functions under existing classes, please ensure you use self._log.debug/info/exception("message") to write helpful logs throughout your function.
18 | - For the first log your function would output, start off the message with "scriptname.py: message" where the script name is whichever file the function is created in. Following logs from the same function do not need to include this.
19 | - If you need to create a new class, pass the L instance from text-script.py if possible.
20 |
21 | ## Testing
22 |
23 | - We are using Pytest and Travis CI for our automated testing
24 | - Please see the Automated Testing section of the Text-Script wiki for information how to add tests
25 | - Please also ensure that you add a corresponding test for any new functions or modules that you add
26 |
27 | ## Pull Request Process
28 |
29 | 1. Ensure any install or build dependencies (such as the build and dist folders generated by Pyinstaller) are not included in the branch.
30 | 2. Update the README.md with any required details such as new features, important new information, or screenshots if needed.
31 | 3. Increase the text_script_version number in text-script.py and the README.md to the new version that this
32 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).
33 | 4. You may create a merge request and wait for one of the developers to review the changes and sign off on them.
34 | 5. Your tests that you added will be automatically built and tested at this stage.
35 | 6. Once this is done, we will merge it into develop.
36 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # >text-script
2 |
3 | 
4 | 
5 |
6 | 
7 | 
8 | 
9 |
10 | An app that allows users to save shortcuts and textblocks. Typing a shortcut automatically replaces said shortcut with the content of the saved textblock. This app runs in the background and improves typing efficiency.
11 |
12 | 
13 |
14 | ## Motivation
15 | I came up with this idea when I discovered there were few quality open source applications to fulfill this function. As a tech support agent, I find myself repeatedly copying the same blocks of text, such as signatures, instructions, and templates, and pasting them into emails. This is a common task in any tech support role, so I wanted to write an app to help my colleagues, and anybody else working in a similar role.
16 |
17 | ## Built With
18 | - Pynput
19 | - Pyperclip
20 |
21 | ## Prerequisites
22 | - Python 3.7
23 | - Dependencies from requirements.txt
24 |
25 | ## Python version notice
26 | Please be advised that I have decided to roll back to Python 3.7 as Pyinstaller, which we use to create executables, is not compatible with 3.8 yet. Once Pyinstaller supports 3.8, we will consider moving Text-Script back to this version as well. Sorry in advance if this causes any issues on your forks.
27 |
28 | ## Screenshots
29 |
30 | ### The main console window
31 | At this stage in the project, text-script runs out of a console window. This outputs your stats, the loaded directories and shortcuts, and any shortcuts that
32 | were added or removed since the program was last ran. A GUI planned for a future release will replace this console window in the future.
33 |
34 | 
35 |
36 | ## Features
37 |
38 | ### Save Shortcuts & Textblocks
39 | text-script lets you create shortcuts which are used to quickly and easily recall textblocks later. I have outlined the process to create new textblocks in the "Using Text-Script" section of the README file.
40 |
41 | ### Works on Windows, Linux, and OSX
42 | Support has been added for Linux and OSX as of version 1.3.2. Please make sure you download the correct binary for your system.
43 |
44 | ### Supports Local and Remote Shortcuts
45 | text-script allows both local and remote shortcuts to be used. Remote shortcuts can be created by a manager or supervisor and can be shared with the whole team on the network drive. While using these remote shortcuts, you can also create your own local shortcuts that only you can see and use.
46 |
47 | ### Built-in Commands
48 | text-script has several commands built in to streamline usage. I recommend using them in a text input field as some of these paste the result of the command and require a text input field to do so. Please also note that I have moved commands to their own delimiter (!) to separate them from regular shortcuts.
49 |
50 | **!help** - Typing this command followed by space, tab, or enter pastes the help text, which shows how to use the program. As it pastes text, some kind of textfield is required.
51 |
52 | **!reload** - Typing this command after adding new textblocks loads them into text-script without having to restart the app.
53 |
54 | ### Saves your statistics
55 | As you use shortcuts, text-script saves the number of shortcuts you use, and the keystrokes you save. Each time the program starts, you are
56 | presented with an estimated amount of time you saved by using text-script.
57 |
58 | ### Runs in the background
59 | This application runs in the background and does not need to be maximized or in focus. Simply starting the app and minimizing it is enough for it to recognize your shortcuts.
60 |
61 | ### Textblock directory can contain many subdirectory levels
62 | It is possible to make folders within the textblock directory to better organize your textblocks. Even these folders can contain more folders so that a complex organizational system is possible.
63 |
64 | ### Privacy
65 | text-script is being designed with privacy in mind. As I intend for this application to be used free of charge by any individual or corporation, it is important to me that this application does not collect any private data. The contents of the textblocks are stored locally or within the user's network, and text-script does not duplicate or send this information anywhere. The local logs only contain characters entered after the shortcut or command delimiter until the word is complete (space, tab, or enter are pressed), and the logs are stored locally and can only be sent to me manually.
66 |
67 | Throughout the development of text-script, I will always keep privacy in mind and will continue to strengthen the capability of text-script to remain anonymous and private. If you have any concerns or find any privacy risks, please feel free to open an issue so that I can address this concern.
68 |
69 | ### Logs
70 | text-script contains anonymous logging capabilities which generate up to six log files. A new log file is created whenever text-script is started, or whenever the current log file becomes too large. These logs may help to resolve any bugs that you experience while using text-script.
71 |
72 | Special care has been taken to keep the logs anonymous and free from private information. The log files contain only program flow debugging messages, and only track characters that text-script believes are part of a shortcut. Specifically, whenever the shortcut (# key) or command (!) delimiter is pressed, text-script logs the keys entered until space, tab, or enter is pressed, which indicates the shortcut is complete. Outside of the shortcut, no other keys are entered into the logs, and neither are the contents of your textblocks. Despite limiting the effectiveness of the logs, this program is being written primarily with privacy in mind.
73 |
74 | The logs are manually created and have to be manually provided when bugs are encountered. You can find these logs in the Logs/ folder within the text-script directory.
75 |
76 | ## Planned future updates
77 | - GUI to configure app and add new textblocks.
78 | - Save whatever the latest clipboard item is and replace it after shortcut is used. Currently the last textblock used fills the last clipboard spot.
79 | - Optional usage tracking to advise the user which textblocks see the most use and which do not.
80 |
81 | ## Installing
82 |
83 | At this time, the program is still in early development, so I recommend always downloading the latest version as it will usually contain fixes for large bugs or issues. The develop version typically is not in a usable state at all times.
84 |
85 | ### Executable installation steps
86 |
87 | 1. Go to the [releases section](https://github.com/GeorgeCiesinski/text-script/releases) of this repository.
88 | 2. Download the top file in the latest release.
89 | 3. Extract the text-script folder within this zip file. The whole folder is needed for the installation.
90 | 4. Open the Config folder, and the config.ini file within this. You can edit the DIRECTORIES section as per the "Configuration" part of this README (below).
91 | 5. Create your shortcuts and textblocks in one of these directories as per the "Using Text-Script" section of this README (below).
92 | 6. Click text-script.exe to run the program. You may need to click yes to allow the program to run.
93 |
94 | ### Executable upgrade steps
95 | 1. Follow steps 1-3 of Executable installation steps.
96 | 2. Simply drag the text-script.exe file into your previous installation location, and click yes to overwrite the old file.
97 | 3. Run the program. This should automatically upgrade the files and preserve your textblocks and stats.
98 |
99 | ### Source Code
100 |
101 | 1. Download or clone the repository.
102 | 2. Install the dependencies from requirements.txt (virtual environment is recommended).
103 | 3. Navigate to the textscript directory and ensure your CWD and sources root is textscript.
104 | 4. Run the text-script.py file.
105 | 5. Follow steps 4 & 5 from the" Executable Installation" Steps to configure text-script and setup your textblocks.
106 |
107 | ### Configuration
108 |
109 | Text-Script must be configured with your textblock directories. The configuration for this app is stored in the textscript/config/ directory.
110 | As this program has to be manually configured until the GUI is complete, please take care to only modify options in the DIRECTORIES section.
111 | The other sections are managed by the program.
112 |
113 | The DIRECTORIES section contains options which refer to a default directory (textscript/textblocks/) which can be disabled by erasing the directory listed
114 | there, or replacing it with None. There are also options to set the local directory and the remote directory. The local directory is any folder
115 | on your computer containing textblocks, and the remote directory is for any folder located on a network drive. Having all three is optional, and only one is
116 | necessary to store and load textblocks.
117 |
118 | ## Using Text-Script
119 |
120 | ### Manually creating textblocks
121 |
122 | At this time, Text-Script does not have a GUI and textblocks must be created manually.
123 |
124 | I recommend either using notepad to create the textblock. Any text editor that lets you select encoding will also work.
125 |
126 | 1. Navigate to the textblock directory you set in the Config file. Using subdirectories in this location is supported, shouldn't cause any issues, and is a helpful way to organize the textblocks.
127 | 2. Create a new text file in this location. The naming convention for the text file is #________.txt where the blank is the shortcut
128 | you will type to recall the textblock.
129 | 3. Open the file. Paste the actual text you want to replace the shortcut with into this file.
130 | 4. If you are currently running Text-Script, typing #reload (version 1.3.0) or !reload (version 1.3.1 +) will automatically reload the shortcuts into the
131 | program including any new shortcuts that have been added.
132 |
133 | **Note:** Text-Script should be able to handle most common text encodings such as ANSI and Unicode. Despite this, you may encounter an error or crash under rare circumstances. If this happens, please open your textblock, and try saving it as "Unicode" or "UTF-16", overwriting the old file.
134 |
135 | ### Pasting the textblocks
136 |
137 | While Text-Script is running, it can be minimized, and listens for the shortcuts you made when creating your textblocks. You can type these shortcuts into any text input field, such as an email, or a notepad, and Text-Script will replace your shortcuts with the textblock.
138 |
139 | Text-Script works by copying the contents of your textblock into your clipboard, and then emulates a keyboard entry of CTRL+V (Win & Linux) or CMD+V (Mac). Text-script 1.3.2 & later should no longer overwrite the last clipboard item with the textblock.
140 |
141 | ## Known Bugs
142 |
143 | ### Textblocks are formatted wrong or cause Text-Script to crash
144 |
145 | Text-Script now attempts to determine the encoding of the Text-Block using the Chardet library. Despite this, encoding is notoriously difficult to determine with complete accuracy. If the textblocks are formatted wrong when they are pasted, or if the program crashes, try changing the encoding to unicode or UTF-16. You can do this by opening the file in notepad or another text editor that lets you set the encoding, and overwriting the original file.
146 |
147 | ### Shortcuts with numeric names are not pasting
148 |
149 | There is a known issue where typing shortcuts using the numpad doesn't work. We are trying to fix this bug, but for now, use the regular number keys to type it in and it should work without issue.
150 |
151 | ## Credits
152 | - George Ciesinski (Lead Developer)
153 | - [Daniel Kokoszka](https://github.com/nulldozer) (OSX Support)
154 | - [Jakub Wlodek](https://github.com/jwlodek) (Continuous Integration)
155 |
156 | ## License
157 | Please see LICENSE.md
158 |
--------------------------------------------------------------------------------
/assets/gifs/email.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeorgeCiesinski/text-script/990862cf796ce981d91f13c7be89d2a4233913e9/assets/gifs/email.gif
--------------------------------------------------------------------------------
/assets/screenshots/ConsoleWindow.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeorgeCiesinski/text-script/990862cf796ce981d91f13c7be89d2a4233913e9/assets/screenshots/ConsoleWindow.PNG
--------------------------------------------------------------------------------
/assets/textscript.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeorgeCiesinski/text-script/990862cf796ce981d91f13c7be89d2a4233913e9/assets/textscript.ico
--------------------------------------------------------------------------------
/conftest.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeorgeCiesinski/text-script/990862cf796ce981d91f13c7be89d2a4233913e9/conftest.py
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | chardet==3.0.4
2 | pynput==1.6.8
3 | pyperclip==1.7.0
4 | python-xlib==0.26
5 | six==1.14.0
6 | pytest
--------------------------------------------------------------------------------
/requirements_dev.txt:
--------------------------------------------------------------------------------
1 | chardet==3.0.4
2 | pynput==1.6.8
3 | pyperclip==1.7.0
4 | python-xlib==0.26
5 | six==1.14.0
6 | pytest
--------------------------------------------------------------------------------
/tests/test_ConfigUtils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | sys.path.append(os.path.abspath('textscript'))
4 |
5 | from textscript.ConfigUtils import Setup, Update
6 |
7 |
8 | def test_basic():
9 | pass
10 |
--------------------------------------------------------------------------------
/tests/test_TextController.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | sys.path.append(os.path.abspath('textscript'))
4 |
5 | # from TextController import WordCatcher, KeyboardEmulator
6 |
7 | """
8 | This testing is pending resolution of issue #59 on the repository. The above import is disabled to prevent the build
9 | from failing. At this time, if you import WordCatcher or KeyboardEmulator, the pynput library tries to use X, which
10 | produces an error on Travis CI.
11 | """
12 |
13 | def test_basic():
14 | pass
--------------------------------------------------------------------------------
/tests/test_glib.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import sys
3 | from textscript import glib
4 |
5 |
6 | def test_check_directory():
7 | assert not glib.check_directory('fasfbabfabflrfb')
8 | assert glib.check_directory('.github')
9 |
10 |
11 | def test_list_subdirectories():
12 |
13 | if sys.platform == 'win32':
14 |
15 | expected_list = ['.\\.github', '.\\assets', '.\\tests', '.\\textscript']
16 |
17 | else:
18 |
19 | expected_list = ['./.github', './assets', './tests', './textscript']
20 |
21 | dir_list = glib.list_subdirectories('.')
22 | for dir in expected_list:
23 | assert dir in dir_list
24 |
25 |
26 | def test_list_files():
27 |
28 | expected_file_names = ['glib.py', 'README.md', '.gitignore', 'pull_request_template.md']
29 |
30 | if sys.platform == 'win32':
31 |
32 | expected_file_paths = ['.\\textscript\\glib.py', '.\\README.md', '.\\.gitignore',
33 | '.\\.github\\pull_request_template.md']
34 |
35 | else:
36 |
37 | expected_file_paths = ['./textscript/glib.py', './README.md', './.gitignore',
38 | './.github/pull_request_template.md']
39 |
40 | file_list, dir_list = glib.list_files('.')
41 | for file in expected_file_names:
42 | assert file in file_list
43 | for file_path in expected_file_paths:
44 | assert file_path in dir_list
45 |
46 |
47 | def test_list_shortcuts():
48 |
49 | sample_file_list = ["#example.txt", "#example2.txt", "#test.txt", "#test2.txt"]
50 | expected_shortcut_list = ["#example", "#example2", "#test", "#test2"]
51 | shortcut_list = glib.list_shortcuts(sample_file_list)
52 | for shortcut in shortcut_list:
53 | assert shortcut in expected_shortcut_list
54 | assert shortcut not in sample_file_list
55 |
56 | def test_shortcut_compatibility_check():
57 |
58 | sample_passing_shortcuts = ["#example", "!example2", "#test1", "!test2"]
59 | sample_failing_shortcuts = ["#example#", "!example!", "#example!", "!example#", "#te#st", "#te!st2"]
60 | for sample in sample_passing_shortcuts:
61 | result = glib._shortcut_compatibility_check(sample)
62 | assert result is True
63 | for sample in sample_failing_shortcuts:
64 | result = glib._shortcut_compatibility_check(sample)
65 | assert result is False
66 |
67 | def test_print_shortcuts():
68 |
69 | # This function relies on the print() function which is expected to work
70 | pass
71 |
--------------------------------------------------------------------------------
/textscript/ConfigUtils.py:
--------------------------------------------------------------------------------
1 | import configparser
2 | from Logger import Logger
3 | import glib
4 | from os import path
5 | import datetime
6 |
7 |
8 | # Config file object
9 | class Config:
10 |
11 | def __init__(self, version):
12 | """
13 | This init function creates three lists:
14 | - config_sections contains the sections and options
15 | - section_comments contains the comments for each section
16 | - config_values contains the default values for those sections
17 | Ensure that this is updated whenever a new section or option is needed in the config as this generates and
18 | repairs the existing config file.
19 | """
20 |
21 | # Key is the sections, Value is a list of options
22 | self.config_sections = {
23 | 'TEXTSCRIPT': ['version'],
24 | 'HISTORY': ['shortcutsused', 'shortcutchars', 'textblockchars'],
25 | 'DIRECTORIES': ['defaultdirectory', 'localdirectory', 'remotedirectory'],
26 | 'SHORTCUTS': ['lastshortcuts'] # Default is empty string
27 | }
28 |
29 | self.section_comments = {
30 | 'TEXTSCRIPT': '; Config file version',
31 | 'HISTORY': '; Keeps a record of the number of keystrokes, and used shortcuts',
32 | 'DIRECTORIES': '; The default directory included with app, local directory, and network directory',
33 | 'SHORTCUTS': '; Keeps a record of previously loaded shortcuts' # Default is empty string
34 | }
35 |
36 | self.config_values = {
37 | 'TEXTSCRIPT': [version], # Default version should be current version
38 | 'HISTORY': ['0', '0', '0'], # Default is 0
39 | 'DIRECTORIES': ['./textblocks/', 'None', 'None'], # Default is none
40 | 'SHORTCUTS': [''] # Default is empty string
41 | }
42 |
43 |
44 | class Setup:
45 |
46 | def __init__(self, _log, text_script_version):
47 |
48 | # Creates instance wide log object
49 | self._log = _log.log
50 |
51 | self._log.debug("ConfigUtils: Starting Setup initialization.")
52 |
53 | # Creates instance of current version variable
54 | self.version = text_script_version
55 |
56 | # Creates instance of ConfigParser object and allows empty values so comments are valid
57 | self._config = configparser.ConfigParser(allow_no_value=True)
58 |
59 | # Shortcut notification variables
60 | self._last_shortcuts = []
61 | self.new_shortcuts = []
62 | self.removed_shortcuts = []
63 |
64 | # Config Directories
65 | self._config_dir = "./config/"
66 | self._config_file_dir = "./config/config.ini"
67 |
68 | self._log.debug("Setup initialized successfully.")
69 |
70 | def config_exists(self):
71 | """
72 | Checks if Config file exists. Calls function to create a new config if doesn't exist.
73 | """
74 |
75 | self._log.debug("ConfigUtils: Starting config_exists.")
76 |
77 | # Create a default config
78 | _default_config = Config(self.version)
79 |
80 | if path.exists(self._config_file_dir):
81 |
82 | self._log.debug(f"Config file found at: {self._config_file_dir}")
83 |
84 | # Checks if the config is up to date or not, stores values from existing config
85 | self._check_config(_default_config)
86 |
87 | else:
88 |
89 | _not_found = "Config file not found. Creating new file."
90 |
91 | self._log.debug(_not_found)
92 |
93 | print(_not_found, "\n")
94 |
95 | # Call create config, send default config
96 | self._create_config(_default_config)
97 |
98 | def _check_config(self, _config_template):
99 | """
100 | Checks if config file is outdated. Updates or adds outdated sections & options config files.
101 |
102 | :param _config_template:
103 | """
104 |
105 | self._log.debug("ConfigUtils: Starting _check_config.")
106 |
107 | _modified_config_template = Config(self.version) # Create a new config template to save existing config values
108 |
109 | _config_outdated = False # True if any values have been modified in _modified_config_template
110 |
111 | _config_template_sections = _config_template.config_sections.keys() # Get config template sections
112 |
113 | self._config.read(self._config_file_dir) # Read the config file
114 |
115 | _current_sections = self._config.sections() # Get config file sections
116 |
117 | _config_version = self._config["TEXTSCRIPT"]["version"]
118 |
119 | # For sections in the config template
120 | for _section in _config_template_sections:
121 |
122 | # If section is in the config file
123 | if _section in _current_sections:
124 |
125 | self._log.info(f"The section {_section} found in config file.")
126 |
127 | _current_options = self._config.options(_section) # Get options for current section from config file
128 |
129 | # Check options. Save data from existing config
130 | for _option in _config_template.config_sections[_section]:
131 |
132 | if _option in _current_options:
133 |
134 | self._log.info(f"The option {_option} found in config file. Saving value.")
135 |
136 | _current_value = self._config[_section][_option] # Gets the value of the option
137 |
138 | # Sets this value in the _modified_config_template
139 | _modified_config_template.config_values[_section][_current_options.index(_option)] = _current_value
140 |
141 | else:
142 |
143 | self._log.info(f"The option {_option} is missing from the config file. Config is outdated.")
144 |
145 | _config_outdated = True
146 |
147 | # If section is not in config file
148 | else:
149 |
150 | # No action required as the template contains default values
151 |
152 | self._log.info(f"The section {_section} is missing from config file. Config is outdated.")
153 |
154 | _config_outdated = True
155 |
156 | if _config_version != self.version:
157 |
158 | self._log.info(f"The config file is set to version {_config_version}. Updating to {self.version}")
159 |
160 | _modified_config_template.config_values["TEXTSCRIPT"][0] = self.version
161 |
162 | _config_outdated = True
163 |
164 | # If config file is outdated, update config file
165 | if _config_outdated is True:
166 |
167 | self._log.info("A section or option was missing, updating the config file.")
168 |
169 | self._create_config(_modified_config_template)
170 |
171 | self._log.info(f"Config file successfully updated to version {self.version}.")
172 |
173 | else:
174 |
175 | self._log.info(f"Config file is up to date.")
176 |
177 | def _create_config(self, _config_template):
178 | """
179 | Takes the dictionary values in the _config_template and creates a new config file based on this. Accepts
180 | either a default config or a config with modified values.
181 |
182 | :param _config_template:
183 | """
184 |
185 | self._log.debug("ConfigUtils: Starting _create_config.")
186 |
187 | # Create directory if doesn't exist
188 | if not glib.check_directory(self._config_dir):
189 | glib.create_folder(self._config_dir)
190 | self._log.debug("No Config directory found. Creating directory.")
191 |
192 | # Create a _sections list
193 | _sections = _config_template.config_sections.keys()
194 |
195 | try:
196 |
197 | for _section in _sections:
198 |
199 | # List of options for this section
200 | _options = _config_template.config_sections[_section]
201 |
202 | # Finds the section comment
203 | _section_comment = _config_template.section_comments[_section]
204 |
205 | # Creates this section
206 | self._config[_section] = {}
207 |
208 | # Writes the config comment for the section
209 | self._config.set(_section, _section_comment)
210 |
211 | for _option in _options: # For each of the options in the list of options
212 |
213 | # Find the option value at the same index
214 | _option_value = _config_template.config_values[_section][_options.index(_option)]
215 |
216 | # Create the option under the section and set the value
217 | self._config.set(_section, _option, _option_value)
218 |
219 | except configparser.Error:
220 |
221 | self._log.exception("Failed to create config file due to configparser error.")
222 | raise
223 |
224 | except Exception:
225 |
226 | self._log.exception("Failed to create config file due to unexpected error.")
227 | raise
228 |
229 | else:
230 |
231 | self._log.debug(f"{self._config_file_dir} file created successfully.")
232 |
233 | # Write the config file (overwrites existing)
234 | with open(self._config_file_dir, 'w') as configfile:
235 | self._config.write(configfile)
236 |
237 | def shortcut_setup(self, _directories):
238 | """
239 | Extends _shortcut_list and _file_dir_list from the _shortcuts and _file_dirs lists.
240 | """
241 |
242 | self._log.debug("ConfigUtils: Starting shortcut_setup.")
243 |
244 | # Todo: Check if exception handling is required here.
245 |
246 | _shortcut_list = []
247 | _file_dir_list = []
248 |
249 | # For each directory in directories
250 | for _directory in _directories:
251 |
252 | # Appends shortcuts only if directory is not None
253 | if _directory is not None:
254 |
255 | # Get shortcuts and file_dirs
256 | _shortcuts, _file_dirs = self._append_directories(_directory)
257 |
258 | # Print shortcut title
259 | if _directory is _directories[0]:
260 |
261 | # print("\nDefault Directory: \n")
262 | self._log.debug("Appending shortcuts from default directory.")
263 |
264 | elif _directory is _directories[1]:
265 |
266 | # print(f"\nLocal Directory: {_directory}\n")
267 | self._log.debug(f"Appending shortcuts from local directory: {_directory}")
268 |
269 | elif _directory is _directories[2]:
270 |
271 | # print(f"\nRemote Directory: {_directory}\n")
272 | self._log.debug(f"Appending shortcuts from remote directory: {_directory}")
273 |
274 | # Print shortcuts
275 | self._log.info(_shortcuts)
276 | # glib.print_shortcuts(_file_dirs, _shortcuts)
277 |
278 | # extends shortcut_list with values in shortcuts
279 | try:
280 |
281 | _shortcut_list.extend(_shortcuts)
282 |
283 | except Exception:
284 |
285 | self._log.exception("Failed to extend shortcut_list.")
286 | raise
287 |
288 | else:
289 |
290 | self._log.debug("Successfully extended shortcut_list")
291 |
292 | # extend file_dirs to file_dir_list
293 | _file_dir_list.extend(_file_dirs)
294 |
295 | self._log.debug("Successfully appended shortcuts and file_dirs.")
296 | self._log.info(f"Shortcuts: {_shortcut_list}")
297 |
298 | return _shortcut_list, _file_dir_list
299 |
300 | def new_shortcut_check(self, _shortcut_list):
301 | """
302 | Checks if any shortcuts have been added or removed since the last time program was run.
303 |
304 | :param _shortcut_list:
305 | """
306 |
307 | self._log.debug("ConfigUtils: Starting new_shortcut_check.")
308 |
309 | # Todo: Split this into smaller functions
310 |
311 | self._log.info("Reading lastshortcuts.")
312 | self._read_shortcuts
313 |
314 | # Reads the shortcuts from the shortcuts.ini file
315 | self._read_shortcuts()
316 |
317 | """
318 | New shortcut check
319 | """
320 |
321 | print("\nNew shortcut check: \n")
322 |
323 | for shortcut in _shortcut_list:
324 |
325 | # If shortcut isn't in the _last_shortcuts list, add it to _new_shortcuts
326 | if shortcut not in self._last_shortcuts:
327 |
328 | self.new_shortcuts.append(shortcut)
329 |
330 | # If there are more than zero new shortcuts, print the new shortcuts
331 | if len(self.new_shortcuts) == 0:
332 |
333 | self._log.info("No new shortcuts have been added.")
334 | print("No new shortcuts have been added.")
335 |
336 | else:
337 |
338 | self._log.info(f"The following shortcuts have been added:{self.new_shortcuts}")
339 | print("The following shortcuts have been added:")
340 | print(self.new_shortcuts)
341 |
342 | """
343 | Removed shortcut check
344 | """
345 |
346 | print("\nRemoved shortcut check: \n")
347 |
348 | for shortcut in self._last_shortcuts:
349 |
350 | # If shortcut is not in _shortcut_list, add it to the _removed_shortcuts list
351 | if shortcut not in _shortcut_list:
352 |
353 | self.removed_shortcuts.append(shortcut)
354 |
355 | # If there are more than 0 removed shortcuts, print the removed shortcuts
356 | if len(self.removed_shortcuts) == 1 and self.removed_shortcuts[0] == "":
357 |
358 | self._log.info("No shortcuts have been removed.")
359 | print("No shortcuts have been removed.")
360 |
361 | elif len(self.removed_shortcuts) > 0:
362 |
363 | self._log.info(f"The following shortcuts have been removed: {self.removed_shortcuts}")
364 | print("The following shortcuts have been removed:")
365 | print(self.removed_shortcuts)
366 |
367 | elif len(self.removed_shortcuts) == 0:
368 |
369 | self._log.info("No shortcuts have been removed.")
370 | print("No shortcuts have been removed.")
371 |
372 | # Replace self._last_shortcuts if list has changed
373 | if _shortcut_list != self._last_shortcuts:
374 |
375 | self._replace_last_shortcuts(_shortcut_list)
376 |
377 | self._log.debug("Completed new shortcut check.")
378 |
379 | def _read_shortcuts(self):
380 | """
381 | Reads the lastshortcuts option from config file to determine the shortcuts last loaded by program.
382 | """
383 |
384 | try:
385 | # Read shortcut history config file
386 | self._config.read(self._config_file_dir)
387 |
388 | self._last_shortcuts = (self._config['SHORTCUTS']['lastshortcuts']).split(', ')
389 |
390 | except configparser.Error:
391 | self._log.exception("Failed to read lastshortcuts from config file due to configparser.error.")
392 | raise
393 |
394 | except configparser.NoSectionError:
395 |
396 | self._log.exception("Failed to read lastshortcuts due to NoSectionError.")
397 | raise
398 |
399 | except Exception:
400 | self._log.exception("Failed to read lastshortcuts due to unexpected error.")
401 | raise
402 |
403 | else:
404 | self._log.info("Successfully read lastshortcuts from config file.")
405 |
406 | def _replace_last_shortcuts(self, _shortcut_list):
407 | """
408 | Updates lastshortcuts with currently loaded shortcuts
409 |
410 | :param _shortcut_list:
411 | """
412 |
413 | _shortcut_string = ', '.join(_shortcut_list)
414 |
415 | try:
416 | self._config.set('SHORTCUTS', 'lastshortcuts', _shortcut_string)
417 |
418 | # Write to the config file
419 | with open(self._config_file_dir, 'w') as configfile:
420 | self._config.write(configfile)
421 |
422 | except configparser.Error:
423 | self._log.exception("Failed to update lastshortcuts due to configparser Error.")
424 | raise
425 |
426 | except configparser.NoSectionError:
427 |
428 | self._log.exception("Failed to update lastshortcuts due to NoSectionError.")
429 | raise
430 |
431 | except Exception:
432 | self._log.exception("Failed to update lastshortcuts due to unexpected Error.")
433 | raise
434 |
435 | else:
436 | self._log.debug("Successfully updated lastshortcuts with updated stats.")
437 |
438 | def get_stats(self):
439 | """
440 | Gets the current usage stats from the config file.
441 | """
442 |
443 | self._log.debug("ConfigUtils: Starting get_stats.")
444 |
445 | try:
446 |
447 | self._config.read(self._config_file_dir)
448 |
449 | _shortcuts_used = self._config['HISTORY']['shortcutsused']
450 | _shortcut_chars = self._config['HISTORY']['shortcutchars']
451 | _textblock_chars = self._config['HISTORY']['textblockchars']
452 |
453 | except configparser.NoSectionError:
454 |
455 | self._log.exception("Unable to get stats from config file: NoSectionError.")
456 | raise
457 |
458 | else:
459 |
460 | self._log.debug("Stats retrieved successfully.")
461 |
462 | # Stats Tuple
463 | _stats = (_shortcuts_used, _shortcut_chars, _textblock_chars)
464 |
465 | return _stats
466 |
467 | def calculate_stats(self, _stats):
468 | """
469 | Prints the usage stats to console.
470 | """
471 |
472 | self._log.debug("ConfigUtils: Starting _calculate_stats.")
473 |
474 | # Extract values from Tuple
475 | _shortcuts_used = _stats[0]
476 | _shortcut_chars = _stats[1]
477 | _textblock_chars = _stats[2]
478 |
479 | try:
480 |
481 | _saved_keystrokes = str(int(_textblock_chars) - int(_shortcut_chars))
482 | _seconds_to_paste = 5
483 | _saved_seconds = int(_shortcuts_used) * _seconds_to_paste
484 | _time_saved = datetime.timedelta(seconds=_saved_seconds)
485 |
486 | except ValueError:
487 |
488 | self._log.exception("The config file contains invalid values in the HISTORY section.")
489 |
490 | _value_error_message = """Stats failed to calculate due to a value error. Your stats have been reset to 0
491 | to correct the error."""
492 |
493 | print(_value_error_message, "\n")
494 |
495 | # Repairs history
496 | self._repair_history()
497 |
498 | else:
499 |
500 | self._log.info("The stats were calculated successfully.")
501 |
502 | _complete_stats = (
503 | _shortcuts_used,
504 | _shortcut_chars,
505 | _textblock_chars,
506 | _saved_keystrokes,
507 | _seconds_to_paste,
508 | _time_saved
509 | )
510 |
511 | return _complete_stats
512 |
513 | def print_stats(self, _stats):
514 |
515 | # Extract values from Tuple
516 | _shortcuts_used = _stats[0]
517 | _shortcut_chars = _stats[1]
518 | _textblock_chars = _stats[2]
519 | _saved_keystrokes = _stats[3]
520 | _seconds_to_paste = _stats[4]
521 | _time_saved = _stats[5]
522 |
523 | _stat_message = f"""Your stats:
524 |
525 | - Number of shortcuts used: {_shortcuts_used}
526 | - You typed a total of {_shortcut_chars} shortcut characters
527 | - Text-Script pasted a total of {_textblock_chars} characters
528 | - You saved {_saved_keystrokes} keystrokes
529 | - If it takes {_seconds_to_paste} seconds to copy & paste an item, you saved {_time_saved}"""
530 |
531 | print(_stat_message)
532 |
533 | self._log.info(_stat_message)
534 |
535 | def _repair_history(self):
536 | """
537 | Repairs history section if an invalid value is found there.
538 | """
539 |
540 | self._log.debug("ConfigUtils: Starting _repair_history.")
541 |
542 | try:
543 |
544 | # Open the config file
545 | self._config.read(self._config_file_dir)
546 |
547 | # Reset HISTORY values to 0
548 | self._config.set('HISTORY', 'shortcutsused', "0")
549 | self._config.set('HISTORY', 'shortcutchars', "0")
550 | self._config.set('HISTORY', 'textblockchars', "0")
551 |
552 | except configparser.Error:
553 | self._log.exception("Failed to read shortcut history due to configparser Error.")
554 | raise
555 |
556 | except configparser.NoSectionError:
557 |
558 | self._log.exception("Failed to read shortcut history due to NoSectionError.")
559 | raise
560 |
561 | except Exception:
562 | self._log.exception("Failed to read shortcut history due to unexpected Error.")
563 | raise
564 |
565 | else:
566 | self._log.debug("Successfully read shortcut history.")
567 |
568 | try:
569 |
570 | # Write to the config file
571 | with open(self._config_file_dir, 'w') as configfile:
572 | self._config.write(configfile)
573 | self._log.debug("Successfully repaired HISTORY.")
574 |
575 | except OSError:
576 |
577 | self._log.exception("Failed to repair history due to OSError.")
578 |
579 | else:
580 |
581 | # Run get_stats again after repair
582 | self.get_stats()
583 |
584 | def find_directories(self):
585 | """
586 | Finds the directories in the config file
587 | """
588 |
589 | self._log.debug("ConfigUtils: Starting find_directories.")
590 |
591 | try:
592 |
593 | self._config.read(self._config_file_dir)
594 |
595 | except configparser.Error:
596 |
597 | self._log.exception("Failed to read directories due to configparser Error.")
598 | raise
599 |
600 | except configparser.NoSectionError:
601 |
602 | self._log.exception("Failed to read directories due to NoSectionError.")
603 | raise
604 |
605 | except Exception:
606 |
607 | self._log.exception("Failed to read directories due to unexpected Error.")
608 | raise
609 |
610 | else:
611 |
612 | # Assign the default, local, and remote directory with value from config file
613 | _default_directory = self._config['DIRECTORIES']['defaultdirectory']
614 | _local_directory = self._config['DIRECTORIES']['localdirectory']
615 | _remote_directory = self._config['DIRECTORIES']['remotedirectory']
616 |
617 | if _default_directory == "None" or _default_directory == "":
618 | _default_directory = None
619 | self._log.debug("Default directory is set to None.")
620 | else:
621 | self._log.debug(f"Default directory is set to {_default_directory}")
622 |
623 | if _local_directory == "None" or _local_directory == "":
624 | _local_directory = None
625 | self._log.debug("Local directory is set to None.")
626 | else:
627 | self._log.debug(f"Local directory is set to {_local_directory}")
628 |
629 | if _remote_directory == "None" or _remote_directory == "":
630 | _remote_directory = None
631 | self._log.debug("Remote directory is set to None.")
632 | else:
633 | self._log.debug(f"Remote directory is set to {_remote_directory}")
634 |
635 | _directories = [_default_directory, _local_directory, _remote_directory]
636 | self._log.debug(f"Retrieved the following directories from config: {_directories}")
637 |
638 | return _directories
639 |
640 | @staticmethod
641 | def _append_directories(_directory):
642 | """
643 | Creates shortcuts and file_dirs
644 | """
645 |
646 | _files, _file_dirs = glib.list_files(_directory)
647 |
648 | # Creates shortcut list with the same index
649 | _shortcuts = glib.list_shortcuts(_files)
650 |
651 | return _shortcuts, _file_dirs
652 |
653 | def save_settings(self, _directories):
654 | """
655 | Overwrites the directories in config.ini
656 | """
657 |
658 | try:
659 | self._log.debug("ConfigUtils: Attempting to save new directories.")
660 |
661 | # Read config file for the shortcuts used, shortcut characters, and textblock characters
662 | self._config.read(self._config_file_dir)
663 |
664 | # Update the config categories with the updated data
665 | self._config.set('DIRECTORIES', 'defaultdirectory', _directories[0])
666 | self._config.set('DIRECTORIES', 'localdirectory', _directories[1])
667 | self._config.set('DIRECTORIES', 'remotedirectory', _directories[2])
668 |
669 | # Write to the config file
670 | with open(self._config_file_dir, 'w') as configfile:
671 | self._config.write(configfile)
672 |
673 | except configparser.Error:
674 | self._log.exception("Failed to update config file due to configparser Error.")
675 | raise
676 |
677 | except OSError:
678 | self._log.exception("Failed to update config file due to OSError.")
679 | raise
680 |
681 | except Exception:
682 | self._log.exception("Failed to update config file due to unexpected Error.")
683 | raise
684 |
685 | else:
686 | self._log.debug("Successfully updated config file with updated stats.")
687 | return True
688 |
689 |
690 | class Update:
691 |
692 | def __init__(self, _log):
693 |
694 | # Creates instance wide log variable
695 | self._log = _log.log
696 |
697 | # Creates instance of ConfigParser
698 | self._config = configparser.ConfigParser(allow_no_value=True)
699 |
700 | # Config Directory
701 | self._config_file_dir = './config/config.ini'
702 |
703 | self._log.debug("Update initialized successfully.")
704 |
705 | def update_history(self, shortcut, textblock):
706 | """
707 | Updates the shortcuts used, total shortcut characters typed, and total textblock characters pasted
708 | """
709 |
710 | try:
711 |
712 | # Read config file for the shortcuts used, shortcut characters, and textblock characters
713 | self._config.read(self._config_file_dir)
714 | shortcuts_used = int(self._config['HISTORY']['shortcutsused'])
715 | shortcut_chars = int(self._config['HISTORY']['shortcutchars'])
716 | textblock_chars = int(self._config['HISTORY']['textblockchars'])
717 |
718 | # Increase shortcuts used by 1
719 | shortcuts_used += 1
720 |
721 | # Increase shortcut characters by the length of the current shortcut
722 | shortcut_chars += len(shortcut)
723 |
724 | # Increase textblock characters by the length of the current textblock
725 | textblock_chars += len(textblock)
726 |
727 | # Update the config categories with the updated data
728 | self._config.set('HISTORY', 'shortcutsused', str(shortcuts_used))
729 | self._config.set('HISTORY', 'shortcutchars', str(shortcut_chars))
730 | self._config.set('HISTORY', 'textblockchars', str(textblock_chars))
731 |
732 | # Write to the config file
733 | with open(self._config_file_dir, 'w') as configfile:
734 | self._config.write(configfile)
735 |
736 | except configparser.Error:
737 | self._log.exception("Failed to update config file due to configparser Error.")
738 | raise
739 |
740 | except OSError:
741 | self._log.exception("Failed to update config file due to OSError.")
742 | raise
743 |
744 | except Exception:
745 | self._log.exception("Failed to update config file due to unexpected Error.")
746 | raise
747 |
748 | else:
749 | self._log.debug("Successfully updated config file with updated stats.")
750 |
751 |
752 | if __name__ == "__main__":
753 |
754 | # Initialize Logger
755 | L = Logger()
756 |
757 | L.log.debug("Program started from ConfigUtils.py.")
758 |
759 | s = Setup(L)
760 |
761 | s.config_exists()
762 |
--------------------------------------------------------------------------------
/textscript/Gui.py:
--------------------------------------------------------------------------------
1 | import glib
2 | import threading
3 | import webbrowser
4 | import tkinter as tk
5 | from tkinter import filedialog, messagebox
6 |
7 |
8 | class Gui:
9 |
10 | def __init__(self, _word_catcher, _log, _setup):
11 |
12 | # Creates instance wide log object
13 | self._log = _log.log
14 | self._log.debug("Gui: Starting Gui initialization.")
15 |
16 | # Imports WordCatcher object initialized in text-script
17 | self._word_catcher = _word_catcher
18 |
19 | # Imports Setup object initialized in text-script
20 | self._setup = _setup
21 |
22 | # Sends the self object to TextController so the Tkinter window can be closed
23 | self._word_catcher.set_gui(self)
24 |
25 | # Initialize root in __init__
26 | self._root = None
27 |
28 | # Threading event: used for communication between threads
29 | self._stop_event = threading.Event()
30 |
31 | # Global Font Settings
32 | # Category Font: Bold and larger than regular font
33 | self._font_category = "Helvetica 12 bold"
34 | # Regular Font
35 | self._font_regular = "Helvetica"
36 | # Bold Font
37 | self._font_bold = "Helvetica 10 bold"
38 | # Monospace Font
39 | self._mono_font = "TkFixedFont"
40 |
41 | # Sets up the window layout
42 | self._setup_root_window()
43 |
44 | # Starts WordCatcher listener
45 | self._start_word_catcher()
46 | self._log.debug("Gui: WordCatcher started successfully.")
47 |
48 | # Close program if window is destroyed
49 | self._root.protocol("WM_DELETE_WINDOW", self._on_closing)
50 |
51 | self._log.debug("Gui: Initialization complete.")
52 |
53 | # Starts the window loop
54 | self._log.debug("Gui: Starting root mainloop.")
55 | self._root.mainloop()
56 |
57 | def _setup_root_window(self):
58 | """
59 | Window Setup
60 | """
61 |
62 | self._log.debug("Gui: Setting up root window.")
63 |
64 | # Creates the root window
65 | self._root = tk.Tk()
66 |
67 | # Prevents window from being resizable
68 | self._root.resizable(False, False)
69 |
70 | # Sets the window corner icon
71 | self._root.iconbitmap(default='../assets/textscript.ico')
72 |
73 | # Window title
74 | self._root.title("Text-Script")
75 |
76 | # Window size
77 | # self._root.geometry("400x400")
78 |
79 | # Create menu
80 | self._create_menu()
81 |
82 | # Create the Info frames
83 | self._create_stats_frame()
84 | self._create_textblock_frame()
85 | self._create_new_shortcuts_frame()
86 | self._create_removed_shortcuts_frame()
87 |
88 | # Place Info Frames
89 | self._organize_frames()
90 |
91 | self._log.debug("Root window setup successfully.")
92 |
93 | """
94 | Menu and Menu Widgets
95 | """
96 |
97 | def _create_menu(self):
98 |
99 | self._log.debug("Gui: Setting up top menu.")
100 |
101 | # Create menu object
102 | _menu = tk.Menu(self._root)
103 | self._root.config(menu=_menu)
104 |
105 | # File menu
106 | _file_menu = tk.Menu(_menu, tearoff=False)
107 | _menu.add_cascade(label="File", underline=0, menu=_file_menu)
108 |
109 | # File Menu
110 | _file_menu.add_command(
111 | label="Settings",
112 | command=self._open_settings
113 | )
114 | _file_menu.add_command(
115 | label="Quit",
116 | underline=0,
117 | command=self.close_text_script,
118 | accelerator="Ctrl+Q"
119 | )
120 |
121 | # Help Menu
122 | _help_menu = tk.Menu(_menu, tearoff=False)
123 | _menu.add_cascade(label="Help", underline=0, menu=_help_menu)
124 |
125 | # Help Menu
126 | _help_menu.add_command(
127 | label="How to Use",
128 | command=self._open_help
129 | )
130 | _help_menu.add_command(
131 | label="Documentation",
132 | command=self._open_documentation
133 | )
134 | _help_menu.add_command(
135 | label="Report a Bug",
136 | command=self._do_nothing
137 | )
138 |
139 | # Shortcuts for menu options
140 | self._root.bind_all("", self.close_text_script)
141 | self._root.bind_all("", self._do_nothing())
142 |
143 | self._log.debug("Gui: Successfully created top menu.")
144 |
145 | def _create_stats_frame(self):
146 | """
147 | Creates a new frame for the stats labels
148 | """
149 |
150 | self._log.debug("Gui: Creating the stats frame.")
151 |
152 | # Create the frame
153 | self._stats_frame = tk.Frame(self._root)
154 |
155 | # Create Information Labels
156 | _your_stats_label = tk.Label(
157 | self._stats_frame,
158 | font=self._font_category,
159 | text="YOUR STATS:"
160 | )
161 | _shortcuts_label = tk.Label(
162 | self._stats_frame,
163 | text="Shortcuts Used: "
164 | )
165 | _characters_typed_label = tk.Label(
166 | self._stats_frame,
167 | text="Shortcut characters typed: "
168 | )
169 | _characters_pasted_label = tk.Label(
170 | self._stats_frame,
171 | text="Textblock characters pasted: "
172 | )
173 | _keystrokes_saved_label = tk.Label(
174 | self._stats_frame,
175 | text="Keystrokes saved: "
176 | )
177 | _time_to_copy_paste_label = tk.Label(
178 | self._stats_frame,
179 | text="Time to copy and paste: "
180 | )
181 | _total_time_saved_label = tk.Label(
182 | self._stats_frame,
183 | text="Total amount of time saved: "
184 | )
185 |
186 | # Get Stats
187 | _stats = self._setup.get_stats()
188 | _complete_stats = self._setup.calculate_stats(_stats)
189 |
190 | # Create StringVars
191 | self._shortcuts_sv = tk.StringVar(self._stats_frame, value=_complete_stats[0])
192 | self._shortcut_chars_sv = tk.StringVar(self._stats_frame, value=_complete_stats[1])
193 | self._textblock_chars_sv = tk.StringVar(self._stats_frame, value=_complete_stats[2])
194 | self._saved_keystrokes_sv = tk.StringVar(self._stats_frame, value=_complete_stats[3])
195 | self._seconds_paste_sv = tk.StringVar(self._stats_frame, value=_complete_stats[4])
196 | self._time_saved_sv = tk.StringVar(self._stats_frame, value=_complete_stats[5])
197 |
198 | # Updates StringVars
199 | self.update_stats_frame()
200 |
201 | # Create StringVar Labels
202 | _shortcuts = tk.Entry(
203 | self._stats_frame,
204 | state="disabled",
205 | textvariable=self._shortcuts_sv
206 | )
207 | _characters_typed = tk.Entry(
208 | self._stats_frame,
209 | state="disabled",
210 | textvariable=self._shortcut_chars_sv
211 | )
212 | _characters_pasted = tk.Entry(
213 | self._stats_frame,
214 | state="disabled",
215 | textvariable=self._textblock_chars_sv
216 | )
217 | _keystrokes_saved = tk.Entry(
218 | self._stats_frame,
219 | state="disabled",
220 | textvariable=self._saved_keystrokes_sv
221 | )
222 | _time_to_copy_paste = tk.Entry(
223 | self._stats_frame,
224 | state="disabled",
225 | textvariable=self._seconds_paste_sv
226 | )
227 | _total_time_saved = tk.Entry(
228 | self._stats_frame,
229 | state="disabled",
230 | textvariable=self._time_saved_sv
231 | )
232 |
233 | # Pack Widgets
234 | # Info Labels
235 | _your_stats_label.grid(column=0, row=0, columnspan=2, sticky="w")
236 | _shortcuts_label.grid(column=0, row=1, sticky="w")
237 | _characters_typed_label.grid(column=0, row=2, sticky="w")
238 | _characters_pasted_label.grid(column=0, row=3, sticky="w")
239 | _keystrokes_saved_label.grid(column=0, row=4, sticky="w")
240 | _time_to_copy_paste_label.grid(column=0, row=5, sticky="w")
241 | _total_time_saved_label.grid(column=0, row=6, sticky="w")
242 | # StringVar Fields
243 | _shortcuts.grid(column=1, row=1, sticky="w")
244 | _characters_typed.grid(column=1, row=2, sticky="w")
245 | _characters_pasted.grid(column=1, row=3, sticky="w")
246 | _keystrokes_saved.grid(column=1, row=4, sticky="w")
247 | _time_to_copy_paste.grid(column=1, row=5, sticky="w")
248 | _total_time_saved.grid(column=1, row=6, sticky="w")
249 |
250 | self._log.debug("Gui: Successfully setup the stats frame.")
251 |
252 | def update_stats_frame(self):
253 | """
254 | Updates the StringVars, which immediately updates the labels
255 | """
256 |
257 | self._log.debug("Gui: Updating stats frame.")
258 |
259 | # Get Stats
260 | _stats = self._setup.get_stats()
261 | _complete_stats = self._setup.calculate_stats(_stats)
262 |
263 | # Create StringVars
264 | self._shortcuts_sv.set(_complete_stats[0])
265 | self._shortcut_chars_sv.set(_complete_stats[1])
266 | self._textblock_chars_sv.set(_complete_stats[2])
267 | self._saved_keystrokes_sv.set(_complete_stats[3])
268 | self._seconds_paste_sv.set(_complete_stats[4])
269 | self._time_saved_sv.set(_complete_stats[5])
270 |
271 | self._log.debug("Gui: Successfully updated stats frame.")
272 |
273 | def _create_textblock_frame(self):
274 | """
275 | Creates a new frame for the stats labels
276 | """
277 |
278 | self._log.debug("Gui: Creating the textblock frame.")
279 |
280 | # Directories, shortcuts, file dirs
281 | _directories = self._setup.find_directories()
282 | _shortcut_list, _file_dir_list = self._setup.shortcut_setup(_directories)
283 |
284 | # Get longest shortcut
285 | _max_shortcut_len = len(max(_shortcut_list, key=len))
286 | _shortcut_len_allowance = _max_shortcut_len + 1
287 |
288 | # Create the frame
289 | self._textblock_frame = tk.Frame(self._root)
290 |
291 | # Create Information Label
292 | _textblocks_label = tk.Label(
293 | self._textblock_frame,
294 | font=self._font_category,
295 | text="TEXTBLOCKS:"
296 | )
297 |
298 | # Scrollbars
299 | _vertical_scrollbar = tk.Scrollbar(
300 | self._textblock_frame
301 | )
302 | _horizontal_scrollbar = tk.Scrollbar(
303 | self._textblock_frame,
304 | orient="horizontal"
305 | )
306 |
307 | # Create Textblock Listbox
308 | _textblocks_listbox = tk.Listbox(
309 | self._textblock_frame,
310 | yscrollcommand=_vertical_scrollbar.set,
311 | xscrollcommand=_horizontal_scrollbar.set,
312 | bd=4,
313 | width=100,
314 | font=self._mono_font,
315 | selectmode="single"
316 | )
317 |
318 | _vertical_scrollbar.config(command=_textblocks_listbox.yview)
319 | _horizontal_scrollbar.config(command=_textblocks_listbox.xview)
320 |
321 | for _shortcut in _shortcut_list:
322 |
323 | # Get shortcut index
324 | _shortcut_index = _shortcut_list.index(_shortcut)
325 | # Get filedir for above index
326 | _file_dir = _file_dir_list[_shortcut_index]
327 |
328 | # Create list item
329 | _list_item = _shortcut
330 |
331 | # Adds spaces to fill up max allowance
332 | _shortcut_length = len(_shortcut)
333 | _add_spaces = _shortcut_len_allowance - _shortcut_length
334 | for _spaces in range(_add_spaces):
335 | _list_item += " "
336 | _list_item += f" - Directory: {_file_dir}"
337 |
338 | # Add item to listbox
339 | _textblocks_listbox.insert((_shortcut_index + 1), _list_item)
340 |
341 | # Pack Widgets
342 | # Info Labels
343 | _textblocks_label.grid(column=0, row=0, columnspan=2, sticky="w")
344 | # Listbox & scrollbar
345 | _textblocks_listbox.grid(column=0, row=1, sticky="w")
346 | _vertical_scrollbar.grid(column=1, row=1, sticky="ns")
347 | _horizontal_scrollbar.grid(column=0, row=2, sticky="ew")
348 |
349 | def _create_new_shortcuts_frame(self):
350 | """
351 | Creates a new frame for the new shortcuts
352 | """
353 |
354 | self._log.debug("Gui: Creating the New Shortcuts frame.")
355 |
356 | # Create the frame
357 | self._new_shortcuts_frame = tk.Frame(self._root)
358 |
359 | # Create Information Label
360 | _new_shortcuts_label = tk.Label(
361 | self._new_shortcuts_frame,
362 | font=self._font_category,
363 | text="NEW SHORTCUTS:"
364 | )
365 |
366 | # Create Textblock Listbox
367 | _new_shortcuts_listbox = tk.Listbox(
368 | self._new_shortcuts_frame,
369 | bd=4,
370 | font=self._mono_font,
371 | selectmode="single",
372 | height=5,
373 | width=30
374 | )
375 |
376 | _new_shortcut_list = self._setup.new_shortcuts
377 |
378 | for _shortcut in _new_shortcut_list:
379 | _shortcut_index = _new_shortcut_list.index(_shortcut)
380 | _new_shortcuts_listbox.insert((_shortcut_index + 1), _shortcut)
381 |
382 | # Pack Widgets
383 | # Info Labels
384 | _new_shortcuts_label.grid(column=0, row=0, sticky="w")
385 | # Listbox & scrollbar
386 | _new_shortcuts_listbox.grid(column=0, row=1, sticky="w")
387 |
388 | def _create_removed_shortcuts_frame(self):
389 | """
390 | Creates a new frame for the removed shortcuts
391 | """
392 |
393 | self._log.debug("Gui: Creating the Removed Shortcuts frame.")
394 |
395 | # Create the frame
396 | self._removed_shortcuts_frame = tk.Frame(self._root)
397 |
398 | # Create Information Label
399 | _removed_shortcuts_label = tk.Label(
400 | self._removed_shortcuts_frame,
401 | font=self._font_category,
402 | text="REMOVED SHORTCUTS:"
403 | )
404 |
405 | # Create Textblock Listbox
406 | _removed_shortcuts_listbox = tk.Listbox(
407 | self._removed_shortcuts_frame,
408 | bd=4,
409 | font=self._mono_font,
410 | selectmode="single",
411 | height=5,
412 | width=30
413 | )
414 |
415 | _removed_shortcut_list = self._setup.removed_shortcuts
416 |
417 | for _shortcut in _removed_shortcut_list:
418 | _shortcut_index = _removed_shortcut_list.index(_shortcut)
419 | _removed_shortcuts_listbox.insert((_shortcut_index + 1), _shortcut)
420 |
421 | # Pack Widgets
422 | # Info Labels
423 | _removed_shortcuts_label.grid(column=0, row=0, sticky="w")
424 | # Listbox & scrollbar
425 | _removed_shortcuts_listbox.grid(column=0, row=1, sticky="w")
426 |
427 | def _organize_frames(self):
428 | """
429 | Organizes frames and widgets in root frame
430 | """
431 |
432 | self._textblock_frame.grid(column=0, row=0, rowspan=2, columnspan=3, padx="3", pady="1", sticky="nw")
433 | self._stats_frame.grid(column=2, row=2, padx="3", pady="1", sticky="nw")
434 | self._new_shortcuts_frame.grid(column=0, row=2, padx="3", pady="1", sticky="nw")
435 | self._removed_shortcuts_frame.grid(column=1, row=2, padx="3", pady="1", sticky="nw")
436 |
437 | def _open_settings(self):
438 | """
439 | Opens a window with the available settings. Alters the config file.
440 | """
441 |
442 | # Get the directories from config file
443 | _directories = self._setup.find_directories()
444 |
445 | # Sets the entry values
446 | if (_directories[0] is None) or (len(_directories[0]) == 0):
447 | _current_default = "Not Set"
448 | else:
449 | _current_default = _directories[0]
450 |
451 | if (_directories[1] is None) or (len(_directories[1]) == 0):
452 | _current_local = "Not Set"
453 | else:
454 | _current_local = _directories[1]
455 |
456 | if (_directories[2] is None) or (len(_directories[2]) == 0):
457 | _current_remote = "Not Set"
458 | else:
459 | _current_remote = _directories[2]
460 |
461 | """
462 | Create Window
463 | """
464 |
465 | # Creates a new window
466 | self._settings_window = tk.Tk()
467 | self._log.debug("Gui: Settings window created successfully.")
468 |
469 | # Window Setup
470 | self._settings_window.title("Settings")
471 | self._settings_window.iconbitmap(default='../assets/textscript.ico') # Sets the window corner icon
472 | self._log.debug("Successfully setup settings window.")
473 |
474 | """
475 | Create Widgets
476 | """
477 |
478 | # Static Labels
479 | _directories_label = tk.Label(
480 | self._settings_window,
481 | justify="left",
482 | text="DIRECTORIES",
483 | font=self._font_category
484 | )
485 | _default_label = tk.Label(
486 | self._settings_window,
487 | justify="left",
488 | text="Default Directory: "
489 | )
490 | _local_label = tk.Label(
491 | self._settings_window,
492 | justify="left",
493 | text="Local Directory: "
494 | )
495 | _remote_label = tk.Label(
496 | self._settings_window,
497 | justify="left",
498 | text="Remote Directory: ",
499 | )
500 | # Save Result Label - shows the result of self._save_settings
501 | self._save_result = tk.Label(
502 | self._settings_window,
503 | justify="left",
504 | fg="red",
505 | font=self._font_bold,
506 | text=""
507 | )
508 |
509 | # TK StringVars (required to change text of entry fields automatically)
510 | # Entry
511 | self._default_sv = tk.StringVar(self._settings_window, value=_current_default)
512 | self._local_sv = tk.StringVar(self._settings_window, value=_current_local)
513 | self._remote_sv = tk.StringVar(self._settings_window, value=_current_remote)
514 |
515 | # Directory Entry Fields
516 | self._default_entry = tk.Entry(
517 | self._settings_window,
518 | justify="left",
519 | width=45,
520 | textvariable=self._default_sv,
521 | )
522 | self._local_entry = tk.Entry(
523 | self._settings_window,
524 | justify="left",
525 | width=45,
526 | textvariable=self._local_sv,
527 | )
528 | self._remote_entry = tk.Entry(
529 | self._settings_window,
530 | justify="left",
531 | width=45,
532 | textvariable=self._remote_sv,
533 | )
534 |
535 | # Buttons
536 | # Default
537 | _btn_enable_default = tk.Button(
538 | self._settings_window,
539 | width=11,
540 | text="Enable",
541 | command=self._enable_default
542 | )
543 | _btn_disable_default = tk.Button(
544 | self._settings_window,
545 | width=11,
546 | text="Disable",
547 | command=self._disable_default
548 | )
549 | # Local
550 | _btn_set_local = tk.Button(
551 | self._settings_window,
552 | width=11,
553 | text="Set",
554 | command=self._set_local
555 | )
556 | _btn_disable_local = tk.Button(
557 | self._settings_window,
558 | width=11,
559 | text="Disable",
560 | command=self._disable_local
561 | )
562 | # Remote
563 | _btn_set_remote = tk.Button(
564 | self._settings_window,
565 | width=11,
566 | text="Set",
567 | command=self._set_remote
568 | )
569 | _btn_disable_remote = tk.Button(
570 | self._settings_window,
571 | width=11,
572 | text="Disable",
573 | command=self._disable_remote
574 | )
575 | # Save
576 | _btn_save = tk.Button(
577 | self._settings_window,
578 | width=11,
579 | text="Save",
580 | command=self._save_settings
581 | )
582 |
583 | self._log.debug("Successfully created widgets.")
584 |
585 | # Pack Widgets
586 | # Description Labels
587 | _directories_label.grid(row=0, column=0, sticky="w", padx=4, pady=2)
588 | _default_label.grid(row=1, column=0, sticky="w", padx=4, pady=2)
589 | _local_label.grid(row=2, column=0, sticky="w", padx=4, pady=2)
590 | _remote_label.grid(row=3, column=0, sticky="w", padx=4, pady=2)
591 | # Entry Fields
592 | self._default_entry.grid(row=1, column=1, sticky="w", padx=4, pady=2)
593 | self._local_entry.grid(row=2, column=1, sticky="w", padx=4, pady=2)
594 | self._remote_entry.grid(row=3, column=1, sticky="w", padx=4, pady=2)
595 | # Buttons
596 | _btn_enable_default.grid(row=1, column=2, sticky="w", padx=4, pady=2)
597 | _btn_disable_default.grid(row=1, column=3, sticky="w", padx=4, pady=2)
598 | _btn_set_local.grid(row=2, column=2, sticky="w", padx=4, pady=2)
599 | _btn_disable_local.grid(row=2, column=3, sticky="w", padx=4, pady=2)
600 | _btn_set_remote.grid(row=3, column=2, sticky="w", padx=4, pady=2)
601 | _btn_disable_remote.grid(row=3, column=3, sticky="w", padx=4, pady=2)
602 | _btn_save.grid(row=4, column=3, sticky="w", padx=4, pady=2)
603 | # Save Result
604 | self._save_result.grid(row=4, column=1, sticky="w", padx=4, pady=2)
605 |
606 | self._log.debug("Successfully placed widgets in the window.")
607 |
608 | def _enable_default(self):
609 | """
610 | Sets the default directory in settings menu
611 | """
612 | try:
613 | self._default_sv.set("./textblocks/")
614 | self._save_result['text'] = ""
615 | self._settings_window.lift()
616 | except Exception:
617 | self._log.exception("Gui: An error has occurred in _enable_default")
618 | else:
619 | self._log.debug("Gui: Successfully enabled default directory")
620 |
621 |
622 | def _disable_default(self):
623 | """
624 | Disables the default directory in settings menu
625 | """
626 | try:
627 | self._default_sv.set("Not Set")
628 | self._save_result['text'] = ""
629 | self._settings_window.lift()
630 | except Exception:
631 | self._log.exception("Gui: An error has occurred in _disable_default")
632 | else:
633 | self._log.debug("Gui: Successfully disabled default directory")
634 |
635 | def _set_local(self):
636 | """
637 | Sets local directory in settings menu
638 | """
639 |
640 | try:
641 | # Uses askdirectory to set the directory
642 | self._local_sv.set(filedialog.askdirectory()) # Shows askdirectory dialog, saves result to StringVar
643 | self._save_result['text'] = "" # Deletes the save result text
644 | self._settings_window.lift() # Lifts the settings window to the front
645 | except Exception:
646 | self._log.exception("Gui: An error has occurred in _set_local")
647 | else:
648 | self._log.debug("Gui: Successfully set the local directory")
649 |
650 | def _disable_local(self):
651 | """
652 | Disables the local directory in settings menu
653 | """
654 |
655 | try:
656 | self._local_sv.set("Not Set")
657 | self._save_result['text'] = ""
658 | self._settings_window.lift()
659 | except Exception:
660 | self._log.exception("Gui: An error has occurred in _disable_local")
661 | else:
662 | self._log.debug("Gui: Successfully disabled local directory")
663 |
664 |
665 | def _set_remote(self):
666 | """
667 | Save remote directory in settings menu
668 | """
669 |
670 | try:
671 | # Uses askdirectory to set the directory
672 | self._remote_sv.set(filedialog.askdirectory())
673 | self._save_result['text'] = ""
674 | self._settings_window.lift()
675 | except Exception:
676 | self._log.exception("Gui: An error has occurred in _set_remote")
677 | else:
678 | self._log.debug("Gui: Successfully set the remote directory")
679 |
680 | def _disable_remote(self):
681 | """
682 | Disables the remote directory in settings menu
683 | """
684 |
685 | try:
686 | self._remote_sv.set("Not Set")
687 | self._save_result['text'] = ""
688 | self._settings_window.lift()
689 | except Exception:
690 | self._log.exception("Gui: An error has occurred in _disable_remote")
691 | else:
692 | self._log.debug("Gui: Successfully disabled remote directory")
693 |
694 | def _save_settings(self):
695 | """
696 | Overwrites the directories in the config file
697 | """
698 |
699 | # Initialize Variables
700 | _save_successful = False # Variable that tracks if save was successful
701 |
702 | # Gets the values from the entry fields
703 | _default = self._default_entry.get()
704 | _local = self._local_entry.get()
705 | _remote = self._remote_entry.get()
706 |
707 | _real_dirs = True # Tracks if all directories are real before saving
708 | _error_message = ""
709 |
710 | # Sets values to None if Not Set
711 | if _default == "Not Set":
712 | _default = "None"
713 | if _local == "Not Set":
714 | _local = "None"
715 | if _remote == "Not Set":
716 | _remote = "None"
717 |
718 | _directories = [_default, _local, _remote] # List of directories
719 |
720 | for _directory in _directories: # For each directory
721 |
722 | if _directory != "None":
723 | _exists = glib.check_directory(_directory) # Check if the directory exists
724 |
725 | if _exists is False: # If doesn't exist
726 | _real_dirs = False # Set _real_dirs to false, else leave it True
727 | _error_message += f"Invalid directory: {_directory}\n"
728 |
729 | if _real_dirs is False:
730 | messagebox.showinfo("Save settings failed", _error_message)
731 | else:
732 | # Writes to config
733 | print(f"Saving directories: {_default}, {_local}, {_remote}")
734 | _save_successful = self._setup.save_settings(_directories)
735 |
736 | if _save_successful is True:
737 | self._log.debug("Successfully saved the settings.")
738 | self._save_result['text'] = "Save Successful"
739 | self._word_catcher.reload_shortcuts(called_externally=True)
740 |
741 | def _open_help(self):
742 | """
743 | Opens a window with the Text-Script Instructions
744 | """
745 |
746 | # Help text
747 | _help_text = glib.help_text()
748 |
749 | # Creates a new window
750 | self._help_window = tk.Tk()
751 |
752 | # Window Setup
753 | self._help_window.title("How to use Text-Script")
754 | self._help_window.iconbitmap(default='../assets/textscript.ico') # Sets the window corner icon
755 |
756 | # Labels
757 | _help_label = tk.Label(
758 | self._help_window,
759 | justify="left",
760 | font=self._font_bold,
761 | text=_help_text
762 | )
763 |
764 | # Packs labels into window
765 | _help_label.grid(row=0, column=0, sticky="w", padx=4, pady=2)
766 |
767 | def _open_documentation(self):
768 | """
769 | Shows the user the link to the documentation and offers to open this in browser. Selecting no closes the window.
770 | """
771 |
772 | # Repository URL
773 | self._documentation_url = "https://github.com/GeorgeCiesinski/text-script"
774 |
775 | # Label text for documentation window
776 | _documentation_message = f"""You can find the documentation at the below link:
777 |
778 | {self._documentation_url}
779 |
780 | """
781 |
782 | # Creates a new window
783 | self._doc_window = tk.Tk()
784 |
785 | # Window setup
786 | self._doc_window.title("Text-Script Documentation")
787 | self._doc_window.iconbitmap(default='../assets/textscript.ico') # Sets the window corner icon
788 | self._doc_window.geometry("340x130")
789 |
790 | # Create Labels
791 | _link_label = tk.Label(
792 | self._doc_window,
793 | justify="left",
794 | font=self._font_bold,
795 | text=_documentation_message
796 | )
797 |
798 | # Create Buttons
799 | _open_link = tk.Button(
800 | self._doc_window,
801 | text="Open Link",
802 | width=11,
803 | height=1,
804 | bd=4,
805 | command=self._open_link
806 | )
807 |
808 | # Packs widgets into window
809 | # Labels
810 | _link_label.grid(row=1, column=0, padx=4, pady=2)
811 | # Buttons
812 | _open_link.grid(row=2, column=0)
813 |
814 | def _open_link(self):
815 | """
816 | Opens documentation link in default browser.
817 | """
818 |
819 | # Opens link after user presses yes. Opens as a tab and raises the window
820 | webbrowser.open(self._documentation_url, new=0, autoraise=True)
821 |
822 | # Calls function to close window
823 | self._close_doc_window()
824 |
825 | def _close_doc_window(self):
826 | """
827 | Destroys the documentation window.
828 | """
829 |
830 | self._doc_window.destroy()
831 |
832 | """
833 | Temporary Methods
834 | """
835 |
836 | def _do_nothing(self):
837 | """
838 | Temporary placeholder function. To be removed once GUI elements are complete.
839 | """
840 |
841 | pass
842 |
843 | """
844 | WordCatcher and Threading
845 | """
846 |
847 | def _start_word_catcher(self):
848 | """
849 | Starts listener as a new thread
850 | """
851 |
852 | self._log.debug("Gui: Starting Word Catcher.")
853 |
854 | word_catcher_thread = self._start_thread(target=self._word_catcher.run_listener)
855 |
856 | def _start_thread(self, target):
857 | """
858 | Starts target as a new thread
859 | """
860 |
861 | self._log.debug("Gui: Starting new thread.")
862 |
863 | self._stop_event.clear()
864 | thread = threading.Thread(target=target)
865 | thread.start()
866 | return thread
867 |
868 | def _on_closing(self):
869 | """
870 | Closes program if user clicks x button on the window
871 | """
872 |
873 | self._log.debug("User clicked the x button. Quiting program.")
874 | self.close_text_script()
875 |
876 | def close_text_script(self, event=None):
877 | """
878 | Kills the GUI. Can be called from outside Gui so Listener can kill it.
879 | """
880 |
881 | self._word_catcher.stop_listener()
882 | self._log.debug("Gui: Listener stopped successfully. Destroying the window.")
883 | self._root.destroy()
884 |
--------------------------------------------------------------------------------
/textscript/Logger.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from logging import handlers
3 | from os import path
4 | import glib
5 |
6 |
7 | class Logger:
8 |
9 | def __init__(self):
10 | """
11 | Initializes an instance of Logging and configures the instance
12 | """
13 |
14 | # Logs directory
15 | self.log_dir = "./Logs/"
16 |
17 | # Basic Settings
18 | self.log = logging.getLogger(__name__)
19 | self.log.setLevel(logging.DEBUG)
20 | formatter = logging.Formatter('%(asctime)s - %(levelname)s : %(message)s')
21 |
22 | # Create directory if doesn't exist
23 | if not glib.check_directory(self.log_dir):
24 | glib.create_folder(self.log_dir)
25 | print(f"Created Logs directory as it did not exist: {self.log_dir}")
26 |
27 | # Check if logs exist
28 | self._rollover_check = path.exists('./Logs/logs.log')
29 |
30 | # Rotating File Handler (5 backups)
31 | self._file_handler = handlers.RotatingFileHandler('./Logs/logs.log', mode='w', maxBytes=100000, backupCount=5)
32 | self._file_handler.setFormatter(formatter)
33 | self.log.addHandler(self._file_handler)
34 |
35 | # Perform rollover check
36 | self._roll_over()
37 |
38 | def _roll_over(self):
39 | """
40 | If log exists, rollover
41 | """
42 |
43 | if self._rollover_check:
44 | self._file_handler.doRollover()
45 |
--------------------------------------------------------------------------------
/textscript/TextController.py:
--------------------------------------------------------------------------------
1 | import glib
2 | from time import sleep
3 | from chardet import detect
4 | from pynput.keyboard import Controller, Key, Listener
5 | import pyperclip
6 | import platform
7 | from Logger import Logger
8 | from ConfigUtils import Update
9 |
10 |
11 | # Class catches individual words as they are typed
12 | class WordCatcher:
13 |
14 | def __init__(self, _log, _keyboard, _shortcut_list, _file_dir_list, _setup):
15 |
16 | """
17 | Setup Class Objects
18 | """
19 | # Creates instance wide log object
20 | self._log = _log.log
21 | self._log.debug("TextController: Starting WordCatcher initialization.")
22 |
23 | # Gui variable
24 | self._gui = None
25 |
26 | # Creates instance wide Setup object
27 | self._setup = _setup
28 | self._log.debug("TextController: Successfully inherited Setup instance.")
29 | # Todo: Will passing the setup object work to save from new object being initialized?
30 |
31 | # Creates instance wide Update object
32 | self._update = Update(_log)
33 | self._log.debug("TextController: Successfully initialized new Update object in WordCatcher.")
34 | # Todo: Will passing the update object work to save from new object being initialized?
35 |
36 | # Creates instance wide keyboard variable
37 | self._keyboard = _keyboard
38 |
39 | # Define listener in __init__
40 | self._listener = None
41 |
42 | """
43 | Setup Text-Script Variables
44 | """
45 |
46 | # Delimiter
47 | self._shortcut_delimiter = "#"
48 | self._command_delimiter = "!"
49 |
50 | # List of Text-Script commands
51 | self._commands = [
52 | "!help",
53 | "!reload"
54 | ]
55 |
56 | # Current key and KeyData
57 | self._key = None
58 | self._keydata = None
59 |
60 | # Creates instance wide shortcut_list & file_dir_list
61 | self._shortcut_list = _shortcut_list
62 | self._file_dir_list = _file_dir_list
63 |
64 | # Temporary word variables
65 | self._word_in_progress = False # There is a word currently being built
66 | self._current_word = "" # The current word
67 | self._is_command = False # Is this word a command
68 |
69 | # Temporary clipboard variable
70 | self._current_clipboard = ""
71 |
72 | # Textblock Variable
73 | self._textblock = ""
74 |
75 | self._log.debug("TextController: WordCatcher initialized successfully.")
76 |
77 | def set_gui(self, _gui):
78 | """
79 | Sets Gui instance so the window can be closed from TextController
80 | """
81 |
82 | self._gui = _gui
83 | self._log.debug("TextController: Successfully set Gui object.")
84 |
85 | def run_listener(self, ):
86 |
87 | # Start self.listener
88 | with Listener(on_press=self.word_builder) as self._listener:
89 | self._log.debug("TextController: Listener started.")
90 | self._listener.join()
91 |
92 | def stop_listener(self):
93 |
94 | self._log.debug("TextController: Stopping listener.")
95 | self._listener.stop()
96 |
97 | def word_builder(self, key):
98 | """
99 | word_test should listen for the delimiter. If delimiter is pressed, this method should:
100 | - append following letters to word
101 | - keep a count of appended letters
102 | - remove letters when Key.backspace is pressed, and reduce count
103 | - print word when tab, space, or backspace is pressed
104 | - delete word after it is printed
105 |
106 | :param key:
107 | """
108 |
109 | # Sets keypress to instance key value
110 | self._key = key
111 |
112 | # Converts to raw value string
113 | self._keycode_to_keydata()
114 |
115 | # Prints keys to console -- debugging
116 | # print(self._keydata)
117 |
118 | # Checks delimiter
119 | self._check_delimiter()
120 |
121 | # Checks if word has ended
122 | self._check_word_end()
123 |
124 | # Checks for backspace
125 | self._check_backspace()
126 |
127 | # Appends letter if word is in progress
128 | self._append_letter()
129 |
130 | def _keycode_to_keydata(self):
131 | """
132 | Converts KeyCode to string and strips quotations (into variable: keydata).
133 | """
134 |
135 | # Converts KeyData to string, strips ' from result
136 | self._keydata = str(self._key)
137 | self._keydata = self._keydata.strip("'")
138 |
139 | def _check_delimiter(self):
140 | """
141 | Checks if shortcut or command delimiter has been entered. Either starts self.current_word or restarts it.
142 | """
143 |
144 | if self._keydata == self._shortcut_delimiter or self._keydata == self._command_delimiter:
145 |
146 | self._is_command = False # Words are not commands by default
147 |
148 | if self._word_in_progress is True:
149 | self._log.debug("TextController: Delimiter detected while word in progress. Restarting word.")
150 | else:
151 | self._log.debug("TextController: Delimiter detected. Starting new word.")
152 |
153 | self._clear_current_word()
154 |
155 | # Sets word_in_progress to True as new word has been started
156 | self._word_in_progress = True
157 |
158 | # Sets _is_command to true if _command_delimiter is detected.
159 | if self._keydata == self._command_delimiter:
160 | self._is_command = True
161 |
162 | def _check_word_end(self):
163 | """
164 | Checks if Key.tab, Key.space, or Key.enter is pressed. Prints word if pressed.
165 | """
166 |
167 | if self._keydata == "Key.tab" or self._keydata == "Key.space" or self._keydata == "Key.enter":
168 |
169 | # Checks if there is a word in progress, clears it if true
170 | if self._word_in_progress is True:
171 |
172 | self._log.debug(f"TextController: Word ended by {self._keydata}: {self._current_word}")
173 |
174 | self._check_shortcut()
175 |
176 | # Clears current word
177 | self._clear_current_word()
178 |
179 | def _check_backspace(self):
180 | """
181 | Checks if backspace was pressed. Erases last letter if pressed.
182 | """
183 |
184 | if self._keydata == "Key.backspace":
185 |
186 | # Removes last letter from word
187 | self._current_word = self._current_word[:-1]
188 |
189 | self._log.debug("TextController: Key.backspace detected.")
190 |
191 | def _append_letter(self):
192 | """
193 | Appends the letter to self.current_word if self.word_in_progress is true
194 | """
195 |
196 | if self._word_in_progress is True and len(self._keydata) == 1:
197 |
198 | # Adds letter to the word
199 | self._current_word += self._keydata
200 |
201 | self._log.debug(f"TextController: Appended {self._keydata} to the current word.")
202 |
203 | def _check_shortcut(self):
204 | """
205 | Checks list of shortcuts for a match. Sets text block if match is found.
206 | """
207 |
208 | self._log.debug(f"TextController: Checking the shortcut {self._current_word}.")
209 |
210 | # If shortcut is in command list, determine which command was used
211 | if self._current_word in self._commands:
212 |
213 | self._determine_command()
214 |
215 | # If shortcut is in shortcut_list, determine which shortcut was used
216 | if self._current_word in self._shortcut_list:
217 |
218 | # Finds index of self.current_word on shortcut list
219 | shortcut_index = self._shortcut_list.index(self._current_word)
220 |
221 | # Passes the above index to self.read_textblock
222 | self._find_file_directory(shortcut_index)
223 |
224 | # Update history
225 | self._update.update_history(self._current_word, self._textblock)
226 |
227 | # Update GUI
228 | self._gui.update_stats_frame()
229 |
230 | # Deletes the typed out shortcut
231 | self._keyboard.delete_shortcut(self._current_word)
232 |
233 | # Saves current clipboard item
234 | self._save_clipboard()
235 |
236 | # Passes the textbox to the keyboard
237 | self._keyboard.paste_block(self._textblock)
238 |
239 | # Retrieves the saved clipboard item
240 | self._retrieve_clipboard()
241 |
242 | def _save_clipboard(self):
243 | """
244 | Saves the current item in the clipboard to be retrieved after textblock is pasted.
245 | """
246 |
247 | _clipboard_item = pyperclip.paste()
248 |
249 | if len(_clipboard_item) > 0:
250 |
251 | self._current_clipboard = _clipboard_item
252 |
253 | self._log.info("Clipboard item saved.")
254 |
255 | else:
256 |
257 | self._log.info("Clipboard item not saved as there doesn't appear to be any item.")
258 |
259 | def _retrieve_clipboard(self):
260 | """
261 | Returns the clipboard item after pasting textblock
262 | """
263 |
264 | if len(self._current_clipboard) > 0:
265 |
266 | sleep(0.05)
267 |
268 | pyperclip.copy(self._current_clipboard)
269 |
270 | self._log.info("Clipboard item retrieved.")
271 |
272 | self._current_clipboard = ""
273 |
274 | else:
275 |
276 | self._log.debug("Unable to retrieve clipboard item as there does not appear to be any item saved.")
277 |
278 | def _determine_command(self):
279 |
280 | # Paste help menu if user typed in #help
281 | if self._current_word == "!help":
282 |
283 | self._log.debug("The user has typed in #help. Pasting help menu.")
284 | self._help_menu()
285 |
286 | if self._current_word == "!reload":
287 |
288 | self._log.debug("The user has typed in #reload. Reloading shortcut_list and file_dir_list.")
289 | self.reload_shortcuts()
290 |
291 | def reload_shortcuts(self, called_externally=False):
292 | """
293 | Reloads the shortcuts without restarting the program.
294 | """
295 |
296 | self._log.debug(f"TextController: Starting reload_shortcuts. Called_externally set to {called_externally}")
297 |
298 | # Gets a list with default, local, and remote directories
299 | directories = self._setup.find_directories()
300 |
301 | # Load shortcuts and file directories
302 | self._shortcut_list, self._file_dir_list = self._setup.shortcut_setup(directories)
303 |
304 | # Check if new shortcuts have been added
305 | self._setup.new_shortcut_check(self._shortcut_list)
306 |
307 | reload_text = "Shortcuts Reloaded."
308 |
309 | self._log.info("TextController: Shortcuts Reloaded.")
310 |
311 | if called_externally is False:
312 |
313 | self._keyboard.delete_shortcut(self._current_word)
314 |
315 | self._keyboard.paste_block(reload_text)
316 |
317 | def _help_menu(self):
318 |
319 | _help_text = glib.help_text()
320 |
321 | self._keyboard.delete_shortcut(self._current_word)
322 |
323 | self._keyboard.paste_block(_help_text)
324 |
325 | def _find_file_directory(self, index):
326 | """
327 | Finds the directory of the Textblock file.
328 | """
329 |
330 | # Searches self.file_dir_list by index for the directory
331 | _textblock_directory = self._file_dir_list[index]
332 | self._log.debug(f"TextController: Successfully found the textblock directory: {_textblock_directory}")
333 |
334 | # Reads the textblock file
335 | self._read_textblock(_textblock_directory)
336 |
337 | def _read_textblock(self, _textblock_directory):
338 | """
339 | Reads the file located in textblock_directory.
340 | """
341 |
342 | # Chardet attempts to guess the file encoding
343 | try:
344 | _chardet_result = detect(open(_textblock_directory, "rb").read())
345 | self._log.debug(f"TextController: Chardet encoding guess: {_chardet_result}")
346 |
347 | _encoding = _chardet_result['encoding']
348 |
349 | except Exception:
350 | self._log.debug("TextController: Failed to guess the encoding using Chardet.")
351 | raise
352 |
353 | except FileNotFoundError:
354 | self._log.debug("TextController: Textblock location cannot be found. Please check if the shortcut still exists.")
355 | raise
356 |
357 | else:
358 |
359 | self._log.debug("TextController: Successfully guessed the textblock encoding.")
360 |
361 | # Attempt to open file in UTF-16
362 | try:
363 | # Opens the textblock directory
364 | with open(_textblock_directory, mode="r", encoding=_encoding) as t:
365 |
366 | # Assigns textblock content to the variable
367 | self._textblock = t.read()
368 | except FileNotFoundError:
369 | self._log.exception("Unable to open textblock as the file is missing.")
370 | raise
371 | except UnicodeDecodeError:
372 | self._log.exception(f"Failed to open file in {_encoding} encoding. Try changing the textblock encoding to Unicode.")
373 | raise
374 | else:
375 | self._log.debug(f"Successfully opened the file in {_encoding} encoding.")
376 | return
377 |
378 | def _clear_current_word(self):
379 | """
380 | Replaces self.current_word with empty string, and sets self.word_in_progress to False
381 | """
382 |
383 | self._current_word = ""
384 | self._word_in_progress = False
385 |
386 | self._log.debug("TextController: Cleared current word & self.current_word changed to False.")
387 |
388 |
389 | class KeyboardEmulator:
390 |
391 | def __init__(self, _log):
392 |
393 | self._log = _log.log
394 |
395 | self._log.debug("TextController: Starting KeyboardEmulator initialization.")
396 |
397 | # Decide whether to use ctrl+v or cmd+v to paste, depending on the OS
398 | if platform.system() == 'Darwin':
399 | self._log.debug("TextController: Detected OS 'Darwin'. Using modifier key 'cmd'.")
400 | self._modifier_key = Key.cmd
401 | else:
402 | self._log.debug("TextController: Using default modifier key 'ctrl_l'.")
403 | self._modifier_key = Key.ctrl_l
404 |
405 | # Initializes controller
406 | self._controller = Controller()
407 |
408 | self._log.debug("Controller initialized.")
409 | self._log.debug("KeyboardEmulator initialized successfully.")
410 |
411 | def delete_shortcut(self, current_word):
412 | """
413 | Deletes the shortcut that the user typed in.
414 | """
415 |
416 | try:
417 | word_length = len(current_word)
418 | for i in range(word_length + 1):
419 | self._controller.press(Key.backspace)
420 | self._controller.release(Key.backspace)
421 | except Exception:
422 | self._log.exception(f"TextController: Failed to delete the shortcut.{current_word}")
423 | raise
424 | else:
425 | self._log.debug(f"TextController: Successfully deleted the shortcut: {current_word}")
426 |
427 | def paste_block(self, _textblock):
428 | """
429 | paste_block copies the textblock into the clipboard and pastes it using pyinput controller.
430 | """
431 |
432 | try:
433 |
434 | pyperclip.copy(_textblock)
435 |
436 | self._controller.press(self._modifier_key)
437 | self._controller.press('v')
438 | self._controller.release(self._modifier_key)
439 | self._controller.release('v')
440 |
441 | except Exception:
442 |
443 | self._log.exception("TextController: Failed to paste the textblock.")
444 | print("An error has occurred while pasting the textblock. Please see the logs for more detail.")
445 | # Todo: What is the behavior if we do not raise this?
446 |
447 | else:
448 | self._log.debug("TextController: Successfully pasted the textblock.")
449 |
450 |
451 | if __name__ == "__main__":
452 |
453 | # Creates instance of Logger
454 | L = Logger()
455 | L.log.debug("Program started from TextController.py. Debugging.")
456 |
457 | # Initializes KeyboardEmulator instance
458 | k = KeyboardEmulator(L)
459 |
460 | # Initializes WordCatcher instance
461 | w = WordCatcher(L, k)
462 |
--------------------------------------------------------------------------------
/textscript/config/config.ini:
--------------------------------------------------------------------------------
1 | [TEXTSCRIPT]
2 | ; config file version
3 | version = 1.3.1
4 |
5 | [HISTORY]
6 | ; keeps a record of the number of keystrokes, and used shortcuts
7 | shortcutsused = 0
8 | shortcutchars = 0
9 | textblockchars = 0
10 |
11 | [DIRECTORIES]
12 | ; the default directory included with app, local directory, and network directory
13 | defaultdirectory = ./textblocks/
14 | localdirectory = None
15 | remotedirectory = None
16 |
17 | [SHORTCUTS]
18 | ; keeps a record of previously loaded shortcuts
19 | lastshortcuts = #example, #sigexample
20 |
21 |
--------------------------------------------------------------------------------
/textscript/glib.py:
--------------------------------------------------------------------------------
1 | """
2 | Contains non-class or miscellaneous functions, and Text-Script information
3 | """
4 |
5 | import os
6 |
7 |
8 | def get_version():
9 | """
10 | Current app version / / Ensure this is correct during updates
11 |
12 | :return current_version:
13 | :rtype string:
14 | """
15 | current_version = "1.3.1"
16 |
17 | return current_version
18 |
19 |
20 | def help_text():
21 | """
22 | Contains the help text used by the program. This is located in one location so it is easier to edit.
23 |
24 | :return help_text:
25 | :rtype string:
26 | """
27 |
28 | help_text = """Help Menu:
29 |
30 | How to make a shortcut:
31 |
32 | 1. Navigate to the program folder, and go to the Textblocks folder
33 | 2. Either navigate to an existing folder in Textblocks, or create a new one
34 | 3. Create a new text file here. The naming convention is #____.txt where ____ is the shortcut you will type
35 | 4. Open the text file and put your text block / signature / template in here
36 |
37 | Note: As long as this is a .txt file, the encoding should not matter, however if you are getting formatting issues
38 | or crashes with that textblock, try changing the encoding to unicode.
39 |
40 | To see this at any time, type: !help into a text input field.
41 | To reload shortcuts, type: !reload
42 | """
43 |
44 | return help_text
45 |
46 |
47 | def check_directory(directory):
48 | """
49 | Checks directory to see if folder exists
50 | """
51 |
52 | # Return true if directory exists
53 | if os.path.isdir(directory):
54 | return True
55 | else:
56 | return False
57 | print("Missing log directory.")
58 |
59 |
60 | def create_folder(directory):
61 | """
62 | Creates directory in project folder
63 | """
64 |
65 | parent_dir = os.getcwd()
66 | folder_dir = os.path.join(parent_dir, directory)
67 |
68 | try:
69 | os.mkdir(folder_dir)
70 | except OSError as error:
71 | print("Unable to create Log directory in project folder due to the following error:")
72 | print(error)
73 |
74 |
75 | def list_subdirectories(_directory):
76 | """
77 | Lists all subdirectories.
78 |
79 | :param _directory:
80 | :return directory_list:
81 | :rtype list:
82 | """
83 |
84 | directory_list = list()
85 |
86 | for _root, _dirs, _files in os.walk(_directory, topdown=False):
87 | for name in _dirs:
88 | directory_list.append(os.path.join(_root, name))
89 |
90 | return directory_list
91 |
92 |
93 | def list_files(_directory):
94 | """
95 | Lists all files and subdirectories in the directory. Returns list
96 |
97 | :param _directory:
98 | :return _file_list, _file_dir_list:
99 | :rtype list:
100 | """
101 |
102 | _file_list = list()
103 | _file_dir_list = list()
104 |
105 | for root, dirs, files in os.walk(_directory, topdown=False):
106 | for name in files:
107 | # Check if shortcut name is compatible
108 | if _shortcut_compatibility_check(name):
109 | # Append to _file_list and _file_dir_list if yes
110 | _file_list.append(name)
111 | _file_dir_list.append(os.path.join(root, name))
112 |
113 | return _file_list, _file_dir_list
114 |
115 |
116 | def list_shortcuts(_file_list):
117 | """
118 | list_shortcuts creates a list of the raw shortcut strings the user would be typing in
119 |
120 | :param _file_list:
121 | :return _shortcut_list:
122 | :rtype list:
123 | """
124 |
125 | _shortcut_list = list()
126 |
127 | for f in _file_list:
128 | f = f.split(".")
129 |
130 | _shortcut_list.append(f[0])
131 |
132 | return _shortcut_list
133 |
134 |
135 | def _shortcut_compatibility_check(_shortcut):
136 | """
137 | Checks if shortcut is formatted contains a second delimiter in the name. Return _is_compatible = False
138 |
139 | :param _shortcut:
140 | :rtype bool:
141 | """
142 |
143 | # Delimiter
144 | _shortcut_delimiter = "#"
145 | _command_delimiter = "!"
146 |
147 | _is_compatible = None
148 |
149 | # If the delimiter appears in the actual shortcut, return False
150 | if _shortcut_delimiter in _shortcut[1:] or _command_delimiter in _shortcut[1:]:
151 |
152 | _is_compatible = False
153 |
154 | else:
155 |
156 | _is_compatible = True
157 |
158 | return _is_compatible
159 |
160 |
161 | def print_shortcuts(_file_dirs, _shortcuts):
162 |
163 | for _file_dir in _file_dirs:
164 | index = _file_dirs.index(_file_dir)
165 | print(f"Shortcut: {_shortcuts[index]} - - - Directory: {_file_dir}")
166 |
167 |
168 | if __name__ == "__main__":
169 |
170 | pass
171 |
--------------------------------------------------------------------------------
/textscript/text-script.py:
--------------------------------------------------------------------------------
1 | import glib
2 | from Gui import Gui
3 | from ConfigUtils import Setup
4 | from Logger import Logger
5 | from TextController import WordCatcher, KeyboardEmulator
6 |
7 |
8 | def main():
9 |
10 | # Get's the current version from glib. Make sure this is accurate before a public release.
11 | text_script_version = glib.get_version()
12 |
13 | """
14 | Initialize Logger
15 | """
16 |
17 | # Initialize Logger
18 | L = Logger()
19 | L.log.debug(f"Program started from text-script. Version: {text_script_version}")
20 |
21 | # Output version
22 | print(f"Running text-script version {text_script_version}.\n")
23 |
24 | """
25 | Configure Settings
26 | """
27 |
28 | # Initialize setup
29 | setup = Setup(L, text_script_version)
30 |
31 | # Check if config file exists, and is up to date
32 | setup.config_exists()
33 |
34 | # Get stats from config
35 | stats = setup.get_stats()
36 | # Calculate remaining stats
37 | complete_stats = setup.calculate_stats(stats)
38 | # Print stats to console
39 | setup.print_stats(complete_stats)
40 |
41 | """
42 | Initialize Text Controller
43 | """
44 |
45 | # Gets a list with default, local, and remote directories
46 | directories = setup.find_directories()
47 |
48 | # Load shortcuts and file directories
49 | shortcut_list, file_dir_list = setup.shortcut_setup(directories)
50 | L.log.debug("text-script retrieved shortcut_list, file_dir_list:")
51 |
52 | # Check if new shortcuts have been added
53 | setup.new_shortcut_check(shortcut_list)
54 |
55 | # Initializes KeyboardEmulator instance
56 | k = KeyboardEmulator(L)
57 |
58 | # Initialize WordCatcher
59 | w = WordCatcher(L, k, shortcut_list, file_dir_list, setup)
60 |
61 | """
62 | Start Gui
63 | """
64 |
65 | # Initialize GUI
66 | g = Gui(w, L, setup)
67 |
68 | # Close program if all threads are killed
69 | raise SystemExit
70 |
71 |
72 | if __name__ == "__main__":
73 |
74 | main()
75 |
--------------------------------------------------------------------------------
/textscript/textblocks/Examples/#example.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GeorgeCiesinski/text-script/990862cf796ce981d91f13c7be89d2a4233913e9/textscript/textblocks/Examples/#example.txt
--------------------------------------------------------------------------------
/textscript/textblocks/Examples/#sigexample.txt:
--------------------------------------------------------------------------------
1 | regards,
2 |
3 | Mr. Elizabeth
4 |
5 | Owner of the manliest name known to mankind.
6 |
7 | Phone: (123) 456 - 7890
8 | Email: mr.elizabeth@manly.man
9 |
10 | This is a highly confidential correspondance. I recommend that you
11 | immediately destroy this email and don't let anybody else on earth
12 | see it. Failure to do this will result in me being super angry.
13 | Trust me, you don't want Mr. Elizabeth to come for you.
14 |
--------------------------------------------------------------------------------