Compare commits

..
459 Commits
Author SHA1 Message Date
aclist 5ba6b6c040 Merge pull request #295 from aclist/fix/lan-server
Mirror to Codeberg / mirror-to-codeberg (push) Has been cancelled
fix: break out of loop when sek out of loop on first server
2026-05-20 00:36:58 +09:00
aclist d3b9ba031d Merge branch 'fix/lan-server' of github.com:aclist/dztui into fix/lan-server 2026-05-20 00:35:49 +09:00
aclist 8bfcb6c8fe fix: break out of loop when scanning LAN 2026-05-20 00:35:35 +09:00
aclist 353b10ebfc fix: break out of loop when sek out of loop on first server 2026-05-20 00:25:10 +09:00
aclist 698150645d Merge pull request #290 from aclist/feat/airgapped-installer
feat: airgapped installer
2026-05-20 00:09:31 +09:00
aclist 87f347870f chore: clean up try/except block
Mirror to Codeberg / mirror-to-codeberg (push) Has been cancelled
2026-05-19 23:41:51 +09:00
aclist 74bf4b5cfc se str, not Path
Mirror to Codeberg / mirror-to-codeberg (push) Waiting to run
2026-05-19 18:35:47 +09:00
aclist 896799f904 chore: update string 2026-05-19 18:34:35 +09:00
aclist 0f591e658c fix: call proper workshop method 2026-05-19 18:31:59 +09:00
aclist f9083b33ef fix: change lan panel tate on map/unmap 2026-05-19 18:28:45 +09:00
aclist 89fcfcb5d6 fix: use hostname.local 2026-05-19 18:26:09 +09:00
aclist fc7f1d7815 chore: update build script paths 2026-05-19 18:25:29 +09:00
aclist fb36425083 chore: bump version 2026-05-19 06:23:53 +09:00
aclist c5d8afbc4d chore: build dependencies into distribution tarball 2026-05-19 06:08:55 +09:00
aclist 17f732fafe feat: continue to main app after config wizard closes 2026-05-19 06:05:22 +09:00
aclist 676a7ea9eb fix: notes file may not be present 2026-05-19 06:04:45 +09:00
aclist d3f64c1ba5 chore: trigger backup workflow
Mirror to Codeberg / mirror-to-codeberg (push) Waiting to run
2026-05-18 22:05:46 +09:00
aclist 5da3397a29 Merge branch 'dzgui7' of github.com:aclist/dztui into dzgui7 2026-05-18 22:03:02 +09:00
aclist eca6df90d4 chore: add .github directory 2026-05-18 22:02:16 +09:00
aclist 2d58df1c89 Merge pull request #288 from aclist/feat/manage-updates
feat: manage updates
2026-05-18 21:46:47 +09:00
aclist de4521a366 chore: use string file 2026-05-18 21:45:08 +09:00
aclist fe9f488e10 fix: source metadata directly from wheel 2026-05-18 21:19:18 +09:00
aclist 7b5d99c34b feat: print version number when loading 2026-05-18 21:18:54 +09:00
aclist 0a84c20d1d fix: explicitly set arcname in tarball 2026-05-18 20:48:23 +09:00
aclist d5309c1ddf chore: include version number in tarball 2026-05-18 20:37:42 +09:00
aclist 418c0f026d chore: restore ALLOW_UPDATES flag 2026-05-18 20:30:02 +09:00
aclist af3a9cfa77 docs: update changelog 2026-05-18 20:25:31 +09:00
aclist 1b20969c30 chore: clear typehinting errors 2026-05-18 20:24:59 +09:00
aclist 7f1125432e chore: bump version 2026-05-18 20:12:20 +09:00
aclist c063059c19 feat: auto update 2026-05-18 20:11:51 +09:00
aclist 80c58be3be chore: update changelog 2026-05-18 05:07:46 +09:00
aclist 821f983f57 feat: package tarball in script 2026-05-18 04:49:05 +09:00
aclist c5edeb163d fix: disable overlay scrolling 2026-05-18 04:36:51 +09:00
aclist 4f722c4655 Merge pull request #35 from aclist/fix/lc-all
fix: LC_ALL handling
2026-05-18 00:23:37 +09:00
aclist 83629c7c8e chore: add return type annotation 2026-05-18 00:23:13 +09:00
aclist 59bde45949 fix: LC_ALL handling 2026-05-18 00:22:18 +09:00
aclist 9b80c98273 Merge pull request #34 from aclist/chore/build-tools
chore: add build scripts
2026-05-17 23:00:00 +09:00
aclist 8a505fbf88 Merge pull request #33 from aclist/feat/setup-wizard
feat: setup wizard
2026-05-17 22:59:38 +09:00
aclist 9b2b26433e chore: drop comment 2026-05-17 22:56:13 +09:00
aclist 13bd36cec6 fix: rearrange preferences box elements 2026-05-17 22:54:03 +09:00
aclist eb1b93843b chore: update docs 2026-05-17 22:38:02 +09:00
aclist a9749e2ebc chore: update submodule checksum 2026-05-17 19:56:17 +09:00
aclist fdb9742fee chore: update buildscript 2026-05-17 19:47:19 +09:00
aclist 180ff8fc47 chore: add build scripts 2026-05-17 19:19:34 +09:00
aclist 25e2e7e20e chore: update build setup 2026-05-17 19:18:39 +09:00
aclist 4841c9e04b chore: add mypy exclusion 2026-05-17 15:54:42 +09:00
aclist 5ef4085922 chore: conform to PEP 440 versioning 2026-05-17 15:51:27 +09:00
aclist 867c47a4eb chore: remove typo 2026-05-17 05:53:28 +09:00
aclist 446d4db290 chore: update file migration logic 2026-05-17 04:54:14 +09:00
aclist 0a6bd831bd feat: static releases button 2026-05-17 04:39:48 +09:00
aclist 59a84e9e3a chore: additional error handling 2026-05-17 04:21:50 +09:00
aclist 5e2d3d1a88 chore: drop unused files 2026-05-17 04:03:23 +09:00
aclist 1b4210dcf5 chore: clear typehinting errors 2026-05-17 03:57:42 +09:00
aclist ea2d1d7e9f feat: write settings to config file 2026-05-17 03:56:15 +09:00
aclist a77697eec0 chore: clear typehinting errors 2026-05-17 03:02:08 +09:00
aclist 07ea73ef2e feat: setup wizard (WIP) 2026-05-17 03:00:12 +09:00
aclist f0e51fa758 chore: bump version 2026-05-16 21:31:22 +09:00
aclist 4a2f8a1073 Merge pull request #31 from aclist/feat/server-threading
feat: server threading
2026-05-16 21:30:07 +09:00
aclist da004c6ab4 fix: add row to history before model is initialized 2026-05-16 21:28:10 +09:00
aclist c4160bbbd8 fix: zero-pad revision number 2026-05-16 20:49:43 +09:00
aclist 08b62e1cfd chore: add boilerplate 2026-05-16 20:11:11 +09:00
aclist 5bb4ab688e feat: capture sigint events in server loops 2026-05-16 20:11:02 +09:00
aclist 73d66ab5e7 fix: support empty lists in extend() 2026-05-16 20:10:26 +09:00
aclist 3befb1276c chore: add return type annotation 2026-05-16 02:08:39 +09:00
aclist b2180c6a5b fix: do not iterater treepaths in worker thread 2026-05-16 02:07:27 +09:00
aclist fa759f4714 chore: clean up server threading 2026-05-16 01:55:41 +09:00
aclist ef459c2fd1 fix: do not swap list store in worker thread 2026-05-16 01:55:18 +09:00
aclist a3875789c1 chore: clear typehinting errors 2026-05-16 00:39:02 +09:00
aclist 8fc7aa5165 fix: rewrite tests 2026-05-15 23:34:43 +09:00
aclist 156c1f8ec4 chore: clear typehinting errors 2026-05-15 23:26:47 +09:00
aclist 2d265c4b9b chore: clear typehinting errors 2026-05-15 19:53:00 +09:00
aclist cacfab35bf chore: boilerplate 2026-05-15 18:57:16 +09:00
aclist 796e4c5de6 fix: cast data types correctly 2026-05-14 17:23:23 +09:00
aclist f77d36ea44 change: convert TreeModelRow to tuple directly 2026-05-14 16:48:16 +09:00
aclist aa6b94905a chore: raise error on Nonetype model 2026-05-14 16:44:37 +09:00
aclist 88c4758c6b chore: use explicit button vars 2026-05-14 16:24:33 +09:00
aclist 2ebe8cad84 chore: clear typehinting errors 2026-05-14 16:15:22 +09:00
aclist ea1b9facd2 fix: add missing import 2026-05-13 20:49:23 +09:00
aclist fb62fe285d change: use Gtk.present_window_with_time() 2026-05-13 20:48:50 +09:00
aclist 866c88fbb0 chore: clear typehinting errors 2026-05-13 20:13:06 +09:00
aclist fe0a6711f0 docs: developers boilerplate 2026-05-13 19:28:36 +09:00
aclist add93a6b0a chore: add strings files 2026-05-13 19:27:56 +09:00
aclist f8e62d05a8 change: use ListStore for combos 2026-05-13 18:28:14 +09:00
aclist 3857b69b70 fix: interpolate client args 2026-05-13 18:28:00 +09:00
aclist 5e0e6e4592 chore: update options page strings 2026-05-13 18:12:31 +09:00
aclist c5a0050004 chore: update strings 2026-05-13 18:00:35 +09:00
aclist cf913eff1b chore: boilerplate 2026-05-13 08:06:12 +09:00
aclist 67eff054a3 chore: drop old dialog 2026-05-13 08:04:10 +09:00
aclist 31ad575f97 chore: update gitignore 2026-05-12 21:06:51 +09:00
aclist 9989b8a880 chore: add strings files 2026-05-12 21:06:35 +09:00
aclist ede750a8d4 fix: namespace collision 2026-05-12 18:37:53 +09:00
aclist a754203d10 Merge branch 'feat/server-threading' of github.com:aclist/dzgui-devel into feat/server-threading 2026-05-12 18:36:36 +09:00
aclist 897186faa0 chore: clear typehinting errors 2026-05-12 18:36:25 +09:00
aclist e52664cf9b chore: clear typehinting errors 2026-05-12 15:58:09 +09:00
aclist f7fe62e661 feat: update history on connect 2026-05-11 21:56:21 +09:00
aclist cdcd38c326 chore: update comments 2026-05-11 18:58:15 +09:00
aclist e298703471 fix: grab tree 2026-05-11 18:58:00 +09:00
aclist bc4fc8005d fix: abort on empty model 2026-05-11 18:57:36 +09:00
aclist 2e5860650f feat: catch cancel and shutdown events 2026-05-11 00:52:48 +09:00
aclist 319966f8e1 chore: clear typehinting errors 2026-05-11 00:51:58 +09:00
aclist 4b291c8cd0 chore: add psutil typing stubs 2026-05-11 00:51:26 +09:00
aclist a1e2876251 fix: update ok label text if no missing mods 2026-05-10 01:26:18 +09:00
aclist fb5397ae91 feat: wait for DayZ process 2026-05-10 01:15:57 +09:00
aclist ff0ced1c33 fix: cast int to str 2026-05-10 00:24:17 +09:00
aclist ed8e79455b feat: concatenate launch parameters 2026-05-09 23:53:14 +09:00
aclist 1268c388b0 feat: version update logic 2026-05-09 22:46:41 +09:00
aclist 6e320763c9 fix: restore missing argument 2026-05-09 21:49:39 +09:00
aclist 7dde9dc0ce chore: restore dropped check 2026-05-09 21:48:22 +09:00
aclist 65df40ee5d chore: update preconnect strings 2026-05-09 21:45:20 +09:00
aclist 6e29a716a5 chore: clear typehinting errors 2026-05-09 20:09:26 +09:00
aclist b51b858e05 fix: typo in error message 2026-05-09 20:02:33 +09:00
aclist 3a22ad630a feat: block connection if client is absent or not running 2026-05-09 20:00:31 +09:00
aclist 77c641327f chore: simplify process checking logic 2026-05-09 19:59:40 +09:00
aclist 7c62aed6b0 feat: get client name via controller 2026-05-09 19:58:59 +09:00
aclist ddf976734d chore: update env var in documentation 2026-05-09 19:58:40 +09:00
aclist a67bbd66f9 chore: remove boilerplate 2026-05-08 11:45:08 +09:00
aclist a0f5d3ea23 fix: grab focus on tree 2026-05-08 11:44:56 +09:00
aclist b2cec8cbdf fix: apply float format func to correct column 2026-05-08 11:44:38 +09:00
aclist c0708b9358 feat: foreground window (WIP) 2026-05-07 22:08:55 +09:00
aclist 2b10fcaaad feat: raise window (WIP) 2026-05-07 16:09:41 +09:00
aclist 90a1740bf0 fix: use MenuShell signal 2026-05-07 07:26:08 +09:00
aclist 9fdb54b65a chore: update changelog 2026-05-07 07:02:53 +09:00
aclist d3e82fc4b1 chore: add boilerplate 2026-05-07 07:00:01 +09:00
aclist fbbf0d9e66 feat: mod enqueue logic (WIP) 2026-05-07 06:30:33 +09:00
aclist 0e6caed64d chore: update warning messages in preconnect dialog 2026-05-07 02:56:38 +09:00
aclist e2022fdee7 feat: preconnect dialog warnings (WIP) 2026-05-07 02:47:42 +09:00
aclist 7523bffbd8 change: simplify routes between query API 2026-05-07 00:19:01 +09:00
aclist a9863ff86b feat: MaskedTree (WIP) 2026-05-06 05:38:29 +09:00
aclist b42aea1e02 feat: preconnect dialog (WIP) 2026-05-06 02:09:40 +09:00
aclist 25640751a5 chore: clear typehinting errors 2026-05-05 23:37:31 +09:00
aclist e64feac425 chore: clear errors 2026-05-05 22:46:16 +09:00
aclist f3ad104b1b chore: additional string files 2026-05-05 22:24:31 +09:00
aclist 5f8795acf7 feat: preconnect dialog fields (WIP) 2026-05-05 21:40:04 +09:00
aclist dcbc1fa716 feat: add CSS file 2026-05-05 21:39:35 +09:00
aclist 52917e7631 change: shorter name field 2026-05-05 19:07:14 +09:00
aclist 73d131a64b feat: set start tab 2026-05-05 18:31:50 +09:00
aclist ce44d67bf6 chore: add comments 2026-05-04 07:35:13 +09:00
aclist 04e0b7ae55 fix: hide popover after initial render 2026-05-04 07:34:57 +09:00
aclist 9bc94f7587 fix: typo in string 2026-05-04 07:34:23 +09:00
aclist 2e5630034a chore: update changelog 2026-05-04 07:33:45 +09:00
aclist 47f8ae2db7 fix: emit signal outside of thread 2026-05-04 07:33:07 +09:00
aclist eecbde24d8 fix: abort distcalc if tab is not loaded 2026-05-04 06:11:11 +09:00
aclist e319c01d58 feat: connection dialog (WIP) 2026-05-04 06:01:19 +09:00
aclist 29082ea1c1 change: consolidate query methods 2026-05-04 04:52:07 +09:00
aclist e3e507598b feat: connection dialog (WIP) 2026-05-04 02:44:16 +09:00
aclist a5c562f022 chore: placeholder logic 2026-05-04 02:04:34 +09:00
aclist 2dbdc3f928 feat: HeadingFrame class 2026-05-04 01:43:41 +09:00
aclist 2c07b8f3f2 fix: do not literally casefold row element 2026-05-04 01:19:04 +09:00
aclist 33fbf765ed feat: preconnection assistant (WIP) 2026-05-04 01:18:09 +09:00
aclist 139b226959 chore: drop unused code 2026-05-03 02:42:43 +09:00
aclist 9bfa39c17e chore: clear typehinting errors 2026-05-03 02:14:08 +09:00
aclist 99083d207a chore: add standalone strings file 2026-05-02 21:16:06 +09:00
aclist 9c821e62ee fix: handle no favorite server 2026-05-02 21:11:45 +09:00
aclist 8bcb64810d feat: casefold mod names before sorting 2026-05-02 20:29:52 +09:00
aclist 5757f79755 chore: clear typehinting errors 2026-05-02 20:01:57 +09:00
aclist 806e05977d chore: clear typehinting errors 2026-05-02 00:14:37 +09:00
aclist 11356547bf chore: clear typehinting errors 2026-05-02 00:01:58 +09:00
aclist 5005f6923e chore: connection logic placeholders 2026-05-02 00:00:43 +09:00
aclist 676f2ac12f chore: suppress branch switching behavior (WIP) 2026-05-01 23:59:57 +09:00
aclist 7139686d9b chore: store filter levels as constant 2026-05-01 23:59:27 +09:00
aclist 0aafe44b4e feat: set exit event on SIGINT 2026-05-01 22:54:20 +09:00
aclist 90f818f462 chore: drop StoredFunc logic from main controller 2026-05-01 22:35:24 +09:00
aclist 7bf0fde3fc fix: block malformed records on config import 2026-05-01 21:56:22 +09:00
aclist 29aeb550b3 chore: consolidate is_in_favs() methods 2026-05-01 21:46:13 +09:00
aclist eb4ee41742 chore: simplify controller logic 2026-05-01 21:01:28 +09:00
aclist 7a9f0dc096 chore: use statusbar internal methods 2026-05-01 20:45:22 +09:00
aclist 63d85b03c1 change: drop statusbar alerts button 2026-05-01 20:37:24 +09:00
aclist 8ec9e5abff change: drop debug key 2026-05-01 20:32:22 +09:00
aclist e6d3775fd0 chore: partially drop Union typehint 2026-05-01 20:31:49 +09:00
aclist 51ccdf7caa feat: version tooltip 2026-04-30 18:49:10 +09:00
aclist b8ed0723e1 feat: add ModManager file 2026-04-30 18:48:50 +09:00
aclist 34d8545c94 fix: handle zero mods 2026-04-30 01:06:20 +09:00
aclist 0fad9155e2 chore: drop unused imports 2026-04-30 00:49:47 +09:00
aclist 343e402403 fix: toggle button sensitivity on map 2026-04-30 00:33:01 +09:00
aclist 4f8d397bbc feat: ModManager 2026-04-30 00:21:18 +09:00
aclist efaaf7f434 chore: document tab navigation keys 2026-04-29 21:44:57 +09:00
aclist 804f1df6be fix: typo in import 2026-04-29 20:21:06 +09:00
aclist 792caf0d2d fix: typo in import 2026-04-29 20:20:48 +09:00
aclist eba9a7bfba chore: restrict logs to app namespace 2026-04-29 20:20:20 +09:00
aclist d6ef55a3b3 chore: explicitly return False instead of GLib macro 2026-04-29 01:04:22 +09:00
aclist 4377f9de7c chore: clear typehinting errors 2026-04-29 00:44:33 +09:00
aclist d0934723e6 changed: delegate set_fav to ConfigManager 2026-04-28 23:51:02 +09:00
aclist 1be7bddbb4 fix: cast ports to int 2026-04-28 23:28:45 +09:00
aclist cba884da7e chore: simplify CalcDist 2026-04-28 22:04:17 +09:00
aclist 52d51f2bd7 chore: clear typehinting errors 2026-04-28 21:41:07 +09:00
aclist 3d33d4f1e0 chore: move method into config manager 2026-04-27 00:00:14 +09:00
aclist f25982ab7a chore: rename threading manager 2026-04-26 22:17:08 +09:00
aclist 218856baab chore: rename filter manager 2026-04-26 22:16:01 +09:00
aclist 75459515ea change: consolidate proxy model methods 2026-04-25 22:47:12 +09:00
aclist 4535a19020 chore: move mod actions into ModManager (WIP) 2026-04-25 22:00:14 +09:00
aclist 39e3bb8d2d chore: move log parse action to LogTreeView 2026-04-25 21:59:32 +09:00
aclist 7b8388376c chore: consolidate filter enums 2026-04-25 21:17:47 +09:00
aclist 4bccaec427 feat: remove history entries (WIP) 2026-04-25 20:30:15 +09:00
aclist 6b50b1e933 fix: capitalize tab name 2026-04-25 20:29:55 +09:00
aclist 5834f39289 fix: do not check favorites on other tabs 2026-04-25 20:29:38 +09:00
aclist 9bd286a924 fix: remove hardcoded argument 2026-04-25 20:28:43 +09:00
aclist 48f69d79e0 chore: consolidate legacy methods 2026-04-25 19:23:53 +09:00
aclist 61735d20cf fix: wipe cache when removing row 2026-04-25 19:17:32 +09:00
aclist ed508c6764 feat: popover bubble 2026-04-25 01:04:14 +09:00
aclist 66909b668b fix: duplicate records in saved servers 2026-04-25 00:24:13 +09:00
aclist c4878ad97c fix: indentation level 2026-04-24 20:08:08 +09:00
aclist 07c98594e1 fixme: private function name 2026-04-24 20:06:44 +09:00
aclist 979e616c4f fix: GLibUnix namespace patch from DZGUI 6 2026-04-24 20:02:15 +09:00
aclist afcc50e8c3 chore: update gitignore 2026-04-24 20:00:20 +09:00
aclist b86cac3709 chore: clear typehinting errors 2026-04-24 19:59:51 +09:00
aclist 2f6a78fc65 feat: wrap TreeModelFilter in TreeModelSort 2026-04-23 00:41:26 +09:00
aclist 8665292ff8 chore: update changelog 2026-04-22 23:21:06 +09:00
aclist dff9b884a8 chore: reword tooltip 2026-04-22 23:20:29 +09:00
aclist 978daa7a28 feat: LogManager 2026-04-22 23:13:26 +09:00
aclist 106b201804 chore: drop test logging 2026-04-22 23:13:11 +09:00
aclist c6f1d62c73 fixme: decrement button after thread closes 2026-04-22 23:11:40 +09:00
aclist d9ec01d9b0 feat: alert button 2026-04-22 22:43:07 +09:00
aclist a2231e3cb9 feat: toggle log levels 2026-04-21 22:20:06 +09:00
aclist d45d0a8da0 chore: drop unused code 2026-04-21 01:37:38 +09:00
aclist 8e6cff4bf0 fix: start filters insensitive if tree is empty 2026-04-21 01:22:56 +09:00
aclist d92a0010e2 chore: clean up unused methods 2026-04-19 20:42:36 +09:00
aclist 95948e3e40 fix: refresh keywords per page 2026-04-19 20:22:58 +09:00
aclist 699c103711 feat: add MapsCombo 2026-04-19 19:31:40 +09:00
aclist 1715d4c110 chore: drop shrink to fit 2026-04-19 19:18:56 +09:00
aclist 891abcc049 chore: drop unused code 2026-04-19 18:58:05 +09:00
aclist 107c672b1c fix: update UserPrefs object 2026-04-18 21:17:12 +09:00
aclist 24d054ca16 fix: do not add server if already in config 2026-04-18 20:56:29 +09:00
aclist af4d79f190 feat: update saved tab label 2026-04-18 20:08:32 +09:00
aclist 0949a0d8a9 chore: remove comments 2026-04-18 18:16:16 +09:00
aclist e1f54bd75d feat: refresh player count 2026-04-18 18:15:27 +09:00
aclist 06450ddadc chore: drop test document write 2026-04-17 22:41:47 +09:00
aclist 7298fc7566 chore: document block_map_change_propagation flag 2026-04-17 22:37:40 +09:00
aclist e8fca22419 feat: skip_cache arg on FilterMan.filter() 2026-04-17 22:27:59 +09:00
aclist a323c4fc75 fix: change button sensitivity on empty 2026-04-12 02:36:40 +09:00
aclist 0b6ca7b6fd chore: update changelog 2026-04-12 02:23:17 +09:00
aclist 81a6d03a59 fix: remove unused arguments 2026-04-12 02:22:09 +09:00
aclist 39abbf3a02 feat: lazy load ping 2026-04-12 02:20:50 +09:00
aclist 933c3b19b0 chore: drop debug logic from treeview 2026-04-11 22:51:16 +09:00
aclist 82cddf261e feat: dynamic tooltip 2026-04-11 22:35:52 +09:00
aclist 600fea8a82 feat: notes manager (WIP) 2026-04-11 22:35:26 +09:00
aclist fa12fc36f9 feat: dynamic notes dialog (WIP) 2026-04-08 01:24:17 +09:00
aclist 560349e16b feat: reimplement notes dialog (WIP) 2026-04-01 00:14:48 +09:00
aclist 55e6af8fe2 feat: abstract base server dialog 2026-03-31 23:58:10 +09:00
aclist 6393265935 feat: reimplement server mod dialog 2026-03-30 22:51:45 +09:00
aclist 4022b4c6b6 feat: reimplement details dialog 2026-03-30 21:42:19 +09:00
aclist ae291eff41 fix: do not refilter on page map 2026-03-29 19:50:09 +09:00
aclist 5391cdde1e fix: reapply filters when map changed 2026-03-04 11:36:30 +09:00
aclist 3bb30887ca chore: update changelog 2026-03-01 00:49:49 +09:00
aclist 9fa93f5938 feat: toggle radio from inside Gtk.Entry 2026-03-01 00:43:27 +09:00
aclist e568814a11 feat: add/connect by record or str 2026-03-01 00:16:43 +09:00
aclist 2fa51c80f4 chore: reroute connect method 2026-02-28 22:34:25 +09:00
aclist 3b40ea1846 feat: _sort_unique_maps() 2026-02-27 23:24:30 +09:00
aclist 940dd41fdf fix: emit missing signal 2026-02-27 23:06:22 +09:00
aclist 672c8f9e9e fix: pass correct number of records 2026-02-27 22:53:31 +09:00
aclist 1b1cb33a6e fix: do not pass BM key during ip method 2026-02-27 22:21:08 +09:00
aclist 374f7d1130 feat: copy version on click 2026-02-27 21:43:35 +09:00
aclist a763b3b9dc fix: defer destroy call 2026-02-25 22:44:49 +09:00
aclist 79eab93629 fix: typo in enum name 2026-02-24 20:32:41 +09:00
aclist f86e37dbe1 fix: separate id/ip methods 2026-02-24 20:30:38 +09:00
aclist f424b019ad chore: delegate config methods to ConfigManager 2026-02-23 23:20:38 +09:00
aclist ed7f803d47 feat: attach FilterManager to each ServerTreeView 2026-02-23 22:57:59 +09:00
aclist 5bcb2b279d chore: rename MapManager to FilterManager 2026-02-23 21:58:10 +09:00
aclist 0283baf3a9 chore: rename to ProxyModelManager 2026-02-23 21:53:20 +09:00
aclist fd9a23c6d6 chore: clear linting errors 2026-02-23 19:39:35 +09:00
aclist d6fd7b2494 feat: add extend() method to ListStore 2026-02-23 06:22:32 +09:00
aclist 3859188ade feat: preserve records on failure 2026-02-23 03:14:29 +09:00
aclist 8d1cc4bb68 chore: drop deprecated controller logic 2026-02-23 02:53:26 +09:00
aclist 575e591c10 feat: restore partial context menu functionality 2026-02-23 02:24:14 +09:00
aclist 5ae18485e8 fix: start LAN columns hidden 2026-02-23 01:55:11 +09:00
aclist 204cca2f09 fix: prevent dialog destruction 2026-02-23 01:54:40 +09:00
aclist 29c4fbcfbc feat: add ConfigManager 2026-02-23 01:06:07 +09:00
aclist 748438414c chore: update controller/config calls 2026-02-23 01:05:30 +09:00
aclist 6bbe0d6882 feat: add ConnectionManager 2026-02-23 00:29:52 +09:00
aclist e56b89fd64 fix: set cell renderer properties 2026-02-22 22:57:44 +09:00
aclist a22d1a6324 feat: standalone clipboard utility 2026-02-22 04:11:23 +09:00
aclist 68cd567249 chore: move signal emission into ServerTreeView 2026-02-22 04:04:37 +09:00
aclist 99ede36a32 chore: ServerModelManager WIP 2026-02-22 01:48:23 +09:00
aclist 473dcafb26 feat: ServerModelManager WIP 2026-02-22 01:42:36 +09:00
aclist bdfebf9a69 chore: change modelman to model factory 2026-02-21 22:03:46 +09:00
aclist 85c1d18622 feat: add standalone managers 2026-02-21 18:35:37 +09:00
aclist dec2bf7e6f chore: clean up context menu mixin 2026-02-21 18:35:06 +09:00
aclist 62da949465 chore: abstract ThreadManager class (WIP) 2026-02-21 17:44:11 +09:00
aclist 42544c6dcc feat: add by id or ip WIP 2026-02-19 23:08:10 +09:00
aclist decc1f636c fix: add keypress signal to KeywordEntry 2026-02-17 00:49:32 +09:00
aclist 59120825dc feat: early abort on LAN 2026-02-17 00:35:33 +09:00
aclist 7766b4c5c2 feat: queue pool in thread 2026-02-16 22:36:44 +09:00
aclist 93a4e231ac feat: load history and saved 2026-02-16 04:16:57 +09:00
aclist 78be350863 feat: push data into row immediately 2026-02-16 02:13:48 +09:00
aclist c479051c2f fix: improve sort algo 2026-02-16 01:57:51 +09:00
aclist 45700e7a4a feat: use StoredFunc for query funcs 2026-02-16 00:34:07 +09:00
aclist 987a4f51ab fix: change developers to debug 2026-02-16 00:18:24 +09:00
aclist 4decd16345 feat: skip first server query in debug mode 2026-02-16 00:13:41 +09:00
aclist c3e2f6e4b4 fix: update active maps combo on tab change 2026-02-15 23:58:48 +09:00
aclist 4d0bb2f4f8 feat: progress bar WIP 2026-02-15 03:05:32 +09:00
aclist b9fe87cf90 feat: threading with GLib WIP 2026-02-15 02:04:54 +09:00
aclist b703af897f feat: add map model 2026-02-14 20:16:56 +09:00
aclist 96244a4560 feat: wrap callback function 2026-02-14 20:16:28 +09:00
aclist 2c8e722d8a fix: lan panel sensitivity 2026-02-14 16:46:44 +09:00
aclist d4b346006d chore: abstract filter panel components 2026-02-13 22:58:09 +09:00
aclist b14c63b23c feat: use concurrency for stale mods 2026-02-13 20:41:09 +09:00
aclist 85cbd2d183 chore: update comments 2026-02-13 19:52:16 +09:00
aclist 7e6013bdbd feat: atomic maps per server context 2026-02-13 19:49:15 +09:00
aclist 82c585a195 feat: use functools.wraps 2026-02-13 02:43:08 +09:00
aclist c786ba2c9a fix: isolate API failure control flow 2026-02-13 02:29:42 +09:00
aclist 7b06973af3 chore: clear linting errors 2026-02-13 01:07:49 +09:00
aclist 24125a7492 feat: update fav server dynamically 2026-02-13 00:59:13 +09:00
aclist 502b574085 fix: use constant when setting CellLayout params 2026-02-12 19:23:07 +09:00
aclist cf754ee286 feat: connect search icon to activate signal 2026-02-12 19:20:23 +09:00
aclist e1d84ec7be fix: evaluate str type 2026-02-12 19:09:42 +09:00
aclist 38883626f5 feat: restore map selection 2026-02-11 21:35:51 +09:00
aclist 25f19cfd10 fix: clean up signal emission 2026-02-11 20:44:07 +09:00
aclist 4946705a8b chore: update changelog 2026-02-08 22:23:36 +09:00
aclist fc6e958c09 fix: signal supression on keyup 2026-02-08 22:09:45 +09:00
aclist 2ef62416c0 fix: statusbar signals 2026-02-07 23:18:25 +09:00
aclist fc294bcede chore: drop interactive prompt in hook 2026-02-07 20:07:55 +09:00
aclist 89477f7365 chore: add venv.rst file 2026-02-07 20:05:52 +09:00
aclist 6b3257ae83 chore: bump docs version 2026-02-07 19:58:47 +09:00
aclist 960396c7fa chore: add dev install isntructions to docs 2026-02-07 19:58:17 +09:00
aclist b735995c65 fix: server threading WIP 2026-02-07 19:07:51 +09:00
aclist 6fc348ea34 fix: signal emission 2026-02-07 18:49:06 +09:00
aclist 045f242e09 feat: toggle panels on signal 2026-02-07 17:42:15 +09:00
aclist 56b32a0048 feat: add navigable context menu to mixins 2026-02-07 17:19:44 +09:00
aclist ac7700ec23 feat: dedicated emitter 2026-02-07 16:42:59 +09:00
aclist ea841395fc chore: add TODOs to readme 2026-02-04 19:34:04 +09:00
aclist 6131d66c9a chore: add untracked crumbs file 2026-02-04 19:33:13 +09:00
aclist e33ae42526 chore: test commit 2026-02-04 19:30:20 +09:00
aclist d361e5d235 chore: test commit 2026-02-04 19:28:21 +09:00
aclist 45f1c5d8c6 chore: clear linting errors 2026-02-03 00:21:52 +09:00
aclist 46a215a472 fix: docstrings 2026-02-02 21:35:01 +09:00
aclist bb94fbf51b feat: add emitter 2026-02-02 16:51:51 +09:00
aclist 8205559f2e feat: spawn dialog on API timeout 2026-01-26 13:28:10 +09:00
aclist d2d5fdb59f chore: clerical fixes 2026-01-26 12:28:00 +09:00
aclist 4f04d26231 feat: filtered model WIP 2026-01-25 10:48:57 +09:00
aclist da8722ec2a feat: filtered model WIP 2026-01-25 10:14:51 +09:00
aclist 5d6a7c9775 feat: threading decorator 2026-01-25 09:52:59 +09:00
aclist e8e78ee6a1 fix: handle null results 2026-01-24 17:19:12 +09:00
aclist ab9c97234e feat: lazy load WIP 2026-01-24 15:56:04 +09:00
aclist 6141145fbe fix: early abort if ip matches 2026-01-24 13:46:56 +09:00
aclist 655bb41f59 fix: focus mod tree on init 2026-01-24 13:37:32 +09:00
aclist 2beea2af20 chore: fix linting errors 2026-01-24 13:33:15 +09:00
aclist f05374bc7d chore: register signals 2026-01-24 13:30:01 +09:00
aclist c952fef5e8 fix: use correct constant name 2026-01-24 09:12:37 +09:00
aclist 69a881cee8 feat: emit warning if icon is missing 2026-01-24 09:11:54 +09:00
aclist eb05cbdbfd chore: dynamic breadcrumbs 2026-01-24 08:55:00 +09:00
aclist e794aa82dc chore: dynamic statusbar WIP 2026-01-24 08:51:22 +09:00
aclist 936bc074a5 chore: dynamic statusbar WIP 2026-01-22 19:41:41 +09:00
aclist 0306cc4380 chore: deprecation warnings 2026-01-22 16:09:38 +09:00
aclist 93c5acb66d chore: drop unused enums 2026-01-22 16:03:06 +09:00
aclist df5f146a6e fix: pass controller 2026-01-22 14:56:28 +09:00
aclist 2aca6c3fa3 chore: clear linting errors 2026-01-22 14:50:01 +09:00
aclist 4cd900b42f fix: dynamic statusbar WIP 2026-01-22 14:31:12 +09:00
aclist 61f2d35f16 fix: dynamic statusbar WIP 2026-01-22 14:20:45 +09:00
aclist 934ff91f05 fix: dynamic statusbar WIP 2026-01-22 12:01:18 +09:00
aclist 9cc1ece0d7 fix: statusbar race condition WIP 2026-01-21 12:04:42 +09:00
aclist 2f9000ee80 chore: register filter panel 2026-01-19 17:09:19 +09:00
aclist 83d78e74de fix: suppress keynav actions on small models 2026-01-19 16:20:02 +09:00
aclist 3092e52515 feat: statusbar substack WIP 2026-01-19 16:15:26 +09:00
aclist 495d6263bb feat: fetch model on startup 2026-01-19 15:20:09 +09:00
aclist 5543d8cb38 feat: add new model manager types 2026-01-19 14:58:48 +09:00
aclist 6f29b1318a feat: initialize ServerTreeViews with atomic FilterModelManagers 2026-01-19 14:55:32 +09:00
aclist fdd6cefe48 feat: server threading WIP 2026-01-19 08:27:10 +09:00
aclist 2788abb755 Merge branch 'feat/server-threading' of github.com:aclist/dzgui-devel into feat/server-threading 2026-01-15 00:49:31 +09:00
aclist e49f452ba5 feat: shrink to fit WIP 2026-01-15 00:49:12 +09:00
aclist 9a96711dac fix: test github endpoitn first 2026-01-14 13:31:52 +09:00
aclist 716eaa187c fix: convert exception to str 2026-01-14 13:16:04 +09:00
aclist 2ef51698bd feat: add derived generic entry types 2026-01-14 01:23:18 +09:00
aclist 00ca59698c feat: threading WIP 2026-01-13 02:56:56 +09:00
aclist fdb6b342f7 feat: dynamic port validation 2026-01-12 23:50:27 +09:00
aclist b119569cf5 fix: move class attribs 2026-01-12 03:46:44 +09:00
aclist 1bc21d6083 chore: normalize dialogs 2026-01-12 03:44:41 +09:00
aclist 45bd0e16ec feat: ExceptionDialog WIP 2026-01-11 04:53:15 +09:00
aclist 59ef15073f feat: connect panel WIP 2026-01-11 01:52:29 +09:00
aclist e2ec093f67 feat: lan button WIP 2026-01-10 21:30:09 +09:00
aclist 10037b86d8 feat: dynamic haversine calc 2026-01-09 22:49:12 +09:00
aclist 775ca2a8d9 Merge pull request #30 from aclist/feat/server-notebook
feat/server notebook
2026-01-09 20:13:32 +09:00
aclist 786232cb4a chore: update notes 2026-01-09 20:10:37 +09:00
aclist 12d367fa7e feat: button cooldown 2026-01-09 20:03:22 +09:00
aclist 91425cbcaa feat: pack pages in ScrolledWindow 2026-01-09 19:08:59 +09:00
aclist 922ff7b3b2 chore: abstraction 2026-01-09 11:09:55 +09:00
aclist 31d289048f fix: fetch ipdb if missing 2026-01-09 10:58:41 +09:00
aclist 3d53ee7ea0 Merge branch 'feat/server-notebook' of github.com:aclist/dzgui-devel into feat/server-notebook 2026-01-09 07:02:35 +09:00
aclist 4e0cd02afa chore: add comments 2026-01-09 07:02:19 +09:00
aclist 3ae06f0bfb feat: add ip field binding 2026-01-09 07:01:55 +09:00
aclist 7fbc75bea9 chore: linting errors 2026-01-09 07:01:25 +09:00
aclist f83eca7c18 fix: ensure log path exists 2026-01-08 17:15:27 +09:00
aclist 42e9cf6378 feat: add Statusbar class 2026-01-07 23:35:22 +09:00
aclist 058cbc39b1 feat: add Servers class 2026-01-07 23:34:25 +09:00
aclist 3b7b131cf5 feat: add Mods class 2026-01-07 23:34:02 +09:00
aclist 271ed76c38 feat: add Help class 2026-01-07 23:33:35 +09:00
aclist 86147db18e feat: add BoldLabel class 2026-01-07 23:32:17 +09:00
aclist 3c82b71f76 feat: live input validation 2026-01-02 06:32:32 +09:00
aclist 8a1c5bea6c fix: open user workshop 2026-01-02 05:29:15 +09:00
aclist 06e6065236 feat: dynamic connect panel (WIP) 2026-01-02 05:25:00 +09:00
aclist 5f0c8f7654 feat: apply scrollable mixin to pages 2026-01-01 23:49:16 +09:00
aclist aba00f732a feat: mediator rewrite (WIP) 2026-01-01 21:31:33 +09:00
aclist 69cde11e8e chore: consolidate buttons 2026-01-01 20:24:44 +09:00
aclist d74060c518 chore: reword tooltip 2026-01-01 20:22:55 +09:00
aclist 645682ee06 fix: only unlink stale links 2026-01-01 20:22:35 +09:00
aclist dc310593d0 chore: clear typehinting errors 2026-01-01 06:04:24 +09:00
aclist 46ade773b3 fix: allocate correct grid rows to right panel 2026-01-01 05:50:25 +09:00
aclist b6210e450f fix: grab treeview focus on refresh 2026-01-01 02:45:08 +09:00
aclist 580ccf0e83 chore: drop deprecated method 2026-01-01 02:41:47 +09:00
aclist e7735e0472 feat: lazy refresh model on page change (WIP) 2026-01-01 02:41:05 +09:00
aclist 72c1081b48 feat: embolden func 2026-01-01 01:58:26 +09:00
aclist c4b918d61e chore: update comments and imports 2026-01-01 01:25:52 +09:00
aclist 64384d1ac6 fix: cache statusbar content 2026-01-01 01:25:02 +09:00
aclist 29e13db5a2 fix: handle invalid filepath 2026-01-01 01:24:36 +09:00
aclist 2c19d999ff chore: update strings 2026-01-01 01:24:06 +09:00
aclist 2fc2eddf87 chore: move statusbar format method to format.py 2026-01-01 01:23:36 +09:00
aclist 618ee47e53 fix: only save column width on quit 2025-12-30 21:36:39 +09:00
aclist 167935b963 fix: update statusbars/crumbs correctly 2025-12-30 21:27:30 +09:00
aclist 029bc1edbd chore: add annotations 2025-12-29 16:57:06 +09:00
aclist b0565bc7f1 feat: log timeout error when attempting update 2025-12-29 16:56:44 +09:00
aclist 5a76c37839 chore: move is_developer to UserPrefs 2025-12-29 16:39:47 +09:00
aclist 2184622918 fix: handle remote repo timeout 2025-12-29 16:35:05 +09:00
aclist a5140d7761 fix: hide connect panel contextually 2025-12-29 16:34:34 +09:00
aclist ad6bdb2e3c feat: server connection panel WIP 2025-12-28 07:14:35 +09:00
aclist ef2742443f feat: col width WIP 2025-12-27 19:41:20 +09:00
aclist 21b6da8471 feat: col width WIP 2025-12-27 19:40:48 +09:00
aclist c0df63b9d8 chore: move import 2025-12-27 19:40:08 +09:00
aclist 248978f993 fix: update crumbs when paginating 2025-12-22 17:03:44 +09:00
aclist 37dab3e83b feat: populate ServerTreeViews 2025-12-21 20:40:29 +09:00
aclist 4a3d407e5f fix: remove main menu enum 2025-12-21 03:04:53 +09:00
aclist 8b3d8c94fd fix: connect signals to new notebook tabs 2025-12-21 03:01:55 +09:00
aclist e281345323 feat: server notebook prototype 2025-12-20 23:06:47 +09:00
aclist 01176c7798 Merge pull request #28 from aclist/fix/type_checking
fix: clear linting errors
2025-12-20 22:17:28 +09:00
aclist f49e0bf560 Merge branch 'main' into fix/type_checking 2025-12-20 22:17:19 +09:00
aclist 89de9aa48a Merge pull request #29 from aclist/feat/model-manager
feat: delegate to model manager
2025-12-20 22:15:47 +09:00
aclist d8a12d13f6 chore: update imports 2025-12-20 22:15:05 +09:00
aclist 5e5d6e886b chore: do not save gport var 2025-12-20 21:46:41 +09:00
aclist 8f20e8cc96 fix: do not write to statusbar 2025-12-20 21:44:42 +09:00
aclist 016f3ac6c9 feat: delegate to model manager 2025-12-20 21:42:19 +09:00
aclist 730e108cea chore: clear linting errors 2025-12-19 20:26:07 +09:00
aclist d5e54c0488 chore: clear linting errors 2025-12-18 20:52:04 +09:00
aclist 3e74174ab8 chore: add temporary exclusions 2025-12-18 20:51:45 +09:00
aclist 3ea2afabed chore: clear linting errors 2025-12-18 14:35:11 +09:00
aclist 6e8a78cf3e chore: update pyproject.toml 2025-12-18 14:30:19 +09:00
aclist 77c42f5b78 chore: clear linting errors 2025-12-18 14:29:00 +09:00
aclist 3cdc36c78b chore: merge main 2025-12-17 15:14:00 +09:00
aclist c150329d30 fix: clear linting errors in controller 2025-12-17 15:09:24 +09:00
aclist 5792b6f598 fix: clear linting errors 2025-12-17 15:03:51 +09:00
aclist 9bd2a0cac7 Merge pull request #18 from aclist/feat/liststore-dataclass
feat: add liststore annotations upfront
2025-12-17 15:02:56 +09:00
aclist 88b85eb502 Merge pull request #24 from aclist/feat/redact-api-key
feat: redact API key in log table
2025-12-17 15:02:19 +09:00
aclist 94e5f9f6c0 Merge pull request #25 from aclist/feat/remove-from-thanks
feat: add admonition to submit ticket
2025-12-13 23:12:13 +09:00
aclist 161957e053 feat: add admonition to submit ticket 2025-12-13 23:10:54 +09:00
aclist f44e195938 chore: move redact_log() to util 2025-12-13 23:05:34 +09:00
aclist 5483717e0c feat: redact API key in log table 2025-12-13 23:00:41 +09:00
aclist 190face11d Merge pull request #20 from aclist/fix/better-config-check
fix: more robust version/config file check
2025-12-12 18:45:17 +09:00
aclist b5a62a9815 fix: more robust version/config file check 2025-12-12 18:43:09 +09:00
aclist 0a0d36c4e8 Merge pull request #19 from aclist/feat/developers-page
feat: add developer debugging page
2025-12-11 17:45:33 +09:00
aclist 7f6d2237eb chore: update changelog 2025-12-11 17:21:26 +09:00
aclist d29f4a91b2 fix: use Gtk.TreePath 2025-12-11 17:20:25 +09:00
aclist e51b4270e2 feat: add notebook page 2025-12-10 13:35:15 +09:00
aclist 1464243776 fix: update breadcrumbs 2025-12-09 18:01:25 +09:00
aclist abb10c4262 Merge branch 'main' into feat/developers-page 2025-12-09 17:59:49 +09:00
aclist 16020aae04 chore: add changelog to package data dir 2025-12-09 17:50:54 +09:00
aclist 94f5397c4c feat: add developer debugging page 2025-12-09 17:48:05 +09:00
aclist 57be68ea73 chore: cleanup 2025-12-09 13:58:37 +09:00
aclist 53b6034f2a feat: add liststore annotations upfront 2025-12-09 13:56:55 +09:00
aclist 9fc8b4ce83 chore: update gitignore 2025-12-09 12:53:39 +09:00
aclist 1279401378 chore: add gitmodules 2025-12-08 18:10:18 +09:00
aclist 78750a656d chore: add dotfiles 2025-12-08 18:09:35 +09:00
aclist 2e5b771137 feat: dzgui 7 alpha 2025-12-08 17:32:25 +09:00
aclist 1acdbd58c5 Initial commit 2025-10-23 13:10:04 +09:00
204 changed files with 14664 additions and 9417 deletions

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@ jobs:
mirror-to-codeberg: mirror-to-codeberg:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: pixta-dev/repository-mirroring-action@v1 - uses: pixta-dev/repository-mirroring-action@v1
+12 -3
View File
@@ -1,4 +1,13 @@
tags *.egg*
__pycache__ __pycache__
pre-commit prio.otl
tests/ bugs
build/
.ruff_cache/
.pytest_cache/
.mypy_cache/
notes.otl
uv.lock
.coverage
pyapp-latest/
dist/
+6
View File
@@ -0,0 +1,6 @@
[submodule "dzgui/lib/dayzquery"]
path = dzgui/lib/dayzquery
url = https://github.com/Yepoleb/dayzquery.git
[submodule "dzgui/lib/a2s"]
path = dzgui/lib/a2s
url = https://github.com/Yepoleb/python-a2s.git
+20
View File
@@ -0,0 +1,20 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.14.6
hooks:
- id: ruff-check
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.18.2
hooks:
- id: mypy
args: [--strict, --ignore-missing-imports]
- repo: local
hooks:
- id: copy-clog
name: Copy CHANGELOG.md to package data dir
entry: python scripts/copy_changelog.py
language: system
- id: untracked
name: Check for untracked files not present in .gitignore
entry: python scripts/untracked.py
language: system
+66 -988
View File
File diff suppressed because it is too large. Load diff
-71
View File
@@ -1,71 +0,0 @@
# Introduction
Thank you for your interest in DZGUI!
This guide goes over development conventions and best practices for contributors.
If you are a developer, you can skip to the end.
# Requesting help
If you encounter a problem with DZGUI, you can submit tickets on the GitHub
[issue tracker](https://github.com/aclist/dztui/issues) under the
`troubleshooting` tag.
# How can I help the project?
There are several ways to help this project.
1. Report bugs that you find
2. Request features that you would like
3. Contribute features and fixes to the codebase
4. Contribute documentation to the project
Before making any contribution, please read the `CODE_OF_CONDUCT.md` and act
accordingly.
## Submitting a ticket
Navigate to the GitHub [issue tracker](https://github.com/aclist/dztui/issues).
From there, follow the onscreen prompts. You will be asked questions such as:
- What version are you using?
- What distribution are you using?
- What is the issue that you found?
- How can we reproduce the issue?
You can also attach screenshots, logs, or other data that can help us.
## Requesting a feature
You can also request features via the same issue tracker. It is good practice to
first search for your idea to see if a similar one has already been posted.
If not, open a ticket where you describe your feature and its possible benefits.
Please note that this is a community project, so it takes time for us to develop
features. Putting in a feature request does not mean that it will be implemented,
but we will do our best to support as many cool ideas as possible.
## Contributing code or documentation
If you would like to take ownership or assist with an issue on the issue tracker, or
contribute a new change, please follow the guidelines below.
Fork this repository and check out the code up to `prerelease/<latest-version>`.
If there is no pending prerelease PR, you can base your changes off of
the `testing` branch. You may later be asked to retarget your PR to the prerelease
branch once a new one is made. This is because out-of-band PRs are consolidated into
the next release before merging.
The following naming conventions apply for PRs:
- fix/<your-fix> - patch/hotfix branches
- feat/<your-feature> - feature branches
- doc/<your-doc-branch> - documentation branches
- infra/<your-infra-branch> - infrastructure branches
Implement your changes and test them locally. If they work you may
open a merge request, and then we review your changes. If everything is OK, it
will be merged to `prerelease/<latest-version>`, then `testing`, and after a live
testing phase, to `stable` as well.
It is recommended to follow
[Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/), as this
integrates well with tooling and helps the project review your code.
+23
View File
@@ -0,0 +1,23 @@
# TODO: link to here from sphinx docs
# Setting up precommit hooks
pre-commit install
# Fetching submodules
git submodule update --recursive --init
# Installing dev dependencies
uv pip install -e .[dev]
# Building documentation
sphinx-build -M html source build -a
# Building standalone DZGUI release binaries
1. Run `./scripts/dl_pyapp.sh`
# TODO: secondary script that packs this archive
2. Download cpython 3.13, linux, gnu, v3
https://github.com/astral-sh/python-build-standalone/releases/download/20251014/cpython-3.13.9%2B20251014-x86_64_v3-unknown-linux-gnu-install_only_stripped.tar.gz
3. Explicitly install dependencies into site-packages
4. Pack back into a tarball
5. Run `python3 scripts/release.py`
6. Generate a release and tag against the bundled `dzgui` executable
+5
View File
@@ -1,3 +1,8 @@
Additional licenses to git submodules not explicitly shipped with the source code:
python-a2s: https://raw.githubusercontent.com/Yepoleb/python-a2s/refs/heads/master/LICENSE
dayzquery: https://raw.githubusercontent.com/Yepoleb/dayzquery/refs/heads/master/LICENSE
GNU GENERAL PUBLIC LICENSE GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007 Version 3, 29 June 2007
+20 -17
View File
@@ -1,34 +1,37 @@
## What this is ## What this is
DZGUI allows you to connect to both official and modded/community DayZ servers on Linux and provides a graphical interface for doing so. DZGUI is a turnkey browser and mod manager for DayZ on Linux. It allows you to connect to both official and modded/community DayZ servers on Linux via a graphical user interface (GUI).
This overcomes certain limitations in the Linux client and helps prepare the game to launch by providing features like: This overcomes certain limitations in the Linux client and helps prepare the game to launch by providing features like:
- Search for and display server metadata in a table (server name, player count, ping, queue size, current gametime, distance, IP) - Search for and display global and LAN servers via an interactive table
- Supports official, third-party, and modded DayZ servers
- Automatically find and prepare mods being requested by servers
- Add/delete/manage favorite servers by IP or ID - Add/delete/manage favorite servers by IP or ID
- Quick-connect to favorite/recent servers - Quick-connect to favorite/recent servers
- Find and prepare mods being requested by servers (choose from manual or automatic installation) - Manage local mods and symlinks
- Bulk delete/update local mods - Prepare launch options to pass to Steam
- Concatenate launch options to pass to Steam
- Connect to mod-enabled LAN servers
## Design philosophy
DZGUI follows a specific set of guidelines, enumerated below:
- Provide a free and open-source tool under GPL
- Do not use undocumented, third-party servers to aggregate data; no central "DZGUI" server
- All connections go to Steam and DayZ servers directly; the tool should function in perpetuity without intermediary endpoints
- Target Linux desktop and Steam deck specifically; not a cross-platform tool
## Setup and usage ## Setup and usage
Refer to the documentation for installation and setup instructions: Please refer to the documentation for installation and setup instructions:
- [GitHub](https://aclist.github.io/dzgui/index.html) - [GitHub](https://aclist.github.io/dzgui/index.html)
- [Mirror (Codeberg)](https://aclist.codeberg.page) - [Codeberg (Mirror)](https://aclist.codeberg.page)
![A screenshot of DZGUI](/images/example.png) ![A screenshot of DZGUI](/images/example.png)
## Attribution ## Attribution
Geolocation records from [DB-IP](https://db-ip.com) under [CC 4.0 license](https://creativecommons.org/licenses/by/4.0/) Geolocation records from [DB-IP](https://db-ip.com) under [CC 4.0 license](https://creativecommons.org/licenses/by/4.0/)
This tool uses [python-a2s](https://github.com/Yepoleb/python-a2s) and [dayzquery](https://github.com/Yepoleb/dayzquery) as submodules; licenses for these submodules can be found in the LICENSES file
of the project root.
Both the geolocation records and submodules listed above are not shipped with the source code, but are retrieved and assembled at runtime.
Finally, executable versions of DZGUI shipped as release binaries are thin wrappers around the Python interpreter, and also retrieve and assemble the above dependencies at runtime on the end-user's
machine, rather than using pre-compiled source code. Users wishing to review these dependencies can inspect the 'pyproject.toml' manifest in the project root.
## Disclaimer
DZGUI is beta-quality software and is provided as-is.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them 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 prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
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
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 3 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, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program 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, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU 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 Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+20
View File
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -a
+22
View File
@@ -0,0 +1,22 @@
## Dependencies:
```
pip install -r requirements.txt
```
## Setup:
1. Modify `source/conf.py`.
2. Add .rst pages to `source` tree.
## Build
```
$ mkdir build
$ sphinx-build -M html source build -a
```
## Publish
Export contents of `build/html` to host.
N.B. For GitHub, touch `.nojekyll` file on the root of the branch.
+35
View File
@@ -0,0 +1,35 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)
if "%1" == "" goto help
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
+2
View File
@@ -0,0 +1,2 @@
sphinx-rtd-theme
sphinx-copybutton
+60
View File
@@ -0,0 +1,60 @@
Submitting a ticket
==========================
Tickets are tracked at the `DZGUI issue tracker <https://github.com/aclist/dztui/issues>`_.
You will need to `register for a GitHub account <https://github.com/signup>`_ in order to submit one.
If have checked the :doc:`kb` and `closed issues <https://github.com/aclist/dztui/issues?q=is%3Aissue+is%3Aclosed>`_ area and did not find a solution, three ticket types are provided for your
convenience:
- **Bug report**: for unexpected, breaking behavior in the application
- **Feature request**: to propose new functionality
- **Troubleshooting**: if all else fails, you can request help here
Reports by example
--------------------------
Below are some examples of how to format a constructive report that will ensure your problem can be resolved in a timely fashion.
A non-actionable report
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Subject: add button
hi, you must add a button to show how long I have to wait to join a full server, the app is useless without this...do your job, guys!!! ;-)
This report exhibits a number of problems:
- Vague title and summary: in addition to being unclear, this will slow down filing the incoming report.
- Problem space is poorly defined: it is not clear where the issue lies, where the feature is supposed to be implemented, nor why.
- Lack of context: the feature may already exist, but there is not enough information to go on. Alternatively, the feature may be technically impossible to implement, but there is not enough
information to go on.
- Incorrect report type: this is a feature request filed as a bug report.
- Unprofessional tone: the message is disrespectful towards project members and inserts the user's subjective opinion.
An actionable report
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Subject: Version 5.5.0-beta.2 crashes when selecting multiple table rows via Ctrl-click
This occurs specifically on version 5.5.0-beta.2 if the setting ALLOW_MULTI is set to ON. I was able to reproduce it using the following steps:
Distribution: Fedora
- Ensure that ALLOW_MULTI is set to ON
- Open the application and immediately navigate to the Server Browser
- Uses the Ctrl-click binding to select multiple rows in the table
- After >1 row is selected, the application crashes to the desktop with the following traceback (see attached dump)
Thanks for looking into this.
This report is actionable because it is objective, specific, and detailed:
- The subject is clearly defined: specific details ensure it will be filed in a timely manner.
- Scope is explicit: the specific version, settings, and conditions under which the problem occur were given.
- Ample context: the user gave steps to reproduce the problem and clarified each one.
- Courteous tone: the user interacted with project members in a professional manner.
- Supporting information: the user provided a crash dump to expedite resolution of the issue.
+40
View File
@@ -0,0 +1,40 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = 'DZGUI'
author = 'aclist'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ['_templates']
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
#html_theme = 'alabaster'
extensions = [
'sphinx_rtd_theme',
'sphinx_copybutton',
"sphinx.ext.autosectionlabel",
"sphinx.ext.githubpages"
]
html_theme = "sphinx_rtd_theme"
#html_static_path = ['_static']
html_show_sphinx = False
html_show_copyright = False
html_show_sourcelink = False
today_fmt = "%Y-%m-%d"
release = "7.x.x"
version = "7.x.x"
+19
View File
@@ -0,0 +1,19 @@
Developers
===========
This project is open source under the GPLv3 license. You can find the source code on
`GitHub <https://github.com/aclist/dztui>`_. If you wish to contribute to
development, you will find further help in the
`CONTRIBUTING.md <https://github.com/aclist/dztui/blob/main/CONTRIBUTING.md>`_
file.
All contributors are expected to act in accordance with the project's
`code of conduct <https://github.com/aclist/dztui/blob/main/CODE_OF_CONDUCT.md>`_,
and follow the project's standards and guidelines.
To install DZGUI and related dependencies for linting, testing, and version control,
invoke the command ``uv pip install .[dev]``.
After this process, install the applicable pre-commit hooks by invoking the command ``pre-commit install``.
These pre-commit hooks enforce code checks that prevent making commits unless the relevant tests pass.
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 609 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 569 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 417 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 223 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

+69
View File
@@ -0,0 +1,69 @@
.. DZGUI documentation master file, created by
sphinx-quickstart on Thu Dec 12 13:12:14 2024.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
DZGUI documentation (|release|)
=================================
Last update: |today|
What this is
----------------
A DayZ server browser/mod manager for Linux. Used to list official and community server details and quick connect to preferred servers by staging mods and concatenating launch options automatically.
Source code:
- `GitHub <https://www.github.com/aclist/dztui>`_
- `Codeberg (mirror) <https://codeberg.org/aclist/dztui>`_
Installation
-------------
- Step 1: :doc:`installation`
- Step 2: :doc:`setup`
Usage
------
See: :doc:`usage`.
Uninstallation
---------------
See: :doc:`uninstallation`.
Troubleshooting
----------------
See: :doc:`kb` or :ref:`Submitting a ticket`.
.. toctree::
:maxdepth: 3
:hidden:
self
.. toctree::
:caption: Setup
:maxdepth: 3
:hidden:
installation
setup
usage
uninstallation
.. toctree::
:caption: Advanced usage
:maxdepth: 3
:hidden:
steam
locale
.. toctree::
:caption: Help
:maxdepth: 3
:hidden:
kb
bugs
development
+110
View File
@@ -0,0 +1,110 @@
Installation
==================
Basic runtime dependencies
---------------------------------
If not already installed, the below can be found in your system’s package manager.
If any dependencies are missing when the application starts, it will warn you, so you need not take any preemptive measures here.
- curl
- jq
- steam
- wmctrl or xdotool
- zenity
.. note::
All dependencies are installed out of the box on Steam Deck.
UI dependencies (Python and PyGObject)
---------------------------------------
.. important::
As of version 6.0.0, you must have a valid Python 3.13 and matching PyGObject environment.
Depending on your distribution, this may require additional manual intervention.
Arch Linux (vanilla variants)
^^^^^^^^^^^^^^^^^^^^^^
You will need the ``python3.13`` package, if it is not already installed.
Install the following build dependencies:
.. code:: console
sudo pacman -S cmake gcc pkgconf python-cairo
.. include:: venv.rst
CachyOS (Arch)
^^^^^^^^^^^^^^^^^^^^^^^
Refer to the build instructions for Arch Linux first.
The ``python3.13`` package is not available on CachyOS, so it is recommended to
use ``uv`` to manage Python versions.
.. code:: console
sudo pacman -S uv
.. include:: venv.rst
Manjaro 26 (Arch)
^^^^^^^^^^^^^^^^^^^^^^^
If Python 3.13 is not already available out of the box, refer to the build instructions for :ref:`Arch Linux (vanilla variants)`.
Debian 13 variants
^^^^^^^^^^^^^^^^^^^^^^^
Python 3.13 and PyGObject are available out of the box. No additional steps are necessary.
You can proceed to the :ref:`Installscript`.
Fedora 43 variants
^^^^^^^^^^^^^^^^^^^^^^^
Fedora 43 ships with a newer version of Python (3.14), so you must set up Python 3.13 in its own
virtual environment (venv) to prevent it from conflicting with the system package.
Install the following build dependencies:
.. code:: console
sudo dnf install cairo cairo-devel cairo-gobject-devel gcc python3.13 python3.13-devel
.. include:: venv.rst
Ubuntu 24 variants
^^^^^^^^^^^^^^^^^^^^^^
Ubuntu ships with an older version of Python (3.12). You must install additional dependencies.
Add the PPA below to add Python 3.13 to your sources:
.. code:: console
sudo add-apt-repository ppa:deadsnakes/ppa
Install the following build dependencies:
.. code:: console
sudo apt install python3.13 python3.13-venv python3.13-dev build-essential python3-gi-cairo pkg-config libgirepository-2.0-dev libcairo2-dev
.. include:: venv.rst
Installscript
-----------------------
Invoke the command below from a terminal. This script fetches the main DZGUI script from the repository,
makes it executable, and launches DZGUI's first-time setup. After running this installscript, you will
have the file ``dzgui.sh`` wherever you invoked the command.
.. code:: console
curl -s "https://codeberg.org/aclist/dztui/raw/branch/dzgui/install.sh" | bash
nixOS installation
----------------------
Two packages are independently maintained by other contributors. Each takes a slightly different approach.
nixOS packages are standalone and do not require cloning the git repository.
- https://github.com/lelgenio/dzgui-nix
- https://github.com/jiriks74/dzgui.flake
Next steps
---------------
Proceed to the next section for setup instructions.
+77
View File
@@ -0,0 +1,77 @@
Knowledge Base
==================
.. _DZG-001:
DZG-001: Periodically getting dropped from servers, or servers appear unreachable
------------------------------------------------------------------------------------
It is a longstanding issue in DayZ that the game opens a large number of connections when querying servers and/or while connected to servers.
This can result in excess traffic on the user's PC which, depending on how much headroom your network has, can lead to getting dropped, unresponsiveness, or a timeout.
If you are on Wi-Fi, try switching to a wired connection and see if the problem resolves itself. If it does, your wireless router settings do not have enough headroom for max simultaneous connections. Use a wired connection, or update your network settings to a more permissive setup.
Bohemia has acknowledged this issue going back 10+ years and stated that DayZ has a heavy impact on the network, but there is as yet no proposed solution on the DayZ side.
This issue is frequently seen on Steam Deck, due to the tendency for users to use it in an untethered Wi-Fi setup.
.. _DZG-002:
DZG-002: Some servers appear locked in the official DayZ client, and are unreachable in DZGUI
-----------------------------------------------------------------------------------------------
This is a variant of :ref:`DZG-001`.
.. _DZG-003:
DZG-003: On Steam Deck, DayZ becomes unresponsive/sluggish over time
---------------------------------------------------------------------------------------------
When DayZ is open for 1+ hours, a gradual loss in performance and FPS may occur on the Steam Deck.
A solution that seems to work for most users is to install `Cryo Utilities <https://github.com/CryoByte33/steam-deck-utilities>`_, a third-party performance management application.
.. _DZG-004:
DZG-004: On Steam Deck, some mods in the Workshop show a black screen when DZGUI attempts to open them
---------------------------------------------------------------------------------------------------------
This is a bug in the Steam client that is being tracked at Valve's Steam for Linux issue tracker here: https://github.com/ValveSoftware/steam-for-linux/issues/9598.
To resolve this issue, manually intervene in the Steam client by selecting a different context (e.g., Store, Library), waiting for it to load, then navigating back to the Workshop context. This should
clear the blockage and allow the contents to render.
.. _DZG-005:
DZG-005: Rendering problems with objects in the Winter Chernarus v2 mod
--------------------------------------------------------------------------
This mod has LOD (level of detail) bugs that may cause objects near the player, such as leaves, to render incorrectly, or cause distant trees to pop in abruptly. This is an acknowledged issue with the mod itself, not with DayZ or DZGUI.
There is no user-side fix for this issue; it is a problem solely on the mod side.
.. _DZG-006:
DZG-006: After moving DayZ to another drive, DZGUI fails to locate it on initial setup
----------------------------------------------------------------------------------------
If you recently moved the location of DayZ using Steam's internal dialogs, it may take some time for this information to update internally on Steam's side.
Steam stores the location of installed games in a unified file, and DZGUI checks this file during initial setup to determine where Steam claims DayZ is installed.
If you recently moved DayZ to a different drive or partition but did not restart Steam, this information may be out of date, causing Steam to report the wrong location.
Try restarting the Steam client and starting the DZGUI initial setup again.
.. _DZG-007:
DZG-007: Why do I need a Steam Web API key? Is it safe?
----------------------------------------------------------
In order to provide a server browser showing a searchable list of all available servers, DZGUI utilizes the Steam Web API.
Actual connections and queries to individual servers are performed directly between the computer and the DayZ server.
DZGUI gets its server information directly from the most authoritative source: Steam. It does this by letting the user be solely in control of their own API key and the application in an authenticated way. Users explicitly get permission to use a Web API key instead of scraping DayZ server info from third-party sites.
Everything that happens between DZGUI and the Steam Web API endpoint takes place solely on the user's computer, using a GET request (fetch server list), and no information gets sent back to the developer. DZGUI does not scrape third party DayZ APIs without permission.
There is some misconception that a Steam Web API key could be used to gain information about a user's account or control their account. Not only is this not possible, but the Web API key is used solely by the user on their own computer and is protected by Steam Guard.
A Steam Web API key is the most strict way of getting authentic, reliable, and consistent server information in a zero-trust model.
You are responsible for the creation, storage, management, and revocation of your Web API key.
+12
View File
@@ -0,0 +1,12 @@
Locale support
==================
For internationalization purposes, DZGUI will inherit the default locale setting on the system when displaying numbers.
This is used for thousands separators in long numbers and decimal separators in fractional numbers.
If you wish to use a specific regional numbering preference while retaining a different base system language (e.g., English language with German-style numbering), pass the desired locale as a variable before launching DZGUI:
``LC_ALL=de_DE.UTF-8 ./dzgui``
If you intend to use this frequently, you could wrap the above in a script or alias.
+53
View File
@@ -0,0 +1,53 @@
Setup
=========
DayZ license
-----------------
Prepare a Steam account with a DayZ license (i.e., own the game). From Steam's right-click menu for the game options, under ``Compatibility``, enable a Proton version ≥ ``6.8`` (or use Proton
Experimental for the latest version).
As of this writing, any recent version of Proton should work, and it is encouraged to use the most recent one.
API keys
-------------
You will need at a minimum a :ref:`Steam Web API key<steam_api>` in order to browse the server index.
.. _steam_api:
Steam Web API key
^^^^^^^^^^^^^^^^^^
**This step is required**.
Register for a `Steam Web API key <https://steamcommunity.com/dev/apikey>`_ (free) using your Steam account. You will be asked for a unique URL for your app when registering.
Since this key is for a personal use application and does not actually call back anywhere, set a generic local identifier here like "127.0.0.1" or some other name that is meaningful to you.
Once configured, you can insert this key in the app when launching it for the first time.
.. note::
If you are confused about this requirement, please refer to DZGUI Knowledge Base article :ref:`DZG-007<DZG-007>` for additional information.
Battlemetrics API key
^^^^^^^^^^^^^^^^^^^^^^
**This step is optional, but recommended**. Using this key lets you also connect to and query servers by their shorthand ID instead of by IP.
Register for an API key at `BattleMetrics <https://www.battlemetrics.com/account/register?after=%2Fdevelopers>`_ (free).
From the ``Personal Access Tokens area``, select ``New Token``.
Give the token any name in the field at the top.
Leave **all options unchecked** and scroll to the bottom. Select ``Create Token``.
Once configured, you can insert this key in the app when launching it for the first time (optional), or later on when using the connect/query by ID methods in the app.
.. tip::
Each server has a unique ID. This is the string of numbers at the end of the URL. For example, in the URL ``https://www.battlemetrics.com/servers/dayz/8039514``, the ID is ``8039514``.
Next steps
--------------
Proceed to the next section for usage instructions.
+90
View File
@@ -0,0 +1,90 @@
Steam integration
====================
DZGUI can be added to Steam as a "non-Steam game" in order to facilitate integration with Steam Deck or desktop environments.
First, launch Steam in the **Large** (default) view.
.. attention::
Steam Deck users: Gaming Mode has limited support for configuration of custom games. You will need to switch to **Desktop Mode** in order to add a non-Steam game.
.. figure:: images/01.png
:scale: 70%
:alt: Adding a non-Steam game
Select **Add a Game** > **Add a Non-Steam Game** from the bottom left corner of the Steam client.
Navigate to ``$HOME/.local/share/applications`` and select ``dzgui.desktop``.
Select **Add Selected Programs** to add a shortcut to DZGUI.
Artwork
^^^^^^^^^^
DZGUI ships with custom artwork that provides various cover/splash images to allow it to integrate with the rest of your games library.
.. figure:: images/02.png
:scale: 70%
:alt: Adding a non-Steam game
From the main library view, navigate to the app’s details page and right-click the blank image header at the top.
.. figure:: images/03.png
:scale: 70%
:alt: Adding a non-Steam game
Select **Set Custom Background**
Select to display **All Files** from the **File type** dropdown
Navigate to ``$HOME/.local/share/dzgui`` and select ``hero.png``.
.. figure:: images/04.png
:scale: 70%
:alt: Adding a non-Steam game
Next, right-click the image background and select **Set Custom Logo**.
Navigate to ``$HOME/.local/share/dzgui`` and select ``logo.png``.
.. figure:: images/05.png
:scale: 70%
:alt: Adding a non-Steam game
Notice that this removes the redundant app name that occluded the image, as seen above.
.. figure:: images/06.png
:scale: 70%
:alt: Adding a non-Steam game
Next, navigate to your Library index (looks like a bookshelf of cover art) and find the DZGUI app.
Right-click its cover and select **Manage** > **Set custom artwork**.
Navigate to ``$HOME/.local/share/dzgui`` and select ``grid.png``.
.. figure:: images/07.png
:scale: 70%
:alt: Adding a non-Steam game
The final result will create box art looking like the above.
.. figure:: images/08.png
:scale: 100%
:alt: Adding a non-Steam game
Next, right-click the DZGUI entry in your Library and select **Properties** to open the properties dialog. Next to the **Shortcut** field, you will see a small square box which represents the game’s
icon. Click this to open a file explorer, navigate to ``$HOME/.local/share/dzgui``, and select ``icon.png``. This will add a small icon to the list view.
Finally, after you launch DZGUI for the first time, you should quit the application and return to the Library view. Select the **Recent Games** dropdown on the right-hand side.
Steam shows a collection of box art based on categories like "Play Next", "Recent Games", etc. Look for a **downward-pointing caret icon** and click it, then select the **Recent Games** category.
.. figure:: images/09.png
:scale: 100%
:alt: Adding a non-Steam game
If DZGUI was the last item played, it will be shown with a landscape, rather than portrait, orientation cover, which is initially blank.
To customize this cover, right click it and select **Manage** > **Set custom artwork**, navigate to ``$HOME/.local/share/dzgui``, then select ``hero.png``.
+12
View File
@@ -0,0 +1,12 @@
Uninstallation
==================
To uninstall DZGUI and its associated files, invoke ``./dzgui.sh`` with the ``-u`` or ``--uninstall`` flag.
Follow the prompts to choose from:
- **Full uninstall** -- removes the application and all user-defined configuration files
- **Partial uninstall** -- removes the application, but keeps user-defined configuration files
.. tip::
If you intend to reinstall DZGUI again, keeping your configuration files is recommended.
+25
View File
@@ -0,0 +1,25 @@
Usage
=========
It is always advised to have Steam running in the background. DZGUI is meant to run "on top of" Steam.
DZGUI can be launched in one of three ways.
From a terminal
------------------
Invoke the command ``./dzgui.sh`` from wherever you downloaded the DZGUI script to.
Launching from a terminal may give more verbose information in the event of a crash, and can be a good way of troubleshooting problems.
From the shortcut shipped with the application
--------------------------------------------------
On most distributions, if you are using a desktop environment based on the Freedesktop specification, shortcuts will be installed for you.
- One shortcut is located under the ``Games`` category of your system’s applications list/start menu.
- The other is accessed via the ``DZGUI`` desktop icon (Steam Deck only)
From Steam
--------------
See :doc:`steam`.
+43
View File
@@ -0,0 +1,43 @@
After satisfying the dependencies above, create a virtual environment (venv) and install PyGObject:
If you have ``uv`` as your Python version manager, invoke the following:
.. code:: console
uv venv --python 3.13 $HOME/.virtualenvs/dzgui
source $HOME/.virtualenvs/dzgui/bin/activate
uv pip install PyGObject
If you installed the ``python3.13`` package directly instead of ``uv``, use the below:
.. code:: console
python3.13 -m venv $HOME/.virtualenvs/dzgui
source $HOME/.virtualenvs/dzgui/bin/activate
pip install PyGObject
You can now proceed to the :ref:`Installscript`.
After installation, refer to the additional remarks below.
.. important::
Since PyGObject is localized to a venv, it is advisable to create a wrapper script to ensure
the venv is activated on subsequent invocations of DZGUI.
.. code:: console
#!/usr/bin/env bash
source $HOME/.virtualenvs/dzgui/bin/activate
<insert your path to dzgui.sh>
Make sure to update the placeholder path on the last line. For example, if you ran the
installscript from your home directory, the wrapper script would look like:
.. code:: console
#!/usr/bin/env bash
source $HOME/.virtualenvs/dzgui/bin/activate
$HOME/dzgui.sh
Save this wrapper script in a location of your choice, e.g., ``mywrapper.sh`` and set the
executable bit: ``chmod +x mywrapper.sh`` This script will be your entrypoint for
future invocations of DZGUI, so you should launch it, not ``dzgui.sh``
-1265
View File
File diff suppressed because it is too large. Load diff
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+40
View File
@@ -0,0 +1,40 @@
import logging
import requests
from typing import Any, Optional, TYPE_CHECKING
from dzgui.const.constants import APP_NAME
from dzgui.const.endpoints import BM_SERVERS
logger = logging.getLogger(APP_NAME)
if TYPE_CHECKING:
from dzgui.api.servers import Record
def get_attributes(key: str, uid: int) -> Any:
# TODO: handle if key is not set
# TODO: tests for malformed IDs/values
hdr = {"Authorization": "Bearer " + key}
payload: dict[str, str] = {
"filter[game]": "dayz",
"sort": "-players",
"filter[ids][whitelist]": str(uid),
}
res = requests.get(BM_SERVERS, params=payload, headers=hdr)
res.raise_for_status()
j = res.json()["data"][0]["attributes"]
return j
def map_id_to_record(key: str, uid: int) -> Optional["Record"]:
from dzgui.api.servers import Record
try:
record = get_attributes(key, uid)
ip = record["ip"]
port = int(record["port"])
qport = int(record["portQuery"])
return Record(ip, port, qport)
except Exception:
return None
+207
View File
@@ -0,0 +1,207 @@
import hashlib
import logging
import shlex
from concurrent.futures import wait
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
import dzgui.api.pefile as PeFile
from dzgui.api.servers import get_rules, fqip_to_record
from dzgui.const.constants import (
APP_NAME,
APPID_DAYZ,
LIBRARYFOLDERS_PATH,
WORKSHOP_PATH,
)
from dzgui.config.query import lookup
from dzgui.const.enum import Preferences
from typing import Any
logger = logging.getLogger(APP_NAME)
@dataclass
class ModMeta:
protocol: str
published_id: str
name: str
timestamp: str
def get_local_mod_ids(steam_path: Path) -> list[int]:
workshop_path = get_local_mod_path(steam_path)
mods = get_local_mods(workshop_path)
return [int(mod.name) for mod in mods]
def get_local_mod_path(steam_path: Path) -> Path:
p = PeFile.get_app_path(steam_path / Path(LIBRARYFOLDERS_PATH), APPID_DAYZ)
workshop_path = p / WORKSHOP_PATH
return workshop_path
def get_local_mods(workshop_path: Path) -> list[Path]:
mods = [file for file in workshop_path.iterdir() if file.is_dir()]
return mods
def parse_meta(file: Path) -> ModMeta | None:
mod = file / "meta.cpp"
if mod.exists() is False:
return None
with open(file / "meta.cpp", "r") as f:
st = f.read()
lex = shlex.shlex(st)
lex.whitespace += "=;"
v = []
while True:
tok = lex.get_token()
if not tok:
break
if tok == "protocol" or tok == "publishedid":
ntok = lex.get_token()
elif tok == "timestamp":
# NOTE: some malformed .NET tick conversions result in numbers < 0
ntok = lex.get_token()
if ntok == "-":
ntok += str(lex.get_token())
elif tok == "name":
ntok = lex.get_token()
if ntok is not None:
ntok = ntok.split('"')[1]
if ntok is not None:
v.append(ntok)
meta = ModMeta(*v)
return meta
def get_mod_size(path: Path) -> float:
s = 0
for f in path.rglob("*"):
s += f.stat().st_size
size = round(s / (1024**2), 3)
return size
def get_delimited_mods(steam_path: Path) -> list[Any]:
workshop_path = get_local_mod_path(steam_path)
mods = get_local_mods(workshop_path)
clean = []
for mod in mods:
mod_dir = mod.name
symlink = _hash(mod_dir)
# FIXME: malformed .cpp files could break this
# mention that mods may be downloading
meta = parse_meta(mod)
if meta is None:
continue
size = get_mod_size(mod)
# NOTE: final col is cell renderer highlight toggle
clean.append([meta.name, symlink, mod_dir, size, False])
clean.sort(key=lambda row: str(row[0]).casefold())
return clean
def get_missing_mods(local: list, remote: list) -> list:
return [mod for mod in remote if mod not in local]
def _hash(uid: str) -> str:
md5 = hashlib.md5()
md5.update(uid.encode("ascii"))
return "@" + md5.hexdigest()[:8]
def remove_stale_signatures(config: Path, versions: Path) -> None:
if versions.is_file() is False:
logger.warning("Creating new version signatures file")
versions.touch()
return
path = lookup(config, Preferences.DEFAULT)
steam_path = Path(path)
ids = get_local_mod_ids(steam_path)
with open(versions, "r") as f:
lines = f.readlines()
for line in lines:
uid = int(line.split(",")[0])
if uid not in ids:
lines.remove(line)
with open(versions, "w") as f:
for line in lines:
f.write(line)
def find_stale_mods(config: Path) -> list[int]:
def push_record(rec: str) -> list:
record = fqip_to_record(rec)
if record is None:
return []
try:
mods = get_rules(record)
except Exception:
return []
return [mod.workshop_id for mod in mods]
steam = lookup(config, Preferences.DEFAULT)
steam_path = Path(steam)
local = get_local_mod_ids(steam_path)
records = lookup(config, Preferences.IP_LIST)
remote_mods = []
with ThreadPoolExecutor() as executor:
futures = [executor.submit(push_record, record) for record in records]
wait(futures)
for future in futures:
res = future.result()
remote_mods.extend(res)
unique_mods = set(remote_mods)
stale = [mod for mod in local if mod not in unique_mods]
return stale
def get_mod_dir_size(path: Path) -> int:
"""
This is not a guarantee of parity, as user may adjusted contents of local mods,
so upstream epoch time is still used
"""
size = 0
for i in Path(path).iterdir():
if i.is_file():
size += i.stat().st_size
elif i.is_dir():
size += get_mod_dir_size(i)
return size
def version_file_to_dict(file: Path) -> dict[str, str]:
versions = file.read_text().splitlines()
d: dict[str, str] = {}
for version in versions:
line = version.split(",")
mod = line[0]
stamp = line[1]
d[mod] = stamp
return d
def update_signatures(
mods: list[tuple[str, str, int, int]], version_file: Path
) -> None:
d = version_file_to_dict(version_file)
for _title, mod, stamp, size in mods:
d[mod] = str(stamp)
versions: list[str] = []
for k, v in d.items():
row = ",".join([k, v])
versions.append(row)
with open(version_file, "w") as f:
for version in versions:
f.write(f"{version}\n")
+80 -111
View File
@@ -1,12 +1,20 @@
import json import json
import struct import struct
import typing # noqa
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum from enum import Enum
from pathlib import Path from pathlib import Path
from shlex import shlex from typing import BinaryIO, Self, Union
from typing import BinaryIO, Union
from dzgui.const.constants import (
APPID_DAYZ,
APPID_DAYZ_EXP,
APPNAME_DAYZ,
APPNAME_DAYZ_EXP,
DAYZ_BINARY,
LIBRARYFOLDERS_PATH,
)
from dzgui.api.steam import vdf2json
# https://learn.microsoft.com/en-us/windows/win32/debug/pe-format # https://learn.microsoft.com/en-us/windows/win32/debug/pe-format
endian = "<" endian = "<"
@@ -25,44 +33,44 @@ class VersionMatch(Enum):
SAME_VERSION = 3 SAME_VERSION = 3
class u8: class u8(int):
fmt = "B" fmt = "B"
class u16: class u16(int):
fmt = "H" fmt = "H"
class u32: class u32(int):
fmt = "L" fmt = "L"
class u64: class u64(int):
fmt = "Q" fmt = "Q"
class i8: class i8(int):
fmt = "b" fmt = "b"
class i16: class i16(int):
fmt = "h" fmt = "h"
class i32: class i32(int):
fmt = "l" fmt = "l"
class i64: class i64(int):
fmt = "q" fmt = "q"
class PackedData: class PackedData:
@classmethod @classmethod
def unpack(cls, data: BinaryIO): def unpack(cls, data: BinaryIO) -> Self:
r = [] r = []
for key, value in cls.__annotations__.items(): for key, value in cls.__annotations__.items():
if value == str: if value is str:
f = data.read(8).rstrip(b"\x00\x00").decode() f = data.read(8).rstrip(b"\x00\x00").decode()
else: else:
fmt = endian + (value.fmt) fmt = endian + (value.fmt)
@@ -231,7 +239,7 @@ class FileVersion:
major: int major: int
minor: int minor: int
build: int build: int
revision: int revision: str
@dataclass(slots=True, frozen=True) @dataclass(slots=True, frozen=True)
@@ -268,13 +276,16 @@ class VDFLoadError(Exception):
pass pass
def parse_version_number(data: BinaryIO): def parse_version_number(data: BinaryIO) -> FileVersion:
# https://learn.microsoft.com/en-us/windows/win32/api/verrsrc/ns-verrsrc-vs_fixedfileinfo # https://learn.microsoft.com/en-us/windows/win32/api/verrsrc/ns-verrsrc-vs_fixedfileinfo
minor = struct.unpack("<L", data.read(4))[0] >> 16 & 0xFFFF minor = struct.unpack("<L", data.read(4))[0] >> 16 & 0xFFFF
major = struct.unpack("<L", data.read(4))[0] >> 0 & 0xFFFF major = struct.unpack("<L", data.read(4))[0] >> 0 & 0xFFFF
build = struct.unpack("<L", data.read(4))[0] >> 0 & 0xFFFF build = struct.unpack("<L", data.read(4))[0] >> 0 & 0xFFFF
revision = struct.unpack("<L", data.read(4))[0] >> 16 & 0xFFFF # NOTE: 0-pad revision number
return FileVersion(major, minor, build, revision) revision = str(struct.unpack("<L", data.read(4))[0] >> 16 & 0xFFFF)
offset = 3 - len(revision)
padded = "0" * offset + revision
return FileVersion(major, minor, build, padded)
def seek_to_hex(address: str, data: BinaryIO) -> None: def seek_to_hex(address: str, data: BinaryIO) -> None:
@@ -291,10 +302,11 @@ def seek_to_pe_stub(data: BinaryIO) -> None:
raise PeFileError("missing PE header data") raise PeFileError("missing PE header data")
def get_dayz_version(file: Path) -> DayZVersion | Exception: def get_dayz_version(file: Path) -> DayZVersion:
try: try:
version = get_version(file) version = get_version(file)
except Exception as e: except Exception as e:
# TODO: log the exception
raise e raise e
patch = str(version.build) + str(version.revision) patch = str(version.build) + str(version.revision)
dz_vers = DayZVersion(version.major, version.minor, int(patch)) dz_vers = DayZVersion(version.major, version.minor, int(patch))
@@ -302,7 +314,8 @@ def get_dayz_version(file: Path) -> DayZVersion | Exception:
def dayz_version_to_str(v: DayZVersion) -> str: def dayz_version_to_str(v: DayZVersion) -> str:
return ".".join(str(el) for el in [v.major, v.minor, v.patch]) return ".".join(el for el in list(map(str, [v.major, v.minor, v.patch])))
# return ".".join(str(el) for el in [v.major, v.minor, v.patch])
def dayz_version_from_str(v: str) -> DayZVersion: def dayz_version_from_str(v: str) -> DayZVersion:
@@ -311,7 +324,7 @@ def dayz_version_from_str(v: str) -> DayZVersion:
return DayZVersion(*[int(el) for el in vers]) return DayZVersion(*[int(el) for el in vers])
def get_version(file): def get_version(file: Path) -> FileVersion:
with open(file, "rb") as f: with open(file, "rb") as f:
seek_to_pe_stub(f) seek_to_pe_stub(f)
COFF = COFF_FILE_HDR.unpack(f) COFF = COFF_FILE_HDR.unpack(f)
@@ -321,6 +334,7 @@ def get_version(file):
magic = hex(struct.unpack("<H", (blob[0:2]))[0]) magic = hex(struct.unpack("<H", (blob[0:2]))[0])
f.seek(pos) f.seek(pos)
OBJW: OPTIONAL_HDR_WIN_X86 | OPTIONAL_HDR_WIN_X64
if magic == PE32_x86: if magic == PE32_x86:
OPTIONAL_HDR_X86.unpack(f) OPTIONAL_HDR_X86.unpack(f)
OBJW = OPTIONAL_HDR_WIN_X86.unpack(f) OBJW = OPTIONAL_HDR_WIN_X86.unpack(f)
@@ -354,18 +368,15 @@ def get_version(file):
table = RESOURCE_DIRECTORY_TABLE.unpack(f) table = RESOURCE_DIRECTORY_TABLE.unpack(f)
total = table.number_of_name_entries + table.number_of_id_entries total = table.number_of_name_entries + table.number_of_id_entries
for entry in range(total): for _iter in range(total):
entry = RESOURCE_DIRECTORY_ENTRY.unpack(f) entry = RESOURCE_DIRECTORY_ENTRY.unpack(f)
if entry.name_or_id == VERSION_RESOURCE: if entry.name_or_id == VERSION_RESOURCE:
while entry.data_or_subdir & (1 << 31): while entry.data_or_subdir & (1 << 31):
shift = entry.data_or_subdir & ~(1 << 31) shift = entry.data_or_subdir & ~(1 << 31)
seek_to_hex(hex(offset + shift), f) seek_to_hex(hex(offset + shift), f)
table = RESOURCE_DIRECTORY_TABLE.unpack(f) table = RESOURCE_DIRECTORY_TABLE.unpack(f)
total = ( total = table.number_of_name_entries + table.number_of_id_entries
table.number_of_name_entries for _iter in range(total):
+ table.number_of_id_entries
)
for entry in range(total):
entry = RESOURCE_DIRECTORY_ENTRY.unpack(f) entry = RESOURCE_DIRECTORY_ENTRY.unpack(f)
break break
if entry.name_or_id > VERSION_RESOURCE: if entry.name_or_id > VERSION_RESOURCE:
@@ -377,7 +388,7 @@ def get_version(file):
offset = data.data_rva - hdr.virtual_address + hdr.pointer_to_raw_data offset = data.data_rva - hdr.virtual_address + hdr.pointer_to_raw_data
seek_to_hex(hex(offset), f) seek_to_hex(hex(offset), f)
hdr = VS_VERSION_INFO_HDR.unpack(f) VS_VERSION_INFO_HDR.unpack(f)
# https://learn.microsoft.com/en-us/windows/win32/menurc/vs-versioninfo # https://learn.microsoft.com/en-us/windows/win32/menurc/vs-versioninfo
byte_len = len(VS_VERSION_INFO_ID.encode("utf-16le")) byte_len = len(VS_VERSION_INFO_ID.encode("utf-16le"))
label = f.read(byte_len).decode("utf-16le") label = f.read(byte_len).decode("utf-16le")
@@ -394,99 +405,57 @@ def get_version(file):
try: try:
version = parse_version_number(f) version = parse_version_number(f)
except Exception as e: except Exception as e:
return PeFileError(e) raise PeFileError(e)
return version return version
def get_pefile_path(path: str, appid: int) -> Path: def get_nested_app_path(steam_path: Path, appid: int) -> Path:
binary = "DayZ_x64.exe" return get_pefile_path(steam_path, appid).parent
identifier = {221100: "DayZ", 1024020: "DayZ Exp"}
def get_pefile_path(steam_path: Path, appid: int) -> Path:
identifier = {APPID_DAYZ: APPNAME_DAYZ, APPID_DAYZ_EXP: APPNAME_DAYZ_EXP}
name = identifier[appid] name = identifier[appid]
binary = DAYZ_BINARY
pe_path = None app_path = get_app_path(steam_path / LIBRARYFOLDERS_PATH, appid)
path = path + "/steamapps/libraryfolders.vdf" pe_path = app_path / f"steamapps/common/{name}/{binary}"
with open(path, "r") as f:
try:
j = json.loads(vdf_to_json(f))
except Exception:
raise VDFLoadError("Failed to parse libraryfolders")
for obj in j["libraryfolders"]:
if str(appid) in j["libraryfolders"][obj]["apps"]:
pe_path = j["libraryfolders"][obj]["path"]
pe_path += f"/steamapps/common/{name}/{binary}"
break
if pe_path is None:
raise AppNotInstalledError(
f"Failed to find a libraryfolder for the appid '{appid}'"
)
pe_path = Path(pe_path)
if pe_path.exists() is False:
raise AppMovedError(
f"Path '{pe_path}' specified in libraryfolders does not exist"
)
return pe_path return pe_path
def compare_versions(local: DayZVersion, remote: DayZVersion): def get_app_path(folders_path: Path, appid: int) -> Path:
""" app_path = None
packaging.version module is not available OOTB on some distributions
"""
if dayz_version_to_str(local) == dayz_version_to_str(remote):
return VersionMatch.SAME_VERSION
if local.major < remote.major: try:
return VersionMatch.LOCAL_OLDER j = json.loads(vdf2json(folders_path))
if local.major > remote.major: except Exception:
return VersionMatch.LOCAL_NEWER raise VDFLoadError("Failed to parse libraryfolders")
if local.major == remote.major:
if local.minor < remote.minor: for obj in j["libraryfolders"]:
return VersionMatch.LOCAL_OLDER if str(appid) in j["libraryfolders"][obj]["apps"]:
if local.minor > remote.minor: app_path = j["libraryfolders"][obj]["path"]
return VersionMatch.LOCAL_NEWER if Path(app_path).exists():
if local.minor == remote.minor: break
if local.patch < remote.patch:
return VersionMatch.LOCAL_OLDER if app_path is None:
if local.patch > remote.patch: raise AppNotInstalledError(
return VersionMatch.LOCAL_NEWER f"Failed to find a libraryfolder for the appid {appid}"
if local.patch == remote.patch: )
return VersionMatch.SAME_VERSION if Path(app_path).exists() is False:
raise AppMovedError(
f"The location '{app_path}' pointed to by '{appid}' no longer exists and may have been changed on the disk."
)
return Path(app_path)
def vdf_to_json(stream): def get_pretty_version(steam_path: Path, appid: int) -> str | None:
def _istr(indent, string): try:
return (indent * " ") + string pe_file_path = get_pefile_path(steam_path, appid)
vers = get_dayz_version(pe_file_path)
jbuf = "{\n" dayz_version = dayz_version_to_str(vers)
lex = shlex(stream) return dayz_version
indent = 1 except Exception as e:
print(e)
while True: return None
tok = lex.get_token()
if not tok:
return jbuf + "}\n"
if tok == "}":
indent -= 1
jbuf += _istr(indent, "}")
ntok = lex.get_token()
lex.push_token(ntok)
if ntok and ntok != "}":
jbuf += ","
jbuf += "\n"
else:
ntok = lex.get_token()
if ntok == "{":
jbuf += _istr(indent, tok + ": {\n")
indent += 1
else:
jbuf += _istr(indent, tok + ": " + ntok)
ntok = lex.get_token()
lex.push_token(ntok)
if ntok != "}":
jbuf += ","
jbuf += "\n"
+63
View File
@@ -0,0 +1,63 @@
import logging
import requests
from typing import Union, TYPE_CHECKING
from dzgui.const.constants import APPID_DAYZ, APP_NAME, REQUEST_TIMEOUT
from dzgui.const import endpoints
logger = logging.getLogger(APP_NAME)
if TYPE_CHECKING:
from requests import Response
def test_steam_api(key: str) -> bool:
appid = APPID_DAYZ
payload: dict[str, Union[int, str]] = {
"filter": r"\appid" + rf"\{appid}",
"limit": 10,
"key": key,
}
try:
res = requests.get(
endpoints.STEAM_SERVERS, params=payload, timeout=REQUEST_TIMEOUT
)
return is_remote_up(res)
except Exception as e:
logger.critical(e)
# TODO: pass exception text into dialog
return False
# TODO: consolidate is_remote_up and exception logic into one function
def test_ipdb() -> bool:
try:
res = requests.get(endpoints.DB_IP, timeout=REQUEST_TIMEOUT)
return is_remote_up(res)
except Exception as e:
logger.critical(e)
return False
def test_bm_api(key: str) -> bool:
payload: dict[str, str] = {
"filter[game]": "dayz",
}
hdr = {"Authorization": "Bearer " + key}
try:
res = requests.get(
endpoints.BM_SERVERS, params=payload, headers=hdr, timeout=REQUEST_TIMEOUT
)
return is_remote_up(res)
except Exception as e:
logger.critical(e)
return False
def is_remote_up(res: "Response") -> bool:
if res.status_code == 200:
return True
else:
return False
+231 -181
View File
@@ -1,20 +1,32 @@
import json import ipaddress
import logging
import math import math
import os import os
import re import re
import requests
import socket import socket
import subprocess import subprocess
import sys import threading
import typing # noqa
from dataclasses import dataclass from dataclasses import dataclass
from urllib import request, parse from typing import Any, Optional, TYPE_CHECKING, Union
from urllib.error import HTTPError
from typing import Union
sys.path.append("a2s") from dzgui.api.bm import map_id_to_record
import a2s # noqa from dzgui.const.constants import APP_NAME, REQUEST_TIMEOUT
from a2s import dayzquery # noqa from dzgui.const.endpoints import STEAM_SERVERS
from dzgui.util import strings
import a2s
import dayzquery
if TYPE_CHECKING:
from a2s import SourceInfo
from dayzquery import DayzMod
logger = logging.getLogger(APP_NAME)
# TODO: confirm that patches from testing are incorporated here
# particularly around malformed values in JSON response. check commit log
params = [ params = [
r"\nor\1\map\chernarusplus\nor\1\map\sakhal\nor\1\map\enoch\empty\1\nor\1\map\namalsk", # noqa r"\nor\1\map\chernarusplus\nor\1\map\sakhal\nor\1\map\enoch\empty\1\nor\1\map\namalsk", # noqa
@@ -29,26 +41,80 @@ params = [
] ]
class BmAPIError(Exception):
pass
class BmIdError(Exception):
pass
class InvalidIpError(Exception): class InvalidIpError(Exception):
pass pass
@dataclass(slots=True, frozen=True)
class Res:
status: int
parsed: bool
json: Union[dict[str, Any], None]
@dataclass(slots=True, frozen=True)
class Details:
data: Union[list, None]
description: str
success: bool
@dataclass(slots=True)
class Record:
"""
The gameport field is manipulated by the RowType.CONN_BY_IP method
"""
ip: str
gameport: int
qport: int
class A2SInfo:
def __init__(self, record: Record, info: a2s.SourceInfo | None) -> None:
self.record = record
self.info = info
def get_record(self) -> Record:
return self.record
def get_info(self) -> a2s.SourceInfo | None:
return self.info
def as_row(self) -> dict[str, Any]:
if self.info is None:
raise AttributeError("No record to convert")
ip = self.record.ip
qport = self.record.qport
try:
return source_info_to_dict(ip, qport, self.info)
except Exception as e:
logger.warning(e)
raise e
def is_modded(self) -> bool:
if self.info is None:
raise ValueError("Cannot call this method on Nonetype")
try:
kw = self.info.keywords.split(",")
state = True if "mod" in kw else False
return state
except Exception as e:
logger.warning(e)
raise e
def get_netmask() -> str: def get_netmask() -> str:
hostname = os.uname()[1] hostname = os.uname()[1]
i = socket.gethostbyname(hostname) i = socket.gethostbyname(f"{hostname}.local")
netmask = i.rsplit(".", 1)[0] netmask = i.rsplit(".", 1)[0]
return netmask return netmask
def test_ip(suffix: int, port: int) -> dict | None: # TODO: rename
def test_ip(suffix: int, port: int, event: threading.Event) -> dict | None:
if event.is_set():
return None
netmask = get_netmask() netmask = get_netmask()
hostname = f"{netmask}.{str(suffix)}" hostname = f"{netmask}.{str(suffix)}"
ping = ["ping", "-c1", "-i", "0.1", "-w", "1"] ping = ["ping", "-c1", "-i", "0.1", "-w", "1"]
@@ -59,6 +125,9 @@ def test_ip(suffix: int, port: int) -> dict | None:
def sanitize(name: str) -> str: def sanitize(name: str) -> str:
"""
Strips extraneous padding and spammy junk chars in server names
"""
name = re.sub(r"\r", r"", name) name = re.sub(r"\r", r"", name)
name = re.sub(r"\n", r"", name) name = re.sub(r"\n", r"", name)
name = re.sub(r"\x01", r"", name) name = re.sub(r"\x01", r"", name)
@@ -111,14 +180,14 @@ def parse_json(json: list) -> list:
continue continue
if "no3rd" in r: if "no3rd" in r:
view = "1PP" view = strings.filter_1pp
else: else:
view = "3PP" view = strings.filter_3pp
if "external" in r: if "external" in r:
provider = "Unoffic." provider = strings.filter_unofficial
else: else:
provider = "Official" provider = strings.filter_official
if "mod" in r: if "mod" in r:
modded = True modded = True
@@ -128,6 +197,8 @@ def parse_json(json: list) -> list:
try: try:
r = row["gametype"].split("lqs") r = row["gametype"].split("lqs")
queue = r[1].split(",")[0] queue = r[1].split(",")[0]
if int(queue) > 255:
continue
except IndexError: except IndexError:
queue = 0 queue = 0
@@ -136,9 +207,9 @@ def parse_json(json: list) -> list:
if test_time: if test_time:
time = test_time.group(0) time = test_time.group(0)
else: else:
time = "Unknown" time = strings.unknown
except AttributeError: except AttributeError:
time = "Unknown" time = strings.unknown
try: try:
ip = row["addr"].split(":")[0] + ":" + str(row["gameport"]) ip = row["addr"].split(":")[0] + ":" + str(row["gameport"])
@@ -154,7 +225,7 @@ def parse_json(json: list) -> list:
mapname = row["map"].lower() mapname = row["map"].lower()
players = row["players"] players = row["players"]
max_players = row["max_players"] max_players = row["max_players"]
raw = [ raw = (
name, name,
mapname, mapname,
view, view,
@@ -167,15 +238,13 @@ def parse_json(json: list) -> list:
ping, ping,
provider, provider,
modded, modded,
] )
rows.append(raw) rows.append(raw)
return rows return rows
def query_direct(ip: str, qport: int, TIMEOUT: float=3.0) -> dict | None: def source_info_to_dict(ip: str, qport: int, info: "SourceInfo") -> dict[str, Any]:
try: try:
info = a2s.info((ip, qport), TIMEOUT)
name = info.server_name name = info.server_name
mapname = info.map_name mapname = info.map_name
address = ip + ":" + str(qport) address = ip + ":" + str(qport)
@@ -200,75 +269,33 @@ def query_direct(ip: str, qport: int, TIMEOUT: float=3.0) -> dict | None:
res["gameport"] = gameport res["gameport"] = gameport
res["ping"] = ping res["ping"] = ping
return res return res
except TimeoutError: except Exception as e:
return None # TODO: generalized function
except KeyError: logger.critical(f"{type(e).__name__}: {e} ({ip}:{qport})")
return None raise e
@dataclass(slots=True, frozen=True) def query_direct(ip: str, qport: int, timeout: float = 3.0) -> dict[str, Any] | None:
class Res:
status: int
parsed: bool
json: Union[str, None]
@dataclass(slots=True, frozen=True)
class Ping:
addr: str
iteration: int
ping: int
@dataclass(slots=True, frozen=True)
class Details:
data: Union[list, None]
description: str
success: bool
@dataclass(slots=True, frozen=True)
class Prereqs:
password: bool
gameport: int
appid: Union[int, None]
version: Union[str, None]
@dataclass(slots=True)
class Record:
"""
The gameport field is manipulated by the RowType.CONN_BY_IP method
"""
ip: str
gameport: int
qport: int
def get_prereqs(ip: str, qport: int) -> Prereqs:
try: try:
info = a2s.info((ip, qport)) info = a2s.info((ip, qport), timeout)
except TimeoutError: return source_info_to_dict(ip, qport, info)
return Prereqs(False, 0, None, None) except Exception as e:
logger.warning(e)
gameport = getattr(info, "port", 0) return None
is_password = getattr(info, "password_protected", False)
appid = getattr(info, "game_id", None)
version = getattr(info, "version", None)
return Prereqs(is_password, gameport, appid, version)
def details(ip: str, qport: int) -> Details: def get_details(record: Record) -> Details:
default_str = "None provided" ip = record.ip
qport = record.qport
default_str = strings.none_provided
try: try:
info = a2s.info((ip, qport)) info = a2s.info((ip, qport))
except TimeoutError: except TimeoutError:
return Details(None, default_str, False) return Details(None, default_str, False)
try: try:
rules = dayzquery.dayz_rules((ip, int(qport))) rules = dayzquery.dayz_rules((ip, qport))
except TimeoutError: except Exception:
return Details(None, default_str, False) return Details(None, default_str, False)
try: try:
@@ -276,9 +303,9 @@ def details(ip: str, qport: int) -> Details:
except AttributeError: except AttributeError:
return Details(None, default_str, False) return Details(None, default_str, False)
battleye = "Disabled" battleye = strings.disabled
if "battleye" in keywords: if "battleye" in keywords:
battleye = "Enabled" battleye = strings.enabled
day_accel = 0.0 day_accel = 0.0
night_accel = 0.0 night_accel = 0.0
@@ -293,43 +320,43 @@ def details(ip: str, qport: int) -> Details:
try: try:
password = info.password_protected password = info.password_protected
if password is False: if password is False:
password = "Disabled" password = strings.disabled
else: else:
password = "Enabled" password = strings.enabled
except AttributeError: except AttributeError:
password = "-" password = "-"
try: try:
vac = info.vac_enabled vac = info.vac_enabled
if vac is False: if vac is False:
vac = "Disabled" vac = strings.disabled
else: else:
vac = "Enabled" vac = strings.enabled
except AttributeError: except AttributeError:
vac = "-" vac = strings.null
try: try:
version = info.version version = info.version
except AttributeError: except AttributeError:
version = "-" version = strings.null
try: try:
dlc = rules.dlc_flags dlc = rules.dlc_flags
if dlc == 0: if dlc == 0:
dlc = "None" dlc = strings.none
if dlc == 2: if dlc == 2:
dlc = "Frostline" dlc = strings.dlc_frostline
except AttributeError: except AttributeError:
dlc = "not specified" dlc = strings.unspecified
try: try:
platform = rules.platform platform = rules.platform
if platform == "win": if platform == "win":
platform = "Windows" platform = strings.windows
if platform == "?": if platform == "?":
platform = "Linux" platform = strings.linux
except AttributeError: except AttributeError:
platform = "not specified" platform = strings.unspecified
try: try:
description = rules.description.strip() description = rules.description.strip()
@@ -352,97 +379,40 @@ def details(ip: str, qport: int) -> Details:
return Details(rows, description, True) return Details(rows, description, True)
def ping(iteration: int, row: list) -> Ping: def ping(ip: str, qport: int) -> int:
addr = row[7]
qport = row[8]
res = None
if row[9] != 9999:
return Ping(addr, iteration, row[9])
try:
ip = addr.split(":")[0]
except IndexError:
ping = 9999
try: try:
res = query_direct(ip, qport, 0.5) res = query_direct(ip, qport, 0.5)
if res is None:
return 9999
else:
return int(res["ping"])
except Exception: except Exception:
pass return 9999
if res is None:
ping = 9999
else:
ping = res["ping"]
return Ping(addr, iteration, ping)
def query_api(key: str, appid: int, param: str) -> Res: def query_api(key: str, appid: int, param: str) -> Res:
LIMIT = 10000 LIMIT = 10000
url = "https://api.steampowered.com/IGameServersService/GetServerList/v1/?"
payload: dict[str, Union[int, str]] = { payload: dict[str, Union[int, str]] = {
"filter": r"\appid" + fr"\{appid}" + param, "filter": r"\appid" + rf"\{appid}" + param,
"limit": LIMIT, "limit": LIMIT,
"key": key, "key": key,
} }
par = parse.urlencode(payload)
url = f"{url}{par}"
status = 200
parsed = True
data = None
try: try:
with request.urlopen(url) as response: """
if response.status != 200: NOTE: the global default timeout is None;
status = response.status using a low timeout (~5s) sometimes fails
try: """
parsed = True res = requests.get(STEAM_SERVERS, params=payload, timeout=REQUEST_TIMEOUT)
data = json.load(response) res.raise_for_status()
except json.decoder.JSONDecodeError: parsed = True
parsed = False status = 200
data = None json = res.json()
except HTTPError: except Exception:
status = 403
parsed = False parsed = False
data = None json = None
status = 403
finally: finally:
return Res(status, parsed, data) return Res(status, parsed, json)
def query_bm_api(api_key: str, bm_id: str) -> Record:
if bm_id.isnumeric() is False:
raise BmIdError("ID must be numeric only")
payload: dict[str, Union[int, str]] = {
"sort": "-players",
"filter[game]": "dayz",
"filter[ids][whitelist]": bm_id,
}
url = "https://api.battlemetrics.com/servers?"
par = parse.urlencode(payload)
url = f"{url}{par}"
hdr = {"Authorization": "Bearer " + api_key}
r = request.Request(url, headers=hdr)
try:
with request.urlopen(r) as response:
try:
j = json.load(response)
except json.decoder.JSONDecodeError:
raise BmAPIError("Malformed response from Battlemetrics")
if len(j["data"]) < 1:
raise BmAPIError("Not a valid Battlemetrics ID")
j = j["data"][0]["attributes"]
return Record(j["ip"], j["port"], j["portQuery"])
except HTTPError:
raise BmAPIError("Failed to query Battlemetrics")
def validate_ip(addr: str) -> Record: def validate_ip(addr: str) -> Record:
@@ -462,11 +432,91 @@ def validate_ip(addr: str) -> Record:
raise InvalidIpError(f"'{port}' is not a valid port") raise InvalidIpError(f"'{port}' is not a valid port")
try: try:
socket.inet_aton(ip) ipaddress.ip_address(ip)
except OSError: except ValueError:
raise InvalidIpError(f"'{ip}' is not a valid IP") raise InvalidIpError(f"'{ip}' is not a valid IP")
ip = addr.split(":")[0] ip = addr.split(":")[0]
qport = int(addr.split(":")[1]) qport = int(addr.split(":")[1])
record = Record(ip, 0, qport) record = Record(ip, 0, qport)
return record return record
def get_rules(record: Record) -> list["DayzMod"]:
ip = record.ip
qport = record.qport
mods = dayzquery.dayz_rules((ip, qport)).mods
return [mod for mod in mods]
def query_playercount(record: Record) -> tuple[int, int] | None:
try:
res = query_direct(record.ip, record.qport)
if res is None:
return None
players = int(res["players"])
r = res["gametype"].split("lqs")
try:
queue = int(r[1].split(",")[0])
except IndexError:
queue = 0
return players, queue
except Exception as e:
logger.critical(e)
return None
def query_by_ip(addr: str) -> A2SInfo:
record = short_ip_to_record(addr)
if record is None:
return A2SInfo(Record("0", 0, 0), None)
return query_by_record(record, update_gameport=True)
def query_by_id(server_id: int, key: str) -> A2SInfo:
"""
Used with numeric Battlemetrics IDs
"""
record = map_id_to_record(key, server_id)
if record is None:
return A2SInfo(Record("0", 0, 0), None)
return query_by_record(record)
def query_by_record(record: Record, update_gameport: bool = False) -> A2SInfo:
try:
info = a2s.info((record.ip, record.qport), 3.0)
if update_gameport:
record = Record(record.ip, info.port, record.qport)
return A2SInfo(record, info)
except Exception as e:
logger.warning(e)
return A2SInfo(record, None)
def short_ip_to_record(addr: str) -> Optional[Record]:
r = addr.split(":")
# TODO: raise exceptions instead of Nonetype
if len(r) != 2:
return None
return Record(r[0], 0, int(r[1]))
def fqip_to_record(addr: str) -> Optional[Record]:
r = addr.split(":")
if len(r) != 3:
return None
return Record(r[0], int(r[1]), int(r[2]))
def response_to_fqip(res: dict) -> str:
ip = res["addr"].split(":")[0]
gameport = res["gameport"]
qport = res["addr"].split(":")[1]
return f"{ip}:{gameport}:{qport}"
def response_to_record(res: dict) -> Record:
ip = res["addr"].split(":")[0]
gameport = res["gameport"]
qport = res["addr"].split(":")[1]
return Record(ip, int(gameport), int(qport))
+214
View File
@@ -0,0 +1,214 @@
import json
import logging
import os
import requests
import subprocess
from shlex import shlex
from pathlib import Path
from dzgui.init.prereqs import has_steam_client
from dzgui.const.constants import (
APP_NAME,
DEBIAN_STEAM_PATH,
DEFAULT_STEAM_PATH,
FLATPAK_STEAM_PATH,
UBUNTU_STEAM_PATH,
VDF_PATH,
)
from dzgui.const.endpoints import STEAM_PUBLISHED_FILES
from dzgui.strings import wizard
from dzgui.util.bash import concat_bash_args
logger = logging.getLogger(APP_NAME)
def get_steam_paths() -> list[tuple[Path, str]]:
paths = []
if has_steam_client():
HOME = Path.home()
env = os.environ.get("XDG_DATA_HOME")
if env is not None:
XDG_DATA_HOME = env
else:
XDG_DATA_HOME = DEFAULT_STEAM_PATH
DEFAULT_PATH = HOME.joinpath(XDG_DATA_HOME)
FLATPAK_PATH = HOME.joinpath(FLATPAK_STEAM_PATH)
UBUNTU_PATH = HOME.joinpath(UBUNTU_STEAM_PATH)
DEBIAN_PATH = HOME.joinpath(DEBIAN_STEAM_PATH)
human = {
DEFAULT_PATH: wizard.desc_default_path,
FLATPAK_PATH: wizard.desc_flatpak_path,
UBUNTU_PATH: wizard.desc_ubuntu_path,
DEBIAN_PATH: wizard.desc_debian_path,
}
for path in DEFAULT_PATH, FLATPAK_PATH, UBUNTU_PATH, DEBIAN_PATH:
if path.joinpath(VDF_PATH).is_file():
paths.append((path, human[path]))
return paths
def concat_mods(mods: list[str]) -> str:
from dzgui.util.symlink import _hash
hashes = []
for mod in mods:
md5sum = _hash(mod)
hashes.append(md5sum)
return ";".join(hashes)
def get_local_signatures(version_file: Path) -> dict[str, int]:
hashes: dict[str, int] = {}
lines = version_file.read_text().splitlines()
for line in lines:
data = line.split(",")
_id = data[0]
_hash = int(data[1])
hashes[_id] = _hash
return hashes
def enqueue_mod(mod: str, appid: int) -> None:
args = [
"steam",
f"steam://url/CommunityFilePage/{mod}+workshop_download_item",
str(appid),
mod,
]
subprocess.Popen(["/usr/bin/env", "bash", *args])
def get_needs_update(
version_file: Path, remote_hashes: list[tuple[str, str, int, int]]
) -> list[tuple[str, str, int, int]]:
local_hashes = get_local_signatures(version_file)
needs_update: list[tuple[str, str, int, int]] = []
for title, _id, _hash, size in remote_hashes:
if _id not in local_hashes:
needs_update.append((title, _id, _hash, size))
elif _hash != local_hashes[_id]:
needs_update.append((title, _id, _hash, size))
else:
continue
return needs_update
def get_remote_signatures(mods: list[str]) -> list[tuple[str, str, int, int]]:
"""
Attempts to continue connecting even if signatures are empty
"""
payload: dict[str, str | int] = {}
payload["itemcount"] = len(mods)
for i, mod in enumerate(mods):
payload[f"publishedfileids[{i}]"] = mod
try:
r = requests.post(STEAM_PUBLISHED_FILES, payload)
except Exception as e:
logger.critical(e)
return []
if r.status_code != 200:
return []
hashes: list[tuple[str, str, int, int]] = []
j = r.json()
rows = j["response"]["publishedfiledetails"]
for row in rows:
title = str(row["title"])
_id = str(row["publishedfileid"])
time = int(row["time_updated"])
size = int(row["file_size"])
hashes.append((title, _id, time, size))
return hashes
# TODO: set config to name=user, use official server and no mods,
# ensure that formatted string is identical to fixture with same hash
def connect(client: str, addr: str, appid: int, name: str, mods: list[str]) -> int:
concat = concat_mods(mods)
client_args = concat_bash_args(client)
# TODO: test flatpak arg expansion
params = [
"-applaunch",
str(appid),
f"-connect={addr}",
"-nolauncher",
"-nosplash",
"-skipintro",
f"-name={name}",
f"-mod={concat}",
]
proc = subprocess.run([*client_args, *params])
return proc.returncode
def find_user_id(path: Path) -> str | None:
resolved_path = path / "config" / "loginusers.vdf"
try:
vdf = vdf2json(resolved_path)
j = json.loads(vdf)
for user in j["users"]:
if j["users"][user]["MostRecent"] == "1":
return str(user)
return None
except Exception as e:
logger.warn(e)
return None
def vdf2json(path: Path) -> str:
def _istr(indent: int, string: str) -> str:
return (indent * " ") + string
jbuf = "{\n"
indent = 1
with open(path, "r") as f:
st = f.read()
lex = shlex(st)
while True:
tok = lex.get_token()
if not tok:
return jbuf + "}\n"
if tok == "}":
indent -= 1
jbuf += _istr(indent, "}")
ntok = lex.get_token()
if ntok is not None:
lex.push_token(ntok)
if ntok and ntok != "}":
jbuf += ","
jbuf += "\n"
else:
ntok = lex.get_token()
if ntok == "{":
jbuf += _istr(indent, tok + ": {\n")
indent += 1
else:
if ntok is not None:
jbuf += _istr(indent, tok + ": " + ntok)
ntok = lex.get_token()
if ntok is not None:
lex.push_token(ntok)
if ntok != "}":
jbuf += ","
jbuf += "\n"
def gen_shortcut() -> None:
# TODO:
"""
during setup, prompt user to select matching user id from loginusers
show user account name, select outer steam id
steam/userdata/<steamid_32>/config/shortcuts.vdf
"""
# STEAMID_MAGIC = 76561197960265728
# STEAMID_64 - STEAMID_MAGIC = STEAMID32
# or get right-most 32 bits
# STEAMID_64 & 0xFFFFFFFF
pass
View File
Whitespace-only changes.
+92
View File
@@ -0,0 +1,92 @@
import json
import shlex
from pathlib import Path
from typing import Any
"""
Convert legacy dztuirc to config.json
"""
class UnsupportedKey(Exception):
pass
def str2bool(string: str) -> bool:
s = string.lower()
match s:
case "":
return False
case "0":
return False
case "1" | "2":
return True
case "false":
return False
case "true":
return True
case _:
raise UnsupportedKey(f"The key {s} is not a valid config key.")
def rc2json(file: Path) -> str:
with open(file, "r") as f:
lex = shlex.shlex(f.read())
lex.whitespace += "="
keys: dict[str, Any] = {}
ips: list[str] = []
toggles = ["fullscreen"]
deprecated = [
"staging_dir",
"src_path",
"steam_path",
"debug",
"branch",
"auto_install",
]
while True:
tok = lex.get_token()
ntok = lex.get_token()
value: str | bool
if ntok is not None:
ntok = ntok.strip('""')
value = ntok
if tok in deprecated:
continue
elif tok in toggles:
if ntok is not None:
value = str2bool(ntok)
elif tok == "preferred_client":
tok = "client"
elif tok == "api_key":
tok = "bm_api"
elif tok == "ip_list":
while True:
ntok = lex.get_token()
if ntok is not None:
ntok = ntok.strip('""')
value = ntok
if ntok == ")":
break
# TODO: make test for this
# NOTE: strip malformed records from ancient config file versions
if ntok is not None:
if len(ntok.split(":")) == 3 and ntok.split(":")[2] != "":
ips.append(ntok)
continue
if not tok:
break
keys[tok] = value
keys["ip_list"] = ips
keys["use_miles"] = False
keys["start_tab"] = 0
return json.dumps(keys, indent=2)
+18
View File
@@ -0,0 +1,18 @@
import textwrap
from pathlib import Path
def write_desktop_file(share_path: Path) -> None:
template = f"""\
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Exec={share_path}/launch.sh
Name=DZGUI
Comment=dzgui
Icon={share_path}/dzgui
Categories=Game"""
file = share_path / "dzgui.desktop"
file.write_text(textwrap.dedent(template))
+99
View File
@@ -0,0 +1,99 @@
import gzip
import logging
import re
import requests
import shutil
from pathlib import Path
from dzgui.const.constants import APP_NAME, REQUEST_TIMEOUT
from dzgui.const.endpoints import DB_IP
logger = logging.getLogger(APP_NAME)
def find_download_url(url: str) -> str | None:
res = requests.get(url, timeout=REQUEST_TIMEOUT)
res.raise_for_status()
reg = r'ref=[\'"]([^\'">]+.csv.gz)'
urls = re.findall(reg, res.text)
if len(urls) < 1:
return None
return str(urls[0])
def get_ipdb(ips_path: Path) -> None:
url = find_download_url(DB_IP)
if url is None:
return
date = find_date(url)
month_file = ips_path.parent / ".month"
if ips_path.exists() and month_file.exists():
old_date = month_file.read_text().rstrip("\n")
if old_date == date:
logger.info(f"IP DB date matches: {date}")
return
# TODO: log additional output
logger.info(f"Fetching IPDB for {date} from {url}")
try:
tmp = serialize(url)
except Exception as e:
logger.critical(e)
return
logger.info(f"Extracting {tmp}")
unzip(tmp, ips_path)
logger.info("Stripping IPv6 records")
try:
strip_ipv6(ips_path)
except Exception as e:
logger.critical(e)
return
with open(month_file, "w") as f:
f.write(date)
logger.info(f"Wrote {date} to {month_file}")
def find_date(url: str) -> str:
date = re.sub(r"(dbip-city-lite-)(.*)(.csv.gz)", r"\2", url)
date = date.split("/")[-1]
return date
def unzip(tmp: Path, ips_path: Path) -> None:
with gzip.open(tmp, "rb") as f:
with open(ips_path, "wb") as outfile:
shutil.copyfileobj(f, outfile)
tmp.unlink()
def serialize(url: str) -> Path:
with requests.get(url, stream=True) as r:
r.raise_for_status()
filename = "ips.csv.gz"
tmp = Path("/tmp") / filename
with open(tmp, "wb") as f:
shutil.copyfileobj(r.raw, f)
return tmp
# TODO: optimize this function
# consider using grep
# cf. grep -vE "^[a-z0-9]{4}:" | grep -v "::" > "$ip_file"
def strip_ipv6(path: Path) -> None:
ips = []
with open(path, "r") as f:
s = f.read()
reg = r"^\d{1,3}\..*"
ips = re.findall(reg, s, re.MULTILINE)
assert ips[0].split(",")[0] == "0.0.0.0"
assert ips[-1].split(",")[0] == "224.0.0.0"
with open(path, "w") as f:
for ip in ips:
f.write(ip + "\n")
+62
View File
@@ -0,0 +1,62 @@
from typing import Any
from pathlib import Path
from dzgui.util._json import read_json
from dzgui.const.enum import Preferences
from dzgui.const.constants import STEAM_CMD, FLATPAK_RUN_CMD, FLATPAK_SANDBOX
class ConfigFileError(Exception):
pass
def lookup(path: Path, enum: Preferences) -> Any:
if path.is_file() is False:
raise ConfigFileError("Not a valid file")
key = enum_to_key(enum)
config = get_config(path)
try:
return config[key]
except KeyError:
return None
def get_config(path: Path) -> Any:
# TODO: is this being called multiple times?
try:
json = read_json(path)
return json
except Exception as e:
raise e
def get_favorites(path: Path) -> list[str]:
try:
conf = get_config(path)
except Exception:
pass
return list(conf["ip_list"])
# def is_in_favs(record: str, path: Path) -> bool:
# favs = get_favorites(path)
# if record in favs:
# return True
# return False
def enum_to_key(enum: Preferences) -> str:
return str(enum.dict["key"])
def get_client_index(client: str) -> int:
if client == STEAM_CMD:
return 0
elif client == FLATPAK_RUN_CMD:
return 1
elif client == FLATPAK_SANDBOX:
return 2
else:
return 0
+12
View File
@@ -0,0 +1,12 @@
# import shutil
from pathlib import Path
def uninstall(path: Path) -> None:
pass
# TODO: use xdg object?
# partial/full (keep config?)
# -u removes state, log
# XDG_SHARE_HOME/dzgui
# XDG_STATE_HOME/dzgui
# XDG_DATA_HOME/dzgui
+29
View File
@@ -0,0 +1,29 @@
from pathlib import Path
from dzgui.const.enum import Preferences
from dzgui.config.query import get_config, enum_to_key
from dzgui.util._json import write_json
# TODO: drop deprecated
# TEST: parametrize writing config values and checking config output in test
def toggle_config(path: Path, key: Preferences) -> None:
real_key = enum_to_key(key)
try:
conf = get_config(path)
cur_val = conf[real_key]
conf[real_key] = not cur_val
write_json(conf, path)
except Exception as e:
raise e
def write_config(path: Path, key: Preferences, value: str) -> None:
real_key = enum_to_key(key)
try:
conf = get_config(path)
conf[real_key] = value
write_json(conf, path)
except Exception as e:
raise e
+19
View File
@@ -0,0 +1,19 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING, Union
if TYPE_CHECKING:
from dzgui.config.xdg import Xdg
from dzgui.util.ip import Coords
# NOTE: mutable dataclass, 'use_miles' key changes on demand
@dataclass(slots=True)
class UserPrefs:
is_steam_deck: bool
is_game_mode: bool
is_debug: bool
coords: Union["Coords", None]
version: str
paths: "Xdg"
latest_release: str | None
use_miles: bool
+94
View File
@@ -0,0 +1,94 @@
import os
from pathlib import Path
from dataclasses import dataclass
from dzgui.const.constants import APP_NAME_LOWER, DEBUG_LOG, SYSTEM_LOG
@dataclass
class Xdg:
config: Path
columns: Path
notes: Path
resolution: Path
history: Path
version: Path
system: Path
debug: Path
ips: Path
def is_writeable(path_str: str) -> bool:
if path_str is None:
return False
path = Path(path_str)
if not path.exists():
try:
path.mkdir(parents=True)
except OSError:
return False
path.unlink()
return True
try:
file = Path(path / "temp")
with open(file, "w") as f:
f.write("")
except Exception:
return False
file.unlink()
return True
def get_xdg_paths() -> dict:
home = Path.home()
xdg_paths = {
"XDG_CONFIG_HOME": home / ".config",
"XDG_STATE_HOME": home / ".local" / "state",
"XDG_DATA_HOME": home / ".local" / "share",
"XDG_CACHE_HOME": home / ".cache",
}
resolved_paths = {}
for path in xdg_paths:
rp = os.environ.get(path)
if rp is not None and is_writeable(rp):
resolved_paths[path] = Path(rp)
else:
resolved_paths[path] = xdg_paths[path] / APP_NAME_LOWER
return resolved_paths
def parse_filepaths(xdg: dict) -> Xdg:
# cache = xdg["XDG_CACHE_HOME"]
# data = xdg["XDG_DATA_HOME"]
config = xdg["XDG_CONFIG_HOME"]
state = xdg["XDG_STATE_HOME"]
config = config / "config.json"
system = state / "logs" / SYSTEM_LOG
debug = state / "logs" / DEBUG_LOG
columns = state / "dzg.columns.json"
notes = state / "dzg.notes.json"
resolution = state / "dzg.res.json"
history = state / "dzg.history"
versions = state / "dzg.versions"
ips = state / "ips.csv"
return Xdg(
config,
columns,
notes,
resolution,
history,
versions,
system,
debug,
ips,
)
+16
View File
@@ -0,0 +1,16 @@
"""
Generic defaults used when initializing a config file from scratch
"""
config_boilerplate = {
"bm_api": "",
"fav_server": "",
"fav_label": "",
"name": "",
"fullscreen": False,
"steam_api": "",
"default_steam_path": "",
"client": "",
"ip_list": [],
"use_miles": False,
"start_tab": 0,
}
+79
View File
@@ -0,0 +1,79 @@
APPID_DAYZ = 221100
APPID_DAYZ_EXP = 1024020
UDP_PORT = 27016
VM_FILE = "/proc/sys/vm/max_map_count"
MIN_COUNT = 1048576
REQUEST_TIMEOUT = 10
APPNAME_DAYZ = "DayZ"
APPNAME_DAYZ_EXP = "DayZ Exp"
APPNAME_DAYZ_EXP_HUMAN = "DayZ Experimental"
DAYZ_BINARY = "DayZ_x64.exe"
LIBRARYFOLDERS_PATH = "steamapps/libraryfolders.vdf"
WORKSHOP_PATH = "steamapps/workshop/content/" + str(APPID_DAYZ)
STEAM_CMD = "steam"
FLATPAK_CMD = "flatpak"
FLATPAK_APPID = "com.valvesoftware.Steam"
FLATPAK_RUN_CMD = "flatpak run " + FLATPAK_APPID
FLATPAK_SANDBOX = "flatpak-spawn --host flatpak run " + FLATPAK_APPID
AUTHOR = "aclist"
STABLE_REPO = "stable"
BETA_REPO = "testing"
APP_NAME = "DZGUI"
APP_NAME_LOWER = "dzgui"
APP_NAME_ABBR = "dzg"
HEX_RED = "#FF0000"
HEX_ORANGE = "#FFAC1C"
CLIPBOARD = "edit-copy-symbolic"
HELP_BUBBLE = "help-about-symbolic"
INPUT_KEYBOARD = "input-keyboard-symbolic"
LIST_ADD = "list-add-symbolic"
REFRESH_ICON = "view-refresh-symbolic"
SEARCH_ICON = "system-search-symbolic"
STEAM_ICON = "steam_tray_mono"
VIEW_CONCEAL = "view-conceal-symbolic"
VIEW_REVEAL = "view-reveal-symbolic"
ERROR = "dialog-error-symbolic"
WARNING = "dialog-warning-symbolic"
WEB_BROWSER = "web-browser-symbolic"
SEPARATOR = "SEPARATOR"
# TODO: drop
NO_PADDING = 0
NO_EXPAND = False
NO_FILL = False
EXPAND = True
FILL = True
SCROLL_INCREMENT = 50
WINDOW_DEFAULT_X = 1400
WINDOW_DEFAULT_Y = 800
LEGACY_CONFIG_PATH = ".config/dztui/dztuirc"
LEGACY_COLS_PATH = ".local/state/dzgui/dzg.cols.json"
LEGACY_IPS_PATH = ".local/share/dzgui/helpers/ips.csv"
DEBUG_LOG = f"{APP_NAME}_DEBUG.LOG"
SYSTEM_LOG = f"{APP_NAME}_SYSTEM.LOG"
CHANGELOG_PATH = "data/CHANGELOG.md"
HERO_PATH = "data/images/hero.png"
CSS_PATH = "data/app.css"
VDF_PATH = "steamapps/libraryfolders.vdf"
DEFAULT_STEAM_PATH = ".local/share/Steam"
FLATPAK_STEAM_PATH = ".var/app/com.valvesoftware.Steam/data/Steam"
UBUNTU_STEAM_PATH = ".steam/steam"
DEBIAN_STEAM_PATH = ".steam/debian-installation"
LOG_FILTERS = ("CRITICAL", "WARNING", "INFO", "DEBUG")
TMP_PATH = "/tmp"
TMP_TARBALL = "/tmp/dzgui.tar.gz"
TMP_EXE = "/tmp/dzgui"
+25
View File
@@ -0,0 +1,25 @@
# internal
STEAM_PUBLISHED_FILES = "https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1/?format=json"
STEAM_SERVERS = "https://api.steampowered.com/IGameServersService/GetServerList/v1/?"
BM_SERVERS = "https://api.battlemetrics.com/servers?"
GITHUB = "https://github.com/aclist"
GITHUB_RELEASES = "https://api.github.com/repos/aclist/dztui/releases/latest"
CODEBERG_RELEASES = "https://codeberg.org/api/v1/repos/aclist/dzgui/releases/latest"
GITHUB_USER_RELEASES = "https://github.com/aclist/dztui/releases"
DB_IP = "https://db-ip.com/db/download/ip-to-city-lite"
IP_ECHO = "https://ipecho.net/plain"
COORDS_API = "http://ip-api.com/json"
# steam URIs
WORKSHOP = "steam://url/CommunityFilePage/"
OPEN_URL = "steam://openurl/"
# user facing
GITHUB_PAGES = "https://aclist.github.io/dzgui/index"
CODEBERG_PAGES = "https://aclist.codeberg.page"
GITHUB_ISSUES = "https://github.com/aclist/dzgui/issues"
FORUM = "https://old.reddit.com/r/dzgui"
SPONSORS = "https://github.com/sponsors/aclist"
STEAM_API_SETUP = "https://steamcommunity.com/dev/apikey"
BM_API_SETUP = "https://www.battlemetrics.com/developers"
BM_BROWSE = "https://www.battlemetrics.com/servers/dayz"
+301
View File
@@ -0,0 +1,301 @@
from enum import Enum
from typing import Any, Self
from dzgui.util import strings
class Port(Enum):
DEFAULT = 1
CUSTOM = 2
class ServerTab(Enum):
BROWSER = 0
SAVED = 1
RECENT = 2
LAN = 3
class Popup(Enum):
WAIT = 1
NOTIFY = 2
CONFIRM = 3
ENTRY = 4
MODLIST = 6
DETAILS = 7
QUIT = 8
class VAdjustment(Enum):
UP = 1
DOWN = 2
TOP = 3
BOTTOM = 4
class CursorPosition(Enum):
UP = 1
DOWN = 2
TOP = 3
BOTTOM = 4
class FilterMode(Enum):
INITIAL = 1
TOGGLE_OFF = 2
TOGGLE_ON = 3
class EnumWithAttrs(Enum):
def __new__(cls, *args: Any, **kwargs: Any) -> Self:
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj
def __init__(self, d: dict):
self.dict = d
class Preferences(EnumWithAttrs):
STEAM = {
"key": "steam_api",
}
BM = {
"key": "bm_api",
}
CLIENT = {
"key": "client",
}
WINDOW = {
"key": "fullscreen",
}
DIST = {
"key": "use_miles",
}
NAME = {
"key": "name",
}
INSTALL = {
"key": "auto_install",
}
DEBUG = {
"key": "debug",
}
DEFAULT = {
"key": "default_steam_path",
}
FAV_LBL = {
"key": "fav_label",
}
FAV_SRV = {
"key": "fav_server",
}
IP_LIST = {
"key": "ip_list",
}
BRANCH = {
"key": "branch",
}
START_TAB = {
"key": "start_tab",
}
class NotebookPage(EnumWithAttrs):
CHANGELOG = {"crumbs": strings.crumbs.changelog, "statusbar": True}
DEVELOPERS = {"crumbs": strings.crumbs.developers, "statusbar": False}
HELP = {"crumbs": strings.crumbs._help, "statusbar": True}
KEYS = {"crumbs": strings.crumbs.keys, "statusbar": True}
LOG = {"crumbs": strings.crumbs.log, "statusbar": True}
MODS = {"crumbs": strings.crumbs.mods, "statusbar": True}
OPTIONS = {"crumbs": strings.crumbs.options, "statusbar": False}
SERVERS = {"crumbs": strings.crumbs.servers, "statusbar": True}
THANKS = {"crumbs": strings.crumbs.thanks, "statusbar": True}
CONNECTION = {"crumbs": "Connect", "statusbar": True}
class RowType(EnumWithAttrs):
# TODO: strings
CHANGELOG = {
"label": "View changelog",
"tooltip": "Opens the DZGUI changelog",
}
SHOW_LOG = {
"label": "Show debug log",
"tooltip": "Read the DZGUI log generated since startup",
}
SEPARATOR = {
"label": "SEPARATOR",
"tooltip": "",
}
DUMP_LOG = {
"label": "Output system info to log file",
"tooltip": "Dump diagnostic data for troubleshooting",
}
DOCS = {
"label": "Documentation/help files (GitHub) ⧉",
"tooltip": "Open the DZGUI documentation in a browser",
}
DOCS_FALLBACK = {
"label": "Documentation/help files (Codeberg mirror) ⧉",
"tooltip": "Open the DZGUI documentation in a browser",
}
BUGS = {
"label": "Report a bug (GitHub) ⧉",
"tooltip": "Open the DZGUI issue tracker in a browser",
}
FORUM = {
"label": "DZGUI Subreddit ⧉",
"tooltip": "Open the DZGUI discussion forum in a browser",
}
SPONSOR = {
"label": "Sponsor (GitHub) ⧉",
"tooltip": "Sponsor development of the DZGUI project",
}
THANKS = {
"label": "Special thanks",
"tooltip": "A list of contributors, testers, and sponsors",
}
# TODO: rename to ContextMenuItem
class ContextMenu(EnumWithAttrs):
ADD_NOTE = {"label": strings.add_note}
ADD_SERVER = {"label": strings.add}
CONNECT = {"label": strings.connect}
COPY_LOG_CLIPBOARD = {"label": strings.copy_log}
COPY_SERVER_IP = {"label": strings.copy_ip}
COPY_SERVER_NAME = {"label": strings.copy_name}
DELETE_MOD = {"label": strings.delete_mod}
OPEN_WORKSHOP = {"label": strings.open_workshop}
REFRESH_PLAYERS = {"label": strings.refresh_players}
REMOVE_HISTORY = {"label": strings.remove_history}
REMOVE_SERVER = {"label": strings.remove}
SET_FAV = {"label": strings.add_fav}
SHOW_DETAILS = {"label": strings.show_details}
SHOW_MODS = {"label": strings.show_mods}
class ContextMenuGroup(Enum):
"""
Groupings of context menu items
"""
SERVER_MOD = (ContextMenu.OPEN_WORKSHOP,)
MOD = (ContextMenu.OPEN_WORKSHOP, ContextMenu.DELETE_MOD)
LOG = (ContextMenu.COPY_LOG_CLIPBOARD,)
SERVER_BROWSER = (
ContextMenu.CONNECT,
ContextMenu.ADD_SERVER,
ContextMenu.SET_FAV,
ContextMenu.COPY_SERVER_NAME,
ContextMenu.COPY_SERVER_IP,
ContextMenu.ADD_NOTE,
ContextMenu.SHOW_MODS,
ContextMenu.SHOW_DETAILS,
ContextMenu.REFRESH_PLAYERS,
)
SCAN_LAN = (
ContextMenu.CONNECT,
ContextMenu.SET_FAV,
ContextMenu.COPY_SERVER_NAME,
ContextMenu.COPY_SERVER_IP,
ContextMenu.ADD_NOTE,
ContextMenu.SHOW_MODS,
ContextMenu.SHOW_DETAILS,
ContextMenu.REFRESH_PLAYERS,
)
SAVED = (
ContextMenu.CONNECT,
ContextMenu.SET_FAV,
ContextMenu.REMOVE_SERVER,
ContextMenu.COPY_SERVER_NAME,
ContextMenu.COPY_SERVER_IP,
ContextMenu.ADD_NOTE,
ContextMenu.SHOW_MODS,
ContextMenu.SHOW_DETAILS,
ContextMenu.REFRESH_PLAYERS,
)
RECENT = (
ContextMenu.CONNECT,
ContextMenu.ADD_SERVER,
ContextMenu.SET_FAV,
ContextMenu.REMOVE_HISTORY,
ContextMenu.COPY_SERVER_NAME,
ContextMenu.COPY_SERVER_IP,
ContextMenu.ADD_NOTE,
ContextMenu.SHOW_MODS,
ContextMenu.SHOW_DETAILS,
ContextMenu.REFRESH_PLAYERS,
)
class ModButton(EnumWithAttrs):
SELECT_ALL = {
"label": strings.mod_panel.select_all,
"tooltip": strings.mod_panel.select_all_tooltip,
}
UNSELECT_ALL = {
"label": strings.mod_panel.unselect_all,
"tooltip": strings.mod_panel.unselect_all_tooltip,
}
HIGHLIGHT_STALE = {
"label": strings.mod_panel.highlight_stale,
"tooltip": strings.mod_panel.highlight_stale_tooltip,
}
UNHIGHLIGHT_STALE = {
"label": strings.mod_panel.unhighlight_stale,
"tooltip": strings.mod_panel.unhighlight_stale_tooltip,
}
DELETE_SELECTED = {
"label": strings.mod_panel.delete_selected,
"tooltip": strings.mod_panel.delete_selected_tooltip,
}
SELECT_STALE = {
"label": strings.mod_panel.select_stale,
"tooltip": strings.mod_panel.select_stale_tooltip,
}
class ButtonType(EnumWithAttrs):
SERVERS = {
"label": strings.buttons.servers_label,
"tooltip": strings.buttons.servers_tooltip,
"opens": NotebookPage.SERVERS,
}
MODS = {
"label": strings.buttons.mods_label,
"tooltip": strings.buttons.mods_tooltip,
"opens": NotebookPage.MODS,
}
OPTIONS = {
"label": strings.buttons.options_label,
"tooltip": strings.buttons.options_tooltip,
"opens": NotebookPage.OPTIONS,
}
HELP = {
"label": strings.buttons.help_label,
"tooltip": strings.buttons.help_tooltip,
"opens": NotebookPage.HELP,
}
EXIT = {
"label": strings.buttons.exit_label,
"tooltip": strings.buttons.exit_tooltip,
"opens": None,
}
HELP_MENU_ROWS = (
RowType.CHANGELOG,
RowType.SHOW_LOG,
RowType.DUMP_LOG,
RowType.SEPARATOR,
RowType.DOCS,
RowType.DOCS_FALLBACK,
RowType.BUGS,
RowType.FORUM,
RowType.SPONSOR,
RowType.SEPARATOR,
RowType.THANKS,
)
+13
View File
@@ -0,0 +1,13 @@
"""
This file is intended to be patched by package maintainers
repackaging DZGUI for use in different distributions.
If DZGUI is going to be installed globally via a package manager
or other means and will reside in an immutable location, or needs to be
explicitly bound to a certain version, set the flag below to False.
This will disable the ability for the application to self-manage and
will suppress the "Updates available" button in the gutter.
"""
ALLOW_UPDATES = True
+152
View File
@@ -0,0 +1,152 @@
from typing import TYPE_CHECKING
import gi
gi.require_version("Gtk", "3.0")
from gi.repository.Gtk import ListStore # noqa E402
from gi.repository import Gdk, GObject # noqa E402
if TYPE_CHECKING:
from dzgui.const.enum import NotebookPage, ServerTab
# TODO: if servers fail to load, may leave dangling widgets waiting for a signal
class Emitter(GObject.GObject):
def __init__(self) -> None:
super().__init__()
# TODO: rename signals to e.g. maps_keybinding_pressed
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def request_keyword_focus(self) -> None:
"""User invoked Ctrl-f keybinding from ServerTreeView"""
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def saved_servers_changed(self) -> None:
"""Record was added/removed from Saved Servers model"""
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def request_maps_focus(self) -> None:
"""User invoked Ctrl-m keybinding from ServerTreeView"""
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def request_ip_entry_focus(self) -> None:
"""User invoked Ctrl-i keybinding from ServerTreeView"""
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def request_custom_port_focus(self) -> None:
"""User invoked Ctrl-n keybinding from ServerTreeView"""
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def request_default_port_focus(self) -> None:
"""user invoked ctrl-d keybinding from servertreeview"""
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def request_button_box_focus(self) -> None:
"""User invoked right movement keybinding from ServerTreeView"""
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(str, str))
def fav_server_changed(self, name: str, addr: str) -> None:
"""Change favorite server via context menu"""
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(int,))
def check_button_pressed(self, keyval: int) -> None:
"""User toggled filter panel check button via keyboard"""
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(object,))
def server_page_changed(self, keyval: int) -> None:
"""Triggered on 'switch-page' signal within tabs of NotebookPage.SERVERS."""
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(bool,))
def server_page_toggled(self, keyval: int) -> None:
"""Triggered on map/unmap signal from NotebookPage.SERVERS. Shows/hides grid panels."""
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def statusbar_loaded(self) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def distcalc_started(self) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(bool,))
def mod_page_toggled(self, state: bool) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(bool,))
def lan_tab_toggled(self, state: bool) -> None:
pass
@GObject.Signal(
flags=GObject.SignalFlags.RUN_LAST,
arg_types=(
object,
object,
),
)
def distcalc_ended(
self, dist: str | None, context: "ServerTab | NotebookPage"
) -> None:
pass
@GObject.Signal(
flags=GObject.SignalFlags.RUN_LAST,
arg_types=(
str,
bool,
),
)
def check_toggled(self, label: str, state: bool) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(object,))
def servers_loaded(self, tag: "ServerTab") -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def servers_loaded_init(self) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(str,))
def map_selection_changed(self, map: str) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(object,))
def load_maps(self, store: ListStore) -> None:
pass
@GObject.Signal(
flags=GObject.SignalFlags.RUN_LAST,
arg_types=(
str,
int,
),
)
def mods_updated(self, msg: str, mods: int) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def mods_highlighted(self) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def api_change_failed(self) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=())
def already_saved_server(self) -> None:
pass
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST, arg_types=(str,))
def keyword_set(self, keyword: str) -> None:
pass
+502
View File
@@ -0,0 +1,502 @@
import logging
import threading
from typing import Any, TYPE_CHECKING, Union
import dzgui.util._json as JSON # noqa
from dzgui.const.enum import (
FilterMode,
Preferences,
NotebookPage,
ButtonType,
ContextMenu,
)
from dzgui.config.userprefs import UserPrefs
from dzgui.const.constants import APP_NAME
from dzgui.controllers.emitter import Emitter
from dzgui.managers.config import ConfigManager
from dzgui.managers.connection import ConnectionManager
from dzgui.managers.contextmenu import ContextMenuManager
from dzgui.managers.mods import ModManager
from dzgui.managers.notes import NoteManager
from dzgui.model.servers import ServerModelManager
from dzgui.util.diag import write_diagnostic
from dzgui.util.format import format_player_count
from dzgui.util.open_links import open_user_workshop, open_workshop_page
from dzgui.views.dialogs.filepicker import FilePicker
from dzgui.views.dialogs.generic import ExceptionDialog
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GLib, GObject # noqa E402
logger = logging.getLogger(APP_NAME)
if TYPE_CHECKING:
from dzgui.api.servers import Record
from dzgui.const.enum import ServerTab
from dzgui.managers.connection import Prerequisites
from dzgui.managers.filter import FilterManager
from dzgui.util.dist import Haversine
from dzgui.views.base import Notebook, Grid, OuterWindow
from dzgui.views.components.buttonbox import ContextualButton
from dzgui.views.components.filter_panel import FilterPanel
from dzgui.views.components.right_panel import RightPanel
from dzgui.views.components.statusbar import Statusbar
from dzgui.views.pages.options import Options
from dzgui.views.pages.preconnect import PreConnectionAssistant
from dzgui.views.pages.servers import ServerNotebook
from dzgui.views.trees.tree_log import LogTreeView
from dzgui.views.trees.tree_menu import MenuTreeView
from dzgui.views.trees.tree_mods import ModTreeView
from dzgui.views.trees.tree_servers import ServerTreeView
class AppNavigation:
window: "OuterWindow"
grid: "Grid"
right_panel: "RightPanel"
statusbar: "Statusbar"
notebook: "Notebook"
modtreeview: "ModTreeView"
menu: "MenuTreeView"
servers: "ServerNotebook"
saved: "ServerTreeView"
recent: "ServerTreeView"
lan: "ServerTreeView"
logtreeview: "LogTreeView"
filters: "FilterPanel"
preconnect: "PreConnectionAssistant"
options: "Options"
class Controller(GObject.GObject):
def __init__(self) -> None:
self.dist_cache: dict[str, "Haversine"] = {}
self.mediator = AppNavigation()
self.prefs: UserPrefs
self.emitter = Emitter()
self.emitter.connect("map_selection_changed", self._on_map_selection_changed)
self.emitter.connect("check_toggled", self._on_check_toggled)
self.emitter.connect("servers_loaded_init", self._on_servers_loaded_init)
# NOTE: suppress requests until entire UI is loaded
self.loaded = False
self.pending_jobs = 1
self.exit_event = threading.Event()
self.cancel_event = threading.Event()
self.connection_man: ConnectionManager
def get_emitter(self) -> Emitter:
return self.emitter
def register_widget(self, attr: str, widget: Gtk.Widget) -> None:
try:
setattr(self.mediator, attr, widget)
except AttributeError:
logger.critical(f"{attr} is not a valid AppNavigation attribute.")
def get_prefs(self) -> UserPrefs:
return self.prefs
def set_prefs(self, prefs: UserPrefs) -> None:
self.config_man = ConfigManager(prefs, self)
self.notes_man = NoteManager(self, prefs.paths.notes)
self.prefs = prefs
def query_config(self, key: Preferences) -> Any:
return self.config_man.lookup(key)
def is_auto_install(self) -> bool:
return bool(self.query_config(Preferences.INSTALL))
def suppress_signal(
self, owner: Any, child: Any, func_name: str, state: bool
) -> None:
func = getattr(owner, func_name)
if state:
child.handler_block_by_func(func)
else:
child.handler_unblock_by_func(func)
def get_active_context(self) -> "ServerTab":
return self.get_active_treeview().get_enum()
def get_active_treeview(self) -> "ServerTreeView":
return self.mediator.notebook.servers.get_active_treeview()
def grab_active_treeview(self) -> None:
self.get_active_treeview().grab_focus()
def save_res_and_quit(self, *args: Any) -> None:
treeview = self.get_active_treeview()
window = self.get_window()
self.config_man.save_res_and_quit(treeview, window)
def set_statusbar(self, enum: "NotebookPage | ServerTab", text: str) -> None:
self.mediator.statusbar.set_by_context(enum, text)
def remove_statusbar(self, context: "NotebookPage | ServerTab") -> None:
self.mediator.statusbar.pop(context)
def set_statusbar_dist(
self, haversine: Union["Haversine", None], enum: "ServerTab"
) -> None:
"""
NOTE: prevents race condition when server tab changed,
but allows caching the distance in the background
"""
context = self.get_active_context()
page = self.mediator.notebook.get_page_by_enum()
if page != NotebookPage.SERVERS:
self.emitter.emit("distcalc_ended", None, context)
return
if enum != context:
self.emitter.emit("distcalc_ended", None, context)
return
if haversine is None:
self.emitter.emit("distcalc_ended", None, context)
return
dist = haversine.get_rounded(self.prefs.use_miles)
self.emitter.emit("distcalc_ended", dist, context)
def toggle_config(self, key: Preferences) -> None:
# NOTE: Preferences.DIST is dynamic
if key == Preferences.DIST:
self.prefs.use_miles = not self.prefs.use_miles
self.config_man.toggle_config(key)
def update_config(self, key: Preferences, value: str) -> None:
self.config_man.update_config(key, value)
def open_keybindings(self) -> None:
notebook = self.mediator.grid.notebook
notebook.toggle_keybindings()
def focus_notebook(self) -> None:
notebook = self.mediator.grid.notebook
notebook.focus_current()
def show_developers_page(self) -> None:
self.open_page(NotebookPage.DEVELOPERS)
def open_page(self, page: NotebookPage) -> None:
self.mediator.grid.notebook.set_page_by_enum(page)
def open_page_by_button(self, button: "ContextualButton") -> None:
# TODO: consolidate methods with set_page_by_enum
match button.context:
case ButtonType.EXIT:
self.save_res_and_quit()
return
case ButtonType.OPTIONS:
try:
# TODO: where to put config file check
self.mediator.grid.notebook.settings.populate_settings()
except Exception:
return
case ButtonType.MODS:
self.load_mods()
self.open_page(button.opens)
def get_help_row(self) -> str:
return self.mediator.menu.get_row_enum()
def open_user_workshop(self, uid: str) -> None:
# NOTE: uid may contain leading zeroes, not a real integer
client = self.query_config(Preferences.CLIENT)
open_user_workshop(uid, client)
def load_mods(self) -> None:
self.mod_man = ModManager(self)
def uncolorize_mods(self) -> None:
self.mod_man.uncolorize_mods()
def highlight_stale(self) -> None:
self.mod_man.highlight_stale()
def toggle_mod_selection(self, state: bool) -> None:
self.mod_man.toggle_mod_selection(state)
def delete_mods(self) -> None:
self.mod_man.delete_mods()
def get_mod_store(self) -> Gtk.TreeModel | None:
return self.mediator.modtreeview.get_model()
def set_fav(self, name: str, record: str, simple_ip: str) -> None:
try:
self.config_man.set_fav(name, record)
self.emitter.emit("fav_server_changed", name, simple_ip)
except Exception as e:
logger.critical(e)
return
def menu_action(self, action: ContextMenu, tree: "ServerTreeView") -> None:
context_man = ContextMenuManager(tree, self)
context_man.process(action)
def populate_log(self) -> None:
log = self.prefs.paths.debug
try:
self.mediator.logtreeview.populate_log(log)
self.open_page(NotebookPage.LOG)
except Exception as e:
dialog = ExceptionDialog(self, str(e))
dialog.run()
def select_colorized(self) -> None:
self.mod_man.select_colorized()
def get_filter_man(self) -> "FilterManager":
"""Each ServerTreeView has an atomic FilterManager"""
return self.get_active_treeview().get_filter_man()
def dump_diagnostics(self) -> None:
picker = FilePicker(self.mediator.window)
file = picker.pick_file()
if file is not None:
try:
write_diagnostic(self.prefs.paths.config, file)
except Exception as e:
dialog = ExceptionDialog(self, str(e))
dialog.run()
def update_api_key(self, key: Preferences, text: str) -> None:
self.config_man.update_api_key(key, text)
def set_resolution(self, window: "OuterWindow") -> None:
self.config_man.set_resolution(window)
def propagate_column_width(self, col: Gtk.TreeViewColumn) -> None:
GLib.idle_add(self.mediator.servers.update_tab_widths, col)
def refresh_tree(self) -> None:
treeview = self.get_active_treeview()
treeview.set_loaded(False)
ServerModelManager(self, treeview).refresh()
def get_player_count(self) -> str:
treeview = self.get_active_treeview()
model, control = treeview.get_model_and_control_model()
count = format_player_count(model, control)
return count
def get_statusbar(self) -> "Statusbar":
return self.mediator.statusbar
def populate_model(self, tv: "ServerTreeView") -> None:
# NOTE: skip on previously loaded tabs
if tv.is_loaded():
self.emitter.emit("servers_loaded", tv.get_enum())
return
self.mediator.statusbar.set_by_context(tv.get_enum(), "")
ServerModelManager(self, tv).load()
def get_dist_cache(self) -> dict[str, "Haversine"]:
return self.dist_cache
def set_dist_cache(self, addr: str, haversine: "Haversine") -> None:
self.dist_cache[addr] = haversine
def get_map_store(self) -> Gtk.ListStore:
filter_man = self.get_filter_man()
return filter_man.get_map_store()
def get_enabled_filters(self) -> dict:
filter_man = self.get_filter_man()
return filter_man.get_filters()
# TODO: rename
def _on_servers_loaded_init(self, emitter: "Emitter") -> None:
"""Triggered after servers load but prior to maps loading"""
# FIXME: wipe maps store when changing tabs if model is none
# e.g. select recent, toggle map, then select lan -> not wiped
tv = self.get_active_treeview()
if tv.loaded is False:
return
store = self.get_map_store()
self.emitter.emit("load_maps", store)
def has_server_model(self) -> bool:
treeview = self.get_active_treeview()
proxy_man = treeview.get_proxy_man()
control = proxy_man.get_control()
if control is None:
return False
if len(control) < 1:
return False
return True
def _on_check_toggled(self, emitter: Emitter, label: str, state: bool) -> None:
filter_man = self.get_filter_man()
filter_man.set_filter(label, state)
mode = FilterMode.TOGGLE_ON if state else FilterMode.TOGGLE_OFF
ServerModelManager(self, self.get_active_treeview()).refilter(mode)
def _on_map_selection_changed(self, emitter: Emitter, selection: str) -> None:
smm = ServerModelManager(self, self.get_active_treeview())
smm.refilter(FilterMode.TOGGLE_ON)
def get_notebook(self) -> "Notebook":
return self.mediator.notebook
def get_prior_page(self) -> NotebookPage:
return self.mediator.notebook.get_prior_page()
def get_servers(self) -> "ServerNotebook":
return self.mediator.servers
def get_server_notebook(self) -> Gtk.Notebook:
return self.mediator.servers.notebook
def get_window(self) -> "OuterWindow":
return self.mediator.window
def get_menu(self) -> "MenuTreeView":
return self.mediator.menu
def has_favorites(self) -> bool:
favs = self.config_man.get_favorites()
if len(favs) < 1:
return False
return True
def get_config_man(self) -> ConfigManager:
return self.config_man
def add_by_str(self, addr: str) -> None:
saved_tree = self.get_servers().get_saved()
ServerModelManager(self, saved_tree).add_by_str(addr)
def add_by_record(self, record: "Record") -> None:
saved_tree = self.get_servers().get_saved()
ServerModelManager(self, saved_tree).add_by_record(record)
def remove_by_record(self, record: "Record") -> None:
saved_tree = self.get_servers().get_saved()
ServerModelManager(self, saved_tree).remove_by_record(record)
def add_to_history(self, record: dict[str, Any]) -> None:
tv = self.get_servers().get_recent()
ServerModelManager(self, tv).add_to_history(record)
def remove_from_history(self, record: "Record") -> None:
# NOTE: remove action is only possible from history tree context menu,
# i.e., the active tree
tv = self.get_active_treeview()
ServerModelManager(self, tv).remove_from_history(record)
def connect_by_str(self, addr: str) -> None:
if addr.isdigit():
config_man = self.get_config_man()
key = config_man.lookup(Preferences.BM)
self.connection_man = ConnectionManager(self)
self.connection_man.connect_by_id(int(addr), key)
else:
self.connection_man = ConnectionManager(self)
self.connection_man.connect_by_ip(addr)
def connect_by_record(self, record: "Record") -> None:
self.connection_man = ConnectionManager(self)
self.connection_man.connect_by_record(record)
def get_details(self, record: "Record") -> None:
ConnectionManager(self).query_details(record)
def get_modlist(self, record: "Record") -> None:
ConnectionManager(self).query_modlist_and_present(record)
def get_server_name(self) -> str:
tv = self.get_active_treeview()
return tv.get_name()
def open_workshop_page(self, mod: str) -> None:
cmd = self.query_config(Preferences.CLIENT)
open_workshop_page(mod, cmd)
def has_note(self) -> bool:
note = self.get_note()
if len(note) > 0:
return True
return False
def get_note_by_record(self, record: str) -> str:
return self.notes_man.get_note(record)
def get_note(self) -> str:
tv = self.get_active_treeview()
record = tv.get_record_string()
return self.notes_man.get_note(record)
def add_note(self, note: str) -> None:
tv = self.get_active_treeview()
record = tv.get_record_string()
self.notes_man.add_note(record, note)
def delete_note(self) -> None:
tv = self.get_active_treeview()
record = tv.get_record_string()
self.notes_man.delete_note(record)
def refresh_players(self, record: "Record") -> None:
treeview = self.get_active_treeview()
model, treeiter = treeview.get_selection().get_selected()
ServerModelManager(self, treeview).update_playercount(treeiter, record)
def get_active_keyword(self) -> str:
return self.get_filter_man().get_active_keyword()
def set_active_keyword(self, keyword: str) -> None:
self.get_filter_man().set_active_keyword(keyword)
def get_modtreeview(self) -> "ModTreeView":
return self.mediator.modtreeview
def get_exit_event(self) -> threading.Event:
return self.exit_event
def set_exit_event(self) -> None:
self.exit_event.set()
def set_cancel_event(self) -> None:
self.cancel_event.set()
def get_cancel_event(self) -> threading.Event:
return self.cancel_event
def clear_cancel_event(self) -> None:
self.cancel_event.clear()
def open_connection_assistant(self, prereqs: "Prerequisites") -> None:
self.open_page(NotebookPage.CONNECTION)
self.mediator.preconnect.populate(prereqs)
def set_start_tab(self) -> None:
ind = self.config_man.get_start_tab()
self.get_servers().notebook.set_current_page(ind)
def update_and_connect(self, raise_window: bool) -> None:
self.connection_man.update_and_connect(raise_window)
def update_status(self) -> None:
self.mediator.preconnect.mark_finished()
def get_steam_client_name(self) -> str:
return self.mediator.options.get_client_name()
def present_window(self) -> None:
self.mediator.window.present_with_time(Gdk.CURRENT_TIME)
+74
View File
@@ -0,0 +1,74 @@
## Added
- Setup wizard
- Changelog text wrapping and formatting
- Changelog ships with source
- Documentation ships with source
- Decouple UI components into modules
- Choose from kilometer or miles distance display
- More granular haversine calculation
- Parse XDG data dirs with fallbacks
- Dedicated mods page
- Dedicated thanks page
- Rearrange menus/breadcrumbs
- Open filepicker when generating system log
- Developers page (and -d flag)
- Redact API key in log table
- Integrate add/connect widgets into main menu
- Favorite/connect/LAN panels integrated with server views
- Abort on first LAN server found
- Colorized IP/ID validation fields
- Copy favorite server IP to clipboard
- Set favorite server from tables
- Detailed/copyable trace in critical error dialogs
- Visual icons
- Integrated server notebook
- Propagate width changes to all tables
- Remember tree position in menus
- Show hidden server count after filtering
- Atomic map filters per server context
- Use concurrency when checking stale mods (performance uplift)
- Copy version by clicking label
- Add server name to server mod dialogs
- Lazy load ping cell data func
- Refresh servers button
- Early load alerts button
- Preconnect dialog
- Preconnect warnings/failsafes like filesize
## Changed
- Conform to PEP 440 versioning for beta versions
- Reduce padding on keys button
- Boldface breadcrumbs
- Bold labels inside frames
- Sidebar buttons do not steal focus
- Copy IP copies IP:queryport only instead of IP:gameport:queryport, mimics syntax needed by add by ip method
- Load new model into view without flushing
- Cull servers with abnormal queue values (integer overflow: 2147483647)
- Packaging structure
- Suppress log messages from imported modules
- Embed Workshop link in Options menu
- Disable overlay scrollbars on server tables
## Dropped
- Debug mode
- Branch switching
- Manual mod install mode (describe rationale)
- Force update mods
## Fixed
- Longstanding issue with left clicks not registering as tree selection changes after spamming keyboard input
- Center server title text on server dialogs
- Rare segfaults when changing maps (threading)
- Moved dialogs out of threads
## Unreleased
- Load offline mods
- Choose to jump into splash screen instead of server
- Local documentation
- Raw debug command in context menu
## Developer-facing
- Add pyproject.toml file
- Show deprecation warnings
- Options -> Dev page
+40
View File
@@ -0,0 +1,40 @@
.invalid-entry {
border-color: red;
}
.frame {
border: 0px;
}
.toast-label {
background-color: black;
border: 1px solid white;
}
.frame > border {
border-radius: 5px;
padding: 5px;
}
.page-heading {
font-size: 1.5rem;
font-weight: 800;
margin-bottom: 0.5rem;
}
.settings-subheading {
font-size: 1.2rem;
font-weight: 700;
}
.left-label {
font-size: 1.3rem;
}
.details-heading {
font-size: 1.2rem
}
.preconnect-heading {
font-size: 1.2rem;
font-weight: 800;
}
.masked-tree {
background-color: transparent;
}
.error-frame border {
border: 2px solid red;
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+24
View File
@@ -0,0 +1,24 @@
import logging
from typing import TYPE_CHECKING
from dzgui.const.constants import APP_NAME
from dzgui.util.ip import get_local_ip, get_coords, Coords
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(APP_NAME)
def get_local_coords(path: "Path") -> Coords | None:
try:
my_ip = get_local_ip()
except Exception as e:
logger.warn(e)
return None
try:
return get_coords(path, my_ip)
except Exception as e:
logger.warn(e)
return None
+23
View File
@@ -0,0 +1,23 @@
import logging
import sys
from pathlib import Path
from dzgui.config.query import lookup
from dzgui.const.constants import APPID_DAYZ, APP_NAME, LIBRARYFOLDERS_PATH
from dzgui.const.enum import Preferences
from dzgui.views.dialogs.early_alert import EarlyAlertDialog
import dzgui.api.pefile as PeFile
logger = logging.getLogger(APP_NAME)
def is_dayz_installed(config: Path) -> None:
try:
path = lookup(config, Preferences.DEFAULT)
PeFile.get_app_path(Path(path) / LIBRARYFOLDERS_PATH, APPID_DAYZ)
except Exception as e:
logger.critical(e)
EarlyAlertDialog(str(e))
sys.exit(1)
+25
View File
@@ -0,0 +1,25 @@
import fcntl
import os
import sys
from pathlib import Path
from typing import TextIO
from dzgui.views.dialogs.early_alert import EarlyAlertDialog
from dzgui.util.strings import cannot_acquire_lock
def lock_release(lock: TextIO) -> None:
fcntl.flock(lock, fcntl.LOCK_UN)
os.close(lock.fileno())
def lock_acquire() -> TextIO:
lockfile = Path("/tmp/dzgui.flock")
lock = open(lockfile, "w")
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
EarlyAlertDialog(cannot_acquire_lock)
sys.exit(1)
return lock
+60
View File
@@ -0,0 +1,60 @@
import shutil
from pathlib import Path
from dzgui.const.constants import LEGACY_CONFIG_PATH, LEGACY_COLS_PATH, LEGACY_IPS_PATH
from dzgui.config.convert import rc2json
from dzgui.util._json import read_json, write_json
def migrate_legacy_conf(config: Path) -> None:
old_conf = Path.home() / LEGACY_CONFIG_PATH
j = rc2json(old_conf)
config.parent.mkdir(parents=True, exist_ok=True)
config.write_text(j)
def has_new_config(config: Path) -> bool:
return config.exists()
def migrate_cols_file(res: Path) -> None:
# NOTE: dzg.columns.json is API 7 spec
old_res = Path.home() / LEGACY_COLS_PATH
if old_res.is_file():
j = read_json(old_res)
cols = j["cols"]
if "View" in cols:
return
cols["View"] = cols.pop("Perspective")
cols["Max"] = cols.pop("Maximum")
write_json(j, res)
def copy_state_files(state_path: Path) -> None:
home = Path.home()
legacy = home / ".local/state/dzgui"
to_copy = [
"dzg.res.json",
"dzg.notes.json",
"dzg.history",
"dzg.versions",
"ips.csv",
".month",
]
if state_path == legacy:
# TODO: log this
return
for file in legacy.iterdir():
if file.name in to_copy:
shutil.copy(file, state_path / file.name)
def copy_ipdb(ips_path: Path) -> None:
home = Path.home()
legacy = home / LEGACY_IPS_PATH
if ips_path == legacy:
return
if legacy.is_file() is False:
return
# TODO: ensure that month file is copied
shutil.copy(legacy, ips_path)
+23
View File
@@ -0,0 +1,23 @@
import os
import sys
from importlib import metadata
from pathlib import Path
from dzgui.const.constants import APP_NAME_LOWER
def is_prefix_writeable() -> bool:
prefix = sys.prefix
path = Path(prefix)
file = path / ".is_writeable"
try:
with open(file, "w") as f:
f.write("")
os.remove(file)
except OSError:
return False
return True
def get_version() -> str:
return metadata.version(APP_NAME_LOWER)
+25
View File
@@ -0,0 +1,25 @@
import logging
import shutil
import subprocess
from dzgui.const.constants import APP_NAME, FLATPAK_APPID, FLATPAK_CMD, STEAM_CMD
logger = logging.getLogger(APP_NAME)
def has_steam_client() -> bool:
if shutil.which(STEAM_CMD):
return True
if not shutil.which(FLATPAK_CMD):
return False
try:
res = subprocess.run(
[FLATPAK_CMD, "list"], capture_output=True, text=True, check=True
)
if FLATPAK_APPID in res.stdout:
return True
else:
return False
except subprocess.CalledProcessError as e:
logger.critical(e)
return False
+85
View File
@@ -0,0 +1,85 @@
import psutil
import subprocess
import shutil
from warnings import deprecated
from dzgui.const.constants import (
DAYZ_BINARY,
STEAM_CMD,
FLATPAK_APPID,
FLATPAK_CMD,
FLATPAK_RUN_CMD,
FLATPAK_SANDBOX,
)
# TODO: move to util.proc
def is_dayz_running() -> bool:
"""Subprocesses spawned from Steam will not show up in regular process tree"""
procs = []
substring = DAYZ_BINARY
for proc in psutil.process_iter():
try:
procs.append(proc.cmdline())
except Exception:
continue
return any(substring in item for sublist in procs for item in sublist)
def is_steam_running(cmd: str) -> bool:
if cmd == STEAM_CMD:
if has_cmd(STEAM_CMD) is False:
return False
return is_running(STEAM_CMD)
elif cmd == FLATPAK_RUN_CMD or FLATPAK_SANDBOX:
return is_flatpak_steam_running()
else:
raise TypeError("Not a valid Steam client selection")
# CHORE: test alternate clients
# TODO: has_flatpak_steam
def is_flatpak_steam_running() -> bool:
if has_cmd(FLATPAK_CMD) is False:
return False
proc = subprocess.check_output([FLATPAK_CMD, "ps"], text=True)
lines = proc.splitlines()
if FLATPAK_APPID in lines:
return True
return False
def is_running(proc: str) -> bool:
for process in psutil.process_iter(["pid", "name"]):
if process.info["name"] == proc:
return True
return False
def has_cmd(cmd: str) -> bool:
if shutil.which(cmd) is not None:
return True
return False
@deprecated("dropped in favor of Gtk native methods")
def foreground(cmd: str, pid: int) -> None:
if cmd == "wmctrl":
proc = subprocess.run(["wmctrl", "-ilp"], capture_output=True, text=True)
lines = proc.stdout.splitlines()
for line in lines:
els = line.split(" ")
if str(pid) in els:
wid = els[0]
break
subprocess.run(["wmctrl", "-ia", wid])
elif cmd == "xdotool":
args = [cmd, "search", "--pid", str(pid)]
proc = subprocess.run([*args], capture_output=True, text=True)
lines = proc.stdout.splitlines()
## NOTE: some forked subprocesses may fail, so skip over them
for line in lines:
subprocess.run(
["xdotool", "windowactivate", line], stderr=subprocess.DEVNULL
)
+39
View File
@@ -0,0 +1,39 @@
import logging
import requests
from packaging.version import Version
from typing import Any
from dzgui.const.constants import APP_NAME, REQUEST_TIMEOUT
from dzgui.const.endpoints import GITHUB_RELEASES, CODEBERG_RELEASES
logger = logging.getLogger(APP_NAME)
def get_latest_release() -> tuple[Any, Any] | tuple[None, None]:
tag = None
url = None
# TODO: check order; github often has gateway errors
for url in [GITHUB_RELEASES, CODEBERG_RELEASES]:
try:
res = requests.get(url, timeout=REQUEST_TIMEOUT)
if res.status_code == 200:
tag = res.json()["tag_name"]
url = res.json()["assets"][0]["browser_download_url"]
break
except Exception as e:
logger.critical(e)
continue
return tag, url
def check_updates(version: str) -> str | None:
try:
latest, url = get_latest_release()
if latest is None:
return None
if Version(version) >= Version(latest):
return None
return url
except Exception:
return None
View File
Whitespace-only changes.
Submodule
+1
Submodule dzgui/lib/a2s added at b40eb24cdb.
Submodule dzgui/lib/dayzquery added at 07483b88ed.
+154
View File
@@ -0,0 +1,154 @@
import argparse
import logging
import os
import sys
import warnings
from typing import TYPE_CHECKING
from dzgui.api.mods import remove_stale_signatures
from dzgui.const.constants import APP_NAME
from dzgui.const.enum import Preferences
from dzgui.config.ipdb import get_ipdb
from dzgui.config.query import lookup
from dzgui.config.userprefs import UserPrefs
from dzgui.config.xdg import get_xdg_paths, parse_filepaths
from dzgui.init.coords import get_local_coords
from dzgui.init.dayz import is_dayz_installed
from dzgui.init.flock import lock_acquire
from dzgui.init.migrate import (
has_new_config,
copy_state_files,
migrate_cols_file,
)
from dzgui.init.prefix import get_version
from dzgui.init.prereqs import has_steam_client
from dzgui.strings import boot
from dzgui.init.update import check_updates
# from dzgui.util.map_count import get_map_count
from dzgui.util.deck import is_steam_deck, is_game_mode
from dzgui.util.localize import set_locale
from dzgui.util.symlink import rebuild_symlinks
from dzgui.util.strings import init, flags
from dzgui.views.base import App
from dzgui.views.dialogs.wizard import SetupWizard
from dzgui.views.dialogs.early_alert import EarlyAlertDialog
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(APP_NAME)
parser = argparse.ArgumentParser(description=flags.description)
parser.add_argument("-v", "--version", action="store_true", help=flags.version)
parser.add_argument("-u", "--uninstall", action="store_true", help=flags.uninstall)
parser.add_argument("-d", "--debug", action="store_true", help=flags.debug)
args = parser.parse_args()
# TODO: profile load time
def make_parents(path: "Path") -> None:
path.parent.mkdir(parents=True, exist_ok=True)
def uninstall() -> None:
# TODO: uninstall data files (-u)
# -u removes state, log, freedesktop
# XDG_SHARE_HOME/dzgui
# XDG_STATE_HOME/dzgui
# XDG_DATA_HOME/dzgui
pass
def setup_logger(log_path: "Path") -> None:
_format = (
"%(asctime)s␞%(levelname)s␞%(filename)s::%(funcName)s::%(lineno)s␞%(message)s"
)
fh = logging.FileHandler(log_path)
formatter = logging.Formatter(_format)
fh.setFormatter(formatter)
fh.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
logger.addHandler(fh)
def main() -> None:
lock = lock_acquire() # noqa
if args.version is True:
print(get_version())
sys.exit(0)
if args.uninstall is True:
uninstall()
sys.exit(0)
if args.debug is True:
warnings.filterwarnings("default", category=DeprecationWarning)
version = get_version()
set_locale()
print(f"{APP_NAME} {version}")
# NOTE: consider aborting this check if steam deck
xdg_paths = get_xdg_paths()
XDG = parse_filepaths(xdg_paths)
if XDG.resolution.parent.is_dir() is False:
make_parents(XDG.resolution)
if XDG.debug.is_file() is False:
make_parents(XDG.debug)
_is_steam_deck = is_steam_deck()
_is_game_mode = is_game_mode() if _is_steam_deck else False
if _is_game_mode:
# NOTE: this may no longer be necessary on newer versions of SteamOS
del os.environ["GTK_IM_MODULE"]
if has_new_config(XDG.config) is False:
migrate_cols_file(XDG.columns)
copy_state_files(xdg_paths["XDG_STATE_HOME"])
# TODO: add logging inside wizard
SetupWizard(_is_steam_deck, XDG.config)
# NOTE: implies that setup wizard failed or was closed
if has_new_config(XDG.config) is False:
return
setup_logger(XDG.debug)
with open(XDG.debug, "w") as f:
f.truncate(0)
latest_release = check_updates(version)
if _is_steam_deck is False:
# TODO: sudo escalation dialog
# count = get_map_count()
# TODO: move into module
if has_steam_client() is False:
EarlyAlertDialog(init.requires_steam)
# NOTE: clears versions file of unlinked mods
rebuild_symlinks(XDG.config)
remove_stale_signatures(XDG.config, XDG.version)
is_dayz_installed(XDG.config)
# TODO: handle IP DB failure and use coords fallback
get_ipdb(XDG.ips)
local_coords = get_local_coords(XDG.ips)
use_miles = lookup(XDG.config, Preferences.DIST)
prefs = UserPrefs(
is_steam_deck=_is_steam_deck,
is_game_mode=_is_game_mode,
is_debug=args.debug,
coords=local_coords,
version=version,
paths=XDG,
latest_release=latest_release,
use_miles=use_miles,
)
print(boot.all_ok)
App(prefs)
+218
View File
@@ -0,0 +1,218 @@
import logging
import traceback
from typing import Any, TYPE_CHECKING
from dzgui.const.constants import (
APP_NAME,
FLATPAK_RUN_CMD,
FLATPAK_SANDBOX,
STEAM_CMD,
WINDOW_DEFAULT_X,
WINDOW_DEFAULT_Y,
)
from dzgui.api.probe import test_steam_api, test_bm_api
from dzgui.const.enum import Preferences
from dzgui.managers.threading import call_on_thread, StoredFunc, ThreadingManager
from dzgui.views.dialogs.generic import ExceptionDialog
from dzgui.util._json import read_json, write_json
import gi
gi.require_version("Gtk", "3.0")
from gi.repository.Gtk import main_quit # noqa E402
if TYPE_CHECKING:
from dzgui.config.userprefs import UserPrefs
from dzgui.controllers.mc import Controller
from dzgui.views.base import OuterWindow
from dzgui.views.trees.tree_servers import ServerTreeView
logger = logging.getLogger(APP_NAME)
class ConfigManager:
def __init__(self, prefs: "UserPrefs", controller: "Controller") -> None:
self.prefs = prefs
self.config = prefs.paths.config
self.controller = controller
self.emitter = controller.get_emitter()
self.thread_man = ThreadingManager(controller)
def lookup(self, enum: Preferences) -> Any:
key = self.enum_to_key(enum)
config = self.get_config()
try:
return config[key]
except KeyError:
return None
def add_saved_server(self, record: str) -> None:
ips = self.lookup(Preferences.IP_LIST)
ips.append(record)
self.update_config(Preferences.IP_LIST, ips)
def update_history_file(self, records: list[Any]) -> None:
with open(self.prefs.paths.history, "w") as f:
for record in records:
addr = f"{record[7]}:{record[8]}"
f.write(f"{addr}\n")
def remove_saved_server(self, record: str) -> None:
ips = self.lookup(Preferences.IP_LIST)
ips.remove(record)
self.update_config(Preferences.IP_LIST, ips)
# TODO: drop/reroute
def update_config(self, key: Preferences, value: str) -> None:
self.write_config(key, value)
# TODO: suppress signals
# then reenable (or it spawns dialog twice)
# TODO: do this on demand if/when in options page
# self.mediator.grid.notebook.settings.populate_settings()
def get_config(self) -> Any:
# TODO: is this being called twice?
try:
return read_json(self.config)
except Exception as e:
logger.critical(e)
raise e
# TODO: strings
@call_on_thread("Checking api")
def update_api_key(self, key: Preferences, text: str) -> None:
if key is Preferences.STEAM:
res = test_steam_api(text)
else:
res = test_bm_api(text)
if res is True:
self.update_config(key, text)
else:
self.thread_man.set_cleanup_func(
StoredFunc(lambda: self.emitter.emit("api_change_failed"))
)
return
def get_start_tab(self) -> Any:
return int(self.lookup(Preferences.START_TAB))
def get_favorites(self) -> list[str]:
return list(self.lookup(Preferences.IP_LIST))
def get_favorite(self) -> tuple[str, str] | None:
fav = str(self.lookup(Preferences.FAV_LBL))
if len(fav) < 1:
return None
ip = str(self.lookup(Preferences.FAV_SRV))
addr = ip.split(":")
return fav, f"{addr[0]}:{addr[2]}"
def is_in_favs(self, record: str) -> bool:
favs = self.get_favorites()
if record in favs:
return True
return False
def enum_to_key(self, enum: Preferences) -> str:
return str(enum.dict["key"])
def get_client_index(self, client: str) -> int:
if client == STEAM_CMD:
return 0
if client == FLATPAK_RUN_CMD:
return 1
if client == FLATPAK_SANDBOX:
return 2
return 0
def toggle_config(self, key: Preferences) -> None:
try:
real_key = self.enum_to_key(key)
_json = self.get_config()
cur_val = not _json[real_key]
_json[real_key] = cur_val
write_json(_json, self.config)
except Exception as e:
logger.critical(e)
raise e
def set_fav(self, name: str, record: str) -> None:
try:
self.write_config(Preferences.FAV_LBL, name)
self.write_config(Preferences.FAV_SRV, record)
except Exception:
return
def write_config(self, key: Preferences, value: str) -> None:
try:
real_key = self.enum_to_key(key)
conf = self.get_config()
conf[real_key] = value
write_json(conf, self.config)
except Exception as e:
logger.critical(e)
trace = traceback.format_exc()
dialog = ExceptionDialog(self.controller, trace)
dialog.run()
raise e
def save_res_and_quit(self, tv: "ServerTreeView", window: "OuterWindow") -> None:
columns = tv.get_columns()
columns_file = self.prefs.paths.columns
try:
data = read_json(columns_file)
except Exception as e:
logger.critical(e)
data = {"cols": {}}
for column in columns:
title = column.get_title()
size = column.get_width()
data["cols"][title] = size
try:
write_json(data, columns_file)
except Exception as e:
logger.critical(e)
logger.info("Normal user exit")
if window.props.is_maximized:
main_quit()
return
w, h = window.get_size()
data = {"res": {"width": w, "height": h}}
res_path = self.prefs.paths.resolution
try:
write_json(data, res_path)
except Exception as e:
logger.critical(e)
main_quit()
def set_resolution(self, window: "OuterWindow") -> None:
if self.prefs.is_game_mode:
window.fullscreen()
return
elif self.lookup(Preferences.WINDOW) is True:
window.fullscreen()
try:
data = read_json(self.prefs.paths.resolution)
valid_json = True
except Exception as e:
valid_json = False
logger.critical(e)
if valid_json:
res = data["res"]
w, h = res["width"], res["height"]
logger.info(f"Restoring window size to {w},{h}")
window.set_default_size(w, h)
else:
w = WINDOW_DEFAULT_X
h = WINDOW_DEFAULT_Y
logger.info(f"Using default window size {w},{h}")
window.set_default_size(w, h)
+316
View File
@@ -0,0 +1,316 @@
import logging
import shutil
import time
from dataclasses import dataclass
from packaging.version import Version
from pathlib import Path
from typing import TYPE_CHECKING
import dzgui.api.pefile as PeFile
import dzgui.api.servers as Servers
from dzgui.api.steam import (
connect,
enqueue_mod,
get_remote_signatures,
get_needs_update,
)
from dzgui.api.mods import (
get_mod_dir_size,
get_local_mod_ids,
get_local_mod_path,
update_signatures,
)
from dzgui.const.constants import (
APP_NAME,
APPID_DAYZ,
APPID_DAYZ_EXP,
APPNAME_DAYZ,
APPNAME_DAYZ_EXP_HUMAN,
)
from dzgui.const.enum import NotebookPage, Preferences
from dzgui.init.proc import is_dayz_running, is_steam_running
from dzgui.managers.threading import call_on_thread, StoredFunc, ThreadingManager
from dzgui.strings.dialogs import waiting_for_launch, waiting_for_mods
from dzgui.strings.server_mods import checkmark, resync
from dzgui.util.format import format_mib
from dzgui.util.strings import dialog, server_timeout
from dzgui.util.symlink import rebuild_symlinks
from dzgui.views.dialogs.generic import ExceptionDialog
from dzgui.views.dialogs.servers import ServerDetailsDialog, ServerModDialog
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib # noqa E402
if TYPE_CHECKING:
from dzgui.api.servers import A2SInfo, Record
from dzgui.controllers.mc import Controller
logger = logging.getLogger(APP_NAME)
@dataclass(slots=True, frozen=True)
class SteamProcess:
name: str
is_running: bool
@dataclass(slots=True, frozen=True)
class Prerequisites:
name: str
appid: int
local_version: Version
remote_version: Version
build: str
binary_missing: bool
required_space: float
available_space: float
passworded: bool
dayz_running: bool
steam_proc: SteamProcess
mods: list[list[str]]
game_mode: bool
class ConnectionManager:
def __init__(self, controller: "Controller") -> None:
self.controller = controller
self.thread_man = ThreadingManager(controller)
self.appid: int
self.record: Record
self.workshop: Path
self.remote_mod_ids: list[str] = []
self.missing_mods: list[tuple[str, str, int, int]] = []
@call_on_thread(dialog.querying)
def connect_by_id(self, _id: int, key: str) -> None:
res = Servers.query_by_id(_id, key)
self._prepare_connection(res)
@call_on_thread(dialog.querying)
def connect_by_ip(self, addr: str) -> None:
res = Servers.query_by_ip(addr)
self._prepare_connection(res)
@call_on_thread(dialog.querying)
def connect_by_record(self, record: Servers.Record) -> None:
res = Servers.query_by_record(record)
self._prepare_connection(res)
def _prepare_connection(self, res: "A2SInfo") -> None:
failure_func = StoredFunc(self._server_timeout)
info = res.get_info()
if info is None:
self.thread_man.set_cleanup_func(failure_func, destroy_first=True)
return
try:
self.history = res.as_row()
except Exception:
self.thread_man.set_cleanup_func(failure_func, destroy_first=True)
return
record = res.get_record()
# NOTE: store metadata for later connection
self.appid = info.game_id
self.record = record
builds = {APPID_DAYZ: APPNAME_DAYZ, APPID_DAYZ_EXP: APPNAME_DAYZ_EXP_HUMAN}
build = builds[self.appid]
binary_missing = False
required_mib = 0.0
free_mib = 0.0
steam_path = Path(self.controller.query_config(Preferences.DEFAULT))
self.workshop = get_local_mod_path(steam_path)
local_version = PeFile.get_pretty_version(steam_path, info.game_id)
if local_version is None:
local_version = "0.0.0"
binary_missing = True
prefs = self.controller.get_prefs()
remote_mods: list[list[str]] = []
if res.is_modded():
try:
remote_mods = self._query_modlist(record)
self.remote_mod_ids = [mod[1] for mod in remote_mods]
except Exception as e:
logger.warning(e)
self.thread_man.set_cleanup_func(failure_func, destroy_first=True)
return
hashes = get_remote_signatures(self.remote_mod_ids)
version_file = prefs.paths.version
self.missing_mods = get_needs_update(version_file, hashes)
for mod in remote_mods:
if any(mod[1] in tuple for tuple in self.missing_mods):
mod[2] = resync
if local_version is not None:
pefile_path = PeFile.get_pefile_path(steam_path, info.game_id)
total, used, free = shutil.disk_usage(pefile_path)
if len(self.missing_mods) > 0:
required_size = sum(row[2] for row in self.missing_mods)
required_mib = format_mib(required_size)
free_mib = format_mib(required_size)
dayz_running = is_dayz_running()
client_name = self.controller.get_steam_client_name()
client = self.controller.query_config(Preferences.CLIENT)
running = is_steam_running(client)
steam_proc = SteamProcess(client_name, running)
game_mode = prefs.is_game_mode
prereqs = Prerequisites(
name=info.server_name,
appid=info.game_id,
local_version=Version(local_version),
remote_version=Version(info.version),
build=build,
binary_missing=binary_missing,
required_space=required_mib,
available_space=free_mib,
passworded=info.password_protected,
dayz_running=dayz_running,
steam_proc=steam_proc,
mods=remote_mods,
game_mode=game_mode,
)
func = StoredFunc(self.controller.open_connection_assistant, prereqs)
self.thread_man.set_cleanup_func(func, destroy_first=True)
@call_on_thread(dialog.querying)
def query_details(self, record: Servers.Record) -> None:
details = Servers.get_details(record)
if details.success is False:
self.thread_man.set_cleanup_func(
StoredFunc(self._server_timeout), destroy_first=True
)
return
self.thread_man.set_cleanup_func(
StoredFunc(self._present_details_dialog, details), destroy_first=True
)
def _query_modlist(self, record: Servers.Record) -> list[list[str]]:
mods = Servers.get_rules(record)
steam_path = self.controller.query_config(Preferences.DEFAULT)
local = get_local_mod_ids(steam_path)
alpha_mods: list[list[str]] = [
[
mod.name,
str(mod.workshop_id),
checkmark if mod.workshop_id in local else "",
]
for mod in mods
]
alpha_mods.sort(key=lambda x: x[0])
return alpha_mods
@call_on_thread(dialog.querying)
def query_modlist_and_present(self, record: Servers.Record) -> None:
try:
mods = self._query_modlist(record)
except Exception:
self.thread_man.set_cleanup_func(
StoredFunc(self._server_timeout), destroy_first=True
)
return
self.thread_man.set_cleanup_func(
StoredFunc(self._present_modlist_dialog, mods),
destroy_first=True,
)
def _present_modlist_dialog(self, mods: list[list[str]]) -> None:
dialog = ServerModDialog(self.controller, mods)
dialog.run()
def _present_details_dialog(self, details: Servers.Details) -> None:
dialog = ServerDetailsDialog(self.controller, details)
dialog.run()
def _server_timeout(self) -> None:
dialog = ExceptionDialog(self.controller, server_timeout)
dialog.run()
def _connect_steam(self) -> None:
addr = f"{self.record.ip}:{self.record.gameport}"
playername = self.controller.query_config(Preferences.NAME)
client = self.controller.query_config(Preferences.CLIENT)
rc = connect(client, addr, self.appid, playername, self.remote_mod_ids)
if rc != 0:
# TODO: log/pop the error
func = StoredFunc(self.controller.update_status)
self.thread_man.set_cleanup_func(func)
return
self.thread_man.show_cancel(False)
self.thread_man.update_dialog(waiting_for_launch)
while True:
# TODO: check cancel event
if self.controller.get_exit_event().is_set():
# TODO: some facility to also close spawned steam process
return
if is_dayz_running():
break
time.sleep(1)
func = StoredFunc(self._add_to_history_and_return)
self.thread_man.set_cleanup_func(func)
def _add_to_history_and_return(self) -> None:
self.controller.add_to_history(self.history)
self.controller.open_page(NotebookPage.SERVERS)
def _update_mods(self, raise_window: bool) -> None:
# NOTE: fast enqueue all mods in auto mode
prefs = self.controller.get_prefs()
for title, mod, stamp, size in self.missing_mods:
# TODO: check cancel and exit events
enqueue_mod(mod, self.appid)
time.sleep(2)
if raise_window is True:
logger.info("Bringing window to foreground")
GLib.idle_add(self.controller.present_window)
for title, mod, stamp, size in self.missing_mods:
mod_path = self.workshop / mod
# NOTE: Steam updates mod chunks in parallel, will finish at the same time
while mod_path.is_dir() is False:
time.sleep(1)
while True:
if self.controller.get_exit_event().is_set():
return
if self.controller.get_cancel_event().is_set():
self.controller.clear_cancel_event()
return
cur_size = get_mod_dir_size(mod_path)
if cur_size == size:
break
time.sleep(1)
update_signatures(self.missing_mods, prefs.paths.version)
# TODO: just push steam path directly
rebuild_symlinks(prefs.paths.config)
self._connect_steam()
@call_on_thread(waiting_for_mods, show_cancel=True)
def update_and_connect(self, raise_window: bool) -> None:
if len(self.missing_mods) > 0:
self._update_mods(raise_window)
else:
self._connect_steam()
+117
View File
@@ -0,0 +1,117 @@
import gi
import logging
from typing import TYPE_CHECKING
from dzgui.const.constants import APP_NAME
from dzgui.const.enum import ContextMenu, Preferences
from dzgui.util.clip import copy_clipboard
from dzgui.util.open_links import open_workshop_page
from dzgui.views.dialogs.note import NoteDialog
from dzgui.views.trees.tree_mods import ModTreeView
from dzgui.views.trees.tree_log import LogTreeView
from dzgui.views.trees.tree_servers import ServerTreeView
from dzgui.views.trees.tree_server_mods import ServerModTreeView
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GLib, GObject # noqa E402
logger = logging.getLogger(APP_NAME)
if TYPE_CHECKING:
from dzgui.controllers.mc import Controller
class ContextMenuManager:
def __init__(
self,
treeview: LogTreeView | ModTreeView | ServerTreeView | ServerModTreeView,
controller: "Controller",
) -> None:
self.controller = controller
self.treeview = treeview
def process(self, action: ContextMenu) -> None:
if isinstance(self.treeview, ServerTreeView):
record = self.treeview.get_record()
if record is None:
return
match action:
# UNTHREADED
case ContextMenu.ADD_NOTE:
dialog = NoteDialog(self.controller)
dialog.run()
case ContextMenu.COPY_SERVER_IP:
self.copy_server_ip()
case ContextMenu.COPY_SERVER_NAME:
self.copy_server_name()
case ContextMenu.SET_FAV:
name = self.treeview.get_value_at_index(0)
# NOTE: fully qualified ip
fqip = self.treeview.get_record_string()
# NOTE: short ip for display purposes
simple = self.treeview.get_simplified_ip()
self.controller.set_fav(name, fqip, simple)
# THREADED
case ContextMenu.ADD_SERVER:
self.controller.add_by_record(record)
case ContextMenu.CONNECT:
self.controller.connect_by_record(record)
case ContextMenu.REFRESH_PLAYERS:
self.controller.refresh_players(record)
case ContextMenu.REMOVE_HISTORY:
self.controller.remove_from_history(record)
case ContextMenu.REMOVE_SERVER:
self.controller.remove_by_record(record)
case ContextMenu.SHOW_DETAILS:
self.controller.get_details(record)
case ContextMenu.SHOW_MODS:
self.controller.get_modlist(record)
if isinstance(self.treeview, ModTreeView):
match action:
case ContextMenu.DELETE_MOD:
self.controller.delete_mods()
case ContextMenu.OPEN_WORKSHOP:
self.open_mod_page()
if isinstance(self.treeview, LogTreeView):
match action:
case ContextMenu.COPY_LOG_CLIPBOARD:
self.copy_log()
if isinstance(self.treeview, ServerModTreeView):
match action:
case ContextMenu.OPEN_WORKSHOP:
self.open_mod_page()
def copy_server_ip(self) -> None:
if not isinstance(self.treeview, ServerTreeView):
return
record = self.treeview.get_simplified_ip()
copy_clipboard(record)
def copy_server_name(self) -> None:
name = self.treeview.get_value_at_index(0)
if name is None:
return
copy_clipboard(name)
def open_mod_page(self) -> None:
if not hasattr(self.treeview, "get_selected_mod"):
return
mod = self.treeview.get_selected_mod()
cmd = self.controller.query_config(Preferences.CLIENT)
open_workshop_page(mod, cmd)
def copy_log(self) -> None:
if not isinstance(self.treeview, LogTreeView):
return
log = self.treeview.concatenate_rows()
if log is None:
return
copy_clipboard(log)
+105
View File
@@ -0,0 +1,105 @@
from typing import TYPE_CHECKING
from dzgui.model.model_factory import ModelFactory
from dzgui.util import strings
from dzgui.util.strings import all_maps
if TYPE_CHECKING:
from dzgui.model.model_factory import FastInsertListStore
class FilterManager:
def __init__(self) -> None:
self.map_store = ModelFactory().make_map_store()
# TODO: namespace under own file: strings.filters
self.default_filters = {
strings.filter_1pp: True,
strings.filter_day: True,
strings.filter_empty: False,
strings.filter_3pp: True,
strings.filter_night: True,
strings.filter_full: False,
strings.filter_lowpop: True,
strings.filter_nonascii: False,
strings.filter_duplicate: False,
strings.filter_official: True,
strings.filter_unofficial: True,
strings.filter_modded: True,
}
self.active_keyword = ""
self.active_map = (0, all_maps)
self.prior_map = all_maps
self.filters: list
self.enabled_filters = dict(self.default_filters)
def set_prior_map(self, name: str) -> None:
self.prior_map = name
def get_active_map_name(self) -> str:
return self.active_map[1]
def get_active_map(self) -> tuple[int, str]:
return self.active_map
def set_active_map(self, ind: int, name: str) -> None:
self.active_map = (ind, name)
def get_active_keyword(self) -> str:
return self.active_keyword
def set_active_keyword(self, word: str) -> None:
self.active_keyword = word
def get_default_filters(self) -> dict:
"""Deep copy of defaults"""
return dict(self.default_filters)
def get_filters(self) -> dict:
return self.enabled_filters
def set_filter(self, label: str, state: bool) -> None:
self.enabled_filters[label] = state
def get_map_store(self) -> "FastInsertListStore":
return self.map_store
def reinit_map_store(self) -> None:
model = ModelFactory().make_map_store()
model.append([all_maps])
self.map_store = model
self.active_map = (0, all_maps)
def append_map(self, row: list[str]) -> None:
self.map_store.append(row)
def set_unique_maps(self, maps: list[str]) -> None:
if maps is None:
return
if len(maps) < 1:
return
self.reinit_map_store()
maps.sort()
for m in maps:
if m == "All maps":
continue
self.append_map([m])
def get_unique_maps(self) -> list[str]:
return [row[0] for row in self.map_store if row != "All maps"]
def get_all_filters(self) -> tuple:
map_name = self.get_active_map_name()
enabled = self.get_filters()
kw = self.get_active_keyword()
filters = []
filters.append(map_name)
filters.append(kw)
for filt in enabled:
if enabled[filt] is False:
filters.append(filt)
return tuple(filters)
+204
View File
@@ -0,0 +1,204 @@
import logging
import shutil
from pathlib import Path
from typing import Any, TYPE_CHECKING
from dzgui.api.mods import (
get_delimited_mods,
get_local_mod_path,
find_stale_mods,
_hash,
remove_stale_signatures,
)
from dzgui.const.constants import APP_NAME, APPID_DAYZ, APPID_DAYZ_EXP
from dzgui.const.enum import Preferences
from dzgui.managers.threading import call_on_thread, StoredFunc, ThreadingManager
from dzgui.model.model_factory import FastInsertListStore, ModelFactory
from dzgui.util.format import format_mods
from dzgui.util.strings import server_timeout
from dzgui.views.dialogs.generic import ExceptionDialog
import dzgui.api.pefile as PeFile
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk # noqa E402
if TYPE_CHECKING:
from dzgui.controllers.mc import Controller
logger = logging.getLogger(APP_NAME)
class ModManager:
"""
Because mods may be dynamically updated on the system,
this manager is instantiated each time the Mods page is opened
"""
def __init__(self, controller: "Controller") -> None:
self.controller = controller
self.emitter = controller.get_emitter()
self.prefs = controller.get_prefs()
self.path = controller.query_config(Preferences.DEFAULT)
self.treeview = self.controller.get_modtreeview()
self.store: FastInsertListStore
self.thread_man = ThreadingManager(controller)
self._get_mods()
# TODO: dialog strings
@call_on_thread("getting mods")
def _get_mods(self) -> None:
mods = get_delimited_mods(self.path)
if len(mods) < 1:
msg = self.format_mod_statusbar()
func = StoredFunc(lambda: self.emitter.emit("mods_updated", msg, 0))
self.thread_man.set_cleanup_func(func)
return
func = StoredFunc(self._on_mods_loaded, mods)
self.thread_man.set_cleanup_func(func)
def _on_mods_loaded(self, mods: list[list[Any]]) -> None:
self.store = ModelFactory().make_mod_store()
self.store.extend(mods)
self.treeview.set_model(self.store)
msg = self.format_mod_statusbar()
total_mods = len(self.store)
self.emitter.emit("mods_updated", msg, total_mods)
def delete_mods(self) -> None:
sel = self.treeview.get_selection()
model, pathlist = sel.get_selected_rows()
# NOTE: reverse when multiple selection
mods: list[tuple[str, Gtk.TreeIter]] = []
for path in reversed(pathlist):
res = self.get_mod_from_tree_path(path)
if res is None:
continue
mod, _iter = res
mods.append((mod, _iter))
self.delete_mods_on_system(mods)
def get_mod_from_tree_path(
self, tree_path: Gtk.TreePath
) -> tuple[str, Gtk.TreeIter] | None:
model = self.treeview.get_model()
if model is None:
return None
tree_iter = model.get_iter(tree_path)
mod = model.get_value(tree_iter, 2)
return mod, tree_iter
# TODO: strings
@call_on_thread("deleting mods")
def delete_mods_on_system(self, mods: list[tuple[str, Gtk.TreeIter]]) -> None:
for mod, _iter in mods:
self.delete_single_mod(mod)
iters = [_iter for mod, _iter in mods]
func = StoredFunc(self._on_mods_deleted, iters)
self.thread_man.set_cleanup_func(func)
def delete_single_mod(self, mod: str) -> None:
steam_path = Path(self.path)
mods_path = get_local_mod_path(steam_path)
app_path = PeFile.get_nested_app_path(steam_path, APPID_DAYZ)
md5 = _hash(mod)
symlink = app_path / md5
symlink.unlink()
shutil.rmtree(mods_path / mod)
# NOTE: second pass to unlink DAYZ_EXP mods
# TODO: test this with working APPID_DAYZ_EXP installation
try:
app_path_exp = PeFile.get_nested_app_path(steam_path, APPID_DAYZ_EXP)
symlink = app_path_exp / md5
symlink.unlink()
except PeFile.AppNotInstalledError:
pass
def _on_mods_deleted(self, iters: list[Gtk.TreeIter]) -> None:
for _iter in iters:
self.store.remove(_iter)
remove_stale_signatures(self.prefs.paths.config, self.prefs.paths.version)
model = self.treeview.get_model()
if model is None:
return
mods = len(model)
msg = self.format_mod_statusbar()
self.emitter.emit("mods_updated", msg, mods)
def uncolorize_mods(self) -> None:
model = self.treeview.get_model()
if model is None:
return
for mod in model:
_iter = mod.iter
path = model.get_path(_iter)
model[path][4] = None
path = Gtk.TreePath.new_from_indices([0])
self.treeview.set_cursor(path)
def toggle_mod_selection(self, state: bool) -> None:
sel = self.treeview.get_selection()
if state:
sel.select_all()
else:
sel.unselect_all()
self.treeview.grab_focus()
def format_mod_statusbar(self) -> str:
total_mods, total_size = self.calc_mod_size()
msg = format_mods(total_size, total_mods)
return msg
def calc_mod_size(self) -> tuple[int, int]:
model = self.treeview.get_model()
if model is None:
return 0, 0
total_mods = len(model)
total_size = 0
for mod in model:
total_size += mod[3]
return total_mods, total_size
def _on_stale_mods_found(self, stale_mods: list) -> None:
"""Manipulates attached ListStore in the main event loop"""
model = self.treeview.get_model()
if model is None:
return
for mod in model:
it = mod.iter
path = model.get_path(it)
if int(mod[2]) in stale_mods:
model[path][4] = True
self.emitter.emit("mods_highlighted")
# TODO: dialog strings
@call_on_thread("working")
def highlight_stale(self) -> None:
stale = find_stale_mods(self.prefs.paths.config)
func = StoredFunc(self._on_stale_mods_found, stale)
self.thread_man.set_cleanup_func(func)
def _server_timeout(self) -> None:
dialog = ExceptionDialog(self.controller, server_timeout)
dialog.run()
def select_colorized(self) -> None:
model = self.treeview.get_model()
if model is None:
return
sel = self.treeview.get_selection()
for mod in model:
it = mod.iter
path = model.get_path(it)
if mod[4] is True:
sel.select_path(path)
+45
View File
@@ -0,0 +1,45 @@
import json
import logging
from typing import TYPE_CHECKING
from dzgui.const.constants import APP_NAME
from dzgui.util._json import read_json
import gi
gi.require_version("Gtk", "3.0")
if TYPE_CHECKING:
from dzgui.controllers.mc import Controller
from pathlib import Path
logger = logging.getLogger(APP_NAME)
class NoteManager:
def __init__(self, controller: "Controller", path: "Path") -> None:
self.notes_path = path
try:
self.cache: dict[str, str] = read_json(self.notes_path)
except Exception:
self.cache = {}
def add_note(self, server: str, note: str) -> None:
self.cache[server] = note
self.write_file()
def delete_note(self, server: str) -> None:
del self.cache[server]
self.write_file()
def get_note(self, server: str) -> str:
try:
text = self.cache[server]
return text
except Exception:
return ""
def write_file(self) -> None:
j = json.dumps(self.cache, indent=2)
self.notes_path.write_text(j)
+127
View File
@@ -0,0 +1,127 @@
import inspect
import logging
import threading
from typing import Any, Literal, TYPE_CHECKING, Union
from functools import wraps
from typing import Callable
from dzgui.const.constants import APP_NAME
from dzgui.views.dialogs.generic import WaitDialog
if TYPE_CHECKING:
from dzgui.controllers.mc import Controller
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib # noqa E402
logger = logging.getLogger(APP_NAME)
def call_on_thread(
dialog_str: str, show_dialog: bool = True, show_cancel: bool = False
) -> Callable:
def decorator(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> None:
self = args[0]
stored = StoredFunc(func, *args, **kwargs)
if not hasattr(self, "thread_man"):
raise AttributeError(f"Object '{self}' has no attribute 'thread_man'")
if type(self.thread_man) is not ThreadingManager:
raise TypeError(
"Attribute 'thread_man' must be of type 'ThreadingManager'"
)
self.thread_man.call_on_thread(dialog_str, stored, show_dialog, show_cancel)
return wrapper
return decorator
class StoredFunc:
def __init__(self, func: Callable, *args: Any, **kwargs: Any) -> None:
sig = inspect.signature(func)
self.func = func
self.bindings = sig.bind(*args, **kwargs)
def call(self) -> None:
self.func(*self.bindings.args, *self.bindings.kwargs)
class ThreadingManager:
def __init__(self, controller: Union["Controller", None]) -> None:
self.controller = controller
self.jobs = 1
self.cleanup_func: StoredFunc | None = None
self.destroy_first = False
def call_on_thread(
self,
dialog_str: str,
func: StoredFunc,
show_dialog: bool = True,
show_cancel: bool = False,
) -> None:
def callback() -> None:
func.call()
GLib.idle_add(self._destroy_on_idle)
if show_dialog is True and self.controller is not None:
self.wait_dialog = WaitDialog(
self.controller, dialog_str, jobs=self.jobs, show_cancel=show_cancel
)
self.wait_dialog.show_all()
thread = threading.Thread(target=callback)
thread.start()
def set_job_count(self, jobs: int) -> None:
self.jobs = jobs
def update_dialog(self, msg: str) -> None:
GLib.idle_add(lambda: self.wait_dialog.update_text(msg))
def increment_dialog(self) -> None:
GLib.idle_add(self.wait_dialog.increment)
def increment_dialog_with_str(self, text: str) -> None:
GLib.idle_add(lambda: self.wait_dialog.increment(text))
def set_cleanup_func(
self, func: StoredFunc | None, destroy_first: bool = False
) -> None:
if type(func) not in (StoredFunc, type(None)):
msg = f"Callback function '{func}' is not of type StoredFunc or None"
logger.critical(msg)
raise TypeError(msg)
self.destroy_first = destroy_first
self.cleanup_func = func
def get_cleanup_func(self) -> StoredFunc | None:
return self.cleanup_func
def destroy_dialog(self) -> None:
if hasattr(self, "wait_dialog"):
self.wait_dialog.destroy()
def _destroy_on_idle(self) -> Literal[False]:
if self.destroy_first:
self.destroy_dialog()
func = self.get_cleanup_func()
if func is not None:
func.call()
self.set_cleanup_func(None)
if not self.destroy_first:
self.destroy_dialog()
return False
def get_wait_dialog(self) -> WaitDialog:
return self.wait_dialog
def show_cancel(self, state: bool) -> None:
GLib.idle_add(self.wait_dialog.show_cancel, state)
+167
View File
@@ -0,0 +1,167 @@
from dataclasses import dataclass
from typing import Any, Sequence, TYPE_CHECKING
from dzgui.const.enum import HELP_MENU_ROWS
from dzgui.util.redact import redact_log
from dzgui.util.strings import delimiter
import gi
gi.require_version("Gtk", "3.0")
from gi.repository.Gtk import ListStore, TreeIter # noqa E402
from gi.repository import GObject # noqa E402
GTYPE_TO_PYTHON = {
GObject.type_from_name(GObject.type_name(ptype)): ptype
for ptype in (int, float, str, bool, object)
}
if TYPE_CHECKING:
from pathlib import Path
@dataclass(slots=True, frozen=True)
class ServerCols:
name: str
_map: str
perspective: str
gametime: str
players: int
_max: int
queue: int
ip: str
qport: int
ping: int
provider: str
modded: bool
@dataclass(slots=True, frozen=True)
class ModCols:
name: str
symlink: str
directory: str
size: float
color: bool
@dataclass(slots=True, frozen=True)
class LogCols:
timestamp: str
flag: str
traceback: str
msg: str
@dataclass(slots=True, frozen=True)
class ServerModCols:
name: str
uid: str
installed: str
@dataclass(slots=True, frozen=True)
class MenuCols:
name: str
hidden: object
class FastInsertListStore(ListStore):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
def _is_same_length(self, lists: Sequence[Any]) -> bool:
first_len = len(lists[0])
if not all(len(sublist) == first_len for sublist in lists):
return False
return True
def _is_type_homogeneous(self, lists: Sequence[Any]) -> bool:
transposed = zip(*lists)
for column in transposed:
first_type = type(column[0])
if not all(type(item) is first_type for item in column):
return False
return True
def extend(self, rows: Sequence[Any]) -> None:
"""
Compared to calling append() directly, introduces negligible overhead,
but guarantees type and length equivalence prior to insertion
"""
n_cols = self.get_n_columns()
expected_types = [
GTYPE_TO_PYTHON[self.get_column_type(i)] for i in range(n_cols)
]
if len(rows) == 0:
return
if not self._is_same_length(rows):
raise ValueError("Sublists are not of uniform length")
if not self._is_type_homogeneous(rows):
raise TypeError("Sublists are not type homogeneous")
if not all(isinstance(a, b) for a, b in zip(rows[0], expected_types)):
raise TypeError("Sublist types are not same as ListStore")
if len(rows[0]) != n_cols:
raise ValueError("Sublist column length is not same as ListStore")
for row in rows:
self.append(row)
def append(self, row: list[Any] | tuple[Any, ...] | None = ...) -> TreeIter: # type: ignore
"""
Optimized for speed, but makes no assurances about row homogeneity
and may segfault if types and length are not identical to ListStore.
For this reason, it is recommended to use the extend() method to insert
an entire list of lists
"""
if row is not None:
total = len(row)
i = len(self)
tree_iter = self.insert_with_values(i, tuple(range(total)), row)
else:
tree_iter = super().append(row)
return tree_iter
class ModelFactory:
def __init__(self) -> None:
pass
def new_model_from_logfile(self, path: "Path") -> FastInsertListStore:
store = self.make_log_store()
with open(path, "r") as f:
lines = [line.split(delimiter) for line in f.read().splitlines()]
for record in lines:
# NOTE: strips PII and API keys
clean = redact_log(record)
store.append(clean)
return store
def new_model_from_class(self, cls: type) -> FastInsertListStore:
store = FastInsertListStore(
*[ftype for field, ftype in cls.__annotations__.items()]
)
return store
def make_map_store(self) -> FastInsertListStore:
return FastInsertListStore(str)
def make_help_store(self) -> FastInsertListStore:
store = self.new_model_from_class(MenuCols)
rows = [[row.dict["label"], row] for row in HELP_MENU_ROWS]
store.extend(rows)
return store
def make_mod_store(self) -> FastInsertListStore:
return self.new_model_from_class(ModCols)
def make_log_store(self) -> FastInsertListStore:
return self.new_model_from_class(LogCols)
def make_server_mod_store(self) -> FastInsertListStore:
return self.new_model_from_class(ServerModCols)
def make_server_store(self) -> FastInsertListStore:
return self.new_model_from_class(ServerCols)
+300
View File
@@ -0,0 +1,300 @@
import re
from typing import Any, TYPE_CHECKING, Union
from warnings import deprecated
from dzgui.const.enum import FilterMode
from dzgui.model.model_factory import ModelFactory
from dzgui.util import strings
if TYPE_CHECKING:
from dzgui.managers.filter import FilterManager
from dzgui.model.model_factory import FastInsertListStore
from dzgui.api.servers import Record
from dzgui.model.servers import NewPlayerCount
class ProxyModelManager:
"""
Manages access to cached FastInsertListStore resources and
performs filtering on behalf of atomic TreeViews,
which share the same column structure.
A ProxyModelManager is attached to each ServerTreeView.
Raw data is cached before being packed into a FastInsertListStore, see get_control()
Filtration creates a proxy of the TreeView's model, see get_proxy_model()
"""
def __init__(self, filter_man: "FilterManager") -> None:
self.filter_cache: dict[
tuple[str],
list[tuple[str, str, str, str, int, int, int, str, int, int, str, bool]],
] = {}
self.proxy_model: "FastInsertListStore"
self.filter_man = filter_man
self.control_model: (
list[tuple[str, str, str, str, int, int, int, str, int, int, str, bool]]
| None
) = None
self.filtered: list[
tuple[str, str, str, str, int, int, int, str, int, int, str, bool]
] = []
self.success = True
def has_control_model(self) -> bool:
if self.control_model is None:
return False
return True
def append_row(self, row: list) -> None:
self.proxy_model.append(row)
def append_row_to_control(
self, row: tuple[str, str, str, str, int, int, int, str, int, int, str, bool]
) -> None:
if self.control_model is None:
raise AttributeError("Trying to add rows to a non-existent model")
self.control_model.append(row)
self.filter(FilterMode.INITIAL, skip_cache=True)
def update_playercount(self, playercount: "NewPlayerCount") -> None:
treeiter = playercount.treeiter
self.proxy_model[treeiter][4] = playercount.players
self.proxy_model[treeiter][6] = playercount.queue
# TODO: use dataclass for record rows
def append_row_to_history(
self,
history: tuple[str, str, str, str, int, int, int, str, int, int, str, bool],
) -> None:
addr = history[7]
qport = history[8]
if self.control_model is None:
raise AttributeError("Trying to append row to empty model")
found = False
for i, row in enumerate(self.control_model):
if addr == row[7] and qport == row[8]:
item = self.control_model.pop(i)
self.control_model.append(item)
found = True
break
if found is False:
self.control_model.append(history)
if len(self.control_model) == 11:
del self.control_model[0]
self.filter(FilterMode.INITIAL, skip_cache=True)
def remove_row_from_control(self, record: "Record") -> None:
if self.control_model is None:
return
addr = f"{record.ip}:{record.gameport}"
qport = record.qport
for row in self.control_model:
if addr == row[7] and qport == row[8]:
self.control_model.remove(row)
break
self.wipe_cache()
self.filter(FilterMode.INITIAL, skip_cache=True)
def clear_proxy_model(self) -> None:
self.proxy_model.clear()
def get_proxy_model(self) -> Union["FastInsertListStore", None]:
if hasattr(self, "proxy_model"):
return self.proxy_model
return None
def filter(
self, mode: FilterMode, skip_cache: bool = False
) -> Union["FastInsertListStore", None]:
"""
Native Gtk.TreeView.refilter() method was not performant enough
when running in the main loop with 40k+ records
skip_cache: used when updating a record on Saved Servers/History and forcing a refilter
"""
# TODO: filter cache: return a dataclass object with clearly enumerated map, keyword, and filter values
# instead of just a serial list of strings
filters = self.filter_man.get_all_filters()
if skip_cache is False:
if filters in self.filter_cache:
cached_rows = self.filter_cache[filters]
clone = ModelFactory().make_server_store()
clone.extend(cached_rows)
self.set_proxy_model(clone)
self.set_filtered(cached_rows)
return None
match mode:
case FilterMode.INITIAL:
rows = self.filter_initial(filters)
case FilterMode.TOGGLE_ON:
rows = self.filter_toggle_on(filters)
case FilterMode.TOGGLE_OFF:
for f in filters[2:]:
self.set_filtered(self.filter_toggle_off(filters, f))
rows = self.filtered
# NOTE: FastInsertListStore manipulation must remain local to the thread
clone = ModelFactory().make_server_store()
if len(rows) > 0:
rows = self.sort_rows(rows)
clone.extend(rows)
self.set_cache(filters, rows)
self.set_proxy_model(clone)
return clone
def sort_rows(self, rows: list) -> list:
rows.sort(key=lambda x: re.sub(r"[^A-Za-z0-9]+", "", x[0].lower()))
return rows
def filter_initial(self, filters: tuple) -> list:
"""
Simply culls the control model of any disabled filters
"""
self.set_filtered(self.control_model)
for f in filters[2:]:
self.set_filtered(self.filter_toggle_off(filters, f))
return self.filtered
def filter_map(self, filters: tuple) -> list:
"""
Multi-filtration for any context starts by narrowing by map
"""
rows = self.filtered
sel_map = self.filter_man.get_active_map_name()
if sel_map == strings.all_maps:
return rows
rows = [row for row in rows if row[1] == sel_map]
return rows
def filter_keyword(self, filters: tuple) -> list:
keyword = self.filter_man.get_active_keyword()
rows = self.filtered
if keyword == "":
return rows
filtered = [
row
for row in rows
if keyword in row[0].lower()
or keyword in row[1].lower()
or keyword in row[7].lower()
]
return filtered
def filter_toggle_off(self, filters: tuple, filter_type: str) -> list:
"""
Sub-filtration of the current model
"""
pairs = {
strings.filter_3pp: strings.filter_1pp,
strings.filter_day: strings.filter_night,
strings.filter_official: strings.filter_unofficial,
}
for k, v in pairs.items():
if k in filters and v in filters:
self.set_filtered(None)
return []
rows = self.filtered
match filter_type:
case strings.filter_3pp:
rows = [row for row in rows if row[2] != strings.filter_3pp]
case strings.filter_1pp:
rows = [row for row in rows if row[2] != strings.filter_1pp]
case strings.filter_official:
rows = [row for row in rows if row[10] != strings.filter_official]
case strings.filter_unofficial:
rows = [row for row in rows if row[10] != strings.filter_unofficial]
case strings.filter_empty:
rows = [row for row in rows if row[4] != 0]
case strings.filter_full:
rows = [row for row in rows if row[4] != row[5]]
case strings.filter_duplicate:
seen = set()
final = []
for row in rows:
if row[0] not in seen:
seen.add(row[0])
final.append(row)
rows = final
case strings.filter_day:
reg = r"([0][0-9]|[1][0-6])"
rows = [row for row in rows if not re.match(reg, row[3])]
case strings.filter_night:
reg = r"([0][0-4]|[1][8]|[2][0-3])"
rows = [row for row in rows if not re.match(reg, row[3])]
case strings.filter_nonascii:
rows = [row for row in rows if row[0].isascii()]
case strings.filter_lowpop:
rows = [row for row in rows if (row[4] / row[5] * 100) > 30]
case strings.filter_modded:
rows = [row for row in rows if not row[11]]
return rows
def filter_toggle_on(self, filters: tuple[str]) -> list:
"""Effectively applies all filters"""
self.set_filtered(self.control_model)
self.set_filtered(self.filter_map(filters))
self.set_filtered(self.filter_keyword(filters))
f: str
for f in filters[2:]:
self.set_filtered(self.filter_toggle_off(filters, f))
return self.filtered
def set_cache(self, filters: tuple[str], filtered_rows: list[tuple]) -> None:
self.filter_cache[filters] = filtered_rows
@deprecated("Currently unused")
# def convert_model_to_list(self, model: "FastInsertListStore") -> list:
# return [[el for el in row] for row in model]
def set_filtered(self, rows: list | None) -> None:
if rows is None:
self.filtered = []
else:
self.filtered = rows
def get_filtered(self) -> list:
return self.filtered
def set_proxy_model(self, model: "FastInsertListStore") -> None:
"""
FastInsertListStore representation of the raw model after filtration
"""
self.proxy_model = model
def set_control(self, rows: list) -> None:
"""
Raw data model prior to filtration
"""
self.control_model = rows
def get_control(self) -> list[Any]:
if self.control_model is None:
raise AttributeError(
"Expected a populated control model, but it is Nonetype"
)
return self.control_model
def wipe_cache(self, full: bool = False) -> None:
self.filtered = []
self.filter_cache = {}
def push(self, data: list[Any]) -> None:
self.wipe_cache()
self.set_control(data)
self.filter(FilterMode.INITIAL)
+435
View File
@@ -0,0 +1,435 @@
import logging
import threading
from concurrent.futures import as_completed
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any, TYPE_CHECKING
import dzgui.api.servers as Servers
from dzgui.const.constants import (
APPID_DAYZ,
APPID_DAYZ_EXP,
APP_NAME,
)
from dzgui.const.enum import FilterMode, Preferences, ServerTab
from dzgui.managers.threading import call_on_thread, StoredFunc, ThreadingManager
from dzgui.util.strings import api_warn_msg, dialog
from dzgui.views.dialogs.generic import ExceptionDialog
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk # noqa E402
if TYPE_CHECKING:
from dzgui.api.servers import A2SInfo
from dzgui.controllers.mc import Controller
from dzgui.model.proxy_model import ProxyModelManager
from dzgui.views.trees.tree_servers import ServerTreeView
logger = logging.getLogger(APP_NAME)
LAN_TIMEOUT = 0.5
API_TIMEOUT = 3
@dataclass
class NewPlayerCount:
treeiter: Gtk.TreeIter
players: int
queue: int
class ServerModelManager:
def __init__(self, controller: "Controller", tv: "ServerTreeView") -> None:
self.tv = tv
self.enum = tv.get_enum()
self.controller = controller
self.emitter = controller.get_emitter()
self.first_iteration: bool
self.preserve_on_fail = False
self.jobs = 1
self.proxy_man = tv.get_proxy_man()
self.thread_man = ThreadingManager(self.controller)
def load(self) -> None:
"""
Load is not called on init. There may be cases where you want to instantiate this class without dumping servers,
e.g., adding saved servers from another tab
"""
self.first_iteration = True
match self.enum:
case ServerTab.BROWSER:
# NOTE: extra DAYZ_EXP param
self.thread_man.set_job_count(len(Servers.params) + 1)
self._dump_api()
case ServerTab.SAVED:
self._dump_favorites()
case ServerTab.RECENT:
self._dump_history()
case ServerTab.LAN:
# NOTE: LAN tab is only loaded on demand
pass
case _:
pass
def refresh(self) -> None:
self.preserve_on_fail = True
self.load()
@call_on_thread(dialog.fetching)
def _dump_api(self) -> None:
# TODO: pass api key a priori in .load() call?
failure_func = StoredFunc(self._cleanup_on_failure)
config_man = self.controller.get_config_man()
key = config_man.lookup(Preferences.STEAM)
job = Servers.query_api
params = Servers.params
servers = []
with ThreadPoolExecutor() as executor:
futures = [executor.submit(job, key, APPID_DAYZ, param) for param in params]
for future in as_completed(futures):
try:
# NOTE: faciliates early aborting via sigint
# TODO: make this logic available to all dump contexts
if self.controller.get_exit_event().is_set():
return
self.thread_man.increment_dialog()
res = future.result(timeout=API_TIMEOUT)
if res.status != 200 or not res.parsed:
self.thread_man.set_cleanup_func(
failure_func, destroy_first=True
)
return
j = res.json
if j is not None:
servers.extend(j["response"]["servers"])
except Exception as e:
logger.critical(e)
self.thread_man.set_cleanup_func(failure_func, destroy_first=True)
return
# NOTE: this step is allowed to fail, since this metadata is incidental
res = Servers.query_api(key, APPID_DAYZ_EXP, "")
if res.status == 200 and res.parsed is True:
j = res.json
if j is not None:
servers.extend(j["response"]["servers"])
parsed = Servers.parse_json(servers)
self._push_data(parsed)
@call_on_thread(dialog.scanning)
def dump_lan(self, port: int, early_abort: bool) -> None:
self.first_iteration = True
servers = []
ports = range(1, 256)
failure_func = StoredFunc(self._cleanup_on_failure)
event = threading.Event()
with ThreadPoolExecutor() as executor:
futures = [executor.submit(Servers.test_ip, i, port, event) for i in ports]
for future in as_completed(futures):
try:
if self.controller.get_exit_event().is_set():
return
res = future.result(timeout=LAN_TIMEOUT)
if res is None:
continue
servers.append(res)
if early_abort is True:
# NOTE: on first non-empty hit, flag pending threads to close
event.set()
break
except Exception as e:
logger.critical(e)
self.thread_man.set_cleanup_func(failure_func, destroy_first=True)
if len(servers) == 0:
self.thread_man.set_cleanup_func(failure_func, destroy_first=True)
return
parsed = Servers.parse_json(servers)
self._push_data(parsed)
@call_on_thread(dialog.fetching)
def _dump_ips(self, ips: list[str]) -> None:
job = Servers.query_direct
servers = []
with ThreadPoolExecutor() as executor:
futures = [
executor.submit(
job,
ip.split(":")[0],
int(ip.split(":")[2]),
)
for ip in ips
]
for future in as_completed(futures):
# TODO: wrap except
if self.controller.get_exit_event().is_set():
return
res = future.result(timeout=API_TIMEOUT)
self.thread_man.increment_dialog()
# NOTE: failing entries are culled
if res is None:
# TODO: log which servers failed
continue
servers.append(res)
if len(servers) == 0:
self.thread_man.set_cleanup_func(
StoredFunc(self._cleanup_on_failure), destroy_first=True
)
return
parsed = Servers.parse_json(servers)
self._push_data(parsed)
@call_on_thread(dialog.querying)
def add_by_id(self, _id: str) -> None:
config_man = self.controller.get_config_man()
key = config_man.lookup(Preferences.BM)
res = Servers.query_by_id(int(_id), key)
self._parse_single_record(res)
@call_on_thread(dialog.querying)
def add_by_ip(self, addr: str) -> None:
res = Servers.query_by_ip(addr)
self._parse_single_record(res)
@call_on_thread(dialog.querying)
def add_by_record(self, record: Servers.Record) -> None:
# NOTE: rationale: a raw Record as shown in server browser may resolve to a different IP
res = Servers.query_by_record(record)
self._parse_single_record(res)
@call_on_thread(dialog.querying)
def remove_by_record(self, record: Servers.Record) -> None:
res = Servers.query_by_record(record)
self._parse_single_record(res, delete=True)
def update_history(
self,
rows: (
list[tuple[str, str, str, str, int, int, int, str, int, int, str, bool]]
| None
) = None,
) -> None:
proxy_man = self._get_proxy_man()
config_man = self.controller.get_config_man()
if rows is not None:
records = rows
else:
control_model = proxy_man.get_control()
records = control_model
config_man.update_history_file(records)
config_man.update_history_file(records)
self._sort_unique_maps(records)
proxy = proxy_man.get_proxy_model()
self.tv.set_model(proxy)
self.emitter.emit("servers_loaded", self.enum)
filter_man = self.tv.get_filter_man()
maps = self._get_new_maps()
filter_man.set_unique_maps(maps)
self.first_iteration = False
self.emitter.emit("servers_loaded_init")
def add_to_history(self, record: dict[str, Any]) -> None:
proxy_man = self._get_proxy_man()
rows = Servers.parse_json([record])
try:
proxy_man.append_row_to_history(rows[0])
except Exception:
self.update_history(rows)
return
self.update_history()
def remove_from_history(self, record: Servers.Record) -> None:
proxy_man = self._get_proxy_man()
proxy_man.remove_row_from_control(record)
self.update_history()
def add_by_str(self, addr: str) -> None:
if addr.isdigit():
self.add_by_id(addr)
else:
self.add_by_ip(addr)
@call_on_thread(dialog.querying)
def update_playercount(
self, treeiter: Gtk.TreeIter, record: Servers.Record
) -> None:
res = Servers.query_playercount(record)
if res is None:
return
players, queue = res
self.playercount = NewPlayerCount(treeiter, players, queue)
self.thread_man.set_cleanup_func(StoredFunc(self._push_playercount))
def _push_playercount(self) -> None:
proxy_man = self._get_proxy_man()
proxy_man.update_playercount(self.playercount)
def _parse_single_record(self, response: "A2SInfo", delete: bool = False) -> None:
self.preserve_on_fail = True
try:
row = response.as_row()
except Exception as e:
logger.warning(e)
self.thread_man.set_cleanup_func(
StoredFunc(self._cleanup_on_failure), destroy_first=True
)
return
# NOTE: expected to only contain one item
records = Servers.parse_json([row])
server = records[0]
if server is None:
return
proxy_man = self._get_proxy_man()
config_man = self.controller.get_config_man()
fqip = Servers.response_to_fqip(row)
record = response.get_record()
# TODO: less convoluted
if delete:
# NOTE: abort early if Saved Servers tab was not loaded yet
config_man.remove_saved_server(fqip)
if proxy_man.has_control_model() is False:
self.thread_man.set_cleanup_func(
StoredFunc(self._cleanup_when_no_model)
)
return
proxy_man.remove_row_from_control(record)
else:
if config_man.is_in_favs(fqip):
func = StoredFunc(lambda: self.emitter.emit("already_saved_server"))
self.thread_man.set_cleanup_func(func)
return
config_man.add_saved_server(fqip)
# FIXME: this is valid if saved servers tab is already open,
# but not if app was just booted; causes single row to appear prematurely
if proxy_man.has_control_model() is False:
proxy_man.push(records)
else:
proxy_man.append_row_to_control(server)
control_model = proxy_man.get_control()
self._sort_unique_maps(control_model)
self.thread_man.set_cleanup_func(StoredFunc(self._cleanup_single_ip))
def _cleanup_when_no_model(self) -> None:
self.emitter.emit("saved_servers_changed")
def _dump_history(self) -> None:
history = self.controller.get_prefs().paths.history
try:
with open(history, "r") as f:
rows = [row.rstrip("\n") for row in f]
except OSError:
self.thread_man.set_cleanup_func(
StoredFunc(self._cleanup_on_failure, False), destroy_first=True
)
return
if len(rows) == 0:
# TODO: customize statusbar to mention how records are added after connecting
self.thread_man.set_cleanup_func(
StoredFunc(self._cleanup_on_failure, False), destroy_first=True
)
return
self.thread_man.set_job_count(len(rows))
self._dump_ips(rows)
def _dump_favorites(self) -> None:
config_man = self.controller.get_config_man()
ips = config_man.lookup(Preferences.IP_LIST)
self.thread_man.set_job_count(len(ips))
if len(ips) == 0:
# TODO: customize statusbar to mention how records can be added via contextmenu
self.thread_man.set_cleanup_func(
StoredFunc(self._cleanup_on_failure, False), destroy_first=True
)
return
self._dump_ips(ips)
def _cleanup_single_ip(self) -> None:
proxy = self._get_proxy_man().get_proxy_model()
self.tv.set_model(proxy)
self.emitter.emit("servers_loaded", self.enum)
filter_man = self.tv.get_filter_man()
# NOTE: maps are set outside of thread because it triggers map changed signals
maps = self._get_new_maps()
filter_man.set_unique_maps(maps)
self.first_iteration = False
self.emitter.emit("servers_loaded_init")
self.emitter.emit("saved_servers_changed")
def _update_maps(self) -> None:
filter_man = self.tv.get_filter_man()
filter_man.set_unique_maps(self._get_new_maps())
self.emitter.emit("servers_loaded_init")
self.first_iteration = False
def _cleanup_on_success(self) -> None:
proxy = self._get_proxy_man().get_proxy_model()
self.tv.set_model(proxy)
# TODO: servers_loaded vs servers_reloaded
self.emitter.emit("servers_loaded", self.enum)
if self.first_iteration:
self._update_maps()
def _cleanup_on_failure(self, show_dialog: bool = True) -> None:
# TODO: disable map, keyword, and filter widgets if model is None
# signal driven (servers_empty, servers_failed_to_load)
if self.preserve_on_fail is False:
self.tv.set_model(None)
filter_man = self.tv.get_filter_man()
filter_man.set_unique_maps([])
# TODO: distinguish signals, e.g. "servers_failed_to_load", "servers_loaded_empty"
# customize statusbar and dialog accordingly
if show_dialog:
dialog = ExceptionDialog(self.controller, api_warn_msg)
dialog.run()
def _push_data(self, data: list[Any]) -> None:
self._get_proxy_man().push(data)
self._sort_unique_maps(data)
self.thread_man.set_cleanup_func(StoredFunc(self._cleanup_on_success))
def _sort_unique_maps(self, data: list) -> None:
u_maps = set([row[1] for row in data])
self._set_new_maps(sorted(u_maps))
def _set_new_maps(self, maps: list[str]) -> None:
self.new_maps: list[str] = maps
def _get_new_maps(self) -> list[str]:
return self.new_maps
def _get_proxy_man(self) -> "ProxyModelManager":
return self.proxy_man
@call_on_thread(dialog.filtering)
def refilter(self, mode: FilterMode) -> None:
# FIXME: causes two wait dialogs when map selection change signal emits after loading servers
self.first_iteration = False
proxy_man = self._get_proxy_man()
proxy_man.filter(mode)
self.thread_man.set_cleanup_func(StoredFunc(self._cleanup_on_success))
+1
View File
@@ -0,0 +1 @@
all_ok = "All OK. Loading UI..."
+2
View File
@@ -0,0 +1,2 @@
workshop = "Steam Workshop"
workshop_tooltip = "Open your Workshop subscriptions"
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff. Show more