diff --git a/cinnamon-world-clock-desklet@curbsoftware/LICENSE b/cinnamon-world-clock-desklet@curbsoftware/LICENSE new file mode 100644 index 000000000..87a4d7b50 --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/LICENSE @@ -0,0 +1,352 @@ +World Clock Desklet is free software: you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by the +Free Software Foundation, either version 2 of the License, or (at your +option) any later version. + +Copyright (C) 2026 CurbSoftware + +World Clock Desklet is derived from TimeAndDate@nightflame, which is +distributed under the GNU General Public License version 2. + +The complete text of the GNU General Public License version 2 follows. + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/cinnamon-world-clock-desklet@curbsoftware/README.md b/cinnamon-world-clock-desklet@curbsoftware/README.md new file mode 100644 index 000000000..2ed9eb827 --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/README.md @@ -0,0 +1,83 @@ +# World Clock + +A Cinnamon desklet that shows a grid of clocks, each with its own name and timezone. + +Left-click does nothing. Click the trailing **+** tile to add a clock. Right-click a tile to edit or remove it. Clocks set to the system timezone (`local`) are outlined. + +![World Clock desklet](screenshots/world-clock-desklet.webp) + +The settings window: + +![World Clock settings](screenshots/world-clock-config.webp) + +## Why this exists + +Good world clock apps are hard to find. On any OS. The good ones live on your phone, or they bury the feature under menus, or they insist on taking over your system timezone. + +I wanted the opposite. A glance at my desktop to see what time it is where my colleagues and partners are, all over the world, without touching my own clock. A grid of clocks, one per timezone, always visible. Nothing more. + +That's what this desklet is. + +## Features + +- Auto (near-square) or fixed rows × columns +- Searchable timezone list (IANA zones plus Local) +- Shared time/date formats; font sizes are maximums and each tile scales down to fit +- Last clock cannot be removed +- Optional confirmation before removing a named clock +- Layout, spacing, and size are configured from Cinnamon Desklet settings + +## Configuration + +Right-click the desklet to **Configure…** + +- **Grid layout mode**: auto or fixed rows/columns +- **Allow adding, removing and editing clocks**: turn off for a read-only grid +- **Show a "+" tile**: hide the add tile while keeping the right-click menu +- **Time / date format**: `strftime` patterns (for example `%H:%M` or `%I:%M %p`) +- **Maximum font sizes**: time, date, and label; tiles shrink so nothing overflows +- **Tile spacing** and **desklet width / height** + +## Manual install + +No root needed. Everything installs into your home directory. + +From a release package: + +```bash +curl -fLO https://github.com/CurbSoftware/cinnamon-world-clock-desklet/releases/latest/download/cinnamon-world-clock-desklet.zip +unzip cinnamon-world-clock-desklet.zip +rm -rf ~/.local/share/cinnamon/desklets/cinnamon-world-clock-desklet@curbsoftware +cp -r cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware \ + ~/.local/share/cinnamon/desklets/cinnamon-world-clock-desklet@curbsoftware +``` + +Or straight from git: + +```bash +git clone https://github.com/CurbSoftware/cinnamon-world-clock-desklet.git +cd cinnamon-world-clock-desklet +rm -rf ~/.local/share/cinnamon/desklets/cinnamon-world-clock-desklet@curbsoftware +cp -r files/cinnamon-world-clock-desklet@curbsoftware \ + ~/.local/share/cinnamon/desklets/cinnamon-world-clock-desklet@curbsoftware +``` + +The `rm -rf` before the copy is the upgrade path: old files are removed so +nothing deleted upstream lingers, then the copy brings the new tree in. Your +settings are stored separately in `~/.config/cinnamon/spices/cinnamon-world-clock-desklet@curbsoftware/` +and survive reinstalls. + +Restart Cinnamon (**Alt-F2**, type `r`, Enter) and add the desklet from +Cinnamon Settings. + +## Notes + +This is a desktop **desklet**, not the panel [World Clock Calendar](https://cinnamon-spices.linuxmint.com/applets/view/108) applet. It can run next to that applet; they do not share settings. + +UUID: `cinnamon-world-clock-desklet@curbsoftware` + +Derived from [TimeAndDate@nightflame](https://cinnamon-spices.linuxmint.com/desklets/view/9). + +## License + +GNU General Public License v2.0 or later. See [LICENSE](LICENSE). diff --git a/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/clockActions.js b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/clockActions.js new file mode 100644 index 000000000..317c83dc2 --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/clockActions.js @@ -0,0 +1,668 @@ +/* global imports */ +/** + * clockActions.js + * + * Pure clock-list and grid-layout helpers for the World Clock desklet. + * Deliberately contains no St/Clutter widgets so the module can be exercised + * by a headless test harness (libst.so cannot be loaded outside the Cinnamon + * process). + * + * computeGridDims / planCells are adapted from the Workspace Grid desklet's + * workspaceActions.js. Cinnamon gives xlets no way to import across xlet + * boundaries, so the maths is duplicated here rather than shared. + */ + +let _translate = function (str) { return str; }; + +function setTranslate(fn) { + if (typeof fn === "function") + _translate = fn; +} + +/* Call sites use _() so cinnamon-xlet-makepot's default keyword extracts + * them; _() always routes through the injected translator. */ +function _(str) { + return _translate(str); +} + +var MIN_CLOCKS = 1; +var MAX_CLOCKS = 36; + +var DEFAULT_CLOCK = { + name: "Local", + timezone: "local" +}; + +function _newId(opts) { + opts = opts || {}; + if (typeof opts.generateId === "function") + return opts.generateId(); + try { + return imports.gi.GLib.uuid_string_random(); + } catch (e) { + return "clock-" + Date.now() + "-" + Math.floor(Math.random() * 1e9); + } +} + +function _toPositiveInt(value, fallback) { + let n = parseInt(value, 10); + if (!Number.isFinite(n) || n < 1) + return fallback; + return n; +} + +/* ------------------------------------------------------------------ * + * Pure layout helpers + * ------------------------------------------------------------------ */ + +/** + * computeGridDims: + * @cellCount (int): total cells to lay out, including the "+" tile + * @mode (string): "fixed" or anything else for auto + * @fixedRows (int): rows to use in fixed mode + * @fixedCols (int): columns to use in fixed mode + * + * Returns (object): { rows, cols }. Auto mode produces a near-square grid. + * Fixed mode returns the requested dimensions verbatim, which may be smaller + * than @cellCount - planCells() handles that overflow. + */ +function computeGridDims(cellCount, mode, fixedRows, fixedCols) { + let n = _toPositiveInt(cellCount, 1); + + if (mode === "fixed") { + return { + rows: _toPositiveInt(fixedRows, 1), + cols: _toPositiveInt(fixedCols, 1) + }; + } + + let cols = Math.ceil(Math.sqrt(n)); + let rows = Math.ceil(n / cols); + return { rows: rows, cols: cols }; +} + +/** + * planCells: + * @clockCount (int): number of clocks to show + * @showAddTile (boolean): whether to reserve a cell for the "+" tile + * @rows (int): grid rows + * @cols (int): grid columns + * + * Decides what goes in each grid cell, in row-major order. When the grid is + * too small to hold everything, clocks are truncated but the "+" tile keeps + * the final cell so it stays reachable. + * + * Returns (array): [{ kind: "clock"|"add", index: int }, ...] + */ +function planCells(clockCount, showAddTile, rows, cols) { + let n = parseInt(clockCount, 10); + if (!Number.isFinite(n) || n < 0) + n = 0; + + let capacity = _toPositiveInt(rows, 1) * _toPositiveInt(cols, 1); + let cells = []; + + if (capacity <= 0) + return cells; + + if (!showAddTile) { + let limit = Math.min(n, capacity); + for (let i = 0; i < limit; i++) + cells.push({ kind: "clock", index: i }); + return cells; + } + + let clockSlots = Math.min(n, capacity - 1); + for (let i = 0; i < clockSlots; i++) + cells.push({ kind: "clock", index: i }); + cells.push({ kind: "add", index: -1 }); + return cells; +} + +/* ------------------------------------------------------------------ * + * Tile text fitting + * ------------------------------------------------------------------ */ + +/** + * Chrome subtracted when turning desklet width/height into a tile's inner + * text box. Keep in sync with stylesheet.css + * (.world-clock-container padding, tile padding/border). + */ +var TILE_LAYOUT = { + containerPad: 6, + tileBorder: 2, + padX: 6, + padY: 4, + lineGap: 2, + minPt: 4, + ptToPx: 4 / 3, + lineHeight: 1.25, + timeEm: 0.72, + dateEm: 0.58, + labelEm: 0.56, + addMaxPt: 16 +}; + +function _finite(value, fallback) { + let n = Number(value); + if (!Number.isFinite(n)) + return fallback; + return n; +} + +function _roundPt(n) { + if (!Number.isFinite(n) || n < 1) + return 1; + return Math.round(n * 10) / 10; +} + +/** + * computeTileInnerSize: + * @deskletWidth (number): main container width in px + * @deskletHeight (number): main container height in px + * @rows (int): grid rows + * @cols (int): grid columns + * @tileSpacing (number): per-side tile margin in px + * @opts (object): optional overrides for TILE_LAYOUT chrome + * + * Returns (object): { width, height } of the text box inside one tile. + */ +function computeTileInnerSize(deskletWidth, deskletHeight, rows, cols, tileSpacing, opts) { + opts = opts || {}; + let pad = TILE_LAYOUT.containerPad; + if (opts.containerPad != null) + pad = Math.max(0, _finite(opts.containerPad, pad)); + let border = TILE_LAYOUT.tileBorder; + if (opts.tileBorder != null) + border = Math.max(0, _finite(opts.tileBorder, border)); + let padX = TILE_LAYOUT.padX; + if (opts.padX != null) + padX = Math.max(0, _finite(opts.padX, padX)); + let padY = TILE_LAYOUT.padY; + if (opts.padY != null) + padY = Math.max(0, _finite(opts.padY, padY)); + + let r = _toPositiveInt(rows, 1); + let c = _toPositiveInt(cols, 1); + let spacing = Math.max(0, _finite(tileSpacing, 0)); + let tableW = Math.max(0, _finite(deskletWidth, 200) - 2 * pad); + let tableH = Math.max(0, _finite(deskletHeight, 200) - 2 * pad); + let cellW = tableW / c; + let cellH = tableH / r; + + return { + width: Math.max(0, cellW - 2 * spacing - 2 * border - 2 * padX), + height: Math.max(0, cellH - 2 * spacing - 2 * border - 2 * padY) + }; +} + +function _glyphEm(ch, em) { + if (ch >= "0" && ch <= "9") + return Math.max(em, 0.72); + if (ch === ":" || ch === ".") + return 0.38; + if (ch === " " || ch === ",") + return 0.33; + return em; +} + +function _textEmUnits(text, em) { + let s = String(text || ""); + let units = 0; + for (let i = 0; i < s.length; i++) + units += _glyphEm(s[i], em); + return units; +} + +function _textWidthPx(text, sizePt, ptToPx, em) { + let units = _textEmUnits(text, em); + if (units <= 0) + return 0; + return units * sizePt * ptToPx; +} + +function _maxPtForWidth(text, innerW, ptToPx, em, cap) { + let units = _textEmUnits(text, em); + if (units <= 0) + return cap; + if (!(innerW > 0) || !(ptToPx > 0)) + return 1; + let pt = innerW / (units * ptToPx); + if (!Number.isFinite(pt) || pt <= 0) + return 1; + return Math.min(cap, pt); +} + +/** + * worstTimeSample: + * @format (string): strftime time format + * @extras (object): { hundredths } to append a ".99" fraction + * + * Returns (string): a wide sample used to size the time line before the + * live string is known, so enabling seconds cannot overflow a tile. + */ +function worstTimeSample(format, extras) { + extras = extras || {}; + let fmt = typeof format === "string" ? format : ""; + let hasSeconds = !fmt || /%[STcT]/.test(fmt); + let twelveHour = /%[IilpPr]/.test(fmt); + let sample; + if (twelveHour) + sample = hasSeconds ? "12:59:59 PM" : "12:59 PM"; + else + sample = hasSeconds ? "23:59:59" : "23:59"; + if (extras.hundredths) + sample += ".99"; + return sample; +} + +/** + * computeFittedFontSizes: + * @innerWidth (number): tile text box width in px + * @innerHeight (number): tile text box height in px + * @texts (object): { time, date, label } sample strings + * @maxSizes (object): { time, date, timezone } caps in pt + * @opts (object): optional TILE_LAYOUT overrides + * + * Settings sizes are caps. Time and date shrink to fit; a long name/timezone + * label ellipsizes instead of shrinking the clock. Hierarchy is + * time >= date >= timezone. "+" tiles use the returned `add` size. + * + * Returns (object): { time, date, timezone, add, ellipsizeLabel } + */ +function computeFittedFontSizes(innerWidth, innerHeight, texts, maxSizes, opts) { + opts = opts || {}; + texts = texts || {}; + maxSizes = maxSizes || {}; + + let ptToPx = _finite(opts.ptToPx, TILE_LAYOUT.ptToPx); + if (!(ptToPx > 0)) + ptToPx = TILE_LAYOUT.ptToPx; + let lineHeight = _finite(opts.lineHeight, TILE_LAYOUT.lineHeight); + if (!(lineHeight > 0)) + lineHeight = TILE_LAYOUT.lineHeight; + let lineGap = Math.max(0, _finite(opts.lineGap, TILE_LAYOUT.lineGap)); + let timeEm = _finite(opts.timeEm, TILE_LAYOUT.timeEm); + let dateEm = _finite(opts.dateEm, TILE_LAYOUT.dateEm); + let labelEm = _finite(opts.labelEm, TILE_LAYOUT.labelEm); + let addMax = _finite(opts.addMaxPt, TILE_LAYOUT.addMaxPt); + + let maxTime = _finite(maxSizes.time, 40); + let maxDate = _finite(maxSizes.date, 15); + let maxTz = _finite(maxSizes.timezone, 12); + if (maxTime < 1) + maxTime = 1; + if (maxDate < 1) + maxDate = 1; + if (maxTz < 1) + maxTz = 1; + + let innerW = Math.max(0, _finite(innerWidth, 0)); + let innerH = Math.max(0, _finite(innerHeight, 0)); + let timeText = texts.time || ""; + let dateText = texts.date || ""; + let labelText = texts.label || ""; + + let add = addMax; + if (innerH > 0) + add = Math.min(add, (innerH * 0.55) / ptToPx); + if (innerW > 0) + add = Math.min(add, (innerW * 0.7) / ptToPx); + + let time = _maxPtForWidth(timeText, innerW, ptToPx, timeEm, maxTime); + let date = _maxPtForWidth(dateText, innerW, ptToPx, dateEm, maxDate); + let timezone = Math.min(maxTz, time, date); + + let neededH = (time + date + timezone) * ptToPx * lineHeight + 2 * lineGap; + if (innerH > 0 && neededH > innerH) { + let avail = Math.max(0, innerH - 2 * lineGap); + let base = (time + date + timezone) * ptToPx * lineHeight; + if (base > 0) { + let scale = avail / base; + time *= scale; + date *= scale; + timezone *= scale; + } + } + + time = Math.min(time, _maxPtForWidth(timeText, innerW, ptToPx, timeEm, maxTime)); + date = Math.min(date, _maxPtForWidth(dateText, innerW, ptToPx, dateEm, maxDate)); + if (date > time) + date = time; + if (timezone > date) + timezone = date; + + let ellipsizeLabel = _textWidthPx(labelText, timezone, ptToPx, labelEm) > innerW && innerW > 0; + + return { + time: _roundPt(time), + date: _roundPt(date), + timezone: _roundPt(timezone), + add: _roundPt(add), + ellipsizeLabel: !!ellipsizeLabel + }; +} + +/* ------------------------------------------------------------------ * + * Clock list helpers + * ------------------------------------------------------------------ */ + +/** + * buildClock: + * @values (object): { name, timezone } + * @existingId (string): keep this id when editing; omit to allocate a new one + * @opts (object): optional { generateId: function } + * + * Returns (object): { id, name, timezone } + */ +function buildClock(values, existingId, opts) { + values = values && typeof values === "object" ? values : {}; + + let id = typeof existingId === "string" ? existingId.trim() : ""; + if (!id || id === "default") + id = _newId(opts); + + let name = typeof values.name === "string" ? values.name.trim() : ""; + let timezone = typeof values.timezone === "string" ? values.timezone.trim() : ""; + if (!timezone) + timezone = DEFAULT_CLOCK.timezone; + + return { + id: id, + name: name, + timezone: timezone + }; +} + +/** + * normalizeClockEntry: + * @clock (object): raw clock record, possibly with legacy size/format fields + * @opts (object): optional { generateId: function } + * + * Drops per-clock format/size fields. Returns { changed, clock }. + */ +function normalizeClockEntry(clock, opts) { + let input = clock && typeof clock === "object" ? clock : {}; + let changed = !(clock && typeof clock === "object"); + + let id = typeof input.id === "string" ? input.id.trim() : ""; + if (!id || id === "default") { + id = _newId(opts); + changed = true; + } + + let name = typeof input.name === "string" ? input.name.trim() : ""; + if (name !== input.name) + changed = true; + + let timezone = typeof input.timezone === "string" ? input.timezone.trim() : ""; + if (!timezone) { + timezone = DEFAULT_CLOCK.timezone; + changed = true; + } else if (timezone !== input.timezone) { + changed = true; + } + + for (let key in input) { + if (key !== "id" && key !== "name" && key !== "timezone") { + changed = true; + break; + } + } + + return { + changed: changed, + clock: { + id: id, + name: name, + timezone: timezone + } + }; +} + +/** + * normalizeClockList: + * @clockList (array): raw clocks setting + * @opts (object): optional { generateId: function } + * + * Returns (object): { clocks, changed }. An empty list becomes one default clock. + */ +function normalizeClockList(clockList, opts) { + let list = Array.isArray(clockList) ? clockList : []; + let normalized = []; + let changed = !Array.isArray(clockList); + + for (let i = 0; i < list.length; i++) { + let result = normalizeClockEntry(list[i], opts); + normalized.push(result.clock); + if (result.changed) + changed = true; + } + + if (normalized.length === 0) { + normalized.push(buildClock(DEFAULT_CLOCK, null, opts)); + changed = true; + } + + return { + clocks: normalized, + changed: changed + }; +} + +function _clocks(clocks) { + return Array.isArray(clocks) ? clocks : []; +} + +/** + * canAdd: + * @clocks (array) + * + * Returns (boolean): whether another clock may be created. + */ +function canAdd(clocks) { + return _clocks(clocks).length < MAX_CLOCKS; +} + +/** + * canRemove: + * @clocks (array) + * + * Returns (boolean): whether a clock may be removed. The last clock is kept. + */ +function canRemove(clocks) { + return _clocks(clocks).length > MIN_CLOCKS; +} + +/** + * isValidIndex: + * @clocks (array) + * @index (int) + * + * Returns (boolean): whether @index addresses an existing clock. + */ +function isValidIndex(clocks, index) { + let n = _clocks(clocks).length; + return Number.isInteger(index) && index >= 0 && index < n; +} + +/** + * getClockLabel: + * @clock (object) + * + * Returns (string): display name, falling back to a short timezone label. + */ +function getClockLabel(clock) { + if (!clock || typeof clock !== "object") + return _("Clock"); + if (typeof clock.name === "string" && clock.name.trim()) + return clock.name.trim(); + if (typeof clock.timezone === "string" && clock.timezone.trim()) + return timezoneDisplayName(clock.timezone); + return _("Clock"); +} + +/** + * timezoneDisplayName: + * @tz (string): "local" or an IANA timezone id + * + * Returns (string): a short label, e.g. "Local" or "Los Angeles". + */ +function timezoneDisplayName(tz) { + if (!tz || tz === "local") + return _("Local"); + let parts = String(tz).split("/"); + return parts[parts.length - 1].replace(/_/g, " "); +} + +/** + * timezoneListLabel: + * @tz (string) + * + * Returns (string): list-row text, e.g. "Los Angeles (America/Los_Angeles)". + */ +function timezoneListLabel(tz) { + if (!tz || tz === "local") + return _("Local (system timezone)"); + let pretty = timezoneDisplayName(tz); + if (pretty === tz) + return tz; + return pretty + " (" + tz + ")"; +} + +function _uniqueSorted(list) { + let seen = Object.create(null); + let out = []; + for (let i = 0; i < list.length; i++) { + let tz = list[i]; + if (typeof tz !== "string" || !tz || tz === "local" || seen[tz]) + continue; + seen[tz] = true; + out.push(tz); + } + out.sort(); + return out; +} + +var FALLBACK_TIMEZONES = [ + "UTC", + "America/New_York", + "America/Chicago", + "America/Denver", + "America/Los_Angeles", + "America/Anchorage", + "America/Honolulu", + "America/Toronto", + "America/Mexico_City", + "America/Sao_Paulo", + "America/Argentina/Buenos_Aires", + "Europe/London", + "Europe/Paris", + "Europe/Berlin", + "Europe/Madrid", + "Europe/Rome", + "Europe/Moscow", + "Africa/Cairo", + "Africa/Johannesburg", + "Asia/Dubai", + "Asia/Kolkata", + "Asia/Shanghai", + "Asia/Singapore", + "Asia/Tokyo", + "Asia/Seoul", + "Australia/Sydney", + "Pacific/Auckland" +]; + +/** + * listTimezones: + * + * Returns (array): ["local", ...IANA ids]. Uses Intl when available. + */ +function listTimezones() { + let zones = []; + try { + if (typeof Intl !== "undefined" && typeof Intl.supportedValuesOf === "function") + zones = Intl.supportedValuesOf("timeZone"); + } catch (e) { + zones = []; + } + if (!zones || !zones.length) + zones = FALLBACK_TIMEZONES.slice(); + return ["local"].concat(_uniqueSorted(zones)); +} + +/** + * filterTimezones: + * @zones (array) + * @query (string) + * + * Returns (array): zones whose id or display name contains @query. + */ +function filterTimezones(zones, query) { + let list = Array.isArray(zones) ? zones : []; + let q = typeof query === "string" ? query.trim().toLowerCase() : ""; + if (!q) + return list.slice(); + return list.filter(function (tz) { + let id = String(tz).toLowerCase(); + let label = timezoneListLabel(tz).toLowerCase(); + let city = String(tz).replace(/_/g, " ").toLowerCase(); + return id.indexOf(q) !== -1 || label.indexOf(q) !== -1 || city.indexOf(q) !== -1; + }); +} + +/** + * addClock: + * @clocks (array) + * @values (object): { name, timezone } + * @opts (object): optional { generateId: function } + * + * Returns (array): a new list with the clock appended, or a copy if at max. + */ +function addClock(clocks, values, opts) { + let list = _clocks(clocks).slice(); + if (!canAdd(list)) + return list; + list.push(buildClock(values, null, opts)); + return list; +} + +/** + * updateClock: + * @clocks (array) + * @clockId (string) + * @values (object): { name, timezone } + * + * Returns (array): a new list with the matching clock replaced. + */ +function updateClock(clocks, clockId, values) { + let list = _clocks(clocks); + if (typeof clockId !== "string" || !clockId) + return list.slice(); + + let found = false; + let next = list.map(function (clock) { + if (clock.id !== clockId) + return clock; + found = true; + return buildClock(values, clock.id); + }); + return found ? next : list.slice(); +} + +/** + * removeClock: + * @clocks (array) + * @clockId (string) + * + * Returns (array): a new list without that clock. Refuses to empty the list. + */ +function removeClock(clocks, clockId) { + let list = _clocks(clocks); + if (!canRemove(list) || typeof clockId !== "string" || !clockId) + return list.slice(); + return list.filter(function (clock) { + return clock.id !== clockId; + }); +} diff --git a/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/clockDialog.js b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/clockDialog.js new file mode 100644 index 000000000..579ea4469 --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/clockDialog.js @@ -0,0 +1,382 @@ +/* global imports, global */ +/** + * clockDialog.js + * + * Modal dialog used to add or edit a world-clock tile (name + timezone list). + * + * The name field is a top-level St.Entry (same pattern as renameDialog.js) so + * ModalDialog.pushModal() can give ClutterText a stage-wide key grab. Nested + * BoxLayout packing and focusable timezone buttons previously stole that grab, + * so typed names never landed in the entry. + */ + +const Clutter = imports.gi.Clutter; +const GObject = imports.gi.GObject; +const St = imports.gi.St; + +const Dialog = imports.ui.dialog; +const ModalDialog = imports.ui.modalDialog; + +let _translate = function (str) { return str; }; + +function setTranslate(fn) { + if (typeof fn === "function") + _translate = fn; +} + +/* Call sites use _() so cinnamon-xlet-makepot's default keyword extracts + * them; _() always routes through the injected translator. */ +function _(str) { + return _translate(str); +} + +function _displayName(tz) { + if (!tz || tz === "local") + return _("Local"); + let parts = String(tz).split("/"); + return parts[parts.length - 1].replace(/_/g, " "); +} + +function _listLabel(tz) { + if (!tz || tz === "local") + return _("Local (system timezone)"); + return _displayName(tz) + " (" + tz + ")"; +} + +function _loadTimezones() { + let zones = []; + try { + if (typeof Intl !== "undefined" && typeof Intl.supportedValuesOf === "function") + zones = Intl.supportedValuesOf("timeZone"); + } catch (e) { + zones = []; + } + if (!zones || !zones.length) { + zones = [ + "UTC", "America/New_York", "America/Chicago", "America/Denver", + "America/Los_Angeles", "America/Toronto", "America/Mexico_City", + "America/Sao_Paulo", "Europe/London", "Europe/Paris", "Europe/Berlin", + "Europe/Moscow", "Africa/Johannesburg", "Asia/Dubai", "Asia/Kolkata", + "Asia/Shanghai", "Asia/Singapore", "Asia/Tokyo", "Asia/Seoul", + "Australia/Sydney", "Pacific/Auckland" + ]; + } + let seen = Object.create(null); + let out = []; + for (let i = 0; i < zones.length; i++) { + let tz = zones[i]; + if (typeof tz !== "string" || !tz || tz === "local" || seen[tz]) + continue; + seen[tz] = true; + out.push(tz); + } + out.sort(); + out.unshift("local"); + return out; +} + +var ClockConfigDialog = GObject.registerClass( +class ClockConfigDialog extends ModalDialog.ModalDialog { + + /** + * _init: + * @title (string): dialog title ("Add Clock" / "Edit Clock") + * @initial (object): { name, timezone } to pre-fill + * @callback (function): called with { name, timezone } on commit + * @timezones (array): selectable timezone ids, including "local" + */ + _init(title, initial, callback, timezones) { + super._init(); + + this._callback = callback; + this._settled = false; + this._activateIds = []; + this._timezones = Array.isArray(timezones) && timezones.length > 1 + ? timezones.slice() + : _loadTimezones(); + this._tzButtons = []; + + initial = initial && typeof initial === "object" ? initial : {}; + this._selectedTimezone = (typeof initial.timezone === "string" && initial.timezone) + ? initial.timezone + : "local"; + if (this._timezones.indexOf(this._selectedTimezone) === -1) + this._timezones.splice(1, 0, this._selectedTimezone); + + let initialName = typeof initial.name === "string" ? initial.name.trim() : ""; + + let content = new Dialog.MessageDialogContent({ + title: title || _("Clock"), + description: _("Type a name, then pick a timezone from the list.") + }); + this.contentLayout.add_child(content); + + this.contentLayout.add_child(new St.Label({ + text: _("Name"), + style_class: "world-clock-dialog-label" + })); + this._nameEntry = this._createEntry( + initialName, + _("Clock name"), + true + ); + this.contentLayout.add_child(this._nameEntry); + + this.contentLayout.add_child(new St.Label({ + text: _("Timezone"), + style_class: "world-clock-dialog-label" + })); + this._filterEntry = this._createEntry( + "", + _("Search city or region"), + false + ); + this.contentLayout.add_child(this._filterEntry); + this._filterEntry.clutter_text.connect("text-changed", () => { + this._rebuildTimezoneList(); + }); + + this._listBox = new St.BoxLayout({ + vertical: true, + x_expand: true, + style_class: "world-clock-tz-box" + }); + this._scroll = new St.ScrollView({ + style_class: "world-clock-tz-list", + x_expand: true, + overlay_scrollbars: true, + hscrollbar_policy: St.PolicyType.NEVER, + vscrollbar_policy: St.PolicyType.AUTOMATIC + }); + this._scroll.add_actor(this._listBox); + this.contentLayout.add_child(this._scroll); + + this._selectedLabel = new St.Label({ + style_class: "world-clock-tz-selected", + text: "" + }); + this.contentLayout.add_child(this._selectedLabel); + + this._rebuildTimezoneList(); + this._updateSelectedLabel(); + + this.setButtons([ + { + label: _("Cancel"), + action: () => this._cancel(), + key: Clutter.KEY_Escape + }, + { + label: _("Save"), + action: () => this._commit(), + default: true + } + ]); + + /* Must come after setButtons(): addButton() focuses the first button + * when nothing else has claimed focus. Focus the ClutterText, not the + * St.Entry wrapper - that is what receives typed characters. */ + this.setInitialKeyFocus(this._nameEntry.clutter_text); + this.connect("opened", () => this._focusName()); + this.connect("destroy", () => this._onDestroy()); + } + + _createEntry(value, hint, commitOnActivate) { + let entry = new St.Entry({ + style_class: "world-clock-dialog-entry", + can_focus: true, + track_hover: true, + reactive: true, + x_expand: true, + hint_text: hint || "" + }); + let text = entry.clutter_text; + text.editable = true; + text.activatable = true; + text.single_line_mode = true; + if (value) + entry.set_text(value); + + /* Clicking the entry must reclaim the modal key grab from timezone + * list items or the default Save button. */ + entry.connect("button-press-event", () => { + global.stage.set_key_focus(text); + return Clutter.EVENT_PROPAGATE; + }); + + let id = text.connect("activate", () => { + if (commitOnActivate) + this._commit(); + else + this._selectFirstVisible(); + }); + this._activateIds.push({ entry: entry, id: id }); + return entry; + } + + _focusName() { + try { + let text = this._nameEntry.clutter_text; + global.stage.set_key_focus(text); + let value = this._nameEntry.get_text() || ""; + text.set_selection(0, value.length); + } catch (e) { + global.logError("[clockDialog] could not focus name entry: " + e); + } + } + + _visibleTimezones() { + let q = ""; + try { + q = this._filterEntry.get_text(); + } catch (e) { + q = ""; + } + q = q.trim().toLowerCase(); + if (!q) + return this._timezones; + return this._timezones.filter((tz) => { + let id = String(tz).toLowerCase(); + let pretty = _displayName(tz).toLowerCase(); + let label = _listLabel(tz).toLowerCase(); + let city = String(tz).replace(/_/g, " ").toLowerCase(); + return id.indexOf(q) !== -1 + || pretty.indexOf(q) !== -1 + || label.indexOf(q) !== -1 + || city.indexOf(q) !== -1; + }); + } + + _rebuildTimezoneList() { + this._listBox.destroy_all_children(); + this._tzButtons = []; + + let zones = this._visibleTimezones(); + let limit = Math.min(zones.length, 400); + for (let i = 0; i < limit; i++) { + let tz = zones[i]; + let button = new St.Button({ + style_class: "world-clock-tz-item", + label: _listLabel(tz), + x_align: St.Align.START, + x_expand: true, + reactive: true, + /* Keep keyboard focus on the name/filter entries. */ + can_focus: false + }); + button.timezone = tz; + button.connect("clicked", () => this._selectTimezone(tz)); + this._listBox.add_child(button); + this._tzButtons.push(button); + } + this._highlightSelection(); + } + + _selectTimezone(tz) { + this._selectedTimezone = tz || "local"; + this._highlightSelection(); + this._updateSelectedLabel(); + + /* Only suggest a name when the field is still empty. Never overwrite + * a name the user is typing or has already set. */ + try { + if (!this._nameEntry.get_text().trim()) + this._nameEntry.set_text(_displayName(this._selectedTimezone)); + } catch (e) { + /* entry gone */ + } + this._focusName(); + } + + _selectFirstVisible() { + let zones = this._visibleTimezones(); + if (zones.length) + this._selectTimezone(zones[0]); + } + + _highlightSelection() { + for (let i = 0; i < this._tzButtons.length; i++) { + let button = this._tzButtons[i]; + if (button.timezone === this._selectedTimezone) + button.add_style_pseudo_class("outlined"); + else + button.remove_style_pseudo_class("outlined"); + } + } + + _updateSelectedLabel() { + this._selectedLabel.set_text( + _("Selected: %s").format(_listLabel(this._selectedTimezone)) + ); + } + + _onDestroy() { + try { + for (let i = 0; i < this._activateIds.length; i++) { + let item = this._activateIds[i]; + if (item.entry && item.id) + item.entry.clutter_text.disconnect(item.id); + } + } catch (e) { + /* entry already finalized */ + } + this._activateIds = []; + this._callback = null; + } + + _cancel() { + if (this._settled) + return; + this._settled = true; + this.destroy(); + } + + _commit() { + if (this._settled) + return; + this._settled = true; + + let name = ""; + let timezone = this._selectedTimezone || "local"; + try { + name = this._nameEntry.get_text().trim(); + } catch (e) { + global.logError("[clockDialog] could not read name: " + e); + } + if (!name) + name = _displayName(timezone); + + let callback = this._callback; + this.destroy(); + + if (callback) { + try { + callback({ name: name, timezone: timezone }); + } catch (e) { + global.logError("[clockDialog] save callback failed: " + e); + } + } + } +}); + +/** + * promptClock: + * @title (string): dialog title + * @initial (object): { name, timezone } + * @callback (function): called with { name, timezone } on commit + * @timezones (array): optional list of timezone ids + * + * Returns (boolean): whether the dialog opened. + */ +function promptClock(title, initial, callback, timezones) { + try { + if (!Array.isArray(timezones) || timezones.length < 2) + timezones = _loadTimezones(); + let dialog = new ClockConfigDialog(title, initial, callback, timezones); + dialog.open(global.get_current_time()); + return dialog; + } catch (e) { + global.logError("[clockDialog] could not open clock dialog: " + e); + return null; + } +} diff --git a/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/desklet.js b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/desklet.js new file mode 100644 index 000000000..55e183ee3 --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/desklet.js @@ -0,0 +1,938 @@ +/* global imports, global */ +const Desklet = imports.ui.desklet; +const St = imports.gi.St; +const Settings = imports.ui.settings; +const Mainloop = imports.mainloop; +const Main = imports.ui.main; +const PopupMenu = imports.ui.popupMenu; +const ModalDialog = imports.ui.modalDialog; +const Gettext = imports.gettext; +const GLib = imports.gi.GLib; +const Pango = imports.gi.Pango; +const Clutter = imports.gi.Clutter; + +const uuid = "cinnamon-world-clock-desklet@curbsoftware"; + +Gettext.bindtextdomain(uuid, GLib.get_user_data_dir() + "/locale"); + +function _(str) { + return Gettext.dgettext(uuid, str); +} + +/* Xlet-local modules. Cinnamon exposes a desklet's own directory through + * imports.ui.deskletManager.desklets[uuid]; resolved lazily in _init() so a + * load-order problem surfaces as a logged error instead of a load failure. */ +let ClockActions = null; +let ClockDialog = null; + +function _loadModules(deskletPath) { + if (ClockActions && ClockDialog) + return true; + const dirs = []; + try { dirs.push(imports.ui.deskletManager.desklets[uuid]); } catch (e) {} + try { dirs.push(imports.desklets[uuid]); } catch (e) {} + for (let i = 0; i < dirs.length; i++) { + const dir = dirs[i]; + if (!dir) + continue; + try { + if (!ClockActions && dir.clockActions) + ClockActions = dir.clockActions; + if (!ClockDialog && dir.clockDialog) + ClockDialog = dir.clockDialog; + } catch (e) {} + } + if ((!ClockActions || !ClockDialog) && deskletPath) { + try { + imports.searchPath.unshift(deskletPath); + if (!ClockActions) + ClockActions = imports.clockActions; + if (!ClockDialog) + ClockDialog = imports.clockDialog; + } catch (e) { + global.logError(uuid + " could not import helpers from " + deskletPath + ": " + e); + } + } + if (!(ClockActions && ClockDialog)) + global.logError(uuid + " could not load helper modules"); + return !!(ClockActions && ClockDialog); +} + +function _formatStrftime(date, fmt, tzName) { + if (!fmt) + return ""; + try { + let tz; + if (tzName && tzName !== "local") + tz = GLib.TimeZone.new(String(tzName).trim()); + else + tz = GLib.TimeZone.new_local(); + let dt = GLib.DateTime.new_from_unix_utc(Math.floor(date.getTime() / 1000)); + if (tz) + dt = dt.to_timezone(tz); + let out = dt.format(fmt); + if (out) + return out; + } catch (e) {} + try { + if (date && typeof date.toLocaleFormat === "function") { + let out = date.toLocaleFormat(fmt); + if (out) + return out; + } + } catch (e2) {} + return ""; +} + +const DEFAULT_TIME_FORMAT = "%H:%M:%S"; +const DEFAULT_DATE_FORMAT = "%A, %e %B"; + +function _centerLabelText(label) { + if (!label || !label.clutter_text) + return; + try { + label.clutter_text.set_line_alignment(Pango.Alignment.CENTER); + if (Clutter.ActorAlign) + label.clutter_text.x_align = Clutter.ActorAlign.CENTER; + } catch (e) {} +} + +function _actorWidth(actor) { + try { + if (!actor || !actor.get_allocation_box) + return 0; + const box = actor.get_allocation_box(); + return Math.max(0, box.x2 - box.x1); + } catch (e) { + return 0; + } +} + +function ClockWidget(clockData, desklet) { + this._init(clockData, desklet); +} + +ClockWidget.prototype = { + _init: function (clockData, desklet) { + this.desklet = desklet; + this.data = clockData; + this.id = clockData.id; + + this.actor = new St.Button({ + style_class: "world-clock-tile", + reactive: true, + can_focus: true, + x_expand: true, + y_expand: true + }); + /* Accept right-click too, so a tile can raise its own context menu. + * St.Button consumes the release, so the Desklet base class right-click + * handler does not also open the desklet menu. */ + this.actor.set_button_mask(St.ButtonMask.ONE | St.ButtonMask.THREE); + + const box = new St.BoxLayout({ + vertical: true + }); + this._contentBox = box; + + this._time = new St.Label({ style_class: "world-clock-time" }); + this._date = new St.Label({ style_class: "world-clock-date" }); + this._timezoneLabel = new St.Label({ style_class: "world-clock-timezone" }); + + try { + this._time.clutter_text.ellipsize = Pango.EllipsizeMode.NONE; + this._time.clutter_text.line_wrap = false; + this._date.clutter_text.ellipsize = Pango.EllipsizeMode.NONE; + this._date.clutter_text.line_wrap = false; + this._timezoneLabel.clutter_text.ellipsize = Pango.EllipsizeMode.END; + this._timezoneLabel.clutter_text.line_wrap = false; + } catch (e) {} + _centerLabelText(this._time); + _centerLabelText(this._date); + _centerLabelText(this._timezoneLabel); + + /* Time/date stay at natural width so the box can center them in the + * tile. Stretching those labels with set_width left-aligns glyphs. */ + box.add(this._time, { x_fill: false, x_align: St.Align.MIDDLE }); + box.add(this._date, { x_fill: false, x_align: St.Align.MIDDLE }); + box.add(this._timezoneLabel, { x_fill: true, x_align: St.Align.MIDDLE }); + + const bin = new St.Bin({ + x_fill: true, + y_fill: false, + x_align: St.Align.MIDDLE, + y_align: St.Align.MIDDLE + }); + bin.set_child(box); + this.actor.set_child(bin); + + const label = ClockActions + ? ClockActions.getClockLabel(this.data) + : (this.data.name || this.data.timezone || ""); + this._timezoneLabel.set_text(label); + }, + + /* Font sizes are recomputed on grid rebuild / setting changes, not on the + * 1s tick. Settings values are caps; the tile shrinks text to fit. */ + applyFittedSizes: function (inner, samples) { + if (!ClockActions || !ClockActions.computeFittedFontSizes) + return; + + inner = inner || {}; + samples = samples || {}; + const box = { + width: Math.max(0, Number(inner.width) || 0), + height: Math.max(0, Number(inner.height) || 0) + }; + if (box.width < 1 || box.height < 1) + return; + + const texts = { + time: samples.time || this._time.get_text() || "23:59:59", + date: samples.date || this._date.get_text() || "Wednesday, 31 December", + label: this._timezoneLabel.get_text() || "" + }; + const maxSizes = { + time: Number(this.desklet.timeSize) || 40, + date: Number(this.desklet.dateSize) || 15, + timezone: Number(this.desklet.timezoneSize) || 12 + }; + + const sizes = ClockActions.computeFittedFontSizes(box.width, box.height, texts, maxSizes); + this._setFontSizes(sizes); + this._constrainLabelWidth(box.width); + this._refineWithMetrics(box, sizes); + }, + + _setFontSizes: function (sizes) { + this._time.set_style("font-size: " + sizes.time + "pt;"); + this._date.set_style("font-size: " + sizes.date + "pt;"); + this._timezoneLabel.set_style("font-size: " + sizes.timezone + "pt;"); + }, + + _constrainLabelWidth: function (width) { + try { + let w = _actorWidth(this._contentBox); + if (!(w > 1)) + w = width; + if (w > 1) + this._timezoneLabel.set_width(Math.max(1, Math.floor(w))); + } catch (e) {} + }, + + _refineWithMetrics: function (inner, sizes) { + /* Skip until the tile is on the stage: querying preferred size on an + * unmapped actor returns -1 and floods St-CRITICAL warnings. */ + if (!this.actor || !this.actor.get_stage()) + return; + try { + const gap = (ClockActions && ClockActions.TILE_LAYOUT) + ? ClockActions.TILE_LAYOUT.lineGap : 2; + for (let i = 0; i < 8; i++) { + const timeW = this._time.get_preferred_width(-1)[1]; + const dateW = this._date.get_preferred_width(-1)[1]; + const timeH = this._time.get_preferred_height(-1)[1]; + const dateH = this._date.get_preferred_height(-1)[1]; + const tzH = this._timezoneLabel.get_preferred_height(-1)[1]; + const totalH = timeH + dateH + tzH + 2 * gap; + const wide = timeW > inner.width + 1 || dateW > inner.width + 1; + const tall = totalH > inner.height + 1; + if (!wide && !tall) + return; + sizes.time = Math.max(1, sizes.time * 0.88); + sizes.date = Math.max(1, Math.min(sizes.date * 0.88, sizes.time)); + sizes.timezone = Math.max(1, Math.min(sizes.timezone * 0.88, sizes.date)); + this._setFontSizes(sizes); + } + } catch (e) { + global.logError(uuid + " font metric refine failed: " + e); + } + }, + + update: function (baseDate) { + let timezoneName = this.data.timezone || "local"; + let displayTz = timezoneName === "local" ? "" : timezoneName; + + if (timezoneName !== "local") { + try { + GLib.TimeZone.new(timezoneName); + this._lastBadTimezone = null; + } catch (e) { + if (this._lastBadTimezone !== timezoneName) { + this._lastBadTimezone = timezoneName; + global.logError(uuid + " invalid timezone: " + timezoneName + ": " + e); + } + timezoneName = "local"; + displayTz = ""; + } + } + + const label = ClockActions + ? ClockActions.getClockLabel(this.data) + : (this.data.name || timezoneName); + + try { + const timeFormat = this.desklet.timeFormat || DEFAULT_TIME_FORMAT; + const dateFormat = this.desklet.dateFormat || DEFAULT_DATE_FORMAT; + this._time.set_text(_formatStrftime(baseDate, timeFormat, displayTz)); + this._date.set_text(_formatStrftime(baseDate, dateFormat, displayTz)); + } catch (e) { + global.logError(uuid + " could not format clock: " + e); + this._time.set_text(""); + this._date.set_text(""); + } + + this._timezoneLabel.set_text(label); + } +}; + +function MyDesklet(metadata, deskletId) { + this._init(metadata, deskletId); +} + +MyDesklet.prototype = { + __proto__: Desklet.Desklet.prototype, + + _init: function (metadata, deskletId) { + Desklet.Desklet.prototype._init.call(this, metadata, deskletId); + + _loadModules(metadata.path); + + if (ClockActions) + ClockActions.setTranslate(_); + if (ClockDialog) + ClockDialog.setTranslate(_); + + this._settingWatchIds = []; + this.settings = new Settings.DeskletSettings(this, this.metadata["uuid"], deskletId); + this.settings.bind("layout-mode", "layoutMode", this.on_setting_changed); + this.settings.bind("fixed-rows", "fixedRows", this.on_setting_changed); + this.settings.bind("fixed-cols", "fixedCols", this.on_setting_changed); + this.settings.bind("tile-spacing", "tileSpacing", this.on_setting_changed); + this.settings.bind("width", "width", this.on_setting_changed); + this.settings.bind("height", "height", this.on_setting_changed); + this.settings.bind("enable-clock-editing", "enableEditing", this.on_setting_changed); + this.settings.bind("show-add-tile", "showAddTile", this.on_setting_changed); + this.settings.bind("confirm-remove", "confirmRemove"); + this.settings.bind("time-format", "timeFormat", this.on_setting_changed); + this.settings.bind("date-format", "dateFormat", this.on_setting_changed); + this.settings.bind("time-size", "timeSize", this.on_setting_changed); + this.settings.bind("date-size", "dateSize", this.on_setting_changed); + this.settings.bind("timezone-size", "timezoneSize", this.on_setting_changed); + this._watchSetting("clocks", "clocks", this._onClocksChanged); + + this._clockWidgets = []; + this.buttons = []; + this._addTiles = []; + this._normalizedClocks = []; + this._timeout = null; + this._tileInner = null; + this._widthSamples = null; + + /* At most one transient tile menu is alive at a time. Tile menus are + * parented to Main.uiGroup, so destroy_all_children() on our own + * container will never reach them - they must be released by hand. */ + this._tileMenu = null; + this._idleSources = []; + this._rebuildTimeout = null; + this._fitId = null; + this._fitRetryId = null; + this._clockDialog = null; + this._confirmDialog = null; + + this.mainContainer = new St.BoxLayout({ + vertical: true, + style_class: "world-clock-container" + }); + this.mainContainer.set_width(this.width || 600); + this.mainContainer.set_height(this.height || 400); + + this.setContent(this.mainContainer); + this.setHeader(_("World Clocks")); + + this._ensureClockDefaults(); + this._rebuildGrid(); + this._scheduleUpdate(); + + /* Desklet.destroy() emits 'destroy' immediately but defers + * on_desklet_removed() until a 500ms fade-out completes. Without this + * hook our timeout keeps firing against a tearing-down desklet for + * half a second. _cleanup() is idempotent. */ + this._destroyId = this.connect("destroy", this._cleanup.bind(this)); + }, + + on_desklet_removed: function () { + this._cleanup(); + }, + + _cleanup: function () { + if (this._cleanedUp) + return; + this._cleanedUp = true; + + this._destroyTileMenu(); + this._dismissDialogs(); + + if (this._idleSources) { + for (let i = 0; i < this._idleSources.length; i++) + Mainloop.source_remove(this._idleSources[i]); + this._idleSources = []; + } + if (this._timeout) { + Mainloop.source_remove(this._timeout); + this._timeout = null; + } + if (this._rebuildTimeout) { + Mainloop.source_remove(this._rebuildTimeout); + this._rebuildTimeout = null; + } + if (this._fitId) { + Mainloop.source_remove(this._fitId); + this._fitId = null; + } + if (this._fitRetryId) { + Mainloop.source_remove(this._fitRetryId); + this._fitRetryId = null; + } + + this._clockWidgets = []; + this.buttons = []; + this._addTiles = []; + + if (this.settings) { + if (this._settingWatchIds) { + for (let i = 0; i < this._settingWatchIds.length; i++) { + try { this.settings.disconnect(this._settingWatchIds[i]); } catch (e) {} + } + this._settingWatchIds = []; + } + this.settings.finalize(); + this.settings = null; + } + + if (this._destroyId) { + this.disconnect(this._destroyId); + this._destroyId = 0; + } + }, + + _dismissDialogs: function () { + if (this._clockDialog) { + try { this._clockDialog.destroy(); } catch (e) {} + this._clockDialog = null; + } + if (this._confirmDialog) { + try { this._confirmDialog.destroy(); } catch (e) {} + this._confirmDialog = null; + } + }, + + _watchSetting: function (key, prop, callback) { + this[prop] = this.settings ? this.settings.getValue(key) : null; + if (this.settings && this.settings.connect) { + const id = this.settings.connect("changed::" + key, () => { + this[prop] = this.settings.getValue(key); + if (callback) + callback.call(this); + }); + if (!this._settingWatchIds) + this._settingWatchIds = []; + this._settingWatchIds.push(id); + } + }, + + on_setting_changed: function () { + try { + this.mainContainer.set_width(this.width); + this.mainContainer.set_height(this.height); + } catch (e) { + global.logError(uuid + " setting change failed: " + e); + } + if (this._cleanedUp) + return; + if (this._rebuildTimeout) { + Mainloop.source_remove(this._rebuildTimeout); + this._rebuildTimeout = null; + } + this._rebuildTimeout = Mainloop.timeout_add(100, () => { + this._rebuildTimeout = null; + this._rebuildGrid(); + return false; + }); + }, + + _onClocksChanged: function () { + try { + if (!ClockActions || !this.mainContainer) + return; + const result = ClockActions.normalizeClockList(this.clocks); + this._normalizedClocks = result.clocks; + if (result.changed) + this.settings.setValue("clocks", result.clocks); + this._rebuildGrid(); + } catch (e) { + global.logError(uuid + " clocks change failed: " + e); + } + }, + + /* setValue does not fire the bind callback in-process, so the grid must + * be rebuilt here. _normalizedClocks is the live list _getClockList uses. */ + _setClockList: function (list) { + this._normalizedClocks = Array.isArray(list) ? list : []; + this.settings.setValue("clocks", this._normalizedClocks); + this._rebuildGrid(); + }, + + /* ------------------------------------------------------------------ * + * Grid construction + * ------------------------------------------------------------------ */ + + _rebuildGrid: function () { + try { + if (!_loadModules(this.metadata && this.metadata.path)) + return; + + this._destroyTileMenu(); + this.mainContainer.destroy_all_children(); + + this._clockWidgets = []; + this.buttons = []; + this._addTiles = []; + + const clocks = this._getClockList(); + const showAdd = !!(this.enableEditing && this.showAddTile && ClockActions.canAdd(clocks)); + const dims = this._computeGridDims(); + const cells = ClockActions.planCells(clocks.length, showAdd, dims.rows, dims.cols); + + const table = new St.Table({ + homogeneous: true, + reactive: true, + style_class: "world-clock-grid" + }); + this.mainContainer.add(table, { + expand: true, + x_expand: true, + y_expand: true, + x_fill: true, + y_fill: true + }); + + for (let i = 0; i < cells.length; i++) { + const cell = cells[i]; + const row = Math.floor(i / dims.cols); + const col = i % dims.cols; + const actor = (cell.kind === "add") + ? this._createAddTile() + : this._createClockTile(clocks[cell.index], cell.index); + + table.add(actor, { + row: row, + col: col, + x_expand: true, + y_expand: true, + x_fill: true, + y_fill: true + }); + } + + this._updateClocks(); + this._widthSamples = this._formatWidthSamples(); + this._tileInner = this._computeTileInnerSize(); + this._scheduleFit(); + this._updateHighlight(); + } catch (e) { + global.logError(uuid + " grid rebuild failed: " + e); + } + }, + + _createClockTile: function (clock, index) { + const widget = new ClockWidget(clock, this); + widget.actor.index = index; + widget.actor.clockId = clock.id; + widget.actor.connect("clicked", this._onClockTileClicked.bind(this)); + widget.actor.set_style("margin:" + Math.max(0, this.tileSpacing || 0) + "px;"); + this._clockWidgets.push(widget); + this.buttons.push(widget.actor); + return widget.actor; + }, + + _createAddTile: function () { + const button = new St.Button({ + style_class: "world-clock-add-tile", + reactive: true, + can_focus: true, + x_expand: true, + y_expand: true + }); + const label = new St.Label({ + text: "+", + style_class: "world-clock-add-label" + }); + try { + label.clutter_text.ellipsize = Pango.EllipsizeMode.NONE; + label.clutter_text.line_wrap = false; + } catch (e) {} + _centerLabelText(label); + const bin = new St.Bin({ + x_fill: false, + y_fill: false, + x_align: St.Align.MIDDLE, + y_align: St.Align.MIDDLE + }); + bin.set_child(label); + button.set_child(bin); + button.connect("clicked", this._onAddClock.bind(this)); + button.set_style("margin:" + Math.max(0, this.tileSpacing || 0) + "px;"); + this._addTiles.push({ button: button, label: label }); + return button; + }, + + _onClockTileClicked: function (actor, clickedButton) { + try { + if (clickedButton === 3) { + if (this.enableEditing) + this._openTileMenu(actor); + } + } catch (e) { + global.logError(uuid + " tile click failed: " + e); + } + }, + + /* ------------------------------------------------------------------ * + * Per-tile context menu + * ------------------------------------------------------------------ */ + + _openTileMenu: function (button) { + try { + this._destroyTileMenu(); + + const index = button.index; + const clocks = this._getClockList(); + const menu = new PopupMenu.PopupMenu(button, St.Side.TOP); + Main.uiGroup.add_actor(menu.actor); + menu.actor.hide(); + + const editItem = new PopupMenu.PopupMenuItem(_("Edit…")); + editItem.connect("activate", () => { + this._onEditClock(index); + }); + menu.addMenuItem(editItem); + + const removeItem = new PopupMenu.PopupMenuItem(_("Remove")); + removeItem.setSensitive(ClockActions.canRemove(clocks)); + removeItem.connect("activate", () => { + this._onRemoveClock(index); + }); + menu.addMenuItem(removeItem); + + menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem()); + + const addItem = new PopupMenu.PopupMenuItem(_("Add clock")); + addItem.setSensitive(ClockActions.canAdd(clocks)); + addItem.connect("activate", this._onAddClock.bind(this)); + menu.addMenuItem(addItem); + + if (this._menuManager) + this._menuManager.addMenu(menu); + + this._tileMenu = menu; + menu.open(true); + } catch (e) { + global.logError(uuid + " could not open tile menu: " + e); + this._destroyTileMenu(); + } + }, + + _destroyTileMenu: function () { + if (!this._tileMenu) + return; + const menu = this._tileMenu; + this._tileMenu = null; + try { + if (menu.isOpen) + menu.close(false); + if (this._menuManager) + this._menuManager.removeMenu(menu); + menu.destroy(); + } catch (e) { + global.logError(uuid + " could not destroy tile menu: " + e); + } + }, + + /* Menu items must not act synchronously: PopupMenuBase closes the menu in + * its own 'activate' handler, which runs after ours. Destroying the menu + * or pushing a modal dialog before that has happened fights the menu's + * grab. Defer to the next main loop turn and track the source so teardown + * can cancel it. + * + * timeout_add(0), not idle_add: idle callbacks sit below Clutter's redraw + * priority, so an action fired while a menu or dialog was still animating + * could be starved for hundreds of milliseconds. */ + _deferAction: function (fn) { + const self = this; + let id = Mainloop.timeout_add(0, function () { + self._idleSources = self._idleSources.filter(function (s) { return s !== id; }); + if (self._cleanedUp) + return false; + try { + fn.call(self); + } catch (e) { + global.logError(uuid + " deferred action failed: " + e); + } + return false; + }); + this._idleSources.push(id); + }, + + _onAddClock: function () { + this._deferAction(function () { + this._destroyTileMenu(); + if (!ClockActions.canAdd(this._getClockList())) + return; + const zones = ClockActions.listTimezones + ? ClockActions.listTimezones() + : null; + this._clockDialog = ClockDialog.promptClock(_("Add Clock"), ClockActions.DEFAULT_CLOCK, (values) => { + if (this._cleanedUp) + return; + this._setClockList(ClockActions.addClock(this._getClockList(), values)); + }, zones); + }); + }, + + _onEditClock: function (index) { + this._deferAction(function () { + this._destroyTileMenu(); + const clocks = this._getClockList(); + if (!ClockActions.isValidIndex(clocks, index)) + return; + const current = clocks[index]; + const zones = ClockActions.listTimezones + ? ClockActions.listTimezones() + : null; + this._clockDialog = ClockDialog.promptClock(_("Edit Clock"), current, (values) => { + if (this._cleanedUp) + return; + this._setClockList(ClockActions.updateClock(this._getClockList(), current.id, values)); + }, zones); + }); + }, + + _onRemoveClock: function (index) { + this._deferAction(function () { + this._destroyTileMenu(); + const clocks = this._getClockList(); + if (!ClockActions.isValidIndex(clocks, index)) + return; + if (!ClockActions.canRemove(clocks)) + return; + + const clock = clocks[index]; + const doRemove = () => { + if (this._cleanedUp) + return; + this._setClockList(ClockActions.removeClock(this._getClockList(), clock.id)); + }; + + if (this.confirmRemove && clock.name) { + const prompt = _("Are you sure you want to remove clock \"%s\"?").format(clock.name); + const dialog = new ModalDialog.ConfirmDialog(prompt, doRemove); + this._confirmDialog = dialog; + dialog.open(); + return; + } + + doRemove(); + }); + }, + + /* ------------------------------------------------------------------ * + * Helpers + * ------------------------------------------------------------------ */ + + _getClockList: function () { + if (this._normalizedClocks && this._normalizedClocks.length) + return this._normalizedClocks; + if (!ClockActions) + return []; + const result = ClockActions.normalizeClockList(this.clocks); + this._normalizedClocks = result.clocks; + return this._normalizedClocks; + }, + + _computeGridDims: function () { + if (!ClockActions) + return { rows: 1, cols: 1 }; + const clocks = this._getClockList(); + const showAdd = !!(this.enableEditing && this.showAddTile && ClockActions.canAdd(clocks)); + const cellCount = clocks.length + (showAdd ? 1 : 0); + return ClockActions.computeGridDims(cellCount, this.layoutMode, this.fixedRows, this.fixedCols); + }, + + _computeTileInnerSize: function () { + const dims = this._computeGridDims(); + if (!ClockActions || !ClockActions.computeTileInnerSize) + return { width: 80, height: 80 }; + return ClockActions.computeTileInnerSize( + this.width || 600, this.height || 400, dims.rows, dims.cols, this.tileSpacing); + }, + + _formatWidthSamples: function () { + const timeFormat = this.timeFormat || DEFAULT_TIME_FORMAT; + const dateFormat = this.dateFormat || DEFAULT_DATE_FORMAT; + const dates = [ + new Date(2023, 11, 27, 23, 59, 59), + new Date(2023, 8, 20, 12, 0, 0), + new Date() + ]; + let time = ClockActions && ClockActions.worstTimeSample + ? ClockActions.worstTimeSample(timeFormat) + : "23:59:59"; + let date = ""; + for (let i = 0; i < dates.length; i++) { + try { + const t = _formatStrftime(dates[i], timeFormat, ""); + const d = _formatStrftime(dates[i], dateFormat, ""); + if (String(t).length > time.length) + time = t; + if (String(d).length > date.length) + date = d; + } catch (e) {} + } + for (let i = 0; i < this._clockWidgets.length; i++) { + const widget = this._clockWidgets[i]; + const t = widget._time.get_text(); + const d = widget._date.get_text(); + if (t && t.length > time.length) + time = t; + if (d && d.length > date.length) + date = d; + } + if (!time) + time = "23:59:59"; + if (!date) + date = "Wednesday, 31 December"; + return { time: time, date: date }; + }, + + _scheduleFit: function () { + if (this._fitId) { + Mainloop.source_remove(this._fitId); + this._fitId = null; + } + this._fitId = Mainloop.timeout_add(0, () => { + this._fitId = null; + if (this._cleanedUp) + return false; + this._fitAllTiles(this._tileInner); + if (this._fitRetryId) + Mainloop.source_remove(this._fitRetryId); + this._fitRetryId = Mainloop.timeout_add(80, () => { + this._fitRetryId = null; + if (this._cleanedUp) + return false; + this._fitAllTiles(this._tileInner); + return false; + }); + return false; + }); + }, + + _fitAllTiles: function (inner) { + inner = inner || this._tileInner; + const samples = this._widthSamples || this._formatWidthSamples(); + this._widthSamples = samples; + if (!inner) + return; + for (let i = 0; i < this._clockWidgets.length; i++) + this._clockWidgets[i].applyFittedSizes(inner, samples); + for (let i = 0; i < this._addTiles.length; i++) + this._applyAddTileSize(this._addTiles[i].label, inner); + }, + + _applyAddTileSize: function (label, inner) { + if (!label || !inner || !ClockActions || !ClockActions.computeFittedFontSizes) + return; + const sizes = ClockActions.computeFittedFontSizes(inner.width, inner.height, {}, { + time: Number(this.timeSize) || 40, + date: Number(this.dateSize) || 15, + timezone: Number(this.timezoneSize) || 12 + }); + label.set_style("font-size: " + sizes.add + "pt;"); + }, + + _ensureClockDefaults: function () { + if (!ClockActions) + return; + + let raw = this.clocks; + if (!Array.isArray(raw) || raw.length === 0 || + (raw.length === 1 && raw[0] && raw[0].id === "default")) { + const legacy = this._legacyClockFromMetadata(); + if (legacy) + raw = [legacy]; + } + + const replacedPlaceholder = raw !== this.clocks; + const result = ClockActions.normalizeClockList(raw); + this._normalizedClocks = result.clocks; + if (result.changed || replacedPlaceholder) + this.settings.setValue("clocks", result.clocks); + }, + + _legacyClockFromMetadata: function () { + const legacy = this.metadata || {}; + const hasLegacy = legacy.timeFormat || legacy.dateFormat || legacy.timeSize || + legacy.timezone || legacy.name; + if (!hasLegacy) + return null; + return ClockActions.buildClock({ + name: legacy.name || ClockActions.DEFAULT_CLOCK.name, + timezone: legacy.timezone || ClockActions.DEFAULT_CLOCK.timezone + }, "legacy"); + }, + + _updateHighlight: function () { + try { + for (let i = 0; i < this._clockWidgets.length; i++) { + const widget = this._clockWidgets[i]; + if (widget.data && widget.data.timezone === "local") + widget.actor.add_style_pseudo_class("outlined"); + else + widget.actor.remove_style_pseudo_class("outlined"); + } + } catch (e) { + global.logError(uuid + " highlight update failed: " + e); + } + }, + + _updateClocks: function () { + const now = new Date(); + this._clockWidgets.forEach(function (widget) { + widget.update(now); + }); + }, + + _scheduleUpdate: function () { + if (this._timeout) { + Mainloop.source_remove(this._timeout); + this._timeout = null; + } + this._timeout = Mainloop.timeout_add_seconds(1, this._onTick.bind(this)); + }, + + _onTick: function () { + if (this._cleanedUp) + return false; + try { + this._updateClocks(); + } catch (e) { + global.logError(uuid + " tick failed: " + e); + } + return true; + } +}; + +function main(metadata, deskletId) { + return new MyDesklet(metadata, deskletId); +} diff --git a/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/icon.png b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/icon.png new file mode 100644 index 000000000..5222c90a9 Binary files /dev/null and b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/icon.png differ diff --git a/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/metadata.json b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/metadata.json new file mode 100644 index 000000000..5f5fec04b --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/metadata.json @@ -0,0 +1,8 @@ +{ + "uuid": "cinnamon-world-clock-desklet@curbsoftware", + "name": "World Clock", + "description": "A grid of world clocks with configurable timezones", + "version": "1.0.0", + "prevent-decorations": false, + "max-instances": 1 +} diff --git a/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/po/cinnamon-world-clock-desklet@curbsoftware.pot b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/po/cinnamon-world-clock-desklet@curbsoftware.pot new file mode 100644 index 000000000..b61f8c40e --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/po/cinnamon-world-clock-desklet@curbsoftware.pot @@ -0,0 +1,223 @@ +# WORLD CLOCK +# This file is put in the public domain. +# RobertAlexanderH, 2026 +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: cinnamon-world-clock-desklet@curbsoftware 1.0.0\n" +"Report-Msgid-Bugs-To: https://github.com/linuxmint/cinnamon-spices-desklets/" +"issues\n" +"POT-Creation-Date: 2026-08-25 07:51-0700\n" +"PO-Revision-Date: \n" +"Last-Translator: \n" +"Language-Team: \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#. clockActions.js:497 clockActions.js:502 clockDialog.js:109 +msgid "Clock" +msgstr "" + +#. clockActions.js:513 clockDialog.js:35 +msgid "Local" +msgstr "" + +#. clockActions.js:526 clockDialog.js:42 +msgid "Local (system timezone)" +msgstr "" + +#. clockDialog.js:110 +msgid "Type a name, then pick a timezone from the list." +msgstr "" + +#. clockDialog.js:115 +msgid "Name" +msgstr "" + +#. clockDialog.js:120 +msgid "Clock name" +msgstr "" + +#. clockDialog.js:126 +msgid "Timezone" +msgstr "" + +#. clockDialog.js:131 +msgid "Search city or region" +msgstr "" + +#. clockDialog.js:165 +msgid "Cancel" +msgstr "" + +#. clockDialog.js:170 +msgid "Save" +msgstr "" + +#. clockDialog.js:309 +#, javascript-format +msgid "Selected: %s" +msgstr "" + +#. desklet.js:351 +msgid "World Clocks" +msgstr "" + +#. desklet.js:615 +msgid "Edit…" +msgstr "" + +#. desklet.js:621 +msgid "Remove" +msgstr "" + +#. desklet.js:630 +msgid "Add clock" +msgstr "" + +#. desklet.js:695 +msgid "Add Clock" +msgstr "" + +#. desklet.js:713 +msgid "Edit Clock" +msgstr "" + +#. desklet.js:738 +#, javascript-format +msgid "Are you sure you want to remove clock \"%s\"?" +msgstr "" + +#. metadata.json->name +msgid "World Clock" +msgstr "" + +#. metadata.json->description +msgid "A grid of world clocks with configurable timezones" +msgstr "" + +#. settings-schema.json->layout->description +msgid "Layout" +msgstr "" + +#. settings-schema.json->layout-mode->description +msgid "Grid layout mode" +msgstr "" + +#. settings-schema.json->layout-mode->options +msgid "Auto (near-square)" +msgstr "" + +#. settings-schema.json->layout-mode->options +msgid "Fixed (rows x cols)" +msgstr "" + +#. settings-schema.json->fixed-rows->units +msgid "rows" +msgstr "" + +#. settings-schema.json->fixed-rows->description +msgid "Rows (fixed layout)" +msgstr "" + +#. settings-schema.json->fixed-cols->units +msgid "cols" +msgstr "" + +#. settings-schema.json->fixed-cols->description +msgid "Columns (fixed layout)" +msgstr "" + +#. settings-schema.json->management->description +msgid "Clock management" +msgstr "" + +#. settings-schema.json->enable-clock-editing->description +msgid "Allow adding, removing and editing clocks" +msgstr "" + +#. settings-schema.json->show-add-tile->description +msgid "Show a \"+\" tile to add a clock" +msgstr "" + +#. settings-schema.json->confirm-remove->description +msgid "Confirm before removing a named clock" +msgstr "" + +#. settings-schema.json->display->description +msgid "Display" +msgstr "" + +#. settings-schema.json->time-format->description +msgid "Time format (strftime)" +msgstr "" + +#. settings-schema.json->date-format->description +msgid "Date format (strftime)" +msgstr "" + +#. settings-schema.json->time-size->units +#. settings-schema.json->date-size->units +#. settings-schema.json->timezone-size->units +msgid "pt" +msgstr "" + +#. settings-schema.json->time-size->description +msgid "Maximum time font size" +msgstr "" + +#. settings-schema.json->time-size->tooltip +msgid "Tiles scale down from this size so the time stays inside the cell" +msgstr "" + +#. settings-schema.json->date-size->description +msgid "Maximum date font size" +msgstr "" + +#. settings-schema.json->date-size->tooltip +msgid "Tiles scale down from this size so the date stays inside the cell" +msgstr "" + +#. settings-schema.json->timezone-size->description +msgid "Maximum label font size" +msgstr "" + +#. settings-schema.json->timezone-size->tooltip +msgid "" +"Tiles scale down from this size. Long names ellipsize rather than overflowing" +msgstr "" + +#. settings-schema.json->style->description +msgid "Style" +msgstr "" + +#. settings-schema.json->tile-spacing->units +#. settings-schema.json->width->units +#. settings-schema.json->height->units +msgid "px" +msgstr "" + +#. settings-schema.json->tile-spacing->description +msgid "Tile spacing" +msgstr "" + +#. settings-schema.json->width->description +msgid "Desklet width" +msgstr "" + +#. settings-schema.json->height->description +msgid "Desklet height" +msgstr "" + +#. settings-schema.json->clocks->description +msgid "Clocks" +msgstr "" + +#. settings-schema.json->clocks->tooltip +msgid "" +"Add clocks and search timezones by city or region. You can also add or edit " +"clocks from the desklet tiles." +msgstr "" diff --git a/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/settings-schema.json b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/settings-schema.json new file mode 100644 index 000000000..3437ffeac --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/settings-schema.json @@ -0,0 +1,149 @@ +{ + "layout": { + "type": "header", + "description": "Layout" + }, + "layout-mode": { + "type": "combobox", + "default": "auto", + "description": "Grid layout mode", + "options": { + "Auto (near-square)": "auto", + "Fixed (rows x cols)": "fixed" + } + }, + "fixed-rows": { + "type": "spinbutton", + "default": 2, + "min": 1, + "max": 10, + "step": 1, + "units": "rows", + "description": "Rows (fixed layout)", + "dependency": "layout-mode=fixed" + }, + "fixed-cols": { + "type": "spinbutton", + "default": 2, + "min": 1, + "max": 10, + "step": 1, + "units": "cols", + "description": "Columns (fixed layout)", + "dependency": "layout-mode=fixed" + }, + + "management": { + "type": "header", + "description": "Clock management" + }, + "enable-clock-editing": { + "type": "checkbox", + "default": true, + "description": "Allow adding, removing and editing clocks" + }, + "show-add-tile": { + "type": "checkbox", + "default": true, + "description": "Show a \"+\" tile to add a clock", + "dependency": "enable-clock-editing" + }, + "confirm-remove": { + "type": "checkbox", + "default": true, + "description": "Confirm before removing a named clock", + "dependency": "enable-clock-editing" + }, + + "display": { + "type": "header", + "description": "Display" + }, + "time-format": { + "type": "entry", + "default": "%H:%M:%S", + "description": "Time format (strftime)" + }, + "date-format": { + "type": "entry", + "default": "%A, %e %B", + "description": "Date format (strftime)" + }, + "time-size": { + "type": "spinbutton", + "default": 40, + "min": 6, + "max": 72, + "step": 1, + "units": "pt", + "description": "Maximum time font size", + "tooltip": "Tiles scale down from this size so the time stays inside the cell" + }, + "date-size": { + "type": "spinbutton", + "default": 15, + "min": 6, + "max": 72, + "step": 1, + "units": "pt", + "description": "Maximum date font size", + "tooltip": "Tiles scale down from this size so the date stays inside the cell" + }, + "timezone-size": { + "type": "spinbutton", + "default": 12, + "min": 6, + "max": 72, + "step": 1, + "units": "pt", + "description": "Maximum label font size", + "tooltip": "Tiles scale down from this size. Long names ellipsize rather than overflowing" + }, + + "style": { + "type": "header", + "description": "Style" + }, + "tile-spacing": { + "type": "spinbutton", + "default": 4, + "min": 0, + "max": 24, + "step": 1, + "units": "px", + "description": "Tile spacing" + }, + "width": { + "type": "spinbutton", + "default": 600, + "min": 200, + "max": 2000, + "step": 50, + "units": "px", + "description": "Desklet width" + }, + "height": { + "type": "spinbutton", + "default": 400, + "min": 200, + "max": 2000, + "step": 50, + "units": "px", + "description": "Desklet height" + }, + + "clocks": { + "type": "custom", + "file": "timezoneWidget.py", + "widget": "ClockListEditor", + "description": "Clocks", + "tooltip": "Add clocks and search timezones by city or region. You can also add or edit clocks from the desklet tiles.", + "default": [ + { + "id": "default", + "name": "Local", + "timezone": "local" + } + ] + } +} diff --git a/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/stylesheet.css b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/stylesheet.css new file mode 100644 index 000000000..8d5726b4e --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/stylesheet.css @@ -0,0 +1,142 @@ +.world-clock-container { + padding: 6px; + border-radius: 10px; + background-color: rgba(0, 0, 0, 0.35); +} + +.world-clock-grid { + /* St.Table doesn't support CSS spacing directly; spacing handled via button margins */ +} + +/* Tile chrome is deliberately dark-backed so the white text stays readable + * on light wallpapers and light Cinnamon themes. */ +.world-clock-tile { + background-color: rgba(0, 0, 0, 0.25); + border: 1px solid rgba(255, 255, 255, 0.25); + border-radius: 8px; + padding: 4px 6px; + transition-duration: 150ms; + transition-property: background-color, border-color, box-shadow; + color: white; +} + +.world-clock-tile:hover { + background-color: rgba(0, 0, 0, 0.32); + border-color: rgba(255, 255, 255, 0.28); +} + +.world-clock-tile:focus { + background-color: rgba(0, 0, 0, 0.38); + border-color: rgba(255, 255, 255, 0.34); + box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.15) inset; +} + +.world-clock-tile:outlined { + border-width: 2px; + border-color: #4aa3ff; + box-shadow: 0 0 0 1px rgba(74, 163, 255, 0.35) inset, 0 0 0 2px rgba(74, 163, 255, 0.15); + background-color: rgba(74, 163, 255, 0.10); +} + +.world-clock-add-tile { + background-color: rgba(0, 0, 0, 0.20); + border: 1px dashed rgba(255, 255, 255, 0.30); + border-radius: 8px; + padding: 4px 6px; + transition-duration: 150ms; + transition-property: background-color, border-color; + color: white; +} + +.world-clock-add-tile:hover { + background-color: rgba(0, 0, 0, 0.30); + border-color: rgba(255, 255, 255, 0.45); +} + +.world-clock-add-tile:focus { + background-color: rgba(0, 0, 0, 0.35); + border-color: rgba(255, 255, 255, 0.50); +} + +.world-clock-add-label { + color: inherit; + font-size: 16pt; + font-weight: 600; + text-align: center; + padding: 0; +} + +.world-clock-time { + font-weight: bold; + text-align: center; + color: inherit; +} + +.world-clock-date { + margin-top: 2px; + text-align: center; + color: inherit; +} + +.world-clock-timezone { + color: #ccc; + font-style: italic; + margin-top: 2px; + text-align: center; +} + +.world-clock-dialog-row { + padding: 4px 0; +} + +.world-clock-dialog-label { + padding: 8px 0 2px 0; + font-weight: 600; +} + +.world-clock-dialog-entry { + min-width: 260px; + padding: 6px 8px; +} + +.world-clock-tz-list { + min-width: 360px; + max-height: 240px; + min-height: 180px; + padding: 4px 0; +} + +.world-clock-tz-box { + spacing: 2px; +} + +/* Dialog items inherit the theme's dialog text colour so they stay readable + * on both light and dark ModalDialog chrome. */ +.world-clock-tz-item { + padding: 5px 8px; + border-radius: 4px; + text-align: left; +} + +.world-clock-tz-item:hover { + background-color: rgba(128, 128, 128, 0.18); +} + +.world-clock-tz-item:outlined { + background-color: rgba(74, 163, 255, 0.22); + border-color: #4aa3ff; +} + +.world-clock-tz-selected { + padding: 4px 2px 0 2px; + font-size: 9pt; +} + +@media (max-width: 240px), (max-height: 160px) { + .world-clock-tile { + border-radius: 6px; + } + .world-clock-time { + font-weight: 600; + } +} diff --git a/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/timezoneWidget.py b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/timezoneWidget.py new file mode 100644 index 000000000..ee0ec88dc --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/files/cinnamon-world-clock-desklet@curbsoftware/timezoneWidget.py @@ -0,0 +1,499 @@ +#!/usr/bin/python3 +"""Filterable timezone widgets for the World Clock desklet settings.""" + +import os +import uuid as uuidlib + +import gi +gi.require_version("Gtk", "3.0") +from gi.repository import Gtk, GLib + +from xapp.SettingsWidgets import SettingsWidget, SettingsLabel + +FALLBACK_ZONES = [ + "UTC", + "America/New_York", + "America/Chicago", + "America/Denver", + "America/Los_Angeles", + "America/Anchorage", + "America/Honolulu", + "America/Toronto", + "America/Mexico_City", + "America/Sao_Paulo", + "America/Argentina/Buenos_Aires", + "Europe/London", + "Europe/Paris", + "Europe/Berlin", + "Europe/Madrid", + "Europe/Rome", + "Europe/Moscow", + "Africa/Cairo", + "Africa/Johannesburg", + "Asia/Dubai", + "Asia/Kolkata", + "Asia/Shanghai", + "Asia/Singapore", + "Asia/Tokyo", + "Asia/Seoul", + "Australia/Sydney", + "Pacific/Auckland", +] + +MIN_CLOCKS = 1 +MAX_CLOCKS = 36 +LOCAL_ID = "local" + + +def _display_name(tz): + if not tz or tz == LOCAL_ID: + return "Local" + parts = str(tz).split("/") + return parts[-1].replace("_", " ") + + +def timezone_label(tz, empty_label="Local (system timezone)"): + if not tz or tz == LOCAL_ID: + return empty_label + pretty = _display_name(tz) + if pretty == tz: + return tz + return "%s (%s)" % (pretty, tz) + + +def list_iana_timezones(): + zones = [] + try: + from zoneinfo import available_timezones + zones = [ + z for z in available_timezones() + if z and z not in ("localtime",) + and not z.startswith("SystemV/") + and not z.startswith("Etc/") + ] + except Exception: + zones = [] + + if not zones: + zone_tab = "/usr/share/zoneinfo/zone.tab" + if os.path.isfile(zone_tab): + try: + with open(zone_tab, "r", encoding="utf-8", errors="replace") as handle: + for line in handle: + line = line.strip() + if not line or line.startswith("#"): + continue + parts = line.split("\t") + if len(parts) >= 3: + zones.append(parts[2]) + except OSError: + zones = [] + + if not zones: + zones = list(FALLBACK_ZONES) + + seen = set() + out = [] + for zone in sorted(zones): + if zone in seen: + continue + seen.add(zone) + out.append(zone) + if "UTC" not in seen: + out.insert(0, "UTC") + return out + + +def filter_timezones(zones, query): + if not query: + return list(zones) + q = query.strip().lower() + if not q: + return list(zones) + hits = [] + for tz in zones: + blob = " ".join([ + str(tz), + str(tz).replace("_", " "), + _display_name(tz), + timezone_label(tz), + ]).lower() + if q in blob: + hits.append(tz) + return hits + + +def _normalize_tz(tz, empty_value=LOCAL_ID): + if tz is None: + return empty_value + value = str(tz).strip() + if not value or value.lower() == "local": + return empty_value + return value + + +class _TimezonePicker(Gtk.Box): + """Standalone searchable timezone list used by chooser and clock editor.""" + + def __init__(self, empty_value=LOCAL_ID, empty_label="Local (system timezone)"): + super(_TimezonePicker, self).__init__(orientation=Gtk.Orientation.VERTICAL, spacing=6) + self.empty_value = empty_value + self.empty_label = empty_label + self._zones = [empty_value] + list_iana_timezones() + self._updating = False + self.timezone = empty_value + + self.search = Gtk.SearchEntry() + self.search.set_placeholder_text("Search city or region") + self.search.connect("search-changed", self._on_query_changed) + self.search.connect("activate", self._on_search_activate) + self.pack_start(self.search, False, False, 0) + + self.store = Gtk.ListStore(str, str) + self.tree = Gtk.TreeView(model=self.store) + self.tree.set_headers_visible(False) + self.tree.set_search_column(-1) + renderer = Gtk.CellRendererText() + column = Gtk.TreeViewColumn("Timezone", renderer, text=1) + self.tree.append_column(column) + self.tree.get_selection().connect("changed", self._on_selection_changed) + + scroll = Gtk.ScrolledWindow() + scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + scroll.set_min_content_height(180) + scroll.set_shadow_type(Gtk.ShadowType.IN) + scroll.add(self.tree) + self.pack_start(scroll, True, True, 0) + + self.selected = Gtk.Label(xalign=0) + self.selected.set_line_wrap(True) + self.selected.get_style_context().add_class("dim-label") + self.pack_start(self.selected, False, False, 0) + + self._rebuild_list("") + self.set_timezone(empty_value, notify=False) + + def _visible_zones(self, query): + rest = [z for z in self._zones if z != self.empty_value] + return [self.empty_value] + filter_timezones(rest, query) + + def _rebuild_list(self, query): + self._updating = True + try: + self.store.clear() + for tz in self._visible_zones(query): + self.store.append([tz, timezone_label(tz, self.empty_label)]) + finally: + self._updating = False + + def _on_query_changed(self, *args): + current = self.timezone + self._rebuild_list(self.search.get_text()) + self.set_timezone(current, notify=False) + + def _on_search_activate(self, *args): + if len(self.store) > 0: + tz = self.store[0][0] + self.set_timezone(tz, notify=True) + + def _on_selection_changed(self, selection): + if self._updating: + return + model, row = selection.get_selected() + if row is None: + return + self.set_timezone(model[row][0], notify=True) + + def set_timezone(self, tz, notify=True): + tz = _normalize_tz(tz, self.empty_value) + self.timezone = tz + self._updating = True + try: + found = False + for i, row in enumerate(self.store): + if row[0] == tz: + self.tree.get_selection().select_iter(row.iter) + self.tree.scroll_to_cell(Gtk.TreePath.new_from_indices([i])) + found = True + break + if not found: + self.store.prepend([tz, timezone_label(tz, self.empty_label)]) + self.tree.get_selection().select_iter(self.store.get_iter_first()) + finally: + self._updating = False + self.selected.set_text("Selected: %s" % timezone_label(tz, self.empty_label)) + + + +class TimezoneChooser(SettingsWidget): + bind_dir = None + + def __init__(self, info, key, settings): + super(TimezoneChooser, self).__init__() + self.set_orientation(Gtk.Orientation.VERTICAL) + self.set_spacing(8) + self.fill_row() + + self.settings = settings + self.key = key + self._saving = False + empty_value = info.get("empty-value", LOCAL_ID) + empty_label = info.get("empty-label", "Local (system timezone)") + + header = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12) + self.label = SettingsLabel(info.get("description", "Timezone")) + header.pack_start(self.label, False, False, 0) + self.pack_start(header, False, False, 0) + + self.picker = _TimezonePicker(empty_value=empty_value, empty_label=empty_label) + self.picker.search.connect("search-changed", lambda *a: None) + self.pack_start(self.picker, True, True, 0) + + if info.get("tooltip"): + self.set_tooltip_text(info["tooltip"]) + + self.picker.tree.get_selection().connect("changed", self._on_picked) + try: + self.settings.listen(self.key, self._on_setting) + except Exception: + pass + self._load_from_settings() + + def _on_setting(self, *args): + if self._saving: + return + self._load_from_settings() + + def _load_from_settings(self): + try: + value = self.settings.get_value(self.key) + except Exception: + value = LOCAL_ID + self.picker.set_timezone(value, notify=False) + + def _on_picked(self, *args): + tz = self.picker.timezone + try: + current = self.settings.get_value(self.key) + except Exception: + current = None + if tz == current: + return + self._saving = True + try: + self.settings.set_value(self.key, tz) + finally: + GLib.idle_add(self._clear_saving) + + def _clear_saving(self): + self._saving = False + return False + + +class ClockListEditor(SettingsWidget): + """Editable clock list with a filterable timezone search on add/edit.""" + + bind_dir = None + + def __init__(self, info, key, settings): + super(ClockListEditor, self).__init__() + self.set_orientation(Gtk.Orientation.VERTICAL) + self.set_spacing(8) + self.fill_row() + + self.settings = settings + self.key = key + self._saving = False + + self.label = SettingsLabel(info.get("description", "Clocks")) + self.pack_start(self.label, False, False, 0) + + self.store = Gtk.ListStore(str, str, str) + self.tree = Gtk.TreeView(model=self.store) + self.tree.set_headers_visible(True) + self.tree.append_column(Gtk.TreeViewColumn("Name", Gtk.CellRendererText(), text=1)) + self.tree.append_column(Gtk.TreeViewColumn("Timezone", Gtk.CellRendererText(), text=2)) + self.tree.connect("row-activated", lambda *a: self._edit_item()) + + scroll = Gtk.ScrolledWindow() + scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) + scroll.set_min_content_height(160) + scroll.set_shadow_type(Gtk.ShadowType.IN) + scroll.add(self.tree) + self.pack_start(scroll, True, True, 0) + + buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6) + self.add_btn = Gtk.Button.new_with_label("Add") + self.edit_btn = Gtk.Button.new_with_label("Edit") + self.remove_btn = Gtk.Button.new_with_label("Remove") + self.add_btn.connect("clicked", lambda *a: self._add_item()) + self.edit_btn.connect("clicked", lambda *a: self._edit_item()) + self.remove_btn.connect("clicked", lambda *a: self._remove_item()) + buttons.pack_start(self.add_btn, False, False, 0) + buttons.pack_start(self.edit_btn, False, False, 0) + buttons.pack_start(self.remove_btn, False, False, 0) + self.pack_start(buttons, False, False, 0) + + hint = Gtk.Label(xalign=0) + hint.set_line_wrap(True) + hint.get_style_context().add_class("dim-label") + hint.set_text("Add or edit a clock, then search the timezone list by city or region.") + self.pack_start(hint, False, False, 0) + + if info.get("tooltip"): + self.set_tooltip_text(info["tooltip"]) + + self.tree.get_selection().connect("changed", self._update_buttons) + try: + self.settings.listen(self.key, self._on_setting) + except Exception: + pass + self._load_from_settings() + self._update_buttons() + + def _on_setting(self, *args): + if self._saving: + return + self._load_from_settings() + + def _clocks(self): + try: + value = self.settings.get_value(self.key) + except Exception: + value = [] + if not isinstance(value, list): + return [] + clocks = [] + for item in value: + if not isinstance(item, dict): + continue + clocks.append({ + "id": str(item.get("id") or uuidlib.uuid4()), + "name": str(item.get("name") or "").strip(), + "timezone": _normalize_tz(item.get("timezone")), + }) + if not clocks: + clocks = [{"id": str(uuidlib.uuid4()), "name": "Local", "timezone": LOCAL_ID}] + return clocks + + def _load_from_settings(self): + self.store.clear() + for clock in self._clocks(): + self.store.append([ + clock["id"], + clock["name"] or _display_name(clock["timezone"]), + timezone_label(clock["timezone"]), + ]) + self._update_buttons() + + def _write(self, clocks): + self._saving = True + try: + self.settings.set_value(self.key, clocks) + finally: + GLib.idle_add(self._clear_saving) + self._load_from_settings() + + def _clear_saving(self): + self._saving = False + return False + + def _selected_id(self): + model, row = self.tree.get_selection().get_selected() + if row is None: + return None + return model[row][0] + + def _update_buttons(self, *args): + n = len(self.store) + has = self._selected_id() is not None + self.add_btn.set_sensitive(n < MAX_CLOCKS) + self.edit_btn.set_sensitive(has) + self.remove_btn.set_sensitive(has and n > MIN_CLOCKS) + + def _prompt_clock(self, title, initial): + dialog = Gtk.Dialog(title=title, transient_for=self.get_toplevel()) + dialog.set_modal(True) + dialog.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL) + dialog.add_button(Gtk.STOCK_OK, Gtk.ResponseType.OK) + dialog.set_default_size(420, 420) + box = dialog.get_content_area() + box.set_spacing(8) + box.set_margin_top(12) + box.set_margin_bottom(12) + box.set_margin_left(12) + box.set_margin_right(12) + + name_label = Gtk.Label(label="Name", xalign=0) + name_entry = Gtk.Entry() + name_entry.set_placeholder_text("Clock name") + name_entry.set_text(initial.get("name") or "") + box.pack_start(name_label, False, False, 0) + box.pack_start(name_entry, False, False, 0) + + tz_label = Gtk.Label(label="Timezone", xalign=0) + picker = _TimezonePicker() + picker.set_timezone(initial.get("timezone") or LOCAL_ID, notify=False) + box.pack_start(tz_label, False, False, 0) + box.pack_start(picker, True, True, 0) + + box.show_all() + response = dialog.run() + name = name_entry.get_text().strip() + timezone = picker.timezone + dialog.destroy() + if response != Gtk.ResponseType.OK: + return None + if not name: + name = _display_name(timezone) + return {"name": name, "timezone": timezone} + + def _add_item(self): + clocks = self._clocks() + if len(clocks) >= MAX_CLOCKS: + return + result = self._prompt_clock("Add Clock", {"name": "", "timezone": LOCAL_ID}) + if not result: + return + clocks.append({ + "id": str(uuidlib.uuid4()), + "name": result["name"], + "timezone": result["timezone"], + }) + self._write(clocks) + + def _edit_item(self): + clock_id = self._selected_id() + if not clock_id: + return + clocks = self._clocks() + current = None + for clock in clocks: + if clock["id"] == clock_id: + current = clock + break + if not current: + return + result = self._prompt_clock("Edit Clock", current) + if not result: + return + next_clocks = [] + for clock in clocks: + if clock["id"] == clock_id: + next_clocks.append({ + "id": clock_id, + "name": result["name"], + "timezone": result["timezone"], + }) + else: + next_clocks.append(clock) + self._write(next_clocks) + + def _remove_item(self): + clock_id = self._selected_id() + if not clock_id: + return + clocks = [c for c in self._clocks() if c["id"] != clock_id] + if len(clocks) < MIN_CLOCKS: + return + self._write(clocks) diff --git a/cinnamon-world-clock-desklet@curbsoftware/info.json b/cinnamon-world-clock-desklet@curbsoftware/info.json new file mode 100644 index 000000000..530cf3154 --- /dev/null +++ b/cinnamon-world-clock-desklet@curbsoftware/info.json @@ -0,0 +1 @@ +{ "author": "RobertAlexanderH" } diff --git a/cinnamon-world-clock-desklet@curbsoftware/screenshot.png b/cinnamon-world-clock-desklet@curbsoftware/screenshot.png new file mode 100644 index 000000000..d73a5f672 Binary files /dev/null and b/cinnamon-world-clock-desklet@curbsoftware/screenshot.png differ diff --git a/cinnamon-world-clock-desklet@curbsoftware/screenshots/world-clock-config.webp b/cinnamon-world-clock-desklet@curbsoftware/screenshots/world-clock-config.webp new file mode 100644 index 000000000..b6a31a595 Binary files /dev/null and b/cinnamon-world-clock-desklet@curbsoftware/screenshots/world-clock-config.webp differ diff --git a/cinnamon-world-clock-desklet@curbsoftware/screenshots/world-clock-desklet.webp b/cinnamon-world-clock-desklet@curbsoftware/screenshots/world-clock-desklet.webp new file mode 100644 index 000000000..5782a1692 Binary files /dev/null and b/cinnamon-world-clock-desklet@curbsoftware/screenshots/world-clock-desklet.webp differ