├── requirements.txt
├── icon.ico
├── images
└── one.png
├── DisplayManagerAppIcon.png
├── README.md
├── LICENSE
└── DisplayPartitioner.py
/requirements.txt:
--------------------------------------------------------------------------------
1 | pywin32
2 | pystray
3 | Pillow
4 | keyboard
5 |
--------------------------------------------------------------------------------
/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Abhijith-Shaju/DisplayPartitioner/HEAD/icon.ico
--------------------------------------------------------------------------------
/images/one.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Abhijith-Shaju/DisplayPartitioner/HEAD/images/one.png
--------------------------------------------------------------------------------
/DisplayManagerAppIcon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Abhijith-Shaju/DisplayPartitioner/HEAD/DisplayManagerAppIcon.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Display Zone Manager
2 |
3 |
4 |
5 |
6 | Display Zone Manager
7 | A lightweight, powerful, and persistent window management utility for Windows.
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 | ---
16 |
17 | **Display Zone Manager** is a "set it and forget it" tool for power users, developers, and anyone who needs precise control over their desktop real estate. It allows you to create custom workspaces on your monitor with an interactive, graphical interface.
18 |
19 | Whether you need to visually partition a large monitor, lock your mouse to a specific area, or automatically arrange application windows into a perfect grid, this tool gives you the power to do so with ease and efficiency.
20 |
21 | ## ✨ Features
22 |
23 | - ✅ **Full Graphical User Interface:** No more editing config files! A modern, responsive settings window gives you a real-time visual representation of your monitor and zones.
24 | - 🎨 **Visual Overlay Zone:** Create a persistent, semi-transparent colored bar to visually divide your monitor space.
25 | - 🖼️ **Intelligent Window Tiling:**
26 | - **Manual Selection:** Choose exactly which applications you want to manage from an auto-detected list, complete with app icons.
27 | - **Dynamic Grid Layout:** The app automatically arranges 1, 2, 3, or 4+ windows into a logical, aesthetically pleasing grid that adapts to your defined zone.
28 | - **Custom Tiling Areas:** Define a tiling zone across a full partition or specify a custom start and end coordinate.
29 | - 🖱️ **Cursor Lock ("Hard Wall"):**
30 | - Lock your mouse cursor to a specific region of your monitor.
31 | - Uses the native `ClipCursor` API for a lag-free, OS-level boundary.
32 | - ✏️ **Interactive & Precise Configuration:**
33 | - **Drag-and-Drop:** Simply drag a line on the screen canvas to set your boundaries.
34 | - **Manual Input:** Type in an exact coordinate for pixel-perfect control.
35 | - ⌨️ **Customizable Global Hotkey:** Bring up the settings window from anywhere with a custom hotkey (defaults to a safe `Ctrl+Alt+P`).
36 | - 💾 **Persistent Settings:** All your configurations—target monitor, zones, colors, opacity, hotkey, and tiled windows—are saved automatically and reloaded on next launch.
37 | - 🚀 **Lightweight & Efficient:** Runs silently in the system tray with minimal CPU and memory usage.
38 |
39 | ## 📺 Demo
40 |
41 |
42 | This is the Application interface
43 |
44 |
45 |
46 | ## Who is this for?
47 |
48 | - **Developers** who want a tiling-like experience on one monitor while keeping another free.
49 | - **Streamers** who need to section off parts of their screen for game, chat, and streaming software.
50 | - **Power Users** looking for more granular control over their desktop than standard Windows settings allow.
51 | - Anyone with an **ultrawide monitor** who wants to create more manageable, focused workspaces.
52 |
53 | ## 🚀 Installation & Usage
54 |
55 | ### For End-Users (Recommended)
56 | No programming knowledge required.
57 |
58 | 1. Go to the [**Releases Page**](https://github.com/Abhijith-Shaju/DisplayPartitioner/releases) of this repository.
59 | 2. Download the latest `Display_Zone_Manager.exe` file.
60 | 3. Place the `.exe` file in a permanent folder on your computer.
61 | 4. Double-click to run. An icon will appear in your system tray.
62 | 5. **Left-click the tray icon** (or right-click and choose "Settings") to open the configuration window and set up your zones.
63 |
64 | ### Auto-Start with Windows
65 | To have the app run automatically every time you log in:
66 |
67 | 1. Create a shortcut to `Display_Zone_Manager.exe`.
68 | 2. Press `Win + R` to open the Run dialog.
69 | 3. Type `shell:startup` and press Enter. This opens your user Startup folder.
70 | 4. Move the shortcut you created into this folder. Done!
71 |
72 | ---
73 |
74 | ## 🛠️ Building from Source
75 |
76 | If you wish to modify or build the application yourself:
77 |
78 | 1. **Clone the Repository:**
79 | ```bash
80 | git clone https://github.com/Abhijith-Shaju/DisplayPartitioner.git
81 | cd DisplayPartitioner
82 | ```
83 | 2. **Create a Virtual Environment (Recommended):**
84 | ```bash
85 | python -m venv venv
86 | .\venv\Scripts\activate # On Windows
87 | # source venv/bin/activate # On macOS/Linux
88 | ```
89 | 3. **Install Dependencies:**
90 | A `requirements.txt` file is included for convenience.
91 | ```bash
92 | pip install -r requirements.txt
93 | ```
94 | 4. **Run the Script:**
95 | ```bash
96 | python DisplayPartitioner.py
97 | ```
98 |
99 | ### Building the Executable
100 | To package the script into a single `.exe` file, [PyInstaller](https://pyinstaller.org/) is used.
101 |
102 | 1. Make sure you have PyInstaller installed (`pip install pyinstaller`).
103 | 2. Run the build command from the project root directory:
104 | ```bash
105 | pyinstaller --onefile --windowed --icon="icon.ico" --add-data "icon.ico;." --name="Display_Zone_Manager" your_script_name.py
106 | ```
107 | *Note: The `--add-data` flag is crucial for ensuring the `icon.ico` is bundled correctly into the final executable.*
108 |
109 | The final `.exe` will be located in the `dist` folder.
110 |
111 | ## Dependencies
112 |
113 | - **pywin32:** For all native Windows API interaction.
114 | - **pystray:** For creating and managing the system tray icon.
115 | - **Pillow:** An image library required by `pystray` and for icon handling.
116 | - **keyboard:** For capturing the global hotkey.
117 |
118 | ---
119 |
120 | ## Author & Contact
121 |
122 | **Abhijith Shaju**
123 | - Email: [abhijithshaju2004@gmail.com](mailto:abhijithshaju2004@gmail.com)
124 |
125 | *Note: AI was used as a tool to help create this project.*
126 |
127 | ## 📄 License
128 | This project is licensed under the GPLv3 License. See the [LICENSE](LICENSE) file for details.
129 |
130 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/DisplayPartitioner.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Display Zone Manager
3 | # Version: 3.0.0 (Stable - Tkinter Overlay Architecture)
4 | #
5 | # Description:
6 | # A comprehensive, stable window management utility. This version migrates
7 | # the overlay from a native Win32 window to a more stable Tkinter-based
8 | # architecture, resolving all startup and handle-invalidation errors.
9 | # =============================================================================
10 | import sys, os, json, time, threading, math, tkinter as tk
11 | from tkinter import ttk, messagebox, colorchooser
12 | from pystray import MenuItem as item, Icon, Menu
13 | from PIL import Image, ImageDraw, ImageTk
14 | import win32api, win32gui, win32con, keyboard, pythoncom, ctypes
15 | from ctypes import wintypes
16 |
17 | # --- CONFIGURATION & CONSTANTS ---
18 | APP_NAME = "DisplayZoneManager"
19 | CONFIG_DIR = os.path.join(os.getenv('APPDATA'), APP_NAME)
20 | CONFIG_FILE = os.path.join(CONFIG_DIR, 'settings.json')
21 | DEFAULT_HOTKEY = "win+alt+z"
22 | DEFAULT_OVERLAY_COLOR = "#000000"
23 | DEFAULT_OVERLAY_OPACITY = 50
24 | # NATIVE_OVERLAY_CLASS no longer needed
25 |
26 | # --- HELPER CLASSES AND FUNCTIONS ---
27 | def hex_to_rgb(hex_color):
28 | hex_color = hex_color.lstrip('#')
29 | return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
30 |
31 |
32 | # --- FINAL DYNAMIC LAYOUT LOGIC ---
33 |
34 | class DynamicProportionalLayout:
35 | """
36 | An intelligent layout that adapts to the number of windows and the
37 | aspect ratio of the tiling zone, following specific user rules.
38 | """
39 | def calculate(self, windows, rect):
40 | positions = {}
41 | x, y, w, h = rect
42 | num_windows = len(windows)
43 |
44 | if not num_windows:
45 | return positions
46 |
47 | # --- Rule for 1 window ---
48 | if num_windows == 1:
49 | positions[windows[0]] = (x, y, w, h)
50 | return positions
51 |
52 | # Determine if the tiling zone is wider than it is tall.
53 | is_horizontal = w > h
54 |
55 | # --- Rule for 2 windows ---
56 | if num_windows == 2:
57 | if is_horizontal: # Split vertically
58 | positions[windows[0]] = (x, y, w // 2, h)
59 | positions[windows[1]] = (x + w // 2, y, w - (w // 2), h)
60 | else: # Split horizontally
61 | positions[windows[0]] = (x, y, w, h // 2)
62 | positions[windows[1]] = (x, y + h // 2, w, h - (h // 2))
63 | return positions
64 |
65 | # --- Rule for 3 windows (Master/Stack layout) ---
66 | if num_windows == 3:
67 | if is_horizontal: # Master on the side
68 | positions[windows[0]] = (x, y, w // 2, h) # Master
69 | positions[windows[1]] = (x + w // 2, y, w - (w // 2), h // 2) # Stack 1
70 | positions[windows[2]] = (x + w // 2, y + h // 2, w - (w // 2), h - (h // 2)) # Stack 2
71 | else: # Master on top
72 | positions[windows[0]] = (x, y, w, h // 2) # Master
73 | positions[windows[1]] = (x, y + h // 2, w // 2, h - (h // 2)) # Stack 1
74 | positions[windows[2]] = (x + w // 2, y + h // 2, w - (w // 2), h - (h // 2)) # Stack 2
75 | return positions
76 |
77 | # --- Fallback Rule for 4+ windows (Smart Grid) ---
78 | if num_windows >= 4:
79 | cols = math.ceil(math.sqrt(num_windows))
80 | rows = math.ceil(num_windows / cols)
81 |
82 | cell_height = h // rows
83 | window_index = 0
84 | for r in range(int(rows)):
85 | remaining_windows = num_windows - window_index
86 | windows_in_this_row = min(int(cols), remaining_windows)
87 | if windows_in_this_row == 0: break
88 |
89 | cell_width = w // windows_in_this_row
90 | for c in range(windows_in_this_row):
91 | hwnd = windows[window_index]
92 | pos_x = x + c * cell_width
93 | pos_y = y + r * cell_height
94 |
95 | pos_w = w - (c * cell_width) if c == windows_in_this_row - 1 else cell_width
96 | pos_h = h - (r * cell_height) if r == rows - 1 else cell_height
97 |
98 | positions[hwnd] = (pos_x, pos_y, pos_w, pos_h)
99 | window_index += 1
100 | return positions
101 |
102 | return positions
103 |
104 |
105 | class LayoutManager:
106 | """Manages which layout algorithm to use."""
107 | def __init__(self):
108 | # We now use our new, intelligent dynamic layout class.
109 | self.layout = DynamicProportionalLayout()
110 |
111 | def tile(self, windows, rect):
112 | return self.layout.calculate(windows, rect) if windows and rect else None
113 |
114 | # --- UI CLASS ---
115 |
116 | # ==============================================================================
117 | # Replace your ENTIRE SettingsWindow class with this one
118 | # ==============================================================================
119 | class SettingsWindow(tk.Toplevel):
120 | def __init__(self, master, app_instance):
121 | super().__init__(master); self.app = app_instance; self.title(f"{APP_NAME} Settings")
122 |
123 | try:
124 | self.iconbitmap('icon.ico')
125 | except tk.TclError:
126 | pass # The warning will be printed once from main()
127 |
128 | self.resizable(True, True) # Allow the window to be resized
129 | self.minsize(820, 500) # Set a reasonable minimum size
130 | self.protocol("WM_DELETE_WINDOW", self.on_close); self.dragged_item = None
131 |
132 | self._link_variables(); self._create_styles(); self._create_widgets(); self.update_all_ui_sections()
133 |
134 | def _link_variables(self):
135 | self.is_overlay_enabled_var = tk.BooleanVar(value=self.app.is_overlay_enabled)
136 | self.is_tiling_enabled_var = tk.BooleanVar(value=self.app.is_tiling_enabled)
137 | self.is_cursor_lock_enabled_var = tk.BooleanVar(value=self.app.is_cursor_lock_enabled)
138 | self.overlay_boundary_var = tk.IntVar(value=self.app.overlay_boundary_x)
139 | self.tiling_start_var = tk.IntVar(value=self.app.tiling_start_x)
140 | self.tiling_end_var = tk.IntVar(value=self.app.tiling_end_x)
141 | self.cursor_lock_boundary_var = tk.IntVar(value=self.app.cursor_lock_x)
142 | self.hotkey_var = tk.StringVar(value=self.app.hotkey); self.color_var = tk.StringVar(value=self.app.overlay_color)
143 | self.opacity_var = tk.IntVar(value=self.app.overlay_opacity); self.tiling_mode_var = tk.StringVar(value=self.app.tiling_mode)
144 | self.cursor_lock_mode_var = tk.StringVar(value=self.app.cursor_lock_mode)
145 | self.all_monitors = self.app.all_monitors; self.monitor_names = [f"Monitor {i} ({mon['Rect'][2]-mon['Rect'][0]}x{mon['Rect'][3]-mon['Rect'][1]}) {'(Primary)' if mon['is_primary'] else ''}" for i, mon in enumerate(self.all_monitors)]
146 | self.monitor_var = tk.StringVar(value=self.monitor_names[self.app.target_monitor_index])
147 |
148 | def _create_styles(self): s=ttk.Style(self);s.configure('Section.TFrame',background='#fafafa',borderwidth=1,relief='groove');s.configure('Sub.TFrame',background='#fafafa')
149 |
150 | # Replace this entire method in the SettingsWindow class
151 | def _create_widgets(self):
152 | # Main frame setup is fine
153 | main_frame = tk.Frame(self,padx=10,pady=10); main_frame.pack(fill='both',expand=True)
154 |
155 | # Top frame setup is fine
156 | top_frame = tk.Frame(main_frame); top_frame.pack(fill='x',pady=(0,10))
157 | tk.Label(top_frame,text="Target Monitor:").grid(row=0,column=0,sticky='w');tk.OptionMenu(top_frame,self.monitor_var,*self.monitor_names,command=self.on_monitor_select).grid(row=0,column=1,padx=5,sticky='w');tk.Label(top_frame,text="Global Hotkey:").grid(row=0,column=2,padx=(20,0));tk.Entry(top_frame,textvariable=self.hotkey_var,width=20).grid(row=0,column=3,padx=5);tk.Button(top_frame,text="Set",command=self.apply_hotkey).grid(row=0,column=4)
158 |
159 | # --- CHANGE 1: Configure the Canvas ---
160 | # The canvas should only fill horizontally, not vertically.
161 | self.canvas = tk.Canvas(main_frame,width=800,height=100,bg="#e0e0e0",relief="sunken",borderwidth=1)
162 | self.canvas.pack(pady=5,padx=5, fill='x') # Changed from just pack(...)
163 | self.canvas.bind("",self._on_drag_start);self.canvas.bind("",self._on_drag_line);self.canvas.bind("",self._on_drag_end)
164 |
165 | # --- CHANGE 2: Configure the Features Container ---
166 | # This container holds the three main sections and should expand both ways.
167 | features_container = tk.Frame(main_frame)
168 | features_container.pack(fill='both',expand=True,pady=10)
169 |
170 | # These two lines are CRITICAL for making the sections resize
171 | features_container.grid_columnconfigure((0,1,2),weight=1) # Makes columns expand horizontally
172 | features_container.grid_rowconfigure(0,weight=1) # Makes the row expand vertically
173 |
174 | # The rest of the creation logic is the same, but it will now be responsive
175 | self.overlay_frame = self._create_section_frame(features_container," Overlay Zone ","Enable Overlay",self.is_overlay_enabled_var,self.toggle_overlay_feature)
176 | self.tiling_frame = self._create_section_frame(features_container," Tiling Zone ","Enable Tiling",self.is_tiling_enabled_var,self.toggle_tiling_feature)
177 | self.cursor_frame = self._create_section_frame(features_container," Cursor Lock ","Enable Cursor Lock",self.is_cursor_lock_enabled_var,self.toggle_cursor_lock_feature)
178 |
179 | # Use 'nsew' sticky to make the frames fill their grid cell completely
180 | self.overlay_frame.grid(row=0,column=0,sticky='nsew',padx=5)
181 | self.tiling_frame.grid(row=0,column=1,sticky='nsew',padx=5)
182 | self.cursor_frame.grid(row=0,column=2,sticky='nsew',padx=5)
183 |
184 |
185 | def _create_section_frame(self, p,t,cb,v,c): f=ttk.Labelframe(p,text=t,padding=10);tk.Checkbutton(f,text=cb,variable=v,command=c).pack(anchor='w',pady=(0,5));cf=ttk.Frame(f,style='Section.TFrame',padding=5);cf.pack(fill='both',expand=True);setattr(self,t.strip().lower().replace(" ","_")+"_controls",cf);return f
186 | def _create_bound_entry(self, p,l,v,cmd): tk.Label(p,text=l).grid(row=0,column=0,sticky='w');e=tk.Entry(p,textvariable=v,width=8);e.grid(row=0,column=1,padx=5);b=tk.Button(p,text="Set",width=5,command=lambda:cmd(v.get()));b.grid(row=0,column=2);e.bind("",lambda e:cmd(v.get()))
187 | # Replace this entire method in the SettingsWindow class
188 | def update_all_ui_sections(self):
189 | # First, clear the detailed controls from all three sections.
190 | # This prepares them for a fresh build.
191 | for f in [self.overlay_zone_controls, self.tiling_zone_controls, self.cursor_lock_controls]:
192 | for c in f.winfo_children():
193 | c.destroy()
194 |
195 | # --- THIS IS THE FIX ---
196 | # Unconditionally call all build methods. The methods themselves contain the
197 | # logic to decide whether to show detailed controls based on the feature's status.
198 | self._build_overlay_controls()
199 | self._build_tiling_controls()
200 | self._build_cursor_controls()
201 |
202 | # Recalculate geometry and update the top canvas after the UI is rebuilt.
203 | self.app.recalculate_geometry()
204 | self.update_canvas()
205 |
206 |
207 | def _open_color_picker(self):
208 | """Opens the OS color picker and applies the selected color."""
209 | # The initialcolor parameter pre-selects the current color in the dialog.
210 | # The title sets the dialog window's title.
211 | # The parent ensures the dialog appears on top of the settings window.
212 | result_color = colorchooser.askcolor(initialcolor=self.app.overlay_color,
213 | title="Select Overlay Color",
214 | parent=self)
215 |
216 | # askcolor returns a tuple: ((r,g,b), '#hexcode') or (None, None) if canceled.
217 | if result_color and result_color[1]:
218 | hex_code = result_color[1]
219 | self.color_var.set(hex_code) # Update the Entry box variable
220 | self.app.set_overlay_color(hex_code) # Apply the color to the app
221 |
222 | # Now, replace the build method
223 | def _build_overlay_controls(self):
224 | f = self.overlay_zone_controls
225 | f.grid_columnconfigure(0, weight=1) # Allow contents to expand horizontally
226 |
227 | # --- THIS IS THE FIX for Request #1 ---
228 | # Create an inner frame for all controls EXCEPT the main "Enable" checkbox.
229 | inner_controls_frame = ttk.Frame(f)
230 | inner_controls_frame.pack(fill='both', expand=True)
231 |
232 | ef = ttk.Frame(inner_controls_frame, style='Sub.TFrame')
233 | ef.grid(row=0, column=0, sticky='ew', pady=(0, 5))
234 | self._create_bound_entry(ef, "Boundary X:", self.overlay_boundary_var, self.app.set_overlay_boundary)
235 |
236 | tk.Label(inner_controls_frame, text="Color:").grid(row=1, column=0, sticky='w')
237 | cf = ttk.Frame(inner_controls_frame, style='Sub.TFrame')
238 | cf.grid(row=2, column=0, sticky='ew', pady=(0, 5))
239 | self.color_preview = tk.Label(cf, text=" ", bg=self.app.overlay_color, relief='sunken', borderwidth=1)
240 | self.color_preview.grid(row=0, column=0, padx=(0, 5))
241 | self.color_entry = tk.Entry(cf, textvariable=self.color_var, width=10)
242 | self.color_entry.grid(row=0, column=1)
243 | self.color_entry.bind("", self.apply_hex_color)
244 | tk.Button(cf, text="Set", command=self.apply_hex_color, width=5).grid(row=0, column=2, padx=5)
245 |
246 | # The command for the "Picker..." button is now our new helper method.
247 | tk.Button(cf, text="Picker...", command=self._open_color_picker, width=8).grid(row=0, column=3, padx=(10, 0))
248 |
249 | tk.Label(inner_controls_frame, text="Opacity:").grid(row=3, column=0, sticky='w', pady=(5, 0))
250 | of = ttk.Frame(inner_controls_frame, style='Sub.TFrame')
251 | of.grid(row=4, column=0, sticky='ew')
252 | tk.Scale(of, from_=0, to=100, orient='h', variable=self.opacity_var, command=lambda v: self.app.set_overlay_opacity(int(v)), showvalue=0).pack(side='left', fill='x', expand=True)
253 | tk.Label(of, textvariable=self.opacity_var).pack(side='left', padx=(5, 0))
254 |
255 | self._create_description_label(inner_controls_frame, "Creates a semi-transparent colored bar on the screen to visually separate monitor space.")
256 |
257 | # Call our helper to set the initial state of the controls.
258 | self._set_child_widgets_state(inner_controls_frame, 'normal' if self.app.is_overlay_enabled else 'disabled')
259 |
260 |
261 | def _build_tiling_controls(self):
262 | self._create_check_images()
263 | f = self.tiling_zone_controls
264 |
265 | # --- THIS IS THE FIX for Request #1 ---
266 | # Create an inner frame for all controls EXCEPT the main "Enable" checkbox.
267 | # This allows us to disable/enable everything at once.
268 | inner_controls_frame = ttk.Frame(f)
269 | inner_controls_frame.pack(fill='both', expand=True)
270 |
271 | inner_controls_frame.grid_columnconfigure(0, weight=1)
272 | inner_controls_frame.grid_rowconfigure(3, weight=1)
273 |
274 | # 1. Tiling Zone Definition
275 | mode_frame = ttk.Frame(inner_controls_frame)
276 | mode_frame.grid(row=0, column=0, sticky='ew')
277 | tk.Label(mode_frame, text="Tiling Zone:").pack(side='left', anchor='w')
278 | tk.Radiobutton(mode_frame, text="Full Partition", variable=self.tiling_mode_var, value="full", command=self.on_tiling_mode_change).pack(side='left', padx=5)
279 | tk.Radiobutton(mode_frame, text="Custom Zone", variable=self.tiling_mode_var, value="custom", command=self.on_tiling_mode_change).pack(side='left', padx=5)
280 |
281 | # 2. Custom Zone Inputs
282 | self.custom_options_frame = ttk.Frame(inner_controls_frame, style='Section.TFrame', padding=5)
283 | start_frame = ttk.Frame(self.custom_options_frame, style='Sub.TFrame'); start_frame.pack(fill='x', pady=(0, 2))
284 | end_frame = ttk.Frame(self.custom_options_frame, style='Sub.TFrame'); end_frame.pack(fill='x')
285 | self._create_bound_entry(start_frame, "Start X:", self.tiling_start_var, self.app.set_tiling_start)
286 | self._create_bound_entry(end_frame, "End X: ", self.tiling_end_var, self.app.set_tiling_end)
287 | self.custom_options_frame.grid(row=1, column=0, sticky='ew', pady=5)
288 |
289 | # 3. Separator
290 | ttk.Separator(inner_controls_frame, orient='horizontal').grid(row=2, column=0, sticky='ew', pady=5)
291 |
292 | # 4. Manual Window Selection UI
293 | list_frame = ttk.Frame(inner_controls_frame)
294 | list_frame.grid(row=3, column=0, sticky='nsew')
295 | list_frame.grid_rowconfigure(1, weight=1)
296 | list_frame.grid_columnconfigure(0, weight=1)
297 |
298 | tk.Button(list_frame, text="Refresh Window List", command=self._refresh_window_list).grid(row=0, column=0, sticky='ew', pady=(0, 5))
299 | self.tree = ttk.Treeview(list_frame, show='tree', height=8)
300 | self.tree.grid(row=1, column=0, sticky='nsew')
301 | self.tree.column("#0", width=350, stretch=tk.YES, anchor='w')
302 | self.tree.heading("#0", text="Window Title", anchor='w')
303 |
304 | scrollbar = ttk.Scrollbar(list_frame, orient='vertical', command=self.tree.yview)
305 | scrollbar.grid(row=1, column=1, sticky='ns')
306 | self.tree.configure(yscrollcommand=scrollbar.set)
307 | self.tree.tag_configure('checked', image=self.check_images['checked'])
308 | self.tree.tag_configure('unchecked', image=self.check_images['unchecked'])
309 | self.tree.bind("", self._on_toggle_check)
310 | self.listbox_windows_map = {}
311 |
312 | # 5. Description
313 | self._create_description_label(inner_controls_frame, "Automatically arranges selected windows into a grid within the defined Tiling Zone. Windows can be selected from the list above.")
314 |
315 | # Call our helper to set the initial state of the controls.
316 | if not self.app.is_tiling_enabled:
317 | self._set_child_widgets_state(inner_controls_frame, state='disabled')
318 |
319 | self.on_tiling_mode_change()
320 | self._refresh_window_list()
321 |
322 |
323 | def _create_check_images(self):
324 | if hasattr(self, 'check_images'): return
325 | unchecked = Image.new('RGBA', (16, 16), (0,0,0,0))
326 | draw = ImageDraw.Draw(unchecked)
327 | draw.rectangle((2, 2, 13, 13), outline='gray', width=1)
328 | checked = unchecked.copy()
329 | draw = ImageDraw.Draw(checked)
330 | draw.line((4, 8, 7, 11, 12, 4), fill='blue', width=2)
331 | self.check_images = {'checked': ImageTk.PhotoImage(checked), 'unchecked': ImageTk.PhotoImage(unchecked)}
332 |
333 |
334 | def _refresh_window_list(self):
335 | for i in self.tree.get_children():
336 | self.tree.delete(i)
337 |
338 | eligible_windows = self.app.get_all_eligible_windows()
339 | self.listbox_windows_map = {hwnd: title for hwnd, title in eligible_windows}
340 |
341 | selected_hwnds = set(self.app.managed_windows)
342 |
343 | for hwnd, title in eligible_windows:
344 | app_icon = self.app.get_icon_for_hwnd(hwnd)
345 | is_checked = hwnd in selected_hwnds
346 | tag_to_apply = 'checked' if is_checked else 'unchecked'
347 |
348 | # --- THE FINAL, ROBUST 2-STEP LOGIC ---
349 |
350 | # Step 1: Insert the item with the absolute bare minimum.
351 | # We only provide the iid and the text. This call is reliable.
352 | self.tree.insert('', 'end', iid=hwnd, text=title)
353 |
354 | # Step 2: Configure ALL other options (image, tags) using the reliable
355 | # .item() method in a separate, secondary call.
356 | if app_icon: # Only apply the image if it exists
357 | self.tree.item(hwnd, image=app_icon, tags=(tag_to_apply,))
358 | else: # Fallback for windows without icons
359 | self.tree.item(hwnd, tags=(tag_to_apply,))
360 |
361 | def _on_toggle_check(self, event):
362 | row_id = self.tree.identify_row(event.y)
363 | if not row_id: return
364 |
365 | hwnd = int(row_id)
366 | current_tags = self.tree.item(hwnd, "tags")
367 |
368 | if 'checked' in current_tags:
369 | self.tree.item(hwnd, tags=('unchecked',))
370 | else:
371 | self.tree.item(hwnd, tags=('checked',))
372 |
373 | self._update_tiling_from_tree_state()
374 |
375 | def _update_tiling_from_tree_state(self):
376 | selected_hwnds = []
377 | for hwnd_str in self.tree.get_children():
378 | tags = self.tree.item(hwnd_str, "tags")
379 | if 'checked' in tags:
380 | selected_hwnds.append(int(hwnd_str))
381 |
382 | self.app.managed_windows = selected_hwnds
383 | self.app.retile_zone()
384 | # ---- END OF CORRECTED TILING UI METHODS ----
385 |
386 | # Replace this entire method in the SettingsWindow class
387 | def _build_cursor_controls(self):
388 | f = self.cursor_lock_controls
389 |
390 | # --- THIS IS THE FIX ---
391 | # Create an inner frame to hold all controls except the main "Enable" checkbox.
392 | inner_controls_frame = ttk.Frame(f)
393 | inner_controls_frame.pack(fill='both', expand=True)
394 | inner_controls_frame.grid_columnconfigure(0, weight=1) # Allow contents to expand horizontally
395 |
396 | # --- Manage all items with Grid inside the inner frame ---
397 | tk.Label(inner_controls_frame, text="Lock Mode:").grid(row=0, column=0, sticky='w')
398 |
399 | rb1 = tk.Radiobutton(inner_controls_frame, text="To Overlay Edge", variable=self.cursor_lock_mode_var, value="overlay", command=self.on_cursor_mode_change)
400 | rb1.grid(row=1, column=0, sticky='w')
401 | # The 'disabled' state of this specific radio button depends on the OVERLAY's status.
402 | rb1.config(state='normal' if self.app.is_overlay_enabled else 'disabled')
403 |
404 | tk.Radiobutton(inner_controls_frame, text="Custom Position", variable=self.cursor_lock_mode_var, value="custom", command=self.on_cursor_mode_change).grid(row=2, column=0, sticky='w')
405 |
406 | self.custom_cursor_frame = ttk.Frame(inner_controls_frame, style='Sub.TFrame')
407 | self.custom_cursor_frame.grid(row=3, column=0, sticky='ew', pady=5)
408 | self._create_bound_entry(self.custom_cursor_frame, "Wall X:", self.cursor_lock_boundary_var, self.app.set_cursor_lock_boundary)
409 |
410 | self.on_cursor_mode_change()
411 |
412 | self._create_description_label(inner_controls_frame, "Restricts the mouse cursor, preventing it from moving past the defined line on the target monitor.")
413 |
414 | # Call our helper to set the initial state of the controls.
415 | if not self.app.is_cursor_lock_enabled:
416 | self._set_child_widgets_state(inner_controls_frame, state='disabled')
417 |
418 | def update_canvas(self):
419 | self.canvas.delete("all");self._scale,self.offset_x,self.offset_y=self._calculate_scale();
420 | for i,mon in enumerate(self.all_monitors):
421 | l,t,r,b=mon['Rect'];h=b-t;cl=self._real_to_canvas_x(l);cr=self._real_to_canvas_x(r);ct=self.offset_y-(h*self._scale*0.4);cb=self.offset_y+(h*self._scale*0.4);fill_color="#ddffdd" if i==self.app.target_monitor_index else"#cccccc";self.canvas.create_rectangle(cl,ct,cr,cb,fill=fill_color,outline="black");self.canvas.create_text((cl+cr)/2,self.offset_y,text=f"M{i}{'P' if mon['is_primary'] else ''}",anchor='center')
422 | tm=self.all_monitors[self.app.target_monitor_index];l,t,r,b=tm['Rect'];h=b-t;ct=self.offset_y-(h*self._scale*0.4);cb=self.offset_y+(h*self._scale*0.4)
423 | if self.app.overlay_rect:x,_,w,_=self.app.overlay_rect;self.canvas.create_rectangle(self._real_to_canvas_x(x),ct,self._real_to_canvas_x(x+w),cb,fill="#ffaaaa",stipple="gray50",outline="")
424 |
425 | if self.app.tiling_rect and self.app.is_tiling_enabled:
426 | x,_,w,_=self.app.tiling_rect
427 | self.canvas.create_rectangle(self._real_to_canvas_x(x),ct,self._real_to_canvas_x(x+w),cb,fill="#aaffaa",stipple="gray25",outline="")
428 |
429 | if self.app.is_overlay_enabled:self._draw_draggable_line(self.app.overlay_boundary_x,'red','overlay_line')
430 | if self.app.is_tiling_enabled and self.app.tiling_mode=="custom":self._draw_draggable_line(self.app.tiling_start_x,'green','tiling_start_line');self._draw_draggable_line(self.app.tiling_end_x,'green','tiling_end_line')
431 | if self.app.is_cursor_lock_enabled and self.app.cursor_lock_mode=="custom":self._draw_draggable_line(self.app.cursor_lock_x,'blue','cursor_line',(4,4))
432 |
433 | def _calculate_scale(self):min_x=min(m['Rect'][0]for m in self.all_monitors);max_x=max(m['Rect'][2]for m in self.all_monitors);w=max_x-min_x;return(800*0.95)/w if w>0 else 1,-min_x,50
434 | def _real_to_canvas_x(self,x):return 20+(x+self.offset_x)*self._scale
435 | def _canvas_to_real_x(self,x):return int(((x-20)/self._scale)-self.offset_x)
436 | def _draw_draggable_line(self,x,c,t,d=None):cx=self._real_to_canvas_x(x);self.canvas.create_line(cx,0,cx,100,fill=c,width=3,tags=(t,"draggable"),dash=d)
437 | def _on_drag_start(self,e):i=self.canvas.find_closest(e.x,e.y,halo=5);self.dragged_item=self.canvas.gettags(i[0])[0]if i and"draggable"in self.canvas.gettags(i[0])else None
438 | def _on_drag_end(self,e):self.dragged_item=None
439 | # Replace this entire method in the SettingsWindow class
440 | def _on_drag_line(self, e):
441 | if not self.dragged_item:
442 | return
443 |
444 | # Get the boundaries of the target monitor on the canvas
445 | target_mon = self.all_monitors[self.app.target_monitor_index]['Rect']
446 | l, _, r, _ = target_mon
447 | canvas_left_bound = self._real_to_canvas_x(l)
448 | canvas_right_bound = self._real_to_canvas_x(r)
449 |
450 | # Constrain the mouse's X position to within the monitor's representation on the canvas
451 | constrained_x = max(canvas_left_bound, min(e.x, canvas_right_bound))
452 | real_x_value = self._canvas_to_real_x(constrained_x)
453 |
454 | # --- THIS IS THE KEY ---
455 | # The dictionary that maps a dragged line's tag to its action.
456 | # We are adding the tiling and cursor lines here.
457 | drag_actions = {
458 | "overlay_line": (self.overlay_boundary_var, self.app.set_overlay_boundary),
459 | "tiling_start_line": (self.tiling_start_var, self.app.set_tiling_start),
460 | "tiling_end_line": (self.tiling_end_var, self.app.set_tiling_end),
461 | "cursor_line": (self.cursor_lock_boundary_var, self.app.set_cursor_lock_boundary)
462 | }
463 |
464 | # Check if the item we are dragging has a defined action
465 | if self.dragged_item in drag_actions:
466 | variable_to_update, setter_function = drag_actions[self.dragged_item]
467 |
468 | # Update the Tkinter variable, which instantly changes the value in the Entry box
469 | variable_to_update.set(real_x_value)
470 |
471 | # Call the main application's function to apply the new value. This will also
472 | # trigger a retile or recalculation of geometry automatically.
473 | setter_function(real_x_value)
474 |
475 | def on_monitor_select(self,s):self.app.set_target_monitor(self.monitor_names.index(s))
476 |
477 | def on_tiling_mode_change(self):
478 | mode = self.tiling_mode_var.get()
479 | self.app.set_tiling_mode(mode)
480 |
481 | # --- THIS IS THE FIX for Request #1 ---
482 | # Explicitly redraw the canvas after mode has changed.
483 | self.app._redraw_canvas_only()
484 |
485 | if hasattr(self, 'custom_options_frame'):
486 | if mode == "custom":
487 | self.custom_options_frame.grid()
488 | else:
489 | self.custom_options_frame.grid_remove()
490 |
491 |
492 | # Replace this method in SettingsWindow
493 | def on_cursor_mode_change(self):
494 | mode = self.cursor_lock_mode_var.get()
495 | self.app.set_cursor_lock_mode(mode)
496 |
497 | # Use grid()/grid_remove() to show/hide the custom control frame
498 | if hasattr(self, 'custom_cursor_frame'):
499 | if mode == "custom":
500 | self.custom_cursor_frame.grid()
501 | else:
502 | self.custom_cursor_frame.grid_remove()
503 |
504 | def toggle_overlay_feature(self):self.app.set_feature_enabled('overlay',self.is_overlay_enabled_var.get())
505 | def toggle_tiling_feature(self):self.app.set_feature_enabled('tiling',self.is_tiling_enabled_var.get())
506 | def toggle_cursor_lock_feature(self):self.app.set_feature_enabled('cursor',self.is_cursor_lock_enabled_var.get())
507 |
508 |
509 |
510 | def _set_child_widgets_state(self, parent_widget, state='normal'):
511 | """Recursively set the state of all child widgets."""
512 | for child in parent_widget.winfo_children():
513 | # Some widgets like Labels don't have a 'state' option.
514 | try:
515 | # Exclude scrollbars from being disabled, as it looks bad.
516 | if 'scrollbar' not in child.winfo_class():
517 | child.configure(state=state)
518 | except tk.TclError:
519 | pass # Widget does not have a 'state' property.
520 | self._set_child_widgets_state(child, state=state)
521 |
522 |
523 |
524 |
525 | def apply_hotkey(self):
526 | if not self.app.set_hotkey(self.hotkey_var.get()):messagebox.showerror("Invalid Hotkey","Invalid hotkey.",parent=self);self.hotkey_var.set(self.app.hotkey)
527 | def apply_hex_color(self,e=None):
528 | c=self.color_var.get();
529 | try:self.color_entry.winfo_rgb(c);self.app.set_overlay_color(c)
530 | except tk.TclError:messagebox.showerror("Invalid Color",f"'{c}' is not a valid color code.",parent=self);self.color_var.set(self.app.overlay_color)
531 |
532 |
533 | # Add this new helper method to the SettingsWindow class
534 | # Replace this entire helper method in the SettingsWindow class
535 | def _create_description_label(self, parent, text):
536 | """Creates a formatted description label using the grid manager."""
537 | desc = ttk.Label(parent, text=text, wraplength=230, justify='left', style='Sub.TFrame')
538 |
539 | # --- THIS IS THE FIX ---
540 | # Use grid() instead of pack() to be compatible with other layouts.
541 | # We place it in the next available row at the bottom of the parent frame.
542 | next_row = parent.grid_size()[1]
543 | desc.grid(row=next_row, column=0, sticky='ew', pady=(10, 0))
544 |
545 |
546 | def on_close(self):self.app.settings_window=None;self.destroy()
547 |
548 |
549 |
550 | class DisplayZoneManager:
551 |
552 | EVENT_SYSTEM_MOVESIZE_END = 0x000B
553 |
554 |
555 | def __init__(self, root):
556 | self.tk_root = root; self.settings_window = None; self.tiling_event_hook_thread = None
557 | self.enforcement_thread = None; self.managed_windows = []; self.overlay_window = None
558 | self.WinEventProc = ctypes.WINFUNCTYPE(None,wintypes.HANDLE,wintypes.DWORD,wintypes.HWND,wintypes.LONG,wintypes.LONG,wintypes.DWORD,wintypes.DWORD)
559 | self.tiling_event_proc = self.WinEventProc(self._tiling_event_callback)
560 | self.layout_manager = LayoutManager(); self.overlay_rect=self.tiling_rect=self.cursor_clip_rect=None
561 |
562 | self._load_config()
563 | self._create_tkinter_overlay() # Use Tkinter-based overlay
564 |
565 | if self.is_tiling_enabled: self._start_tiling_hooks()
566 | self._start_enforcement_loop()
567 | self.tk_root.after_idle(self.recalculate_geometry) # Defer initial calculation
568 | self._register_initial_hotkey()
569 |
570 | def _load_config(self):
571 | self.all_monitors=self.get_all_monitors(); self.target_monitor_index=0
572 | try:
573 | with open(CONFIG_FILE,'r')as f: cfg=json.load(f)
574 | for k,v in cfg.items(): setattr(self,k,v)
575 | except (FileNotFoundError,json.JSONDecodeError): self._set_default_config()
576 |
577 | def _set_default_config(self):
578 | mon=self.all_monitors[self.target_monitor_index]['Rect']; l,_,r,_=mon; w=r-l
579 | self.is_overlay_enabled,self.is_tiling_enabled,self.is_cursor_lock_enabled=False,False,False
580 | self.tiling_mode,self.cursor_lock_mode='full','overlay'
581 | self.overlay_boundary_x,self.tiling_start_x,self.tiling_end_x,self.cursor_lock_x=l+w//4,l+w//4,l+w*3//4,l+w//2
582 | self.hotkey,self.overlay_color,self.overlay_opacity=DEFAULT_HOTKEY,DEFAULT_OVERLAY_COLOR,DEFAULT_OVERLAY_OPACITY
583 |
584 | def save_config(self):
585 | cfg={k:v for k,v in self.__dict__.items() if isinstance(v,(bool,str,int,float)) and k!='all_monitors'}
586 | os.makedirs(CONFIG_DIR,exist_ok=True);open(CONFIG_FILE,'w').write(json.dumps(cfg,indent=4))
587 |
588 | def _trigger_full_ui_update(self):
589 | if self.settings_window and self.settings_window.winfo_exists():self.settings_window.update_all_ui_sections()
590 | def _redraw_canvas_only(self):
591 | if self.settings_window and self.settings_window.winfo_exists():self.settings_window.update_canvas()
592 |
593 | def set_feature_enabled(self, feature, enabled):
594 | if feature == 'overlay':
595 | self.is_overlay_enabled = enabled
596 | elif feature == 'tiling':
597 | self.is_tiling_enabled = enabled
598 | if not enabled: # If tiling is disabled, clear the managed windows
599 | self.managed_windows.clear()
600 | elif feature == 'cursor':
601 | self.is_cursor_lock_enabled = enabled
602 |
603 | self.recalculate_geometry()
604 | self.retile_zone()
605 |
606 | # --- THIS IS THE FIX for Request #2 ---
607 | # Explicitly redraw the canvas to show/hide tiling zones immediately.
608 | self._redraw_canvas_only()
609 |
610 | self._trigger_full_ui_update()
611 |
612 | def set_overlay_boundary(self,v):self.overlay_boundary_x=int(v);self.recalculate_geometry();self.retile_zone();self._redraw_canvas_only()
613 |
614 | # Replace this method
615 | def set_tiling_start(self,v):
616 | self.tiling_start_x = int(v)
617 | self.recalculate_geometry_and_retile()
618 | self._redraw_canvas_only() # <-- ADD THIS LINE
619 |
620 | # Replace this method
621 | def set_tiling_end(self,v):
622 | self.tiling_end_x = int(v)
623 | self.recalculate_geometry_and_retile()
624 | self._redraw_canvas_only() # <-- ADD THIS LINE
625 |
626 | def set_cursor_lock_boundary(self,v):self.cursor_lock_x=int(v);self.recalculate_geometry();self._redraw_canvas_only()
627 |
628 | # NEW, CORRECTED METHOD
629 | def set_tiling_mode(self, m):
630 | self.tiling_mode = m
631 | self.recalculate_geometry_and_retile()
632 | # We no longer call self._trigger_full_ui_update() here.
633 |
634 | # NEW, CORRECTED METHOD
635 | def set_cursor_lock_mode(self, m):
636 | self.cursor_lock_mode = m
637 | self.recalculate_geometry()
638 | # DO NOT trigger a full UI update here. The SettingsWindow will handle its own state.
639 | self._redraw_canvas_only() # Just redraw the canvas, which is safe.
640 |
641 |
642 | def set_target_monitor(self,i):
643 | if self.settings_window:self.settings_window.destroy();self.settings_window=None
644 | self.target_monitor_index=i;self._set_default_config()
645 | self.recalculate_geometry_and_retile();self.show_settings_window()
646 |
647 | def set_overlay_color(self,c):self.overlay_color=c;self._update_overlay_visuals();self._trigger_full_ui_update()
648 | def set_overlay_opacity(self,o):self.overlay_opacity=o;self._update_overlay_visuals()
649 |
650 | def recalculate_geometry(self):
651 | mon=self.all_monitors[self.target_monitor_index]['Rect'];l,t,r,b=mon;h=b-t
652 | self.overlay_rect,self.tiling_rect = None,None
653 | if self.is_overlay_enabled:self.overlay_rect = (l, t, self.overlay_boundary_x - l, h)
654 | if self.is_tiling_enabled:
655 | s_x,e_x=(self.overlay_boundary_x,r)if self.tiling_mode=='full'and self.is_overlay_enabled else(l,r)if self.tiling_mode=='full'else(min(self.tiling_start_x,self.tiling_end_x),max(self.tiling_start_x,self.tiling_end_x))
656 | self.tiling_rect=(s_x, t, e_x - s_x, h)
657 | self._update_overlay_visuals();self._update_cursor_clip()
658 | def recalculate_geometry_and_retile(self):self.recalculate_geometry();self.retile_zone()
659 |
660 | def _start_enforcement_loop(self):
661 | if not self.enforcement_thread or not self.enforcement_thread.is_alive():
662 | self.enforcement_thread=threading.Thread(target=self._enforcement_loop,daemon=True)
663 | self.enforcement_thread.start()
664 |
665 | def _enforcement_loop(self):
666 | while True:
667 | if self.is_cursor_lock_enabled and self.cursor_clip_rect:
668 | try:win32api.ClipCursor(self.cursor_clip_rect)
669 | except win32api.error:pass
670 | time.sleep(0.25)
671 |
672 | def _unclip_cursor(self):
673 | try:
674 | full=(win32api.GetSystemMetrics(76),win32api.GetSystemMetrics(77),win32api.GetSystemMetrics(78),win32api.GetSystemMetrics(79))
675 | win32api.ClipCursor((full[0],full[1],full[0]+full[2],full[1]+full[3]))
676 | except win32api.error:pass
677 |
678 | def _update_cursor_clip(self):
679 | if not self.is_cursor_lock_enabled:self._unclip_cursor();self.cursor_clip_rect=None;return
680 | target_mon = self.all_monitors[self.target_monitor_index]; primary_handle=next((m['Handle']for m in self.all_monitors if m['is_primary']), target_mon['Handle'])
681 | wall_x = self.overlay_boundary_x if self.cursor_lock_mode=='overlay' and self.is_overlay_enabled else self.cursor_lock_x
682 | usable_area = (wall_x, target_mon['Rect'][1], target_mon['Rect'][2], target_mon['Rect'][3])
683 | if primary_handle==target_mon['Handle']:self.cursor_clip_rect=usable_area
684 | else:
685 | primary_rect = win32api.GetMonitorInfo(primary_handle)['Monitor']
686 | self.cursor_clip_rect=(min(primary_rect[0], usable_area[0]),min(primary_rect[1],usable_area[1]),max(primary_rect[2],usable_area[2]),max(primary_rect[3],usable_area[3]))
687 |
688 |
689 |
690 | def get_all_eligible_windows(self):
691 | """Enumerates all top-level windows and returns a list of (hwnd, title)
692 | tuples for those that are manageable."""
693 | eligible_windows = []
694 | def enum_callback(hwnd, lParam):
695 | if self.is_window_manageable(hwnd):
696 | title = win32gui.GetWindowText(hwnd)
697 | eligible_windows.append((hwnd, title))
698 | return True # Continue enumeration
699 |
700 | win32gui.EnumWindows(enum_callback, None)
701 | return sorted(eligible_windows, key=lambda item: item[1].lower())
702 |
703 |
704 |
705 | def _start_tiling_hooks(self):
706 | if not self.tiling_event_hook_thread or not self.tiling_event_hook_thread.is_alive():self.tiling_event_hook_thread=threading.Thread(target=self._tiling_event_loop,daemon=True);self.tiling_event_hook_thread.start()
707 | def _stop_tiling_hooks(self):
708 | if self.tiling_event_hook_thread:self.is_tiling_enabled=False;self.tiling_event_hook_thread.join(timeout=1.5);self.managed_windows.clear()
709 |
710 | def _tiling_event_loop(self):
711 | pythoncom.CoInitialize()
712 | user32 = ctypes.windll.user32
713 |
714 | # More reliable and specific event hooks
715 | events_to_hook = [
716 | win32con.EVENT_OBJECT_SHOW,
717 | win32con.EVENT_OBJECT_HIDE,
718 | win32con.EVENT_OBJECT_DESTROY,
719 | self.EVENT_SYSTEM_MOVESIZE_END, # <-- CORRECTED
720 | ]
721 |
722 | hooks = []
723 | for event in events_to_hook:
724 | # Note: The event range in SetWinEventHook is [event, event] (inclusive)
725 | hook = user32.SetWinEventHook(event, event, 0, self.tiling_event_proc, 0, 0, 0)
726 | if hook:
727 | hooks.append(hook)
728 |
729 | print(f"Tiling hooks installed: {len(hooks)} active.")
730 |
731 | while self.is_tiling_enabled:
732 | pythoncom.PumpWaitingMessages()
733 | time.sleep(0.1)
734 |
735 | for h in hooks:
736 | if h:
737 | user32.UnhookWinEvent(h)
738 | pythoncom.CoUninitialize()
739 | print("Tiling hooks uninstalled.")
740 |
741 | def _tiling_event_callback(self, hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime):
742 | # ... (the first part of the function is unchanged) ...
743 |
744 | was_managed = hwnd in self.managed_windows
745 | is_in_zone = self.is_window_in_tiling_zone(hwnd)
746 | needs_retile = False
747 |
748 | # --- Tiling Logic ---
749 | if event in (win32con.EVENT_OBJECT_HIDE, win32con.EVENT_OBJECT_DESTROY):
750 | # A window was hidden or closed, remove it if we were managing it.
751 | if was_managed:
752 | self.managed_windows.remove(hwnd)
753 | needs_retile = True
754 |
755 | elif event in (win32con.EVENT_OBJECT_SHOW, self.EVENT_SYSTEM_MOVESIZE_END): # <-- CORRECTED
756 | # A window appeared or finished moving.
757 | if is_in_zone and not was_managed:
758 | # It's IN the zone and we WEREN'T managing it: add it.
759 | self.managed_windows.append(hwnd)
760 | needs_retile = True
761 | elif not is_in_zone and was_managed:
762 | # It's OUT of the zone and we WERE managing it: remove it.
763 | self.managed_windows.remove(hwnd)
764 | needs_retile = True
765 |
766 | if needs_retile:
767 | self.retile_zone()
768 |
769 | def retile_zone(self):
770 | # We now use self.managed_windows directly. The layout manager will
771 | # get all selected windows, even if they are minimized.
772 | windows_to_tile = self.managed_windows
773 |
774 | if not self.is_tiling_enabled or not self.tiling_rect or not windows_to_tile:
775 | return
776 |
777 | # The sorting order of `windows_to_tile` (from user selection) is preserved.
778 | positions = self.layout_manager.tile(windows_to_tile, self.tiling_rect)
779 |
780 | if positions:
781 | user32 = ctypes.windll.user32
782 | # The Begin/EndDeferWindowPos combo prevents flicker by applying all changes at once.
783 | hDWP = user32.BeginDeferWindowPos(len(positions))
784 | flags = win32con.SWP_NOZORDER | win32con.SWP_NOOWNERZORDER | win32con.SWP_NOACTIVATE
785 |
786 | if hDWP:
787 | for hwnd, (x, y, w, h) in positions.items():
788 | # SW_RESTORE (9) will un-minimize the window if needed.
789 | win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
790 | user32.DeferWindowPos(hDWP, hwnd, 0, x, y, w, h, flags)
791 | user32.EndDeferWindowPos(hDWP)
792 |
793 |
794 |
795 |
796 |
797 |
798 | # Add this method inside the DisplayZoneManager class
799 | def get_icon_for_hwnd(self, hwnd):
800 | # We'll cache icons to improve performance and avoid memory issues
801 | if not hasattr(self, 'icon_cache'):
802 | self.icon_cache = {}
803 | if hwnd in self.icon_cache:
804 | return self.icon_cache[hwnd]
805 |
806 | # Constants for icon retrieval
807 | ICON_SMALL = 0
808 | ICON_BIG = 1
809 | GCL_HICONSM = -34
810 | WM_GETICON = 0x007F
811 |
812 | hIcon = None
813 | try:
814 | # Send a message to the window to get its icon handle
815 | result = ctypes.windll.user32.SendMessageTimeoutW(hwnd, WM_GETICON, ICON_SMALL, 0, 2, 500, ctypes.pointer(ctypes.c_size_t()))
816 | if result: hIcon = result
817 |
818 | if not hIcon: # Fallback 1: Try big icon
819 | result = ctypes.windll.user32.SendMessageTimeoutW(hwnd, WM_GETICON, ICON_BIG, 0, 2, 500, ctypes.pointer(ctypes.c_size_t()))
820 | if result: hIcon = result
821 |
822 | if not hIcon: # Fallback 2: Get icon from the window class
823 | hIcon = ctypes.windll.user32.GetClassLongPtrW(hwnd, GCL_HICONSM)
824 |
825 | if not hIcon: # If we still have no icon, we can't proceed
826 | self.icon_cache[hwnd] = None
827 | return None
828 |
829 | # --- Convert HICON to Tk PhotoImage ---
830 | icon_info = win32gui.GetIconInfo(hIcon)
831 | if not icon_info: return None
832 |
833 | hdc = win32gui.GetDC(0)
834 | mem_dc = win32gui.CreateCompatibleDC(hdc)
835 | bmp = win32gui.CreateCompatibleBitmap(hdc, 16, 16)
836 | win32gui.SelectObject(mem_dc, bmp)
837 |
838 | # Draw the icon onto the memory bitmap
839 | ctypes.windll.user32.DrawIconEx(mem_dc, 0, 0, hIcon, 16, 16, 0, 0, 3) # DI_NORMAL
840 |
841 | # Create a Pillow image from the raw bitmap data
842 | bitmap_bits = win32gui.GetBitmapBits(bmp, True)
843 | img = Image.frombuffer('RGBA', (16, 16), bitmap_bits, 'raw', 'BGRA', 0, 1)
844 |
845 | # Convert to PhotoImage and cache it
846 | photo_img = ImageTk.PhotoImage(image=img)
847 | self.icon_cache[hwnd] = photo_img
848 |
849 | # CRITICAL: Clean up GDI objects
850 | win32gui.DeleteObject(bmp)
851 | win32gui.DeleteDC(mem_dc)
852 | win32gui.ReleaseDC(0, hdc)
853 | win32gui.DestroyIcon(icon_info[0])
854 | win32gui.DestroyIcon(icon_info[1])
855 |
856 | return photo_img
857 |
858 | except Exception as e:
859 | # print(f"Icon error for {hwnd}: {e}") # for debugging
860 | self.icon_cache[hwnd] = None
861 | return None
862 |
863 |
864 |
865 |
866 |
867 |
868 |
869 |
870 |
871 | def is_window_manageable(self,hwnd):
872 | if not hwnd or not win32gui.IsWindowVisible(hwnd) or win32gui.GetParent(hwnd)!=0 or not win32gui.GetWindowText(hwnd):return False
873 | if not(win32gui.GetWindowLong(hwnd,-16)&12582912):return False
874 | try:mon_h=win32api.MonitorFromWindow(hwnd,1);mon_r=win32api.GetMonitorInfo(mon_h)['Monitor'];return win32gui.GetWindowRect(hwnd)!=mon_r
875 | except:return False
876 | def is_window_in_tiling_zone(self,hwnd):
877 | if not self.tiling_rect or not win32gui.IsWindowVisible(hwnd):return False
878 | try:l,_,r,_=win32gui.GetWindowRect(hwnd);cx=l+(r-l)//2
879 | except:return False
880 | tz_x,_,tz_w,_=self.tiling_rect;return tz_x<=cx<=(tz_x+tz_w)
881 |
882 | def _create_tkinter_overlay(self):
883 | if self.overlay_window and self.overlay_window.winfo_exists(): return
884 | self.overlay_window = tk.Toplevel(self.tk_root)
885 | self.overlay_window.overrideredirect(True)
886 | self.overlay_window.attributes("-topmost", True)
887 | self.overlay_window.attributes("-disabled", True) # Make window click-through
888 | self.overlay_window.withdraw()
889 |
890 | def _destroy_tkinter_overlay(self):
891 | if self.overlay_window and self.overlay_window.winfo_exists():
892 | self.overlay_window.destroy()
893 | self.overlay_window = None
894 |
895 | def _update_overlay_visuals(self):
896 | if not self.overlay_window or not self.overlay_window.winfo_exists(): return
897 | if self.overlay_rect and self.is_overlay_enabled:
898 | x, y, w, h = self.overlay_rect
899 | w, h = max(1, w), max(1, h)
900 | self.overlay_window.geometry(f"{w}x{h}+{x}+{y}")
901 | self.overlay_window.configure(bg=self.overlay_color)
902 | self.overlay_window.attributes("-alpha", self.overlay_opacity / 100.0)
903 | self.overlay_window.deiconify()
904 | else:
905 | self.overlay_window.withdraw()
906 |
907 | def get_all_monitors(self):return[{'Handle':h,'Rect':r,'is_primary':win32api.GetMonitorInfo(h).get('Flags')==1} for h,_,r in win32api.EnumDisplayMonitors()]
908 | def _register_initial_hotkey(self):
909 | try:keyboard.add_hotkey(self.hotkey,self.show_settings_window,suppress=True)
910 | except Exception as e:messagebox.showwarning("Hotkey Error",f"Could not register '{self.hotkey}': {e}")
911 |
912 | def set_hotkey(self,new):
913 | try:keyboard.remove_hotkey(self.hotkey)
914 | except:pass
915 | try:keyboard.add_hotkey(new,self.show_settings_window,suppress=True);self.hotkey=new;return True
916 | except:
917 | try:keyboard.add_hotkey(self.hotkey,self.show_settings_window,suppress=True)
918 | except:pass
919 | return False
920 |
921 | def cleanup(self):
922 | print("Cleaning up...");self.is_cursor_lock_enabled=False;self.is_tiling_enabled=False
923 | self._unclip_cursor();self._stop_tiling_hooks()
924 | if self.enforcement_thread and self.enforcement_thread.is_alive(): self.enforcement_thread.join(timeout=0.5)
925 | self.tk_root.after(1, self._destroy_tkinter_overlay)
926 | keyboard.unhook_all();self.save_config();print("Cleanup complete.")
927 |
928 | def show_settings_window(self):
929 | if not self.settings_window or not self.settings_window.winfo_exists():self.settings_window=SettingsWindow(self.tk_root,self)
930 | else:self.settings_window.deiconify();self.settings_window.focus_force()
931 |
932 | # --- MAIN EXECUTION ---
933 | # Replace the entire main() function at the end of the script
934 |
935 | def main():
936 | # Set DPI awareness for sharp UI rendering
937 | try:
938 | ctypes.windll.shcore.SetProcessDpiAwareness(1)
939 | except (AttributeError, OSError):
940 | pass # Not available on older Windows versions
941 |
942 | root = tk.Tk()
943 | root.withdraw()
944 | app = DisplayZoneManager(root)
945 |
946 | # Set the icon for the root Tk window. This ensures any dialogs
947 | # (like messageboxes) or future windows will inherit the icon.
948 | # It also helps set the taskbar icon when the settings window is open.
949 | try:
950 | # Assumes 'icon.ico' is in the same directory as the script
951 | root.iconbitmap('icon.ico')
952 | except tk.TclError:
953 | print("Warning: 'icon.ico' not found. Using default icon.")
954 |
955 |
956 | def on_quit(icon, item):
957 | app.cleanup()
958 | icon.stop()
959 |
960 | def create_tray_icon(app_instance):
961 | # --- THIS IS THE FIX (PART 2) ---
962 | # Replace the procedurally generated image with your .ico file
963 | try:
964 | image = Image.open("icon.ico")
965 | except FileNotFoundError:
966 | # Fallback to the old image if icon.ico is not found
967 | print("Warning: 'icon.ico' not found. Using default tray icon.")
968 | image = Image.new('RGB', (64, 64), 'black')
969 | draw = ImageDraw.Draw(image)
970 | draw.rectangle((20, 20, 44, 44), outline='white', width=4)
971 | draw.line((32, 0, 32, 64), fill='white', width=2)
972 |
973 | tooltip_text = f"{APP_NAME} | Hotkey: {app_instance.hotkey}"
974 |
975 | menu = Menu(
976 | item('Settings...', app_instance.show_settings_window, default=True),
977 | Menu.SEPARATOR,
978 | item('Quit', on_quit)
979 | )
980 |
981 | icon = Icon(APP_NAME, image, tooltip_text, menu)
982 | icon.run()
983 |
984 | threading.Thread(target=create_tray_icon, args=(app,), daemon=True).start()
985 | print(f"{APP_NAME} is running.")
986 | root.mainloop()
987 | print(f"{APP_NAME} has shut down.")
988 |
989 | if __name__ == "__main__":
990 | main()
--------------------------------------------------------------------------------